From 730695a7a26967889405b12fc54099bb006c8231 Mon Sep 17 00:00:00 2001 From: huazhongming Date: Tue, 7 Nov 2023 15:40:13 +0800 Subject: [PATCH] [3.2]Use spotless to format the code (#13320) * Use spotless to format the code Signed-off-by: crazyhzm * Support develop with JDK 21 Signed-off-by: crazyhzm --------- Signed-off-by: crazyhzm --- dubbo-build-tools/pom.xml | 137 +- dubbo-cluster/pom.xml | 192 +- .../dubbo/registry/AddressListener.java | 5 +- .../org/apache/dubbo/rpc/cluster/Cluster.java | 4 +- .../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 | 239 +- .../cluster/directory/StaticDirectory.java | 23 +- .../rpc/cluster/filter/ClusterFilter.java | 3 +- .../filter/DefaultFilterChainBuilder.java | 20 +- .../cluster/filter/FilterChainBuilder.java | 53 +- .../cluster/filter/ProtocolFilterWrapper.java | 4 +- .../support/ConsumerClassLoaderFilter.java | 4 +- .../filter/support/ConsumerContextFilter.java | 34 +- .../filter/support/MetricsClusterFilter.java | 12 +- .../filter/support/MetricsConsumerFilter.java | 7 +- .../support/ObservationSenderFilter.java | 6 +- .../DefaultGovernanceRuleRepositoryImpl.java | 1 - .../governance/GovernanceRuleRepository.java | 1 - .../loadbalance/AbstractLoadBalance.java | 5 +- .../loadbalance/AdaptiveLoadBalance.java | 48 +- .../ConsistentHashLoadBalance.java | 10 +- .../loadbalance/LeastActiveLoadBalance.java | 7 +- .../loadbalance/RandomLoadBalance.java | 5 +- .../loadbalance/RoundRobinLoadBalance.java | 9 +- .../ShortestResponseLoadBalance.java | 25 +- .../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/router/AbstractRouter.java | 10 +- .../cluster/router/RouterSnapshotFilter.java | 2 +- .../cluster/router/RouterSnapshotNode.java | 78 +- .../router/RouterSnapshotSwitcher.java | 2 +- .../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 | 29 +- .../argument/ArgumentConditionMatcher.java | 14 +- .../AttachmentConditionMatcher.java | 18 +- .../param/UrlParamConditionMatcher.java | 1 - .../pattern/range/RangeValuePattern.java | 13 +- .../router/file/FileStateRouterFactory.java | 5 +- .../mesh/route/MeshAppRuleListener.java | 43 +- .../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 - .../virtualservice/match/AddressMatch.java | 9 +- .../rule/virtualservice/match/BoolMatch.java | 6 +- .../virtualservice/match/DoubleMatch.java | 3 - .../match/DoubleRangeMatch.java | 3 - .../match/DubboAttachmentMatch.java | 4 +- .../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/mesh/util/MeshRuleDispatcher.java | 11 +- .../router/mesh/util/MeshRuleListener.java | 2 - .../router/mock/MockInvokersSelector.java | 15 +- .../router/mock/MockStateRouterFactory.java | 1 - .../router/script/ScriptStateRouter.java | 55 +- .../script/ScriptStateRouterFactory.java | 1 - .../script/config/AppScriptStateRouter.java | 53 +- .../script/config/model/ScriptRule.java | 4 +- .../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 +- .../cluster/router/tag/TagStateRouter.java | 76 +- .../rpc/cluster/router/tag/model/Tag.java | 34 +- .../router/tag/model/TagRouterRule.java | 67 +- .../router/tag/model/TagRuleParser.java | 4 +- .../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 +- .../rpc/cluster/support/MergeableCluster.java | 1 - .../support/MergeableClusterInvoker.java | 35 +- .../DefaultProviderURLMergeProcessor.java | 14 +- .../support/registry/ZoneAwareCluster.java | 3 +- .../registry/ZoneAwareClusterInvoker.java | 34 +- .../support/wrapper/AbstractCluster.java | 54 +- .../support/wrapper/MockClusterInvoker.java | 56 +- .../support/wrapper/MockClusterWrapper.java | 3 +- .../support/wrapper/ScopeClusterInvoker.java | 71 +- .../support/wrapper/ScopeClusterWrapper.java | 4 +- .../dubbo/rpc/cluster/ConfiguratorTest.java | 15 +- .../dubbo/rpc/cluster/RouterChainTest.java | 191 +- .../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 +- .../cluster/directory/MockDirInvocation.java | 25 +- .../directory/StaticDirectoryTest.java | 26 +- .../filter/AbstractObservationFilterTest.java | 3 +- .../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 +- .../filter/MetricsClusterFilterTest.java | 49 +- .../rpc/cluster/filter/MockInvocation.java | 5 +- .../filter/ObservationSenderFilterTest.java | 31 +- .../loadbalance/AbstractLoadBalanceTest.java | 12 +- .../loadbalance/AdaptiveLoadBalanceTest.java | 52 +- .../ConsistentHashLoadBalanceTest.java | 35 +- .../loadbalance/LeastActiveBalanceTest.java | 12 +- .../loadbalance/LoadBalanceBaseTest.java | 32 +- .../loadbalance/RandomLoadBalanceTest.java | 11 +- .../RoundRobinLoadBalanceTest.java | 39 +- .../ShortestResponseLoadBalanceTest.java | 30 +- .../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 | 135 +- .../router/ConfigConditionRouterTest.java | 82 +- .../dubbo/rpc/cluster/router/MockInvoker.java | 6 +- .../router/RouterSnapshotFilterTest.java | 3 +- .../condition/ConditionStateRouterTest.java | 604 +- .../ProviderAppConditionStateRouterTest.java | 43 +- .../router/file/FileRouterEngineTest.java | 40 +- .../mesh/route/MeshAppRuleListenerTest.java | 225 +- .../router/mesh/route/MeshRuleCacheTest.java | 18 +- .../mesh/route/MeshRuleManagerTest.java | 120 +- .../router/mesh/route/MeshRuleRouterTest.java | 366 +- .../StandardMeshRuleRouterFactoryTest.java | 5 +- .../router/mesh/rule/DestinationRuleTest.java | 80 +- .../mesh/rule/VirtualServiceRuleTest.java | 40 +- .../virtualservice/DubboMatchRequestTest.java | 25 +- .../virtualservice/match/BoolMatchTest.java | 6 +- .../virtualservice/match/DoubleMatchTest.java | 6 - .../match/DubboAttachmentMatchTest.java | 30 +- .../match/DubboMethodMatchTest.java | 53 +- .../match/ListBoolMatchTest.java | 6 +- .../match/ListDoubleMatchTest.java | 7 +- .../match/ListStringMatchTest.java | 8 +- .../virtualservice/match/StringMatchTest.java | 5 - .../mesh/util/MeshRuleDispatcherTest.java | 61 +- .../router/mock/MockInvokersSelectorTest.java | 27 +- .../router/script/ScriptStateRouterTest.java | 83 +- .../config/AppScriptStateRouterTest.java | 53 +- .../rpc/cluster/router/state/BitListTest.java | 15 +- .../router/tag/TagStateRouterTest.java | 173 +- .../support/AbstractClusterInvokerTest.java | 101 +- .../support/AvailableClusterInvokerTest.java | 7 +- .../support/BroadCastClusterInvokerTest.java | 13 +- .../rpc/cluster/support/ClusterUtilsTest.java | 105 +- .../support/ConnectivityValidationTest.java | 52 +- .../support/FailSafeClusterInvokerTest.java | 14 +- .../support/FailbackClusterInvokerTest.java | 83 +- .../support/FailfastClusterInvokerTest.java | 8 +- .../support/FailoverClusterInvokerTest.java | 26 +- .../support/ForkingClusterInvokerTest.java | 14 +- .../dubbo/rpc/cluster/support/Menu.java | 4 +- .../rpc/cluster/support/MenuService.java | 1 - .../support/MergeableClusterInvokerTest.java | 206 +- .../support/TagProviderURLMergeProcessor.java | 1 - .../DefaultProviderURLMergeProcessorTest.java | 73 +- .../registry/ZoneAwareClusterInvokerTest.java | 118 +- .../support/wrapper/AbstractClusterTest.java | 29 +- .../support/wrapper/DemoClusterFilter.java | 5 +- .../wrapper/MockClusterInvokerTest.java | 301 +- .../wrapper/MockProviderRpcExceptionTest.java | 38 +- .../support/wrapper/MyMockException.java | 2 - .../wrapper/ScopeClusterInvokerTest.java | 117 +- dubbo-common/pom.xml | 171 +- .../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 +- .../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 | 154 +- .../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 | 73 +- .../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 +- .../file/FileSystemDynamicConfiguration.java | 185 +- .../CompositeDynamicConfiguration.java | 12 +- .../dubbo/common/constants/ClusterRules.java | 3 - .../common/constants/CommonConstants.java | 7 +- .../common/constants/FilterConstants.java | 1 - .../common/constants/LoadbalanceRules.java | 1 - .../common/constants/LoggerCodeConstants.java | 2 - .../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 | 38 +- .../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 | 409 +- .../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 | 8 +- .../common/json/impl/AbstractJSONImpl.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 - .../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 | 1 - .../common/logger/jdk/JdkLoggerAdapter.java | 9 +- .../logger/log4j/Log4jLoggerAdapter.java | 6 +- .../logger/log4j2/Log4j2LoggerAdapter.java | 4 +- .../common/logger/slf4j/Slf4jLogger.java | 1 - .../logger/slf4j/Slf4jLoggerAdapter.java | 8 +- .../support/FailsafeErrorTypeAwareLogger.java | 17 +- .../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 | 61 +- .../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 | 113 +- .../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 +- .../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 +- .../dubbo/common/utils/NativeUtils.java | 2 - .../apache/dubbo/common/utils/NetUtils.java | 86 +- .../apache/dubbo/common/utils/PathUtils.java | 5 +- .../apache/dubbo/common/utils/PojoUtils.java | 153 +- .../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 | 134 +- .../dubbo/config/AbstractInterfaceConfig.java | 84 +- .../dubbo/config/AbstractMethodConfig.java | 8 +- .../dubbo/config/AbstractReferenceConfig.java | 9 +- .../dubbo/config/AbstractServiceConfig.java | 3 +- .../dubbo/config/ApplicationConfig.java | 30 +- .../apache/dubbo/config/ArgumentConfig.java | 4 +- .../dubbo/config/ConfigCenterConfig.java | 5 +- .../org/apache/dubbo/config/ConfigKeys.java | 1 - .../org/apache/dubbo/config/Constants.java | 18 +- .../apache/dubbo/config/ConsumerConfig.java | 7 +- .../dubbo/config/MetadataReportConfig.java | 15 +- .../org/apache/dubbo/config/MethodConfig.java | 40 +- .../apache/dubbo/config/MetricsConfig.java | 4 +- .../org/apache/dubbo/config/ModuleConfig.java | 3 +- .../apache/dubbo/config/MonitorConfig.java | 4 +- .../apache/dubbo/config/ProtocolConfig.java | 28 +- .../apache/dubbo/config/ProviderConfig.java | 4 +- .../dubbo/config/ReferenceConfigBase.java | 37 +- .../apache/dubbo/config/RegistryConfig.java | 3 +- .../dubbo/config/ServiceConfigBase.java | 27 +- .../org/apache/dubbo/config/SslConfig.java | 15 +- .../apache/dubbo/config/TracingConfig.java | 4 +- .../dubbo/config/annotation/Argument.java | 6 +- .../dubbo/config/annotation/DubboService.java | 1 - .../dubbo/config/annotation/Method.java | 1 - .../dubbo/config/annotation/ProvidedBy.java | 1 - .../dubbo/config/annotation/Service.java | 1 - .../config/context/AbstractConfigManager.java | 120 +- .../dubbo/config/context/ConfigManager.java | 39 +- .../dubbo/config/context/ConfigValidator.java | 1 - .../config/context/ModuleConfigManager.java | 29 +- .../dubbo/config/nested/BaggageConfig.java | 1 - .../dubbo/config/nested/ExporterConfig.java | 1 - .../dubbo/config/nested/HistogramConfig.java | 1 - .../config/nested/PropagationConfig.java | 1 - .../apache/dubbo/config/support/Nested.java | 4 +- .../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 | 213 +- .../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 | 77 +- .../cache/FileCacheStoreFactoryTest.java | 14 +- .../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 +- ...SystemDynamicConfigurationFactoryTest.java | 7 +- .../FileSystemDynamicConfigurationTest.java | 54 +- .../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 | 13 +- .../common/logger/slf4j/Slf4jLoggerTest.java | 7 +- .../FailsafeErrorTypeAwareLoggerTest.java | 32 +- .../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 | 30 +- .../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 | 59 +- .../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 +- .../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 | 21 +- .../utils/TestAllowClassNotifyListener.java | 10 +- .../dubbo/common/utils/TimeUtilsTest.java | 1 - .../dubbo/common/utils/UrlUtilsTest.java | 22 +- .../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 | 98 +- .../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 | 60 +- .../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 | 30 +- .../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 | 204 +- .../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 | 134 +- .../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-compiler/pom.xml | 165 +- .../apache/dubbo/gen/AbstractGenerator.java | 167 +- .../dubbo/gen/dubbo/Dubbo3Generator.java | 5 +- .../dubbo/gen/tri/Dubbo3TripleGenerator.java | 1 - .../ReactorDubbo3TripleGenerator.java | 4 +- dubbo-config/dubbo-config-api/pom.xml | 453 +- .../dubbo/config/ConfigInitializer.java | 10 +- .../dubbo/config/ConfigPostProcessor.java | 9 +- .../config/ConfigScopeModelInitializer.java | 1 - .../dubbo/config/DubboShutdownHook.java | 34 +- .../apache/dubbo/config/ReferenceConfig.java | 184 +- .../apache/dubbo/config/ServiceConfig.java | 274 +- .../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 | 129 +- .../bootstrap/builders/MethodBuilder.java | 1 + .../bootstrap/builders/ProtocolBuilder.java | 2 +- .../bootstrap/builders/ServiceBuilder.java | 18 +- .../deploy/DefaultApplicationDeployer.java | 382 +- .../deploy/DefaultMetricsServiceExporter.java | 57 +- .../config/deploy/DefaultModuleDeployer.java | 153 +- .../config/deploy/FrameworkModelCleaner.java | 4 +- .../ConfigurableMetadataServiceExporter.java | 30 +- .../metadata/ExporterDeployListener.java | 37 +- ...ataServiceURLParamsMetadataCustomizer.java | 6 +- .../config/utils/CompositeReferenceCache.java | 14 +- .../config/utils/ConfigValidationUtils.java | 159 +- .../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 | 474 +- .../dubbo/config/RegistryConfigTest.java | 29 +- .../dubbo/config/ServiceConfigTest.java | 175 +- .../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 | 29 +- .../DefaultApplicationDeployerTest.java | 6 +- ...bstractRegistryCenterExporterListener.java | 12 +- ...AbstractRegistryCenterServiceListener.java | 4 +- .../config/integration/IntegrationTest.java | 2 +- .../integration/multiple/AbstractStorage.java | 1 - .../config/integration/multiple/Storage.java | 2 +- ...ryCenterExportMetadataIntegrationTest.java | 43 +- ...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 | 38 +- ...gleRegistryCenterExportProviderFilter.java | 2 +- ...ryCenterExportProviderIntegrationTest.java | 55 +- ...xportProviderRegistryProtocolListener.java | 13 +- .../SingleRegistryCenterInjvmFilter.java | 2 +- ...gleRegistryCenterInjvmIntegrationTest.java | 24 +- .../DelegateProviderMetaDataInvokerTest.java | 4 +- ...erviceURLParamsMetadataCustomizerTest.java | 22 +- .../dubbo/config/mock/GreetingLocal1.java | 6 +- .../dubbo/config/mock/GreetingLocal2.java | 2 +- .../dubbo/config/mock/GreetingLocal3.java | 2 +- .../dubbo/config/mock/GreetingMock1.java | 5 +- .../dubbo/config/mock/GreetingMock2.java | 5 +- .../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 | 140 +- .../config/url/RpcConfigGetSetProxy.java | 8 +- .../apache/dubbo/config/url/UrlTestBase.java | 44 +- .../utils/ConfigValidationUtilsTest.java | 55 +- .../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 | 471 +- .../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 +- .../AbstractAnnotationBeanPostProcessor.java | 126 +- .../AnnotationPropertyValuesAdapter.java | 26 +- .../DubboConfigAliasPostProcessor.java | 8 +- .../ReferenceAnnotationBeanPostProcessor.java | 183 +- .../ServiceAnnotationPostProcessor.java | 187 +- .../annotation/ServiceBeanNameBuilder.java | 10 +- .../annotation/ServicePackagesHolder.java | 2 - ...DefaultPropertyValueBeanPostProcessor.java | 17 +- .../DubboBootstrapApplicationListener.java | 26 +- .../DubboConfigApplicationListener.java | 21 +- .../context/DubboConfigBeanInitializer.java | 13 +- .../DubboDeployApplicationListener.java | 35 +- .../DubboInfraBeanRegisterPostProcessor.java | 18 +- .../context/DubboSpringInitContext.java | 6 +- .../context/DubboSpringInitCustomizer.java | 1 - .../DubboSpringInitCustomizerHolder.java | 4 +- .../context/DubboSpringInitializer.java | 42 +- .../DubboClassPathBeanDefinitionScanner.java | 24 +- .../annotation/DubboComponentScan.java | 5 +- .../DubboComponentScanRegistrar.java | 30 +- .../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 | 2 - .../schema/DubboBeanDefinitionParser.java | 205 +- .../status/DataSourceStatusChecker.java | 12 +- .../spring/status/SpringStatusChecker.java | 9 +- .../config/spring/util/AnnotationUtils.java | 230 +- .../spring/util/DubboAnnotationUtils.java | 84 +- .../config/spring/util/DubboBeanUtils.java | 72 +- .../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 | 10 +- .../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/pom.xml | 66 +- .../dubbo-configcenter-apollo/pom.xml | 103 +- .../apollo/ApolloDynamicConfiguration.java | 85 +- .../ApolloDynamicConfigurationFactory.java | 4 +- .../ApolloDynamicConfigurationTest.java | 58 +- .../support/apollo/EmbeddedApolloJunit5.java | 25 +- .../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 | 49 +- .../dubbo-configcenter-zookeeper/pom.xml | 155 +- .../support/zookeeper/CacheListener.java | 17 +- .../zookeeper/ZookeeperDataListener.java | 10 +- .../ZookeeperDynamicConfiguration.java | 35 +- .../ZookeeperDynamicConfigurationTest.java | 86 +- dubbo-configcenter/pom.xml | 55 +- 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 | 71 +- .../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 | 193 +- .../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 | 157 +- .../dubbo/demo/consumer/Application.java | 25 +- .../dubbo-demo-api-provider/pom.xml | 162 +- .../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 | 446 +- .../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 | 443 +- .../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 | 293 +- .../demo/consumer/ConsumerApplication.java | 2 +- .../dubbo-demo-spring-boot-interface/pom.xml | 31 +- .../dubbo/springboot/demo/DemoService.java | 1 - .../dubbo-demo-spring-boot-provider/pom.xml | 281 +- .../demo/provider/DemoServiceImpl.java | 9 +- .../demo/provider/ProviderApplication.java | 7 +- dubbo-demo/dubbo-demo-spring-boot/pom.xml | 80 +- dubbo-demo/dubbo-demo-triple/pom.xml | 344 +- .../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 | 280 +- .../dubbo/demo/rest/api/RestConsumer.java | 25 +- ...DubboServiceAnnotationServiceConsumer.java | 1 + .../demo/rest/api/config/DubboConfig.java | 3 +- .../dubbo-demo-jaxrs-rest-provider/pom.xml | 280 +- .../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 | 14 +- .../pom.xml | 281 +- .../demo/rest/api/SpringMvcRestConsumer.java | 12 +- .../demo/rest/api/config/DubboConfig.java | 5 +- .../SpringRestDemoServiceConsumer.java | 5 +- .../pom.xml | 280 +- .../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 | 242 +- .../dubbo/demo/provider/DemoServiceImpl.java | 20 +- .../demo/provider/RestDemoServiceImpl.java | 8 +- .../demo/provider/TripleServiceImpl.java | 1 - dubbo-demo/dubbo-demo-xml/pom.xml | 76 +- dubbo-demo/pom.xml | 49 +- dubbo-dependencies-bom/pom.xml | 1980 ++--- .../pom.xml | 402 +- .../dubbo-dependencies-zookeeper/pom.xml | 270 +- dubbo-dependencies/pom.xml | 205 +- dubbo-distribution/pom.xml | 194 +- dubbo-filter/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-filter/dubbo-filter-validation/pom.xml | 119 +- .../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-filter/pom.xml | 53 +- dubbo-kubernetes/pom.xml | 107 +- .../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 | 159 +- .../maven/plugin/aot/DubboProcessAotMojo.java | 22 +- dubbo-metadata/dubbo-metadata-api/pom.xml | 125 +- .../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 | 163 +- .../dubbo/metadata/MetadataParamsFilter.java | 16 +- .../metadata/MetadataServiceDetector.java | 1 - .../metadata/ParameterTypesComparator.java | 4 - .../dubbo/metadata/RevisionResolver.java | 2 - .../dubbo/metadata/ServiceNameMapping.java | 6 +- .../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 | 190 +- .../AbstractMetadataReportFactory.java | 6 +- .../metadata/report/support/Constants.java | 1 - .../report/support/NopMetadataReport.java | 29 +- ...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 | 6 +- .../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 +- .../PathVariableParameterProcessor.java | 2 - .../RequestHeaderParameterProcessor.java | 11 +- .../RequestParamParameterProcessor.java | 10 +- .../SpringMvcServiceRestMetadataResolver.java | 18 +- .../dubbo/metadata/rest/tag/BodyTag.java | 3 +- .../dubbo/metadata/rest/tag/ParamTag.java | 3 +- .../AbstractServiceNameMappingTest.java | 46 +- .../apache/dubbo/metadata/DemoService.java | 2 - .../dubbo/metadata/MetadataInfoTest.java | 60 +- .../dubbo/metadata/PathMatcherTest.java | 12 +- .../metadata/ServiceNameMappingTest.java | 125 - .../apache/dubbo/metadata/TestMediaType.java | 1 + .../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 | 185 +- .../metadata/rest/DefaultRestService.java | 12 +- .../rest/NoAnnotationApiDemoResolverTest.java | 17 +- .../dubbo/metadata/rest/RestService.java | 5 +- .../metadata/rest/SpringRestService.java | 43 +- .../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 +- .../JAXRSServiceRestMetadataResolverTest.java | 40 +- .../rest/jaxrs/JaxrsRestDoubleCheckTest.java | 21 +- ...ingMvcServiceRestMetadataResolverTest.java | 44 +- .../test/JTestMetadataReport4Test.java | 11 +- .../test/JTestMetadataReportFactory4Test.java | 1 - .../pom.xml | 48 +- .../protobuf/ProtobufTypeBuilder.java | 28 +- .../protobuf/ProtobufTypeBuilderTest.java | 22 +- .../definition/protobuf/model/GooglePB.java | 7497 +++++++++-------- .../dubbo-metadata-processor/pom.xml | 268 +- .../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 | 40 +- .../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 | 112 +- .../zookeeper/ZookeeperMetadataReport.java | 8 +- .../ZookeeperMetadataReportFactory.java | 1 - .../ZookeeperMetadataReportTest.java | 158 +- dubbo-metadata/pom.xml | 55 +- dubbo-metrics/dubbo-metrics-api/pom.xml | 82 +- .../dubbo/metrics/MetricsConstants.java | 4 +- .../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 | 8 +- .../collector/MethodMetricsCollector.java | 2 - .../metrics/collector/MetricsCollector.java | 5 +- .../collector/ServiceMetricsCollector.java | 2 - .../collector/stat/MetricsStatHandler.java | 2 - .../data/ApplicationStatComposite.java | 7 +- .../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/MetricsEvent.java | 13 +- .../dubbo/metrics/event/MetricsEventBus.java | 2 - .../event/MetricsEventMulticaster.java | 1 - .../dubbo/metrics/event/MetricsInitEvent.java | 12 +- .../event/SimpleMetricsEventMulticaster.java | 1 - .../dubbo/metrics/event/TimeCounterEvent.java | 5 +- .../MetricsNeverHappenException.java | 1 - .../listener/AbstractMetricsKeyListener.java | 10 +- .../listener/AbstractMetricsListener.java | 5 +- .../listener/MetricsApplicationListener.java | 34 +- .../metrics/listener/MetricsLifeListener.java | 7 +- .../metrics/listener/MetricsListener.java | 4 - .../listener/MetricsServiceListener.java | 26 +- .../metrics/model/ApplicationMetric.java | 6 +- .../metrics/model/ConfigCenterMetric.java | 11 +- .../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 +- .../apache/dubbo/metrics/model/TimePair.java | 1 - .../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 +- .../dubbo/metrics/model/key/MetricsKey.java | 35 +- .../metrics/model/key/MetricsKeyWrapper.java | 4 +- .../dubbo/metrics/model/key/MetricsLevel.java | 7 +- .../metrics/model/key/MetricsPlaceValue.java | 1 - .../dubbo/metrics/model/key/TypeWrapper.java | 2 - .../model/sample/CounterMetricSample.java | 7 +- .../model/sample/GaugeMetricSample.java | 32 +- .../metrics/model/sample/MetricSample.java | 37 +- ...ractDefaultDubboObservationConvention.java | 11 +- ...faultDubboClientObservationConvention.java | 11 +- ...faultDubboServerObservationConvention.java | 3 +- .../observation/DubboClientContext.java | 4 +- .../DubboObservationDocumentation.java | 3 - .../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 - .../dubbo/metrics/MetricsSupportTest.java | 18 +- .../dubbo/metrics/aggregate/PaneTest.java | 5 +- .../metrics/aggregate/SlidingWindowTest.java | 12 +- .../aggregate/TimeWindowAggregatorTest.java | 19 +- .../aggregate/TimeWindowCounterTest.java | 1 - .../aggregate/TimeWindowQuantileTest.java | 21 +- .../SimpleMetricsEventMulticasterTest.java | 21 +- .../metrics/model/ApplicationMetricTest.java | 35 +- ...tDubboClientObservationConventionTest.java | 9 +- ...tDubboServerObservationConventionTest.java | 6 +- .../utils/ObservationConventionUtils.java | 15 +- .../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 +- .../collector/AggregateMetricsCollector.java | 181 +- .../collector/DefaultMetricsCollector.java | 79 +- .../collector/HistogramMetricsCollector.java | 38 +- .../MetricThreadPoolExhaustedListener.java | 15 +- .../sample/MetricsCountSampleConfigurer.java | 11 +- .../collector/sample/MetricsCountSampler.java | 2 - .../collector/sample/MetricsSampler.java | 1 - .../sample/SimpleMetricsCountSampler.java | 15 +- .../sample/ThreadPoolMetricsSampler.java | 95 +- .../ThreadRejectMetricsCountSampler.java | 44 +- .../metrics/event/DefaultSubDispatcher.java | 79 +- .../dubbo/metrics/event/RequestEvent.java | 47 +- .../dubbo/metrics/filter/MetricsFilter.java | 17 +- .../metrics/filter/MetricsProviderFilter.java | 7 +- .../ObservationReceiverFilter.java | 6 +- .../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 +- .../metrics/DefaultMetricsServiceTest.java | 21 +- .../dubbo/metrics/TestMetricsInvoker.java | 6 +- .../AggregateMetricsCollectorTest.java | 83 +- .../collector/DefaultCollectorTest.java | 125 +- .../collector/InitServiceMetricsTest.java | 52 +- .../sample/ThreadPoolMetricsSamplerTest.java | 13 +- .../metrics/filter/MetricsFilterTest.java | 39 +- .../metrics/model/MethodMetricTest.java | 19 +- .../model/sample/GaugeMetricSampleTest.java | 12 +- .../model/sample/MetricSampleTest.java | 8 +- .../metrics/service/MetricsEntityTest.java | 8 +- .../AbstractObservationFilterTest.java | 2 - .../metrics/observation/MockInvocation.java | 5 +- .../ObservationReceiverFilterTest.java | 41 +- 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 | 271 +- .../metadata/MetadataStatCompositeTest.java | 49 +- .../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 | 97 +- .../RegistryMetricsCollectorTest.java | 256 +- .../collector/RegistryMetricsSampleTest.java | 33 +- .../collector/RegistryMetricsTest.java | 29 +- .../collector/RegistryStatCompositeTest.java | 84 +- dubbo-metrics/pom.xml | 64 +- dubbo-monitor/dubbo-monitor-api/pom.xml | 89 +- .../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 - .../support/AbstractMonitorFactory.java | 20 +- .../CallbackConsumerContextFilter.java | 2 +- .../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 | 128 +- .../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 | 118 +- .../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 | 53 +- dubbo-native-plugin/pom.xml | 169 +- .../dubbo/maven/plugin/CodeGenerator.java | 146 +- .../plugin/DubboNativeCodeGeneratorMojo.java | 25 +- .../org/apache/dubbo/maven/plugin/Test.java | 4 +- dubbo-native/pom.xml | 38 +- .../dubbo/aot/generate/AotProcessor.java | 22 +- .../aot/generate/ClassSourceScanner.java | 56 +- .../aot/generate/ConditionalDescriber.java | 1 - .../aot/generate/ExecutableDescriber.java | 10 +- .../apache/dubbo/aot/generate/JarScanner.java | 4 - .../aot/generate/NativeClassSourceWriter.java | 39 +- .../generate/NativeConfigurationWriter.java | 12 +- .../ReflectConfigMetadataRepository.java | 24 +- .../aot/generate/ReflectionConfigWriter.java | 106 +- .../aot/generate/ResourceBundleDescriber.java | 1 - .../ResourceConfigMetadataRepository.java | 3 +- .../aot/generate/ResourceConfigWriter.java | 21 +- .../generate/ResourcePatternDescriber.java | 9 +- .../dubbo/aot/generate/ResourceScanner.java | 17 +- .../dubbo/aot/generate/TypeDescriber.java | 11 +- .../ResourcePatternDescriberTest.java | 7 +- dubbo-plugin/dubbo-auth/pom.xml | 53 +- .../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-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 | 123 +- .../dubbo/qos/QosScopeModelInitializer.java | 8 +- .../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 | 77 +- .../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 | 29 +- .../command/impl/SerializeWarnedClasses.java | 18 +- .../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/ChangeTelnetHandler.java | 5 +- .../dubbo/qos/legacy/LogTelnetHandler.java | 18 +- .../dubbo/qos/legacy/TraceTelnetHandler.java | 9 +- ...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 | 27 +- .../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/ChangeTelnetHandlerTest.java | 28 +- .../qos/legacy/LogTelnetHandlerTest.java | 3 +- .../dubbo/qos/legacy/ProtocolUtils.java | 6 +- .../qos/legacy/TraceTelnetHandlerTest.java | 14 +- .../dubbo/qos/legacy/channel/MockChannel.java | 4 +- .../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 | 207 +- .../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 | 156 +- .../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 | 61 +- dubbo-registry/dubbo-registry-api/pom.xml | 174 +- .../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 +- .../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 | 133 +- .../client/RegistryClusterIdentifier.java | 4 +- .../registry/client/ServiceDiscovery.java | 13 +- .../client/ServiceDiscoveryFactory.java | 3 +- .../client/ServiceDiscoveryRegistry.java | 81 +- .../ServiceDiscoveryRegistryDirectory.java | 289 +- .../ServiceDiscoveryRegistryFactory.java | 1 - .../registry/client/ServiceInstance.java | 1 - .../RetryServiceInstancesChangedEvent.java | 2 +- .../event/ServiceInstancesChangedEvent.java | 2 - .../ServiceInstancesChangedListener.java | 171 +- .../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 | 246 +- .../integration/RegistryProtocol.java | 394 +- .../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 | 96 +- .../registry/support/RegistryManager.java | 42 +- .../CacheableFailbackRegistryTest.java | 19 +- .../registry/ListenerRegistryWrapperTest.java | 21 +- .../registry/MockCacheableRegistryImpl.java | 8 +- .../org/apache/dubbo/registry/MockLogger.java | 56 +- .../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 | 235 +- .../AbstractServiceDiscoveryFactoryTest.java | 8 +- .../client/DefaultServiceInstanceTest.java | 12 +- .../FileSystemServiceDiscoveryTest.java | 57 - .../client/InstanceAddressURLTest.java | 84 +- .../client/ServiceDiscoveryCacheTest.java | 35 +- .../client/ServiceDiscoveryRegistryTest.java | 78 +- .../registry/client/ServiceDiscoveryTest.java | 247 - .../ServiceInstancesChangedListenerTest.java | 97 +- ...hangedListenerWithoutEmptyProtectTest.java | 94 +- ...efaultServiceInstanceDeserializerTest.java | 58 - .../MetadataServiceNameMappingTest.java | 40 +- .../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 | 139 +- .../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 | 206 +- .../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 | 78 +- .../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 +- .../nacos/util/NacosNamingServiceUtils.java | 12 +- .../registry/nacos/MockNamingService.java | 112 +- .../nacos/NacosConnectionsManagerTest.java | 43 +- .../nacos/NacosNamingServiceWrapperTest.java | 448 +- .../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 | 100 +- .../zookeeper/ZookeeperRegistryFactory.java | 1 - .../zookeeper/ZookeeperServiceDiscovery.java | 54 +- ...ookeeperServiceDiscoveryChangeWatcher.java | 39 +- .../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 | 77 +- .../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 +- .../RemotingScopeModelInitializer.java | 22 +- .../apache/dubbo/remoting/RemotingServer.java | 1 - .../dubbo/remoting/TimeoutException.java | 5 +- .../apache/dubbo/remoting/Transporter.java | 1 - .../apache/dubbo/remoting/Transporters.java | 8 +- .../remoting/api/AbstractWireProtocol.java | 7 +- .../dubbo/remoting/api/ProtocolDetector.java | 6 +- .../connection/AbstractConnectionClient.java | 8 +- .../api/connection/ConnectionHandler.java | 1 - .../api/connection/ConnectionManager.java | 1 - .../MultiplexProtocolConnectionManager.java | 7 +- .../SingleProtocolConnectionManager.java | 4 +- .../api/pu/AbstractPortUnificationServer.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 +- .../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/ChanelHandlerTest.java | 20 +- .../remoting/PerformanceClientCloseTest.java | 75 +- .../remoting/PerformanceClientFixedTest.java | 37 +- .../dubbo/remoting/PerformanceClientMain.java | 2 - .../dubbo/remoting/PerformanceClientTest.java | 134 +- .../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 | 118 +- .../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 | 31 +- dubbo-remoting/dubbo-remoting-netty/pom.xml | 75 +- .../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 | 101 +- .../netty4/Netty4BatchWriteQueue.java | 14 +- .../netty4/NettyBackedChannelBuffer.java | 69 +- .../transport/netty4/NettyChannel.java | 39 +- .../transport/netty4/NettyChannelHandler.java | 19 +- .../transport/netty4/NettyClient.java | 100 +- .../transport/netty4/NettyClientHandler.java | 10 +- .../transport/netty4/NettyCodecAdapter.java | 12 +- .../transport/netty4/NettyConfigOperator.java | 51 +- .../netty4/NettyConnectionClient.java | 100 +- .../netty4/NettyConnectionHandler.java | 35 +- .../netty4/NettyEventLoopFactory.java | 17 +- .../netty4/NettyPortUnificationServer.java | 79 +- .../NettyPortUnificationServerHandler.java | 80 +- .../NettyPortUnificationTransporter.java | 4 +- .../transport/netty4/NettyServer.java | 60 +- .../transport/netty4/NettyServerHandler.java | 25 +- .../netty4/NettySslContextOperator.java | 3 +- .../transport/netty4/NettyTransporter.java | 1 - .../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/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-curator5/pom.xml | 90 +- .../curator5/Curator5ZookeeperClient.java | 122 +- .../Curator5ZookeeperTransporter.java | 1 - .../curator5/Curator5ZookeeperClientTest.java | 190 +- .../Curator5ZookeeperTransporterTest.java | 3 +- .../AbstractZookeeperTransporterTest.java | 156 +- .../dubbo-remoting-zookeeper/pom.xml | 121 +- .../curator/CuratorZookeeperClient.java | 144 +- .../curator/CuratorZookeeperTransporter.java | 2 - .../curator/CuratorZookeeperClientTest.java | 193 +- .../CuratorZookeeperTransporterTest.java | 4 +- .../AbstractZookeeperTransporterTest.java | 157 +- dubbo-remoting/pom.xml | 60 +- dubbo-rpc/dubbo-rpc-api/pom.xml | 81 +- .../org/apache/dubbo/rpc/AdaptiveMetrics.java | 30 +- .../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 | 100 +- .../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 - .../dubbo/rpc/filter/AccessLogFilter.java | 61 +- .../dubbo/rpc/filter/ActiveLimitFilter.java | 13 +- .../rpc/filter/AdaptiveLoadBalanceFilter.java | 37 +- .../dubbo/rpc/filter/CompatibleFilter.java | 13 +- .../dubbo/rpc/filter/ContextFilter.java | 29 +- .../dubbo/rpc/filter/DeprecatedFilter.java | 8 +- .../apache/dubbo/rpc/filter/EchoFilter.java | 1 - .../dubbo/rpc/filter/ExceptionFilter.java | 51 +- .../dubbo/rpc/filter/ExecuteLimitFilter.java | 19 +- .../dubbo/rpc/filter/GenericFilter.java | 203 +- .../dubbo/rpc/filter/GenericImplFilter.java | 73 +- .../rpc/filter/ProfilerServerFilter.java | 50 +- .../dubbo/rpc/filter/RpcExceptionFilter.java | 6 +- .../dubbo/rpc/filter/TimeoutFilter.java | 12 +- .../apache/dubbo/rpc/filter/TokenFilter.java | 12 +- .../dubbo/rpc/filter/TokenHeaderFilter.java | 10 +- .../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 - .../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 +- .../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 +- .../proxy/bytebuddy/ByteBuddyInterceptor.java | 10 +- .../rpc/proxy/bytebuddy/ByteBuddyProxy.java | 34 +- .../bytebuddy/ByteBuddyProxyInvoker.java | 8 +- .../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 - .../dubbo/rpc/support/AccessLogData.java | 37 +- .../rpc/support/Dubbo2RpcExceptionUtils.java | 3 +- .../apache/dubbo/rpc/support/MockInvoker.java | 51 +- .../dubbo/rpc/support/MockProtocol.java | 2 +- .../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 +- .../dubbo/rpc/filter/AccessLogFilterTest.java | 14 +- .../rpc/filter/ActiveLimitFilterTest.java | 22 +- .../rpc/filter/ClassLoaderFilterTest.java | 7 +- .../filter/CompatibleFilterFilterTest.java | 28 +- .../dubbo/rpc/filter/ContextFilterTest.java | 4 +- .../rpc/filter/DeprecatedFilterTest.java | 7 +- .../dubbo/rpc/filter/EchoFilterTest.java | 7 +- .../dubbo/rpc/filter/ExceptionFilterTest.java | 27 +- .../rpc/filter/ExecuteLimitFilterTest.java | 15 +- .../dubbo/rpc/filter/GenericFilterTest.java | 53 +- .../rpc/filter/GenericImplFilterTest.java | 72 +- .../dubbo/rpc/filter/TimeoutFilterTest.java | 5 +- .../dubbo/rpc/filter/TokenFilterTest.java | 7 +- .../rpc/filter/tps/DefaultTPSLimiterTest.java | 17 +- .../dubbo/rpc/filter/tps/StatItemTest.java | 13 +- .../rpc/filter/tps/TpsLimitFilterTest.java | 3 +- .../rpc/protocol/CountInvokerListener.java | 7 +- .../protocol/ProtocolListenerWrapperTest.java | 87 +- .../dubbo/rpc/proxy/AbstractProxyTest.java | 33 +- .../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 +- .../bytebuddy/ByteBuddyInterceptorTest.java | 12 +- .../bytebuddy/ByteBuddyProxyFactoryTest.java | 1 - .../bytebuddy/ByteBuddyProxyInvokerTest.java | 11 +- .../proxy/bytebuddy/ByteBuddyProxyTest.java | 7 +- .../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/DemoServiceAMock.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 +- .../dubbo/rpc/support/MockInvokerTest.java | 80 +- .../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 | 173 +- .../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 +- .../protocol/dubbo/filter/FutureFilter.java | 37 +- .../protocol/dubbo/filter/TraceFilter.java | 18 +- .../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 | 175 +- .../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 | 250 +- .../rpc/protocol/dubbo/FutureFilterTest.java | 4 +- .../protocol/dubbo/ImplicitCallBackTest.java | 406 - .../rpc/protocol/dubbo/MultiThreadTest.java | 35 +- .../ReferenceCountExchangeClientTest.java | 31 +- .../rpc/protocol/dubbo/RpcFilterTest.java | 15 +- .../dubbo/decode/DubboTelnetDecodeTest.java | 219 +- .../dubbo/decode/LocalEmbeddedChannel.java | 4 +- .../protocol/dubbo/decode/MockChannel.java | 28 +- .../dubbo/decode/MockChannelHandler.java | 3 +- .../protocol/dubbo/decode/MockHandler.java | 4 +- .../protocol/dubbo/filter/MockChannel.java | 15 +- .../dubbo/filter/TraceFilterTest.java | 16 +- .../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 | 85 +- .../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 | 280 +- .../dubbo/rpc/protocol/rest/Constants.java | 2 - .../protocol/rest/NettyHttpRestServer.java | 45 +- .../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 | 60 +- .../rpc/protocol/rest/RestProtocolServer.java | 3 - .../protocol/rest/RestRPCInvocationUtil.java | 45 +- .../rpc/protocol/rest/RestServerFactory.java | 2 - .../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 | 11 +- .../inercept/PathVariableIntercept.java | 12 +- .../inercept/RequestHeaderIntercept.java | 12 +- .../inercept/SerializeBodyIntercept.java | 22 +- .../annotation/metadata/MetadataResolver.java | 36 +- .../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 | 5 +- .../provider/BodyProviderParamParser.java | 4 +- .../provider/HeaderProviderParamParser.java | 11 +- .../provider/ParamProviderParamParser.java | 8 +- .../provider/PathProviderParamParser.java | 5 +- .../parse/provider/ProviderParamParser.java | 5 - .../parse/provider/ProviderParseContext.java | 7 - .../protocol/rest/constans/RestConstant.java | 3 - .../protocol/rest/deploy/ServiceDeployer.java | 23 +- .../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 | 84 +- .../resteasy/filter/DubboBuiltResponse.java | 1 - .../DubboContainerResponseContextImpl.java | 79 +- .../DubboPreMatchContainerRequestContext.java | 43 +- .../filter/ResteasyNettyHttpResponse.java | 15 +- ...ResteasyRequestContainerFilterAdapter.java | 25 +- ...esteasyResponseContainerFilterAdapter.java | 33 +- .../DubboServerWriterInterceptorContext.java | 39 +- .../ResteasyWriterInterceptorAdapter.java | 62 +- .../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 | 66 +- .../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 | 1 - .../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 +- .../rpc/protocol/rest/netty/NettyServer.java | 39 +- .../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 - .../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 +- .../rpc/protocol/rest/util/NumberUtils.java | 8 +- .../rpc/protocol/rest/util/ReflectUtils.java | 15 +- .../rpc/protocol/rest/DataParseUtilsTest.java | 13 +- .../dubbo/rpc/protocol/rest/DemoService.java | 9 +- .../rpc/protocol/rest/DemoServiceImpl.java | 16 +- .../protocol/rest/ExceptionMapperTest.java | 16 +- .../rest/HttpMessageCodecManagerTest.java | 20 +- .../protocol/rest/JaxrsRestProtocolTest.java | 171 +- .../rpc/protocol/rest/MediaTypeUtilTest.java | 13 +- .../protocol/rest/NettyRequestFacadeTest.java | 32 +- .../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 | 72 +- .../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/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 | 229 +- .../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 | 145 +- .../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 | 91 +- .../dubbo/rpc/protocol/tri/TripleInvoker.java | 126 +- .../rpc/protocol/tri/TriplePathResolver.java | 2 - .../protocol/tri/TriplePingPongHandler.java | 14 +- .../rpc/protocol/tri/TripleProtocol.java | 79 +- .../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 | 6 +- .../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/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 | 32 +- .../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 | 15 +- .../TripleServerConnectionHandler.java | 26 +- .../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 | 1 - .../dubbo/rpc/protocol/tri/PbUnpackTest.java | 10 +- .../tri/ReflectionPackableMethodTest.java | 52 +- .../protocol/tri/SingleProtobufUtilsTest.java | 14 +- .../tri/TripleCustomerProtocolWapperTest.java | 195 +- .../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 | 6 +- .../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 | 41 +- .../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 | 272 +- ...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 | 139 +- .../BinderDubboConfigBinder.java | 20 +- ...DubboRelaxedBinding2AutoConfiguration.java | 10 +- .../BinderDubboConfigBinderTest.java | 6 +- ...oRelaxedBinding2AutoConfigurationTest.java | 20 +- ...ropertiesEnvironmentPostProcessorTest.java | 6 +- .../actuator/pom.xml | 190 +- .../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 | 9 +- .../DubboConfigurationProperties.java | 6 +- .../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 | 11 +- ...utoConfigurationTestWithoutProperties.java | 9 +- ...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 - .../dubbo-spring-boot-compatible/pom.xml | 107 +- .../dubbo-spring-boot-starter/pom.xml | 77 +- .../dubbo-nacos-spring-boot-starter/pom.xml | 43 +- .../pom.xml | 166 +- .../pom.xml | 51 +- .../observability/autoconfigure/pom.xml | 250 +- ...bboMicrometerTracingAutoConfiguration.java | 21 +- .../DubboObservationAutoConfiguration.java | 68 +- .../autoconfigure/ObservabilityUtils.java | 15 +- .../ObservationHandlerGrouping.java | 13 +- .../ObservationRegistryPostProcessor.java | 15 +- .../ConditionalOnDubboTracingEnable.java | 7 +- .../brave/BraveAutoConfiguration.java | 140 +- .../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 | 163 +- ...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 | 38 +- dubbo-spring-boot/pom.xml | 308 +- dubbo-test/dubbo-dependencies-all/pom.xml | 927 +- dubbo-test/dubbo-test-check/pom.xml | 158 +- ...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 | 117 +- .../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 | 95 +- .../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 | 473 +- dubbo-test/dubbo-test-spring/pom.xml | 366 +- .../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 | 180 +- dubbo-test/dubbo-test-spring4.1/pom.xml | 177 +- dubbo-test/dubbo-test-spring4.2/pom.xml | 177 +- dubbo-test/pom.xml | 53 +- dubbo-xds/pom.xml | 210 +- .../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 | 82 +- .../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 | 188 +- .../router/xds/rule/HeaderMatcherTest.java | 3 - .../router/xds/rule/PathMatcherTest.java | 3 - pom.xml | 1721 ++-- 3271 files changed, 54105 insertions(+), 49701 deletions(-) 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/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-build-tools/pom.xml b/dubbo-build-tools/pom.xml index 07185557b6c..a3826c7aba9 100644 --- a/dubbo-build-tools/pom.xml +++ b/dubbo-build-tools/pom.xml @@ -13,76 +13,77 @@ See the License for the specific language governing permissions and limitations under the License. --> - - 4.0.0 + + 4.0.0 - org.apache.dubbo - dubbo-build-tools - 1.0.0 - jar + org.apache.dubbo + dubbo-build-tools + 1.0.0 + jar - - true - 2.40.0 - check - 1.0.0 - + + true + 2.40.0 + check + 1.0.0 + 2.38.0 + - - - 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-cluster/pom.xml b/dubbo-cluster/pom.xml index 7e2d58a95ae..91a7b40f69e 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 - - + + 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 + + - - - - 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 e45c6e8cd48..c72655478ff 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 909693cb90d..0ddc3628afd 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 @@ static Cluster getCluster(ScopeModel scopeModel, String name, boolean wrap) { 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/Configurator.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Configurator.java index 1f1df9c2009..f99b05ac87a 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 @@ static Optional> toConfigurators(List urls) { 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 @@ static Optional> toConfigurators(List urls) { 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 031f597dc04..920d936cb6e 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 ab8c50b568c..0e59f2cacf4 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 94b28a8bc3f..42a556d2c64 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 64bccf8cbdd..b505772cccb 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 @@ 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 f38424e4df1..4421755bbcf 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 23c4fefca7d..678888b4ec2 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 @@ default List> route(List> invokers, URL url, Invocatio * @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 @@ default RouterResult> route(List> invokers, URL url, I * @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 @@ default void notify(List> invokers) { 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 e0d15af1fe4..895aa582ba3 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.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()); - - List> stateRouters = moduleModel - .getExtensionLoader(StateRouterFactory.class) - .getActivateExtension(url, ROUTER_KEY) - .stream() - .map(factory -> factory.getRouter(interfaceClass, url)) - .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()); - 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 SingleRouterChain getSingleChain(URL url, BitList> availabl // 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 synchronized void setInvokers(BitList> invokers, Runnable swit } // 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 synchronized void setInvokers(BitList> invokers, Runnable swit } // 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 synchronized void setInvokers(BitList> invokers, Runnable swit } // 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 f2cecdc4d7f..211e03a56a2 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 @@ 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 278722eded4..c217bdb0d69 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.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 StateRouter getHeadStateRouter() { 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 @@ private void printRouterSnapshot(URL url, BitList> availableInvokers, /** * 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 RouterSnapshotNode buildRouterSnapshot(URL url, BitList> av // 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 RouterSnapshotNode buildRouterSnapshot(URL url, BitList> av } 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 void destroy() { 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 void destroy() { 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 1a6b1381b94..a72956054a9 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 URL getUrl() { @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 URL configure(URL url) { @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 @@ private URL configureIfMatch(String host, URL url) { 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 @@ private URL configureIfMatch(String host, URL url) { } } } 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 @@ private boolean isV27ConditionMatchOrUnset(URL url) { 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 @@ private boolean isV27ConditionMatchOrUnset(URL url) { 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 @@ private boolean isDeprecatedConditionMatch(Set conditionKeys, URL url) { 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 @@ private boolean startWithTilde(String key) { } 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 bd8a325463d..182f9107cba 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 AbsentConfigurator(URL url) { 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 479eb5082a0..737d67ca12a 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 a61190d7cd0..72895aeb8af 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 URL doConfigure(URL currentUrl, URL configUrl) { 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 504ae3b5d7b..972eac4ceae 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 7a12e0f3792..203033c7343 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.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 @@ private static List serviceItemToUrls(ConfigItem item, ConfiguratorConfig c 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 @@ private static String toParameterString(ConfigItem item) { } 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 4a828d4484f..853a6ae8df3 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 boolean isMatch(String host, URL url) { @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 249baeb556a..78547fd7d86 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 static ConfigItem parseFromMap(Map map) { 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 static ConfigItem parseFromMap(Map map) { 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 4a9c8e13a19..2b51957c04c 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 static ConfiguratorConfig parseFromMap(Map map) { 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 42303e6a494..ad6dae436f7 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 boolean isMatch(URL url) { @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 dab89c08486..087eacbadea 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 AbstractDirectory(URL url, RouterChain routerChain, boolean isUrlFromR // 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 AbstractDirectory(URL url, RouterChain routerChain, boolean isUrlFromR 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 List> list(Invocation invocation) throws RpcException { 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 void addInvalidateInvoker(Invoker invoker) { // 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<>(); + + // 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); + } + } } - } - } - // 2. try to check the invoker's status - for (Invoker invoker : invokersToTry) { - if (invokers.contains(invoker)) { - if (invoker.isAvailable()) { - needDeleteList.add(invoker); + // 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); + } } - } 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."); + // 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(); } - 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); + // 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 void refreshInvoker() { 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 void addDisabledInvoker(Invoker invoker) { 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 void recoverDisabledInvoker(Invoker invoker) { } } - 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 @@ protected void setInvokers(BitList> invokers) { 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 @@ private boolean addValidInvoker(Invoker invoker) { 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 @@ private boolean removeValidInvoker(Invoker invoker) { 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 @@ protected String joinValidInvokerAddresses() { 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 @@ private Map groupByServiceKey(Collection> invokers) @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 6fae2eeb8ff..14a4a5747f9 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 StaticDirectory(URL url, List> invokers) { } 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 void destroy() { 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/ClusterFilter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/ClusterFilter.java index 6497d3b687a..56e59d6a33a 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/ClusterFilter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/ClusterFilter.java @@ -21,5 +21,4 @@ import org.apache.dubbo.rpc.BaseFilter; @SPI(scope = ExtensionScope.MODULE) -public interface ClusterFilter extends BaseFilter { -} +public interface ClusterFilter extends BaseFilter {} 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 22a22cd9827..4be2ba9ba1e 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 Invoker buildInvokerChain(final Invoker originalInvoker, String 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 Invoker buildInvokerChain(final Invoker originalInvoker, String 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 Invoker buildInvokerChain(final Invoker originalInvoker, String * 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 @@ private List getModuleModelsFromUrl(URL url) { } 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 815f8821dd2..92ab4a58485 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 boolean isAvailable() { 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 String toString() { * @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 boolean isDestroyed() { } 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 Result invoke(Invocation invocation) throws RpcException { } } } 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 void destroy() { } } - 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 boolean isDestroyed() { } } - - @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 boolean isAvailable() { 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 String toString() { } } - @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 efbc4540cc6..1a8c144c799 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 Exporter export(Invoker invoker) throws RpcException { } 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 void destroy() { public List getServers() { return protocol.getServers(); } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ConsumerClassLoaderFilter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ConsumerClassLoaderFilter.java index c16b5f3e98d..8447906d4c5 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ConsumerClassLoaderFilter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ConsumerClassLoaderFilter.java @@ -35,8 +35,8 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept 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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ConsumerContextFilter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ConsumerContextFilter.java index a5a6dcf5344..674e4a61e40 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ConsumerContextFilter.java +++ b/dubbo-cluster/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 Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept 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 Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept 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 @@ private void removeContext(Invocation invocation) { 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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsClusterFilter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsClusterFilter.java index 9a53935032a..35f9942fe4c 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsClusterFilter.java +++ b/dubbo-cluster/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 @@ private void handleMethodException(Throwable t, Invocation invocation) { 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-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 10136c17d86..7e3619094b4 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 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/filter/support/ObservationSenderFilter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ObservationSenderFilter.java index 233a5ed35b5..71931c91641 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ObservationSenderFilter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ObservationSenderFilter.java @@ -50,7 +50,8 @@ public ObservationSenderFilter(ApplicationModel applicationModel) { applicationModel.getApplicationConfigManager().getTracing().ifPresent(cfg -> { if (Boolean.TRUE.equals(cfg.getEnabled())) { observationRegistry = applicationModel.getBeanFactory().getBean(ObservationRegistry.class); - clientObservationConvention = applicationModel.getBeanFactory().getBean(DubboClientObservationConvention.class); + clientObservationConvention = + applicationModel.getBeanFactory().getBean(DubboClientObservationConvention.class); } }); } @@ -64,7 +65,8 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept 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-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 1d8d7183c30..57913b0a523 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 String getRule(String key, String group, long timeout) throws IllegalStat 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 7c51a04c24b..3bd0dd1c99a 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 @@ default void addListener(String key, ConfigurationListener listener) { 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 59ecd9a3053..c4eec1e0054 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 Invoker select(List> invokers, URL url, Invocation invo 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 @@ protected int getWeight(Invoker invoker, Invocation invocation) { } 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/AdaptiveLoadBalance.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/AdaptiveLoadBalance.java index 7f99e371af9..501d2b10aa8 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/AdaptiveLoadBalance.java +++ b/dubbo-cluster/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 @@ private Invoker selectByP2C(List> invokers, Invocation invocat 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 @@ private String buildServiceKey(Invoker invoker,Invocation invocation){ 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 @@ private Invoker chooseLowLoadInvoker(Invoker invoker1,Invoker invok } return load1 > load2 ? invoker2 : invoker1; } - } 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 37386ab1862..7fdfd8f79b0 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 @@ private Invoker selectForKey(long hash) { 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 9eb41f6fe9a..76f82ebb7df 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 @@ protected Invoker doSelect(List> invokers, URL url, Invocation // 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 1b0b9fce7e5..c264aa63a82 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 @@ protected Invoker doSelect(List> invokers, URL url, Invocation } } 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 @@ protected Invoker doSelect(List> invokers, URL url, Invocation 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 0ee6a82c5df..f60c0f61b9e 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 @@ protected Collection getInvokerAddrList(List> invokers, I @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 @@ protected Invoker doSelect(List> invokers, URL url, Invocation }); if (weight != weightedRoundRobin.getWeight()) { - //weight changed + // weight changed weightedRoundRobin.setWeight(weight); } long cur = weightedRoundRobin.increaseCurrent(); @@ -129,5 +131,4 @@ protected Invoker doSelect(List> invokers, URL url, Invocation // 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 1244e761478..09837a31977 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 @@ protected Invoker doSelect(List> invokers, URL url, Invocation 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 @@ protected Invoker doSelect(List> invokers, URL url, Invocation } 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/merger/BooleanArrayMerger.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/BooleanArrayMerger.java index 9ff15becb7b..cc08d3fb2ec 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/BooleanArrayMerger.java +++ b/dubbo-cluster/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 boolean[] merge(boolean[]... items) { } return result; } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/ByteArrayMerger.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/ByteArrayMerger.java index ae7685fd483..60d417b9af0 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/ByteArrayMerger.java +++ b/dubbo-cluster/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 byte[] merge(byte[]... items) { } return result; } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/CharArrayMerger.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/CharArrayMerger.java index ad03f1136f7..e4e03f121f8 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/CharArrayMerger.java +++ b/dubbo-cluster/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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/DoubleArrayMerger.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/DoubleArrayMerger.java index 9dbe83a0355..83f20559e07 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/DoubleArrayMerger.java +++ b/dubbo-cluster/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 double[] merge(double[]... items) { 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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/FloatArrayMerger.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/FloatArrayMerger.java index cf6d6351518..1c49117e82d 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/FloatArrayMerger.java +++ b/dubbo-cluster/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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/IntArrayMerger.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/IntArrayMerger.java index da676dec05a..cc8603d2f1f 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/IntArrayMerger.java +++ b/dubbo-cluster/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 int[] merge(int[]... items) { 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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/ListMerger.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/ListMerger.java index d01f1f3dc1e..2364ae325d1 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/ListMerger.java +++ b/dubbo-cluster/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 List merge(List... items) { 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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/LongArrayMerger.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/LongArrayMerger.java index 4583e06a353..99e5b28ab5c 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/LongArrayMerger.java +++ b/dubbo-cluster/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 long[] merge(long[]... items) { 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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/MapMerger.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/MapMerger.java index 484c4c24234..eaa863ed640 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/MapMerger.java +++ b/dubbo-cluster/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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/MergerFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/MergerFactory.java index 038e38f2b08..3aa07f2ad3b 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/MergerFactory.java +++ b/dubbo-cluster/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 Merger getMerger(Class returnType) { } 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 @@ private Class getActualTypeArgument(Class mergerCls) { 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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/ShortArrayMerger.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/ShortArrayMerger.java index ebf9157d5e6..36792d7c524 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/ShortArrayMerger.java +++ b/dubbo-cluster/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-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 d6778434394..b38581264e5 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 void setPriority(int priority) { 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 93f47f800dc..62b48dee090 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 @@ 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 b0a09759b68..faa57f0a40c 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 String toString() { 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("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("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(","))); } 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 139a0bcee28..39bda00c273 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/condition/ConditionStateRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouter.java index ddbb1966e6a..b89395ca69c 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouter.java @@ -84,7 +84,8 @@ public ConditionStateRouter(URL url, String rule, boolean force, boolean enabled 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 ConditionStateRouter(URL url) { 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 void init(String rule) { 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 void init(String rule) { } } - 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 @@ else if ("&".equals(separator)) { // 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 @@ else if ("=".equals(separator)) { // 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 @@ else if ("!=".equals(separator)) { // 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 @@ protected BitList> doRoute(BitList> invokers, URL url, Inv 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 @@ protected BitList> doRoute(BitList> invokers, URL url, Inv } 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 @@ protected BitList> doRoute(BitList> invokers, URL url, Inv @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 @@ private ConditionMatcher getMatcher(String key) { 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 @@ private boolean matchThen(URL url, URL param) { 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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ListenableStateRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ListenableStateRouter.java index 0efbe0be399..575bd462822 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ListenableStateRouter.java +++ b/dubbo-cluster/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 ListenableStateRouter(URL url, String ruleKey) { @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 synchronized void process(ConfigChangedEvent event) { 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 @@ private boolean isRuleRuntime() { 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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ProviderAppStateRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ProviderAppStateRouter.java index b39b3167666..09bf667895e 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ProviderAppStateRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ProviderAppStateRouter.java @@ -33,7 +33,8 @@ * 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 void notify(BitList> invokers) { // 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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceStateRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceStateRouterFactory.java index d5f3d6ca244..ecc536953b3 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceStateRouterFactory.java +++ b/dubbo-cluster/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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRouterRule.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRouterRule.java index 0cfb8bdf4bd..7d9c936c3f8 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRouterRule.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRouterRule.java @@ -34,15 +34,14 @@ public static ConditionRouterRule parseFromMap(Map map) { 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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRuleParser.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRuleParser.java index 699a18b90a8..9aa80f908bb 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRuleParser.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRuleParser.java @@ -18,12 +18,12 @@ 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 static ConditionRouterRule parse(String rawRule) { return rule; } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/AbstractConditionMatcher.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/AbstractConditionMatcher.java index db5cd94b95e..992b42d0873 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/AbstractConditionMatcher.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/AbstractConditionMatcher.java @@ -38,7 +38,8 @@ * 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 AbstractConditionMatcher(String key, ModuleModel model) { 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 static String getSampleValueFromUrl(String conditionKey, 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 boolean isMatch(Map sample, URL param, Invocation invocat } 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 Set getMismatches() { } // 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."); - - ValuePattern paramValueMatcher = model.getExtensionLoader(ValuePattern.class).getExtension("wildcard"); + 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"); return paramValueMatcher.match(pattern, value, url, invocation, isWhenCondition); } @@ -135,5 +145,4 @@ protected boolean doPatternMatch(String pattern, String value, URL url, Invocati * 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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/argument/ArgumentConditionMatcher.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/argument/ArgumentConditionMatcher.java index d66bff1f386..6fcf78246b1 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/argument/ArgumentConditionMatcher.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/argument/ArgumentConditionMatcher.java @@ -38,7 +38,8 @@ */ @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 String getValue(Map sample, URL url, Invocation invocatio 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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/attachment/AttachmentConditionMatcher.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/attachment/AttachmentConditionMatcher.java index c7dc1481005..60fd727e4f2 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/attachment/AttachmentConditionMatcher.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/attachment/AttachmentConditionMatcher.java @@ -38,7 +38,8 @@ */ @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 @@ protected String getValue(Map sample, URL url, Invocation invoca 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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/param/UrlParamConditionMatcher.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/param/UrlParamConditionMatcher.java index b1a8d5ba58b..23ae175381a 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/param/UrlParamConditionMatcher.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/param/UrlParamConditionMatcher.java @@ -37,5 +37,4 @@ public UrlParamConditionMatcher(String key, ModuleModel model) { protected String getValue(Map sample, URL url, Invocation invocation) { return getSampleValueFromUrl(key, sample, url, invocation); } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/pattern/range/RangeValuePattern.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/pattern/range/RangeValuePattern.java index f876b3b3778..5ed7e449035 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/pattern/range/RangeValuePattern.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/pattern/range/RangeValuePattern.java @@ -46,7 +46,11 @@ public boolean match(String pattern, String value, URL url, Invocation invocatio 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 boolean match(String pattern, String value, URL url, Invocation invocatio } } } 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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileStateRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileStateRouterFactory.java index 5e037a9a6f7..cab3968aa16 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileStateRouterFactory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileStateRouterFactory.java @@ -46,7 +46,9 @@ public StateRouter getRouter(Class interfaceClass, URL url) { 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 StateRouter getRouter(Class interfaceClass, URL url) { throw new IllegalStateException(e.getMessage(), e); } } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshAppRuleListener.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshAppRuleListener.java index f49f8e9b166..ef70b7806fa 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshAppRuleListener.java +++ b/dubbo-cluster/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; @@ -26,24 +25,23 @@ 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; 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); @@ -62,8 +60,7 @@ public MeshAppRuleListener(String appName) { @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<>(); @@ -79,19 +76,34 @@ public void receiveConfigInfo(String configInfo) { 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); @@ -123,7 +135,6 @@ public void register(MeshRuleListener subscriber) { meshRuleDispatcher.register(subscriber); } - public void unregister(MeshRuleListener subscriber) { meshRuleDispatcher.unregister(subscriber); } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshEnvListener.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshEnvListener.java index 6d9853436ed..4c70ec26759 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshEnvListener.java +++ b/dubbo-cluster/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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleCache.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleCache.java index 097162e9278..098b9bd4cf0 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleCache.java +++ b/dubbo-cluster/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 boolean containsRule() { 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 static MeshRuleCache build(String protocolServiceKey, BitList>> 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 static MeshRuleCache build(String protocolServiceKey, BitList 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 static MeshRuleCache build(String protocolServiceKey, BitList(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 boolean equals(Object o) { 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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleManager.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleManager.java index ac494757fba..99a6656cb8d 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleManager.java +++ b/dubbo-cluster/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 @@ private synchronized MeshAppRuleListener subscribeAppRule(String app) { 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 @@ private synchronized void unsubscribeAppRule(String app, MeshAppRuleListener mes envListener.onUnSubscribe(app); } } - } public synchronized void register(String app, MeshRuleListener subscriber) { diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleRouter.java index 0d3d8b56dde..06d43e94325 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleRouter.java @@ -74,13 +74,20 @@ public MeshRuleRouter(URL url) { 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 @@ protected BitList> doRoute(BitList> invokers, URL url, Inv // 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 @@ protected BitList> doRoute(BitList> invokers, URL url, Inv 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 @@ protected BitList> doRoute(BitList> invokers, URL url, Inv /** * 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 @@ protected List getDubboRouteDestination(DubboRoute dubboR 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 @@ protected List getDubboRouteDestination(DubboRoute dubboR /** * 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 @@ protected String randomSelectDestination(MeshRuleCache meshRuleCache, String 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 @@ protected String randomSelectDestination(MeshRuleCache meshRuleCache, String /** * 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 synchronized void onRuleChange(String appName, List> 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 synchronized void clearRule(String appName) { } 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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/StandardMeshRuleRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/StandardMeshRuleRouterFactory.java index 343f12c3862..6c407bbb090 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/StandardMeshRuleRouterFactory.java +++ b/dubbo-cluster/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.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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/BaseRule.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/BaseRule.java index 0c0b64efadd..232467384b3 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/BaseRule.java +++ b/dubbo-cluster/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 void setMetadata(Map metadata) { @Override public String toString() { - return "BaseRule{" + - "apiVersion='" + apiVersion + '\'' + - ", kind='" + kind + '\'' + - ", metadata=" + metadata + - '}'; + return "BaseRule{" + "apiVersion='" + + apiVersion + '\'' + ", kind='" + + kind + '\'' + ", metadata=" + + metadata + '}'; } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/VsDestinationGroup.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/VsDestinationGroup.java index 6b150d4d09e..3bb18c5437f 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/VsDestinationGroup.java +++ b/dubbo-cluster/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 java.util.LinkedList; import java.util.List; - public class VsDestinationGroup { private String appName; private List virtualServiceRuleList = new LinkedList<>(); diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/ConnectionPoolSettings.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/ConnectionPoolSettings.java index 32b7af9cd85..8fadc9bcde3 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/ConnectionPoolSettings.java +++ b/dubbo-cluster/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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/DestinationRule.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/DestinationRule.java index 42bc0494556..b78caae7663 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/DestinationRule.java +++ b/dubbo-cluster/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 void setSpec(DestinationRuleSpec spec) { @Override public String toString() { - return "DestinationRule{" + - "base=" + super.toString() + - ", spec=" + spec + - '}'; + return "DestinationRule{" + "base=" + super.toString() + ", spec=" + spec + '}'; } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/DestinationRuleSpec.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/DestinationRuleSpec.java index 57d8b063e6d..ee9efd9121f 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/DestinationRuleSpec.java +++ b/dubbo-cluster/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 void setTrafficPolicy(TrafficPolicy trafficPolicy) { @Override public String toString() { - return "DestinationRuleSpec{" + - "host='" + host + '\'' + - ", subsets=" + subsets + - ", trafficPolicy=" + trafficPolicy + - '}'; + return "DestinationRuleSpec{" + "host='" + + host + '\'' + ", subsets=" + + subsets + ", trafficPolicy=" + + trafficPolicy + '}'; } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/Subset.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/Subset.java index 9438ec4dd85..dd0a995450d 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/Subset.java +++ b/dubbo-cluster/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 void setLabels(Map labels) { @Override public String toString() { - return "Subset{" + - "name='" + name + '\'' + - ", labels=" + labels + - '}'; + return "Subset{" + "name='" + name + '\'' + ", labels=" + labels + '}'; } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TCPSettings.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TCPSettings.java index 09dc93a8f06..9e1e12a7378 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TCPSettings.java +++ b/dubbo-cluster/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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TcpKeepalive.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TcpKeepalive.java index 3bc43c7342a..5887f1c7268 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TcpKeepalive.java +++ b/dubbo-cluster/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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TrafficPolicy.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TrafficPolicy.java index 7f771f0d763..402ff63a51a 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TrafficPolicy.java +++ b/dubbo-cluster/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 void setLoadBalancer(LoadBalancerSettings loadBalancer) { @Override public String toString() { - return "TrafficPolicy{" + - "loadBalancer=" + loadBalancer + - '}'; + return "TrafficPolicy{" + "loadBalancer=" + loadBalancer + '}'; } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/ConsistentHashLB.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/ConsistentHashLB.java index 213dfee9e1b..95ad44e91e4 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/ConsistentHashLB.java +++ b/dubbo-cluster/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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/LoadBalancerSettings.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/LoadBalancerSettings.java index 1f8b60ed4eb..1be425328a1 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/LoadBalancerSettings.java +++ b/dubbo-cluster/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 void setConsistentHash(ConsistentHashLB consistentHash) { @Override public String toString() { - return "LoadBalancerSettings{" + - "simple=" + simple + - ", consistentHash=" + consistentHash + - '}'; + return "LoadBalancerSettings{" + "simple=" + simple + ", consistentHash=" + consistentHash + '}'; } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/SimpleLB.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/SimpleLB.java index 003f1f6a903..80394084115 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/SimpleLB.java +++ b/dubbo-cluster/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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboMatchRequest.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboMatchRequest.java index 8255a228edd..11ab9beb773 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboMatchRequest.java +++ b/dubbo-cluster/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 java.util.Map; import java.util.Set; - public class DubboMatchRequest { private String name; private DubboMethodMatch method; @@ -76,16 +74,16 @@ public void setHeaders(Map headers) { @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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboRoute.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboRoute.java index d6bf12443c3..530abcb0066 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboRoute.java +++ b/dubbo-cluster/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 void setRoutedetail(List routedetail) { @Override public String toString() { - return "DubboRoute{" + - "name='" + name + '\'' + - ", services=" + services + - ", routedetail=" + routedetail + - '}'; + return "DubboRoute{" + "name='" + name + '\'' + ", services=" + services + ", routedetail=" + routedetail + '}'; } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboRouteDetail.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboRouteDetail.java index ce425914129..cad8c0f700a 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboRouteDetail.java +++ b/dubbo-cluster/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 void setRoute(List route) { @Override public String toString() { - return "DubboRouteDetail{" + - "name='" + name + '\'' + - ", match=" + match + - ", route=" + route + - '}'; + return "DubboRouteDetail{" + "name='" + name + '\'' + ", match=" + match + ", route=" + route + '}'; } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/VirtualServiceRule.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/VirtualServiceRule.java index 8f5497a0995..76c6204b0b7 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/VirtualServiceRule.java +++ b/dubbo-cluster/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 void setSpec(VirtualServiceSpec spec) { @Override public String toString() { - return "VirtualServiceRule{" + - "base=" + super.toString() + - ", spec=" + spec + - '}'; + return "VirtualServiceRule{" + "base=" + super.toString() + ", spec=" + spec + '}'; } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/VirtualServiceSpec.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/VirtualServiceSpec.java index 648fe3be405..69f13e96142 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/VirtualServiceSpec.java +++ b/dubbo-cluster/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 void setDubbo(List dubbo) { @Override public String toString() { - return "VirtualServiceSpec{" + - "hosts=" + hosts + - ", dubbo=" + dubbo + - '}'; + return "VirtualServiceSpec{" + "hosts=" + hosts + ", dubbo=" + dubbo + '}'; } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/destination/DubboDestination.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/destination/DubboDestination.java index c21a008790b..a3945e0f36e 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/destination/DubboDestination.java +++ b/dubbo-cluster/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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/destination/DubboRouteDestination.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/destination/DubboRouteDestination.java index b9588c40cfd..3f0179a1097 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/destination/DubboRouteDestination.java +++ b/dubbo-cluster/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-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 b8fdc3b5782..834a5194967 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 boolean isMatch(String input) { 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 c9a6fab9e53..b185cf488e7 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 void setExact(Boolean exact) { 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 55db3e232ce..b3fd223b89b 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 void setMod(Double mod) { 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 ad4ea5633c0..6deccf479ae 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 void setEnd(Double end) { 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/DubboAttachmentMatch.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboAttachmentMatch.java index a6cb45d2748..083df7cb5cc 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboAttachmentMatch.java +++ b/dubbo-cluster/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 java.util.Map; import java.util.Set; - public class DubboAttachmentMatch { private Map tracingContext; private Map dubboContext; @@ -49,7 +47,7 @@ public boolean isMatch(Invocation invocation, Set contex 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-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 d02cd0793b6..3095e509dff 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 boolean isMatch(Object input) { @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 f2524104783..e724e9f10c5 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 java.util.List; import java.util.Map; - public class DubboMethodMatch { private StringMatch name_match; private Integer argc; @@ -73,13 +71,12 @@ public void setHeaders(Map headers) { @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 boolean isMatch(Invocation invocation) { 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 boolean isMatch(Invocation invocation) { 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 boolean isMatch(Invocation invocation) { 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 570a5e8551e..940d9a8b1ff 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 boolean isMatch(boolean input) { 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 0a19334eccb..d1599521d98 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 0fce7275033..4c555780e6c 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 void setOneof(List oneof) { 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 dda2de7df35..3a2a85b5fda 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 boolean isMatch(String input) { @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/mesh/util/MeshRuleDispatcher.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleDispatcher.java index 713c44bd1b8..9592b776c7d 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleDispatcher.java +++ b/dubbo-cluster/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 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 synchronized void post(Map>> ruleMap) { 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 synchronized void register(MeshRuleListener listener) { return; } ConcurrentHashMapUtils.computeIfAbsent(listenerMap, listener.ruleSuffix(), (k) -> new ConcurrentHashSet<>()) - .add(listener); + .add(listener); } public synchronized void unregister(MeshRuleListener listener) { diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleListener.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleListener.java index ce4fa56b52e..17f102babf4 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleListener.java +++ b/dubbo-cluster/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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelector.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelector.java index 1ea813c5989..c8526eb0fff 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelector.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelector.java @@ -49,9 +49,14 @@ public MockInvokersSelector(URL url) { } @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 @@ protected String doBuildSnapshot() { 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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockStateRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockStateRouterFactory.java index 4297ac95224..9bff80a573a 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockStateRouterFactory.java +++ b/dubbo-cluster/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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouter.java index d0f918094a4..19baa1ab46c 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouter.java @@ -37,6 +37,7 @@ 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 ScriptStateRouter(URL url) { 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 @@ private ScriptEngine getEngine(URL url) { } @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 @@ protected BitList> doRoute(BitList> invokers, URL url, Inv 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 @@ protected BitList> getRoutedInvokers(BitList> invokers, Ob 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 boolean isRuntime() { public boolean isForce() { return this.getUrl().getParameter(FORCE_KEY, false); } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouterFactory.java index 43bcd3067f1..1849dcb4c88 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouterFactory.java +++ b/dubbo-cluster/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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/config/AppScriptStateRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/config/AppScriptStateRouter.java index 8b158e31fdf..e872a7ea3f3 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/config/AppScriptStateRouter.java +++ b/dubbo-cluster/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.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 AppScriptStateRouter(URL url) { } @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 @@ protected BitList> doRoute(BitList> invokers, @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 synchronized void process(ConfigChangedEvent event) { 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 void notify(BitList> invokers) { 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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/config/model/ScriptRule.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/config/model/ScriptRule.java index 1ee885e456e..b181d140b44 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/config/model/ScriptRule.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/config/model/ScriptRule.java @@ -18,12 +18,12 @@ 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-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 2b25ed55648..f3f1bd208ac 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 void notify(BitList> invokers) { } @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 final BitList> route(BitList> invokers, URL url, In * @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 final void setNextRouter(StateRouter nextRouter) { @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 b3fda639480..2c04539b071 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 @@ 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 BitList subList(int fromIndex, int toIndex) { 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 BitList subList(int fromIndex, int toIndex) { 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 ArrayList cloneToArrayList() { @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 91d28bbbbcc..3447fc79f7a 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 fed028b7e2e..8eabe701608 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 Map>> getGrouping() { @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 94d82fd4054..ccfa60c5de6 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 @@ BitList> route(BitList> invokers, URL url, Invocation invo 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 8a0780c763d..e5b4a999eeb 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 static TailStateRouter getInstance() { 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 URL getUrl() { } @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 boolean isForce() { } @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/router/tag/TagStateRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouter.java index c3470776b25..630e9550758 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouter.java @@ -64,8 +64,8 @@ public TagStateRouter(URL url) { @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 { @@ -77,13 +77,25 @@ public synchronized void process(ConfigChangedEvent event) { 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."); @@ -101,8 +113,9 @@ public BitList> doRoute(BitList> invokers, URL url, Invoca } 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)) { @@ -113,33 +126,35 @@ public BitList> doRoute(BitList> invokers, URL url, Invoca // 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); @@ -184,16 +199,21 @@ public BitList> doRoute(BitList> invokers, URL url, Invoca 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; } @@ -210,7 +230,8 @@ public boolean isForce() { } 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) { @@ -242,7 +263,12 @@ private boolean checkAddressMatch(Set addresses, String host, int port) 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; @@ -264,8 +290,12 @@ public void notify(BitList> invokers) { 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; } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/Tag.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/Tag.java index 13c94d7911b..3af1dea3fb1 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/Tag.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/Tag.java @@ -41,22 +41,35 @@ public static Tag parseFromMap(Map map, String version) { 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 List getMatch() { public void setMatch(List match) { this.match = match; } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/TagRouterRule.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/TagRouterRule.java index f938a7e8008..5060d3c6bba 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/TagRouterRule.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/TagRouterRule.java @@ -60,8 +60,10 @@ public static TagRouterRule parseFromMap(Map map) { 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 void init(TagStateRouter router) { 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 Map> getAddressToTagnames() { return addressToTagnames; } - public Map> getTagnameToAddresses() { return tagnameToAddresses; } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/TagRuleParser.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/TagRuleParser.java index 5c9712acc80..3c78112bcb3 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/TagRuleParser.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/TagRuleParser.java @@ -18,12 +18,12 @@ 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-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 745e602f1f1..4411eae7a95 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 @@ */ 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 AbstractClusterInvoker(Directory directory, URL url) { } 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 boolean isDestroyed() { * @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 @@ protected Invoker select(LoadBalance loadbalance, Invocation invocation, 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 @@ private Invoker doSelect(LoadBalance loadbalance, Invocation invocation, } 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 @@ private Invoker doSelect(LoadBalance loadbalance, Invocation invocation, 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 @@ private Invoker doSelect(LoadBalance loadbalance, Invocation invocation, * @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 @@ private Invoker reselect(LoadBalance loadbalance, Invocation invocation, // 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 @@ private Invoker reselect(LoadBalance loadbalance, Invocation invocation, 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 Result invoke(final Invocation invocation) throws RpcException { 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 Result invoke(final Invocation invocation) throws RpcException { 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 Result invoke(final Invocation invocation) throws RpcException { 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 String toString() { 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 @@ protected Result invokeWithContext(Invoker invoker, Invocation invocation) { 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 @@ protected Result invokeWithContextAsync(Invoker invoker, Invocation invocatio 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 @@ protected List> list(Invocation invocation) throws RpcException { 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 @@ private Invoker setContext(Invoker invoker, URL consumerUrl) { 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 cf71aa2370f..184332680d6 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 AvailableClusterInvoker(Directory directory) { } @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 Result doInvoke(Invocation invocation, List> invokers, LoadBal } 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 c9798de61a2..9c4137dadbe 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 bdf8f6f02eb..83141fefb90 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 @@ */ 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 BroadcastClusterInvoker(Directory directory) { @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 Result doInvoke(final Invocation invocation, List> invokers, L 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 Result doInvoke(final Invocation invocation, List> invokers, L } } 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 Result doInvoke(final Invocation invocation, List> invokers, L 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 eca39939648..591f16a3773 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 static org.apache.dubbo.common.constants.CommonConstants.URL_MERGE_PROCESSOR_KEY; - /** * ClusterUtils */ @@ -45,9 +44,13 @@ public URL mergeUrl(URL remoteUrl, Map localMap) { 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 Map mergeLocalParams(Map localMap) { 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 0916f724bc0..7bfaadef9d4 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 @@ */ 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 1a208397680..5dbc97d1052 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 @@ */ 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 FailbackClusterInvoker(Directory directory) { 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 @@ protected Result doInvoke(Invocation invocation, List> invokers, Load // 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 @@ private class RetryTimerTask implements TimerTask { */ 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 @@ private class RetryTimerTask implements TimerTask { @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 2a04a1535b9..0c9fe5a1d27 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 @@ */ 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 87b3b45c5a0..f8f7e04dbc0 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 FailfastClusterInvoker(Directory directory) { } @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 Result doInvoke(Invocation invocation, List> invokers, LoadBal 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 e9e6101b054..7bf6b3300f1 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 @@ */ 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 b0cdb8ff53c..a840773c51c 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 @@ */ 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 FailoverClusterInvoker(Directory directory) { @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 Result doInvoke(Invocation invocation, final List> invokers, L 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 Result doInvoke(Invocation invocation, final List> invokers, L 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 Result doInvoke(Invocation invocation, final List> invokers, L } } } - 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 @@ private int calculateInvokeTimes(String methodName) { 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 70649504891..baaa1191f36 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 @@ */ 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 78c35408951..ba255405c76 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 @@ * */ 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 83ecbb8c3b3..82f1784e76b 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 @@ */ 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 b2f0d2e095b..b9d67834f31 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 Result doInvoke(final Invocation invocation, List> invokers, L 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 Result doInvoke(final Invocation invocation, List> invokers, L 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/MergeableCluster.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableCluster.java index 720d21dfad3..9bc030729f6 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableCluster.java +++ b/dubbo-cluster/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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java index 6d61eb2194a..e7c5f9d781b 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java @@ -51,14 +51,16 @@ @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 @@ protected Result doInvoke(Invocation invocation, List> invokers, Load } 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 @@ protected Result doInvoke(Invocation invocation, List> invokers, Load 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 @@ protected Result doInvoke(Invocation invocation, List> invokers, Load try { Result r = asyncResult.get(Integer.MAX_VALUE, TimeUnit.MILLISECONDS); if (r.hasException()) { - log.error(CLUSTER_FAILED_GROUP_MERGE, "Invoke " + getGroupDescFromServiceKey(entry.getKey()) + - " failed: " + r.getException().getMessage(), "", r.getException().getMessage()); + log.error( + CLUSTER_FAILED_GROUP_MERGE, + "Invoke " + getGroupDescFromServiceKey(entry.getKey()) + " failed: " + + r.getException().getMessage(), + "", + r.getException().getMessage()); } else { resultList.add(r); } @@ -127,8 +135,8 @@ protected Result doInvoke(Invocation invocation, List> invokers, Load 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 @@ protected Result doInvoke(Invocation invocation, List> invokers, Load 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 @@ protected Result doInvoke(Invocation invocation, List> invokers, Load } } 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 @@ protected Result doInvoke(Invocation invocation, List> invokers, Load return AsyncRpcResult.newDefaultAsyncResult(result, invocation); } - @Override public Class getInterface() { return directory.getInterface(); 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 8610bc893f0..8a97a0f21fa 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.TIMESTAMP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; - public class DefaultProviderURLMergeProcessor implements ProviderURLMergeProcessor { @Override @@ -104,14 +103,18 @@ public URL mergeUrl(URL remoteUrl, Map localParametersMap) { // 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 URL mergeUrl(URL remoteUrl, Map localParametersMap) { 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 cfd36e12549..a1cbf14e60f 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 @@ 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 f6550cb8afc..c537f03381d 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 ZoneAwareClusterInvoker(Directory directory) { @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 Result doInvoke(Invocation invocation, final List> invokers, L 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 Result doInvoke(Invocation invocation, final List> invokers, L 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 2a19a54e688..98082f971ce 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 Invoker join(Directory directory, boolean buildFilterChain) thr } 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 @@ static class ClusterFilterInvoker extends AbstractClusterInvoker { 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 Directory getDirectory() { return filterInvoker.getDirectory(); } - - @Override public URL getRegistryUrl() { return filterInvoker.getRegistryUrl(); @@ -118,8 +126,9 @@ public URL getUrl() { * 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 ClusterInvoker getFilterInvoker() { 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 URL getUrl() { * 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 @@ static class InterceptorInvokerNode extends AbstractClusterInvoker { 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 String toString() { } @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/MockClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java index 348c6e032dd..f5c10fbb6b0 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java @@ -47,7 +47,8 @@ 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 getInterface() { 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 Result invoke(Invocation invocation) throws RpcException { } 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 @@ private Result doMockInvoke(Invocation invocation, RpcException e) { 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 @@ private Result doMockInvoke(Invocation invocation, RpcException e) { 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 @@ private String getMockExceptionMessage(Throwable t, Throwable mt) { */ 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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterWrapper.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterWrapper.java index 4f8be0a28a6..0836e48e258 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterWrapper.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterWrapper.java @@ -35,8 +35,7 @@ public MockClusterWrapper(Cluster 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-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 d1d47645f7b..50e172b1494 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 Result invoke(Invocation invocation) throws RpcException { // 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 void onExporterChangeExport(Exporter exporter) { 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 void onExporterChangeExport(Exporter exporter) { @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 @@ private void init() { 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 @@ private void init() { * @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 @@ private boolean isInjvmExported() { // 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 @@ private void createInjvmInvoker(Exporter exporter) { 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 @@ private void destroyInjvmInvoker() { @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 f76b8710c68..0513f358433 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 ScopeClusterWrapper(Cluster 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 bdf95198dff..7227362ccd3 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.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 @@ void test() { 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 index a905ca90bc5..926308e4d2d 100644 --- 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 @@ -16,13 +16,6 @@ */ 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; @@ -41,6 +34,13 @@ 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 java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -66,11 +66,7 @@ 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); + URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 20881, DemoService.class.getName(), parameters); RouterChain routerChain = RouterChain.buildChain(DemoService.class, url); return routerChain; @@ -118,27 +114,43 @@ void testRoute() { map5.put("serialization", "hessian2"); Invoker invoker5 = createNormalInvoker(map5); - BitList> invokers = new BitList<>(Arrays.asList(mockInvoker, invoker1, invoker2, invoker3, invoker4, invoker5)); + 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); + 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 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); + 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); + 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 @@ -149,38 +161,40 @@ void testRoute() { rpcInvocation.setObjectAttachment(TAG_KEY, "TAG_"); RpcContext.getServiceContext().setNeedPrintRouterSnapshot(true); - RouterSnapshotSwitcher routerSnapshotSwitcher = FrameworkModel.defaultModel().getBeanFactory().getBean(RouterSnapshotSwitcher.class); + 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); + 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"; + "[ 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); + 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() { @@ -200,54 +214,51 @@ private Invoker createNormalInvoker(Map parameters) 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"; + private static final 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 static final 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 d19cf3f720e..e728d4b0be8 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.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 @@ public void setUp() throws Exception { invokers.add(invoker2); clusterinvoker = new StickyClusterInvoker(dic); - } @Test @@ -101,7 +96,7 @@ void testMethodStickyForceCheck() { @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 @@ public int testSticky(String methodName, boolean check) { return count; } - static class StickyClusterInvoker extends AbstractClusterInvoker { private Invoker selectedInvoker; @@ -150,8 +144,8 @@ public StickyClusterInvoker(Directory directory, URL url) { } @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 ec862a93580..869c97e4d4a 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.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 @@ void testOverrideApplication() { @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 @@ void testOverrideHost() { @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 @@ void testAbsentForVersion27() { } { - 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 @@ void testAbsentForVersion27() { // 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 @@ void testAbsentForVersion27() { 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 193f7ac3644..0893b618bea 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 @@ * 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 ea139d0e048..f85155852d5 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.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 @@ void testOverride_Application() { @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 @@ void testOverride_Host() { 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 @@ void testOverride_Host() { @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 @@ void testOverrideForVersion27() { } { - 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 @@ void testOverrideForVersion27() { // 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 @@ void testOverrideForVersion27() { 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 @@ void testOverrideForVersion3() { // 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 @@ void testOverrideForVersion3() { 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 f5596d56b4d..f68a68efe11 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.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 @@ void parseConfiguratorsAppMultiServicesTest() throws IOException { } } - @Test void parseConfiguratorsAppAnyServicesTest() throws IOException { try (InputStream yamlStream = this.getClass().getResourceAsStream("/AppAnyServices.yml")) { @@ -182,9 +181,11 @@ void parseProviderConfigurationV3() throws IOException { 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 @@ void parseProviderConfigurationV3Compatibility() throws IOException { 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 @@ void parseProviderConfigurationV3Conflict() throws IOException { 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 @@ void parseProviderConfigurationV3Conflict() throws IOException { @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 @@ void parseURLJsonArrayCompatible() { 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/directory/MockDirInvocation.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java index aad1d49e19e..0e1a4b1b5e2 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java +++ b/dubbo-cluster/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 @@ public String getServiceName() { } 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 @@ public void setAttachment(String key, String value) { @Override public void setAttachment(String key, Object value) { - setObjectAttachment(key, value); + setObjectAttachment(key, value); } @Override @@ -141,9 +141,7 @@ public Object get(Object key) { } @Override - public void setServiceModel(ServiceModel serviceModel) { - - } + public void setServiceModel(ServiceModel serviceModel) {} @Override public ServiceModel getServiceModel() { @@ -169,9 +167,7 @@ public String getAttachment(String key, String defaultValue) { } @Override - public void addInvokedInvoker(Invoker invoker) { - - } + public void addInvokedInvoker(Invoker invoker) {} @Override public List> getInvokedInvokers() { @@ -186,5 +182,4 @@ public Object getObjectAttachment(String key, Object defaultValue) { } return result; } - } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java index 68ee46afb1f..d18bb8fe66f 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java @@ -28,12 +28,12 @@ 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 @@ private URL getRouteUrl(String rule) { @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-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/AbstractObservationFilterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/AbstractObservationFilterTest.java index 567e9cab3b7..edf059db8ce 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/AbstractObservationFilterTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/AbstractObservationFilterTest.java @@ -33,7 +33,7 @@ abstract class AbstractObservationFilterTest extends SampleTestRunner { ApplicationModel applicationModel; - RpcInvocation invocation; + RpcInvocation invocation; BaseFilter filter; @@ -80,5 +80,4 @@ private void initParam() { invocation.setMethodName(METHOD_NAME); invocation.setParameterTypes(new Class[] {String.class}); } - } 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 3a173c2ceb2..3acd3716994 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 @@ void testBuildInvokerChainForLocalReference() { 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 @@ void testBuildInvokerChainForRemoteReference() { // 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 6c8f7fff83c..3501992d6b2 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 @@ /** * 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 58f176aab8c..8ad99c24760 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 f7650da9c46..7d8b14a85cc 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 @@ /** * TestService */ - class DemoServiceLocal implements DemoService { - public DemoServiceLocal(DemoService demoService) { - } + public DemoServiceLocal(DemoService demoService) {} public String sayHello(String name) { return name; @@ -33,11 +31,7 @@ public int plus(int a, int b) { return a + b; } - public void ondisconnect() { - - } - - public void onconnect() { + public void ondisconnect() {} - } + 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 d230eaf5b85..206818a14db 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 @@ /** * 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 0007d65ad32..dc2b8725fc9 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 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 Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept } @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/filter/MetricsClusterFilterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/MetricsClusterFilterTest.java index a0c00adb2fe..be8e5176961 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/MetricsClusterFilterTest.java +++ b/dubbo-cluster/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.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.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 @@ public void setup() { 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 @@ public void teardown() { } @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 @@ private void testClusterFilterError(int errorCode,String name){ 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 @@ public Result invoke(Invocation invocation) throws RpcException { @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 @@ public boolean isAvailable() { } @Override - public void destroy() { - - } + public void destroy() {} } } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/MockInvocation.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/MockInvocation.java index 9bd89552e30..2ca6eff0ce8 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/MockInvocation.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/MockInvocation.java @@ -119,9 +119,7 @@ public Invoker getInvoker() { } @Override - public void setServiceModel(ServiceModel serviceModel) { - - } + public void setServiceModel(ServiceModel serviceModel) {} @Override public ServiceModel getServiceModel() { @@ -164,5 +162,4 @@ public Object getObjectAttachment(String key, Object defaultValue) { } return result; } - } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/ObservationSenderFilterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/ObservationSenderFilterTest.java index 13156867403..30dfb18fd98 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/ObservationSenderFilterTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/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.rpc.cluster.filter; import org.apache.dubbo.common.URL; @@ -42,20 +41,32 @@ public SampleTestRunner.SampleTestRunnerConsumer yourCode() { 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-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 d5419a0a95a..f2613818998 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.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 @@ void testGetRegistryWeight() { 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/AdaptiveLoadBalanceTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/AdaptiveLoadBalanceTest.java index 1a8e90f5ff6..0f8c80f1df4 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/AdaptiveLoadBalanceTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/AdaptiveLoadBalanceTest.java @@ -21,18 +21,18 @@ 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 @@ void testSelectByWeight() { 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 @@ void testSelectByAdaptive() { 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 @@ void testSelectByAdaptive() { 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 @@ void testSelectByAdaptive() { 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-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 4e4b1e7b636..64641a57984 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 @@ void testConsistentHashLoadBalanceInGenericCall() { 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 @@ void testConsistentHashLoadBalance() { } } - 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 @@ void testNormalWhenRouterEnabled() { 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 64ee44b863e..4326ef079bb 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 @@ 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 @@ void testLeastActiveLoadBalance_select() { 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 @@ void testSelectByWeight() { 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 564680472d8..9aa57ef6906 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.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 @@ public void setUp() throws Exception { 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 @@ public Map getGenericInvokeCounter(int runs, String loadbal } 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 @@ public String toString() { } 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 @@ public void before() throws Exception { 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 @@ protected Map getWeightedInvokeResult(int runs, String lo 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 @@ protected Map getWeightedInvokeResult(int runs, String lo } 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 f01ac1d5265..7fb7864340b 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 @@ 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 @@ void testRandomLoadBalanceSelect() { 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 @@ void testSelectByWeight() { 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 0a407847bea..f201bbf7dbf 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 @@ 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.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 @@ void testSelectByWeight() { 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 @@ void testSelectByWeight() { @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 @@ void testNodeCacheShouldNotRecycle() { // 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 @@ void testNodeCacheShouldRecycle() { { 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 @@ void testNodeCacheShouldRecycle() { } 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 @@ void testNodeCacheShouldRecycle() { // 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 bf617a69231..6275ab65d71 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.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 @@ public void testSelectByResponse() throws NoSuchFieldException, IllegalAccessExc 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 @@ public void testSelectByResponse() throws NoSuchFieldException, IllegalAccessExc } } 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/merger/DoubleSumMerger.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/DoubleSumMerger.java index 35e210668f3..f3e69adaef5 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/DoubleSumMerger.java +++ b/dubbo-cluster/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-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/FloatSumMerger.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/FloatSumMerger.java index 68313272317..0efaf99a3c0 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/FloatSumMerger.java +++ b/dubbo-cluster/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-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/IntSumMerger.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/IntSumMerger.java index e3551d26d20..703ee77507c 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/IntSumMerger.java +++ b/dubbo-cluster/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-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/LongSumMerger.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/LongSumMerger.java index 5e8e139c31b..aaca3236c7f 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/LongSumMerger.java +++ b/dubbo-cluster/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-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/ResultMergerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/ResultMergerTest.java index db0b83c1b41..8606ce322cb 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/ResultMergerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/ResultMergerTest.java @@ -19,10 +19,6 @@ import org.apache.dubbo.rpc.cluster.Merger; 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; import java.util.HashMap; @@ -35,9 +31,13 @@ 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(); @@ -242,25 +242,31 @@ void testIntArrayMerger() { */ @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); @@ -275,22 +281,28 @@ void testListMerger() { */ @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); @@ -326,28 +338,34 @@ void testLongArrayMerger() { */ @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()); @@ -386,7 +404,7 @@ void testIntSumMerger() { 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)); } @@ -395,11 +413,12 @@ void testIntSumMerger() { */ @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)); } @@ -412,7 +431,7 @@ void testFloatSumMerger() { 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)); } @@ -425,7 +444,7 @@ void testLongSumMerger() { 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)); } @@ -438,7 +457,7 @@ void testIntFindAnyMerger() { Merger merger = ApplicationModel.defaultModel().getExtension(Merger.class, "intany"); Assertions.assertNotNull(merger.merge(intArr)); - intArr = new Integer[]{}; + intArr = new Integer[] {}; Assertions.assertNull(merger.merge(intArr)); } @@ -451,7 +470,7 @@ void testIntFindFirstMerger() { 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-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/ConfigConditionRouterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/ConfigConditionRouterTest.java index 8cc7f5b1d15..5290fc65a10 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/ConfigConditionRouterTest.java +++ b/dubbo-cluster/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 @@ void normalConditionRuleApplicationLevelTest() { @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 @@ void normalConditionRuleApplicationServiceLevelTest() { @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 @@ void normalConditionRuleServiceLevelTest() { @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-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 11a87dcf09c..7de17830285 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 Result invoke(Invocation invocation) throws RpcException { } @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 4dd245f1f34..2c6d1c0b9fa 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 @@ static void setUp() { @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/condition/ConditionStateRouterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouterTest.java index 4735e7970b1..080f7584c97 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouterTest.java +++ b/dubbo-cluster/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.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 @@ private URL getRouteUrl(String rule) { 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 @@ void testRoute_matchFilter() { 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))); - - - - 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<>()); + 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<>()); Assertions.assertEquals(1, filteredInvokers1.size()); Assertions.assertEquals(0, filteredInvokers2.size()); Assertions.assertEquals(0, filteredInvokers3.size()); @@ -142,106 +200,146 @@ void testRoute_matchFilter() { 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 @@ void testRoute_HostFilter() { @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 @@ void testRoute_Empty_HostFilter() { @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 @@ void testRoute_False_HostFilter() { @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 @@ void testRoute_Placeholder() { @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 @@ void testRoute_Arguments() { 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 @@ void testRoute_Key_Not_Exist() { 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 @@ void testRoute_Key_Not_Exist() { 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-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/config/ProviderAppConditionStateRouterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/config/ProviderAppConditionStateRouterTest.java index 975a78bceb0..7348868954b 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/config/ProviderAppConditionStateRouterTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/config/ProviderAppConditionStateRouterTest.java @@ -25,14 +25,14 @@ 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 @@ void test() { 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 @@ void test() { 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-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java index b025e8f8e98..e2aff971362 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java @@ -33,16 +33,17 @@ 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 @@ void testRouteNotAvailable() { 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 @@ void testRouteAvailable() { 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 @@ void testRouteByMethodName() { 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 @@ void testRouteByMethodName() { 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 @@ void testRouteByMethodName() { } 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 @@ private void initInvokers(URL url, boolean invoker1Status, boolean invoker2Statu 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 @@ public MockClusterInvoker(Directory directory, URL url) { } @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/router/mesh/route/MeshAppRuleListenerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshAppRuleListenerTest.java index 8619baf5812..07724fb9fb9 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshAppRuleListenerTest.java +++ b/dubbo-cluster/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; @@ -23,6 +22,10 @@ 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; @@ -31,91 +34,79 @@ 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() { @@ -152,10 +143,22 @@ void register() { 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); @@ -177,7 +180,6 @@ void register() { Assertions.assertTrue(rulesReceived.contains(yaml.load(rule2))); Assertions.assertEquals("demo-route", appCaptor.getValue()); - } @Test @@ -189,16 +191,35 @@ void unregister() { 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 @@ -208,8 +229,11 @@ void process() { 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); @@ -224,8 +248,11 @@ void process() { 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); @@ -236,8 +263,11 @@ void process() { 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"); @@ -290,9 +320,7 @@ public void onRuleChange(String appName, List> rules) { } @Override - public void clearRule(String appName) { - - } + public void clearRule(String appName) {} @Override public String ruleSuffix() { @@ -311,9 +339,7 @@ public void onRuleChange(String appName, List> rules) { } @Override - public void clearRule(String appName) { - - } + public void clearRule(String appName) {} @Override public String ruleSuffix() { @@ -346,7 +372,8 @@ public String ruleSuffix() { 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-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleCacheTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleCacheTest.java index a1fbb399595..76409a9f90c 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleCacheTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleCacheTest.java @@ -25,14 +25,14 @@ 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; @@ -41,7 +41,8 @@ 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; @@ -55,7 +56,6 @@ void containMapKeyValue() { when(url.getOriginalServiceParameter("test", "key3")).thenReturn("value3"); when(url.getOriginalServiceParameter("test", "key4")).thenReturn("value4"); - Map originMap = new HashMap<>(); originMap.put("key1", "value1"); @@ -71,13 +71,12 @@ void containMapKeyValue() { 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"); @@ -99,7 +98,8 @@ void testBuild() { 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-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleManagerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleManagerTest.java index ab609ec8603..b81b96706a7 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleManagerTest.java +++ b/dubbo-cluster/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; @@ -23,6 +22,12 @@ 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; @@ -31,12 +36,6 @@ 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; @@ -44,31 +43,25 @@ 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; @@ -105,9 +98,7 @@ public void onRuleChange(String appName, List> rules) { } @Override - public void clearRule(String appName) { - - } + public void clearRule(String appName) {} @Override public String ruleSuffix() { @@ -120,9 +111,9 @@ public String ruleSuffix() { 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()); @@ -134,9 +125,7 @@ public void onRuleChange(String appName, List> rules) { } @Override - public void clearRule(String appName) { - - } + public void clearRule(String appName) {} @Override public String ruleSuffix() { @@ -145,17 +134,18 @@ public String ruleSuffix() { }; 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 @@ -175,9 +165,7 @@ public void onRuleChange(String appName, List> rules) { } @Override - public void clearRule(String appName) { - - } + public void clearRule(String appName) {} @Override public String ruleSuffix() { @@ -191,8 +179,15 @@ public String ruleSuffix() { 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); @@ -221,9 +216,7 @@ public void onRuleChange(String appName, List> rules) { } @Override - public void clearRule(String appName) { - - } + public void clearRule(String appName) {} @Override public String ruleSuffix() { @@ -238,17 +231,15 @@ public String ruleSuffix() { 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) { @@ -256,9 +247,7 @@ public void onRuleChange(String appName, List> rules) { } @Override - public void clearRule(String appName) { - - } + public void clearRule(String appName) {} @Override public String ruleSuffix() { @@ -267,17 +256,18 @@ public String ruleSuffix() { }; 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-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleRouterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleRouterTest.java index 35f2a7e9ae0..2cf9da4cf2e 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleRouterTest.java +++ b/dubbo-cluster/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; @@ -29,14 +28,6 @@ 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; import java.util.HashMap; @@ -46,123 +37,126 @@ 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; @@ -196,27 +190,29 @@ public void teardown() { } 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); @@ -265,7 +261,8 @@ void testRuleChange() { @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); @@ -282,10 +279,12 @@ void testRoute2() { 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")); @@ -296,19 +295,43 @@ void testRoute2() { 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)); @@ -323,22 +346,54 @@ void testRoute2() { 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<>(); @@ -363,15 +418,31 @@ void testRoute2() { 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")); @@ -380,6 +451,5 @@ void testRoute2() { meshRuleRouter.notify(invokers); invokers.removeAll(Arrays.asList(isolation, testingTrunk, testing)); assertEquals(invokers, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null)); - } } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/StandardMeshRuleRouterFactoryTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/StandardMeshRuleRouterFactoryTest.java index 53a0de3ad36..c134325a1c3 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/StandardMeshRuleRouterFactoryTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/StandardMeshRuleRouterFactoryTest.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,12 +21,12 @@ 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-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/DestinationRuleTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/DestinationRuleTest.java index b73ffdf62b6..4dd045156eb 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/DestinationRuleTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/DestinationRuleTest.java @@ -14,48 +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 java.util.Map; + import org.junit.jupiter.api.Test; import org.yaml.snakeyaml.Yaml; -import java.util.Map; - 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()); @@ -64,30 +62,41 @@ void parserTest() { 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(SimpleLB.ROUND_ROBIN, destinationRule.getSpec().getTrafficPolicy().getLoadBalancer().getSimple()); - assertEquals(null, destinationRule.getSpec().getTrafficPolicy().getLoadBalancer().getConsistentHash()); + 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()); } - @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; @@ -102,5 +111,4 @@ void parserMultiRuleTest() { } } } - } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/VirtualServiceRuleTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/VirtualServiceRuleTest.java index cca13f2e21c..02392330023 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/VirtualServiceRuleTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/VirtualServiceRuleTest.java @@ -14,29 +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 java.util.List; + import org.junit.jupiter.api.Test; import org.yaml.snakeyaml.Yaml; -import java.util.List; - 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); @@ -64,19 +64,31 @@ void parserTest() { 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-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboMatchRequestTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboMatchRequestTest.java index 7c2e433515e..02d512137ef 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboMatchRequestTest.java +++ b/dubbo-cluster/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; @@ -23,16 +22,15 @@ 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 @@ -75,7 +73,6 @@ void isMatch() { assertTrue(dubboMatchRequest.isMatch(rpcInvocation, inputSourceLabelsMap, Collections.emptySet())); assertFalse(dubboMatchRequest.isMatch(rpcInvocation, inputSourceLabelsMap2, Collections.emptySet())); - // tracingContext DubboAttachmentMatch dubboAttachmentMatch = new DubboAttachmentMatch(); Map tracingContextMatchMap = new HashMap<>(); @@ -91,8 +88,8 @@ void isMatch() { 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"); @@ -100,10 +97,10 @@ void isMatch() { 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<>(); @@ -112,7 +109,6 @@ void isMatch() { eagleeyecontextMatchMap.put("name", nameMatch); dubboAttachmentMatch.setTracingContext(eagleeyecontextMatchMap); - Map dubboContextMatchMap = new HashMap<>(); StringMatch dpathMatch = new StringMatch(); dpathMatch.setExact("PRE"); @@ -121,18 +117,19 @@ void isMatch() { 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-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 5b9ad498aed..fcef780c743 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 2412e175e4f..630bb37f85f 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 @@ void rangeStartMatch() { assertFalse(doubleMatch.isMatch(9.0)); } - @Test void rangeEndMatch() { DoubleMatch doubleMatch = new DoubleMatch(); @@ -61,7 +58,6 @@ void rangeEndMatch() { assertTrue(doubleMatch.isMatch(9.0)); } - @Test void rangeStartEndMatch() { DoubleMatch doubleMatch = new DoubleMatch(); @@ -79,7 +75,6 @@ void rangeStartEndMatch() { assertFalse(doubleMatch.isMatch(10.1)); assertTrue(doubleMatch.isMatch(6.0)); - } @Test @@ -97,5 +92,4 @@ void modMatch() { 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/DubboAttachmentMatchTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboAttachmentMatchTest.java index 66bfd3e1497..bb4042ab9b7 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboAttachmentMatchTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboAttachmentMatchTest.java @@ -14,25 +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 @@ -45,7 +42,6 @@ void dubboContextMatch() { nameMatch.setExact("qinliujie"); dubbocontextMatchMap.put("name", nameMatch); - StringMatch machineGroupMatch = new StringMatch(); machineGroupMatch.setExact("test_host"); dubbocontextMatchMap.put("machineGroup", machineGroupMatch); @@ -62,7 +58,6 @@ void dubboContextMatch() { assertTrue(dubboAttachmentMatch.isMatch(rpcInvocation, Collections.emptySet())); - Map invokeDubboContextMap2 = new HashMap<>(); invokeDubboContextMap2.put("name", "jack"); invokeDubboContextMap2.put("machineGroup", "test_host"); @@ -73,7 +68,6 @@ void dubboContextMatch() { assertFalse(dubboAttachmentMatch.isMatch(rpcInvocation2, Collections.emptySet())); - Map invokeDubboContextMap3 = new HashMap<>(); invokeDubboContextMap3.put("name", "qinliujie"); invokeDubboContextMap3.put("machineGroup", "my_host"); @@ -85,7 +79,6 @@ void dubboContextMatch() { assertFalse(dubboAttachmentMatch.isMatch(rpcInvocation3, Collections.emptySet())); } - @Test void tracingContextMatch() { DubboAttachmentMatch dubboAttachmentMatch = new DubboAttachmentMatch(); @@ -108,7 +101,8 @@ void tracingContextMatch() { 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"); @@ -116,8 +110,8 @@ void tracingContextMatch() { 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"); @@ -125,10 +119,10 @@ void tracingContextMatch() { 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(); @@ -158,7 +152,6 @@ void contextMatch() { rpcInvocation.setAttachments(invokeDubboContextMap); assertTrue(dubboAttachmentMatch.isMatch(rpcInvocation, Collections.singleton(tracingContextProvider))); - Map invokeTracingContextMap1 = new HashMap<>(); invokeTracingContextMap1.put("name", "jack"); invokeTracingContextMap1.put("machineGroup", "test_host"); @@ -169,7 +162,6 @@ void contextMatch() { rpcInvocation1.setAttachments(invokeDubboContextMap); assertFalse(dubboAttachmentMatch.isMatch(rpcInvocation1, Collections.singleton(tracingContextProvider1))); - Map invokeDubboContextMap1 = new HashMap<>(); invokeDubboContextMap1.put("dpath", "PRE-2"); @@ -178,13 +170,11 @@ void contextMatch() { 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"); @@ -200,11 +190,9 @@ void contextMatch() { 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-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 267a30f6623..ca478c58684 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 @@ void nameMatch() { 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 @@ void argpMatch() { 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 @@ void parametersMatch() { List parametersMatch = new ArrayList<>(); - //----- index 0 + // ----- index 0 { DubboMethodArg dubboMethodArg0 = new DubboMethodArg(); dubboMethodArg0.setIndex(0); @@ -102,10 +104,9 @@ void parametersMatch() { parametersMatch.add(dubboMethodArg0); } - //-----index 1 + // -----index 1 { - DubboMethodArg dubboMethodArg1 = new DubboMethodArg(); dubboMethodArg1.setIndex(1); @@ -127,28 +128,32 @@ void parametersMatch() { 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 7984a028ae0..e5edd0f134e 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 1730b76bd7d..74176a1e728 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 7a7e68cf0b7..7c41cb702ff 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 @@ void isMatch() { 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 5a3b13c57a8..fdae04519e8 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 @@ void exactMatch() { assertFalse(stringMatch.isMatch(null)); } - @Test void prefixMatch() { StringMatch stringMatch = new StringMatch(); @@ -46,7 +43,6 @@ void prefixMatch() { assertFalse(stringMatch.isMatch(null)); } - @Test void regxMatch() { StringMatch stringMatch = new StringMatch(); @@ -58,7 +54,6 @@ void regxMatch() { 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/mesh/util/MeshRuleDispatcherTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleDispatcherTest.java index 5f548c7efde..e37b744990a 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleDispatcherTest.java +++ b/dubbo-cluster/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 @@ public void onRuleChange(String appName, List> rules) { } @Override - public void clearRule(String appName) { - - } + public void clearRule(String appName) {} @Override public String ruleSuffix() { @@ -69,9 +66,7 @@ public void onRuleChange(String appName, List> rules) { } @Override - public void clearRule(String appName) { - - } + public void clearRule(String appName) {} @Override public String ruleSuffix() { @@ -112,13 +107,10 @@ void register() { 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 @@ public String ruleSuffix() { 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 @@ void unregister() { 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 @@ public String ruleSuffix() { 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 @@ public String ruleSuffix() { 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 @@ public String ruleSuffix() { 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-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelectorTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelectorTest.java index 011e871e6ae..7ad19152e4d 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelectorTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelectorTest.java @@ -22,13 +22,13 @@ 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 @@ void test() { 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-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouterTest.java index 2254ec51cc4..51982cec4a6 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouterTest.java +++ b/dubbo-cluster/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.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.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 @@ private URL getRouteUrl(String rule) { @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 @@ void testRoutePickInvokers() { @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 @@ void testRouteHostFilter() { @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 @@ void testRoute_throwException() { 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-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/config/AppScriptStateRouterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/config/AppScriptStateRouterTest.java index 00e59d5ff85..36aba171cee 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/config/AppScriptStateRouterTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/config/AppScriptStateRouterTest.java @@ -25,6 +25,9 @@ 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.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 @@ void testConfigScriptRoute() { 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 @@ void testConfigScriptRoute() { 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-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 54bc765fb28..9996de577f6 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.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 @@ void testAddAll() { Assertions.assertEquals(3, bitList1.size()); Assertions.assertFalse(bitList1.hasMoreElementInTailList()); - bitList1.addAll(bitList2); Assertions.assertEquals(3, bitList1.size()); @@ -353,7 +352,10 @@ void testListIterator1() { } @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 @@ void testListIterator5() { 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/router/tag/TagStateRouterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouterTest.java index d5d7746303b..cd3e9d67bd3 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouterTest.java +++ b/dubbo-cluster/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.extension.ExtensionLoader; @@ -33,16 +31,16 @@ 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.ArrayList; import java.util.HashSet; import java.util.List; 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.TAG_KEY; import static org.mockito.Mockito.when; @@ -61,7 +59,6 @@ public void setup() { ScopeBeanFactory beanFactory = Mockito.spy(originBeanFactory); when(moduleModel.getBeanFactory()).thenReturn(beanFactory); - ExtensionLoader extensionLoader = Mockito.mock(ExtensionLoader.class); tracingContextProviders = new HashSet<>(); when(extensionLoader.getSupportedExtensionInstances()).thenReturn(tracingContextProviders); @@ -76,7 +73,8 @@ void testTagRoutePickInvokers() { 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); @@ -89,7 +87,8 @@ void testTagRoutePickInvokers() { 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)); } @@ -101,9 +100,12 @@ void testTagRouteWithDynamicRuleV3() { 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); @@ -118,9 +120,10 @@ void testTagRouteWithDynamicRuleV3() { 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)); } /** @@ -133,22 +136,21 @@ void testTagRouteWithDynamicRuleV3() { */ @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); @@ -171,46 +173,44 @@ void tagRouterRuleParseTest() { 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); @@ -232,14 +232,14 @@ void tagRouterRuleParseTestV3() { 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); @@ -247,20 +247,19 @@ public BitList> getInvokers() { } 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; 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 9ca725f8f7a..7d637a7da4c 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.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.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; @@ -79,8 +79,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; @@ -157,17 +160,19 @@ protected Result doInvoke(Invocation invocation, List invokers, LoadBalance load } }; - 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"; @@ -176,7 +181,7 @@ void testBindingAttachment() { // 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 @@ -197,7 +202,7 @@ protected Result doInvoke(Invocation invocation, List invokers, LoadBalance load @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); @@ -215,7 +220,7 @@ void testSelectedInvokers() { 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); @@ -233,7 +238,7 @@ void testSelect_Invokersize1() { 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); } @@ -244,7 +249,7 @@ void testSelect_Invokersize2AndselectNotNull() { 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); @@ -269,7 +274,7 @@ void testSelect_multiInvokers() { @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); @@ -278,11 +283,11 @@ void testCloseAvailablecheck() { 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); @@ -300,7 +305,7 @@ void testDonotSelectAgainAndNoCheckAvailable() { LoadBalance lb = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(RoundRobinLoadBalance.NAME); initlistsize5(); { - //Boundary condition test . + // Boundary condition test . selectedInvokers.clear(); selectedInvokers.add(invoker2); selectedInvokers.add(invoker3); @@ -310,7 +315,7 @@ void testDonotSelectAgainAndNoCheckAvailable() { Assertions.assertSame(invoker1, sinvoker); } { - //Boundary condition test . + // Boundary condition test . selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker3); @@ -320,7 +325,7 @@ void testDonotSelectAgainAndNoCheckAvailable() { Assertions.assertSame(invoker2, sinvoker); } { - //Boundary condition test . + // Boundary condition test . selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker2); @@ -330,7 +335,7 @@ void testDonotSelectAgainAndNoCheckAvailable() { Assertions.assertSame(invoker3, sinvoker); } { - //Boundary condition test . + // Boundary condition test . selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker2); @@ -340,7 +345,7 @@ void testDonotSelectAgainAndNoCheckAvailable() { Assertions.assertSame(invoker5, sinvoker); } { - //Boundary condition test . + // Boundary condition test . selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker2); @@ -350,7 +355,6 @@ void testDonotSelectAgainAndNoCheckAvailable() { Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers); Assertions.assertTrue(invokers.contains(sinvoker)); } - } @Test @@ -359,7 +363,7 @@ void testSelectAgainAndCheckAvailable() { LoadBalance lb = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(RoundRobinLoadBalance.NAME); initlistsize5(); { - //Boundary condition test . + // Boundary condition test . selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker2); @@ -369,7 +373,7 @@ void testSelectAgainAndCheckAvailable() { Assertions.assertSame(sinvoker, invoker4); } { - //Boundary condition test . + // Boundary condition test . selectedInvokers.clear(); selectedInvokers.add(invoker2); selectedInvokers.add(invoker3); @@ -379,7 +383,7 @@ void testSelectAgainAndCheckAvailable() { 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); @@ -387,7 +391,7 @@ void testSelectAgainAndCheckAvailable() { } } { - //Boundary condition test . + // Boundary condition test . for (int i = 0; i < 100; i++) { selectedInvokers.clear(); selectedInvokers.add(invoker1); @@ -398,7 +402,7 @@ void testSelectAgainAndCheckAvailable() { } } { - //Boundary condition test . + // Boundary condition test . for (int i = 0; i < 100; i++) { selectedInvokers.clear(); selectedInvokers.add(invoker1); @@ -412,7 +416,6 @@ void testSelectAgainAndCheckAvailable() { } } - public void testSelect_multiInvokers(String lbname) { int min = 100, max = 500; @@ -497,18 +500,19 @@ void testSelectBalance() { 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); @@ -546,12 +550,12 @@ public Result invoke(Invocation invocation) throws RpcException { } @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(); @@ -596,6 +600,5 @@ void testMockedInvokerSelect() { Assertions.assertEquals(5, invokers.size()); } - 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 b3357e9ba48..d4d03530a24 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.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 9cba72c0758..5e63e97153c 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.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 @@ public void setUp() throws Exception { clusterInvoker = new BroadcastClusterInvoker(dic); } - @Test void testNormal() { given(dic.list(invocation)).willReturn(Arrays.asList(invoker1, invoker2, invoker3, invoker4)); @@ -91,7 +89,8 @@ void testEx() { 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 @@ public boolean isAvailable() { } @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 2f3bbe0e412..da26d2be04a 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.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.URL_MERGE_PROCESSOR_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; - class ClusterUtilsTest { private ClusterUtils clusterUtils; @@ -57,39 +56,37 @@ public void setup() { @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 @@ void testMergeUrl() { // 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 @@ void testMergeLocalParams() { // 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 @@ void testMergeLocalParams() { // 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(); - - Map paramsForTag = clusterUtils.mergeLocalParams(consumerUrlForTag.getParameters()); + .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()); 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 23cb42831fc..a2f6b1499fe 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.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.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 @@ void testBasic() throws InterruptedException { 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 @@ void testBasic() throws InterruptedException { 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 @@ void testBasic() throws InterruptedException { 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 @@ void testRetry() throws InterruptedException { 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 @@ void testRandomSelect() throws InterruptedException { 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 @@ public ConnectivityClusterInvoker(Directory directory) { } @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 @@ private void waitRefresh(Set invokerSet) throws InterruptedException { 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 91c1c9ddd9b..b1fe930960f 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.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 @@ private void resetInvokerToNoException() { given(invoker.getInterface()).willReturn(DemoService.class); } - //TODO assert error log + // TODO assert error log @Test void testInvokeExceptoin() { resetInvokerToException(); @@ -115,12 +114,11 @@ void testNoInvoke() { 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 bbc17745fca..413cc9615d0 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.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.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 @@ public void tearDown() { invokers.clear(); } - private void resetInvokerToException() { given(invoker.invoke(invocation)).willThrow(new RuntimeException()); given(invoker.getUrl()).willReturn(url); @@ -172,9 +169,9 @@ public void testNoInvoke() { 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 @@ public void testNoInvoke() { @Test @Order(4) public void testARetryFailed() throws Exception { - //Test retries and + // Test retries and resetInvokerToException(); @@ -195,19 +192,23 @@ public void testARetryFailed() throws Exception { 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 @@ private long getRetryFailedPeriod() throws NoSuchFieldException, IllegalAccessEx @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 @@ public void testInvokeRetryTimesWithZeroValue() throws InterruptedException, NoS 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 @@ public void testInvokeRetryTimesWithTwoValue() throws InterruptedException, NoSu 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 @@ public void testInvokeRetryTimesWithDefaultValue() throws InterruptedException, 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 @@ public void testInvokeRetryTimesWithIllegalValue() throws InterruptedException, 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 f1f34121380..972d3d76831 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.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 @@ void testNoInvoke() { 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 4c99c50b356..bc48b8629c1 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.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 @@ public void setUp() throws Exception { invokers.add(invoker2); } - @Test void testInvokeWithRuntimeException() { given(invoker1.invoke(invocation)).willThrow(new RuntimeException()); @@ -197,7 +196,8 @@ void testInvoke_retryTimes_withBizException() { @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 @@ void testInvoke_without_retry() { @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 @@ void testNoInvoke() { invokers.add(invoker1); - FailoverClusterInvoker invoker = new FailoverClusterInvoker<>(dic); try { invoker.invoke(invocation); @@ -276,7 +276,8 @@ void testNoInvoke() { */ @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 @@ void testInvokerDestroyAndReList() { 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 @@ void testInvokerDestroyAndReList() { clusterInvoker.invoke(inv); } - public interface Demo { - } + public interface Demo {} public static class MockInvoker extends AbstractInvoker { URL url; @@ -362,7 +362,9 @@ public MockDirectory(URL url, List> invokers) { } @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 4fe7400a330..1076babf800 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.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 @@ public void setUp() throws Exception { invokers.add(invoker1); invokers.add(invoker2); invokers.add(invoker3); - } private void resetInvokerToException() { @@ -134,7 +133,9 @@ void testClearRpcContext() { 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 @@ void testInvokeWithIllegalForksParam() { Result ret = invoker.invoke(invocation); Assertions.assertSame(result, ret); } - } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/Menu.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/Menu.java index cfd5a55bc6a..93e5e46eb99 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/Menu.java +++ b/dubbo-cluster/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 @@ public void merge(Menu menu) { addMenu(entry.getKey(), entry.getValue()); } } - } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MenuService.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MenuService.java index f1b6f7566f1..d1f2b9ba8d8 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MenuService.java +++ b/dubbo-cluster/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-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.java index eab0b6c44cc..97e07c76f32 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.java @@ -28,10 +28,6 @@ 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; import java.util.Arrays; @@ -40,6 +36,10 @@ 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; @@ -98,7 +98,6 @@ public void setUp() throws Exception { firstInvoker = mock(Invoker.class); secondInvoker = mock(Invoker.class); invocation = mock(RpcInvocation.class); - } @Test @@ -108,36 +107,38 @@ void testGetMenuSuccessfully() { 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; - }); - - 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; - }); + 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; + }); given(directory.list(invocation)).willReturn(new ArrayList() { @@ -184,8 +185,8 @@ void testAddMenu() { }; 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); @@ -215,7 +216,6 @@ void testAddMenu() { Result result = mergeableClusterInvoker.invoke(invocation); Assertions.assertNull(result.getValue()); - } @Test @@ -233,36 +233,38 @@ void testAddMenu1() { }; 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; - }); - - 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; - }); + 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; + }); given(directory.list(invocation)).willReturn(new ArrayList() { @@ -280,7 +282,6 @@ void testAddMenu1() { Result result = mergeableClusterInvoker.invoke(invocation); Assertions.assertNull(result.getValue()); - } @Test @@ -294,8 +295,8 @@ void testInvokerToNoInvokerAvailableException() { }; 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); @@ -303,13 +304,15 @@ void testInvokerToNoInvokerAvailableException() { 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() { @@ -349,8 +352,8 @@ void testInvokerToException() { }; 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); @@ -397,8 +400,8 @@ void testGetMenuResultHasException() { 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); @@ -443,40 +446,41 @@ void testGetMenuWithMergerDefault() { 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; - }); - - 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; - }); + 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; + }); given(directory.list(invocation)).willReturn(new ArrayList() { @@ -503,8 +507,8 @@ void testGetMenuWithMergerDefault() { @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-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 02d8ed6789a..347146f0a70 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 9d3ce74e365..b26407b7ca4 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 @@ public void setup() { @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 @@ void testMergeUrl() { @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 @@ void testUseProviderParams() { 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 @@ void testUseProviderParams() { 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 9a200789351..6ced222f620 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.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 @@ void testPreferredStrategy() { 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 @@ void testRegistryZoneStrategy() { 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 @@ void testRegistryZoneForceStrategy() { 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 @@ public void testNoAvailableInvoker() { 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 395620923aa..beb4536325e 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.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 @@ void testBuildClusterInvokerChain() { 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 @@ void testBuildClusterInvokerChain() { 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 @@ protected Result doInvoke(Invocation invocation, List list, LoadBalance loadbala 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 2cea0f44083..e17176b98b6 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 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/MockClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java index b15c87324fd..cc4dbb94bc9 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java @@ -32,16 +32,16 @@ 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 @@ public void beforeMethod() { @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 @@ void testMockInvokerInvoke_normal() { @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 @@ void testMockInvokerInvoke_failmock() { 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 @@ void testMockInvokerInvoke_failmock() { 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 @@ void testMockInvokerInvoke_forcemock() { 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 @@ void testMockInvokerInvoke_forcemock_defaultreturn() { @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 @@ void testMockInvokerFromOverride_Invoke_Fock_someMethods() { @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 @@ void testMockInvokerFromOverride_Invoke_Fock_WithOutDefault() { @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 @@ void testMockInvokerFromOverride_Invoke_Fock_WithDefault() { @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 @@ void testMockInvokerFromOverride_Invoke_Fock_WithFailDefault() { 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 @@ void testMockInvokerFromOverride_Invoke_Fock_WithFailDefault() { @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 @@ void testMockInvokerFromOverride_Invoke_Fock_WithForceDefault() { @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 @@ void testMockInvokerFromOverride_Invoke_Fock_Default() { @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 @@ void testMockInvokerFromOverride_Invoke_checkCompatible_return() { @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 @@ void testMockInvokerFromOverride_Invoke_checkCompatible_ImplMock() { @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 @@ void testMockInvokerFromOverride_Invoke_checkCompatible_ImplMock2() { @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 @@ void testMockInvokerFromOverride_Invoke_checkCompatible_ImplMock3() { 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 @@ void testMockInvokerFromOverride_Invoke_check_Boolean() { @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 @@ void testMockInvokerFromOverride_Invoke_check_ListString_empty() { @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 @@ void testMockInvokerFromOverride_Invoke_check_ListString() { @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 @@ void testMockInvokerFromOverride_Invoke_check_ListPojoAsync() throws ExecutionEx 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 @@ void testMockInvokerFromOverride_Invoke_check_ListPojo() { @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 @@ void testMockInvokerFromOverride_Invoke_check_ListPojo_error() { @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 @@ void testMockInvokerFromOverride_Invoke_force_throw() { @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 @@ void testMockInvokerFromOverride_Invoke_force_throwCustemException() throws Thro @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 @@ void testMockInvokerFromOverride_Invoke_force_throwCustemExceptionNotFound() { @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 @@ void testMockInvokerFromOverride_Invoke_mock_false() { } 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 @@ public Boolean getBoolean2() { } 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 @@ public void sayHello() { } public static class IHelloServiceMock implements IHelloService { - public IHelloServiceMock() { - - } + public IHelloServiceMock() {} public String getSomething() { return "somethingmock"; @@ -860,17 +875,17 @@ public String getSomething4() { } 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 @@ public static class User { private int id; private String name; - public User() { - } + public User() {} public User(int id, String name) { super(); @@ -919,6 +933,5 @@ public String getName() { public void setName(String name) { this.name = name; } - } } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockProviderRpcExceptionTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockProviderRpcExceptionTest.java index e692aae745f..697f4b68d2d 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockProviderRpcExceptionTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockProviderRpcExceptionTest.java @@ -28,16 +28,16 @@ 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 @@ public void beforeMethod() { @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 @@ void testMockInvokerProviderRpcException() { 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 @@ public Boolean getBoolean2() { } 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 @@ public void sayHello() { } public static class IHelloRpcServiceMock implements IHelloRpcService { - public IHelloRpcServiceMock() { - - } + public IHelloRpcServiceMock() {} public String getSomething() { return "somethingmock"; @@ -190,11 +190,11 @@ public String getSomething4() { } 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 @@ public static class User { private int id; private String name; - public User() { - } + public User() {} public User(int id, String name) { super(); @@ -242,6 +241,5 @@ public String getName() { public void setName(String name) { this.name = name; } - } } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MyMockException.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MyMockException.java index f353745cc73..9e10bc1c903 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MyMockException.java +++ b/dubbo-cluster/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-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 389aab4d4d6..f04617e6687 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.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.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 @@ void after() throws Exception { @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 @@ void testScopeNull_RemoteInvoke() { @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 @@ void testScopeNull_LocalInvoke() { @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 @@ void testScopeRemoteInvoke() { @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 @@ void testScopeLocalInvoke() { 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 @@ void testScopeLocalInvoke() { @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 @@ void testInjvmRefer() { 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 @@ void testInjvmRefer() { @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 @@ void testListenUnExport() throws NoSuchFieldException, IllegalAccessException { @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 @@ void testPeerInvoke() { 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 @@ void testDynamicInvoke() { 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 @@ void testDynamicInvoke() { 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 @@ void testDynamicInvoke() { 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 @@ void testDynamicInvoke() { @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 @@ void testBroadcast() { 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 @@ void testBroadcast() { 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 @@ private Invoker getClusterInvoker(URL url) { 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 @@ public String doSomething1() { @Override public String doSomething2() { return "doSomething2"; - } @Override @@ -425,5 +418,3 @@ public String doSomething8() { } } } - - diff --git a/dubbo-common/pom.xml b/dubbo-common/pom.xml index d9413ee7ad7..f59666e545f 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 + + 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 c958f565081..a8cd6a6fd3b 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 @@ private void run(Executor executor) { } } - 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 746bc1b7ad5..5429b9cad91 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 @@ */ @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 4e4815bc131..520184014e3 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 @@ */ @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 1bd8c74e644..68206dbf4bb 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 42f7bd5459a..4a368b2a89e 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 Parameters(String... pairs) { } 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 int hashCode() { 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 0cc8b203d4d..e4f5862c028 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 static boolean isMatch(ProtocolServiceKey rule, ProtocolServiceKey target 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 873c0be17ca..2121c783dab 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 c8d8f846cc0..6b906d5edee 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 boolean equals(Object o) { 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 String toString() { 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 static boolean isMatch(ServiceKey rule, ServiceKey target) { 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 @@ else if (!Objects.equals(rule.getVersion(), target.getVersion())) { 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 15e2185494b..28c841996c9 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 @@ * @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 @@ public URL(String protocol, String host, int port) { 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 @@ public URL(String protocol, String username, String password, String host, int p 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 @@ public URL(String protocol, 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 @@ public static URL valueOf(URL url, String[] reserveParams, String[] reserveParam } } } - 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 @@ public String getUsername() { 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 @@ public String getPassword() { 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 @@ public URL setHost(String host) { } } - public int getPort() { return urlAddress == null ? 0 : urlAddress.getPort(); } @@ -625,7 +646,10 @@ public T getParameter(String key, Class valueType, T defaultValue) { 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 @@ public ServiceModel getServiceModel() { return (ServiceModel) getAttribute(CommonConstants.SERVICE_MODEL); } - - public URL getUrlParameter(String key) { String value = getParameterAndDecoded(key); if (StringUtils.isEmpty(value)) { @@ -1155,7 +1177,8 @@ public String toIdentityString() { } 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 @@ protected void buildParameters(StringBuilder buf, boolean concat, String[] param 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 @@ private String buildString(boolean appendUser, boolean appendParameter, String.. 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 @@ public String getDisplayServiceKey() { if (StringUtils.isEmpty(getVersion())) { return getServiceInterface(); } - return getServiceInterface() + - COLON_SEPARATOR + getVersion(); + return getServiceInterface() + COLON_SEPARATOR + getVersion(); } /** @@ -1485,10 +1507,12 @@ public boolean equals(Object obj) { 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 fba84657ab3..e5c18bdaafd 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 URLBuilder(String protocol, 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 static URLBuilder from(URL url) { 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 d4b5143f7cc..3b1761e2ffb 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 @@ private static URL parseURLBody(String fullURLStr, String decodedBody, Map 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 @@ private static URL parseURLBody(String fullURLStr, String decodedBody, Map parseParams(String rawParams, boolean encoded) */ 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 @@ private static Map parseEncodedParams(String str, int from) { 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 @@ private static boolean addParam(String str, boolean isEncoded, int nameStart, in } 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 @@ private static String decodeComponent(String s, int from, int toExcluded, boolea 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 ec317703a5a..a33be42ddcc 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 @@ private static void tryLoadVersionFromResource() throws IOException { 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 @@ private static void tryLoadVersionFromResource() throws IOException { } } - private Version() { - } + private Version() {} public static String getProtocolVersion() { return DEFAULT_DUBBO_PROTOCOL_VERSION; @@ -169,9 +175,13 @@ public static int getIntVersion(String 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 static String getVersion(Class cls, String defaultVersion) { // 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 static String getVersion(Class cls, String defaultVersion) { 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 @@ private static void checkArtifacts(Set artifactIds) throws IOException { } 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 @@ private static void checkArtifact(String artifactId) throws IOException { 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 @@ private static Set loadArtifactIds() throws IOException { } return artifactIds; } - } 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 570e9fdb92e..e55b5e46f7b 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 @@ * 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 8d2647135cc..0da12b38933 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 @@ private T createAndRegisterBean(String name, Class clazz) { 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 T getOrRegisterBean(Class type, Function, ? exten 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 @@ private void initializeBean(String name, Object bean) { 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 @@ private boolean containsBean(String name, Object bean) { } 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 @@ private T getBeanInternal(String name, Class type) { 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 void destroy() { 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 9d73843279f..980b3ee209e 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 T instantiate(Class type) throws ReflectiveOperationException { 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 @@ private Object getArgumentValueForType(Class parameterType) { } 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 7160de265fe..ab5bcfa438f 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 static boolean isAccessByMethod(JavaBeanAccessor accessor) { 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 d572720fc15..e39150fc3cb 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 cl) { return new JavaBeanDescriptor(cl.getName(), JavaBeanDescriptor.TYPE_BEAN); } - private static JavaBeanDescriptor createDescriptorIfAbsent(Object obj, JavaBeanAccessor accessor, - IdentityHashMap cache) { + private static JavaBeanDescriptor createDescriptorIfAbsent( + Object obj, JavaBeanAccessor accessor, IdentityHashMap cache) { if (cache.containsKey(obj)) { return cache.get(obj); } @@ -121,8 +120,11 @@ private static JavaBeanDescriptor createDescriptorIfAbsent(Object obj, JavaBeanA 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 @@ private static void serializeInternal(JavaBeanDescriptor descriptor, Object obj, 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 @@ private static void serializeInternal(JavaBeanDescriptor descriptor, Object obj, } } // ~ 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 static Object deserialize(JavaBeanDescriptor beanDescriptor, ClassLoader 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 @@ private static void deserializeInternal(Object result, JavaBeanDescriptor beanDe } } } else { - throw new IllegalArgumentException("Unsupported type " + - beanDescriptor.getClassName() + - ":" + beanDescriptor.getType()); + throw new IllegalArgumentException( + "Unsupported type " + beanDescriptor.getClassName() + ":" + beanDescriptor.getType()); } } @@ -312,8 +312,7 @@ private static Method getSetterMethod(Class cls, String property, Class va 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 static Object getConstructorArg(Class cl) { 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 @@ private static boolean isArray(String type) { } 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 f6a12df2efe..95ee995c551 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.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.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 @@ private ClassGenerator(ClassLoader classLoader, ClassPool pool) { } 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 ClassGenerator addMethod(String name, int mod, Class rt, Class[] pt 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 ClassPool getClassPool() { * 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 Class toClass(Class neighborClass, ClassLoader loader, ProtectionDo 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 Class toClass(Class neighborClass, ClassLoader loader, ProtectionDo 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 Class toClass(Class neighborClass, ClassLoader loader, ProtectionDo 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 @@ private CtClass getCtClass(Class c) throws NotFoundException { } 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 f0c5b377f28..1f3252bceb0 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 DubboLoaderClassPath() { @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 12293d1976c..81cadc0d76a 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 @@ protected 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 static Mixin mixin(Class[] ics, Class dc) { * @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 static Mixin mixin(Class[] ics, Class[] dcs, ClassLoader cl) { 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 static Mixin mixin(Class[] ics, Class[] dcs, ClassLoader cl) { 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 @@ private static void assertInterfaceArray(Class[] ics) { * @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 31679daa70b..0cf1743b004 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 @@ /** * 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 7b6f8ecef35..015ca47e32c 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 @@ /** * 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 256eb63e954..29b990894df 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 @@ private static Class buildProxyClass(ClassLoader cl, Class[] ics, Protecti 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 @@ private static Class buildProxyClass(ClassLoader cl, Class[] ics, Protecti 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 d5be038cb53..b42d5e286fb 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.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.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 boolean hasProperty(String name) { } @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 @@ private static Wrapper makeWrapper(Class c) { 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() + "{ "); - - 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); }"); + 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); }"); Map> pts = new HashMap<>(); // Map ms = new LinkedHashMap<>(); // @@ -147,12 +160,28 @@ private static Wrapper makeWrapper(Class c) { 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 @@ private static Wrapper makeWrapper(Class c) { } 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 @@ private static Wrapper makeWrapper(Class c) { 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 @@ private static Wrapper makeWrapper(Class c) { 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 @@ private static Wrapper makeWrapper(Class c) { 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 @@ private static Wrapper makeWrapper(Class c) { 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 @@ private static String args(Class[] cs, String name) { } 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 @@ private static String propertyName(String pn) { * * @return property name array. */ - abstract public String[] getPropertyNames(); + public abstract String[] getPropertyNames(); /** * get property type. @@ -361,7 +430,7 @@ private static String propertyName(String pn) { * @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 @@ private static String propertyName(String pn) { * @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 @@ private static String propertyName(String pn) { * @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 @@ private static String propertyName(String pn) { * @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 @@ private static String propertyName(String pn) { * @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 Object[] getPropertyValues(Object instance, String[] pns) throws NoSuchPr * @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 void setPropertyValues(Object instance, String[] pns, Object[] pvs) throw * * @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 boolean hasMethod(String name) { * @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 231b79a152e..227289b1968 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 synchronized Map loadCache(int entrySize) throws IOExcept } 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 @@ private void unlock() { 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 synchronized void refreshCache(Map properties, String com 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 synchronized void refreshCache(Map properties, String com 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); } } @@ -176,8 +180,7 @@ public static class Builder { 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 154e59658b0..be69c90b91a 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; @@ -51,27 +50,30 @@ private 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); - } - for (char c = 'a'; c <= 'z'; c++) { - add(c); - } - for (char c = 'A'; c <= 'Z'; 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); + } } - }}); + }); public static FileCacheStore getInstance(String basePath, String cacheName) { return getInstance(basePath, cacheName, true); @@ -96,8 +98,12 @@ public static FileCacheStore getInstance(String basePath, String cacheName, bool } 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); } @@ -155,14 +161,17 @@ private static FileCacheStore getFile(String name, boolean enableFileCache) { 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); } @@ -186,7 +195,8 @@ private static void tryFileLock(FileCacheStore.Builder builder, String fileName) } 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(); @@ -210,5 +220,4 @@ public PathNotExclusiveException(String msg) { 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 c3a3952e0a6..f492847a68b 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 @@ private static Class loadAnnotation(String name) { 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 0e4e28d2e0e..2bf3b25efa6 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 @@ 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 @@ private static Class lo } } - private static Constructor loadConstructor(Class... parameterTypes) { + private static Constructor loadConstructor( + Class... parameterTypes) { if (GENERIC_EXCEPTION_CLASS == null) { return null; } @@ -63,9 +70,12 @@ private static Constructor getGenericExceptionClass() { @@ -94,7 +104,8 @@ public static org.apache.dubbo.rpc.service.GenericException newGenericException( } } - 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 static org.apache.dubbo.rpc.service.GenericException newGenericException( } } - 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 dca8ec5eb26..b5b1d0a5eeb 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 @@ default Class compile(String code, ClassLoader classLoader) { 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 7d4886814cc..dacfe3043a0 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 Class compile(Class neighbor, String code, ClassLoader classLoader) } 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 @@ protected Class doCompile(ClassLoader classLoader, String name, String source 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 2518c22789e..aac8e6d434e 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 compile(Class neighbor, String code, ClassLoader classLoader) } 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 c6d477b0701..d2c39053d60 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 static Class classForName(String className) throws ClassNotFoundExcept } 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 static URI toURI(String name) { } 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 static String toString(Throwable e) { 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 static String getMethodName(Method method, Class[] parameterClasses, S 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 static String getSimpleClassName(String qualifiedName) { 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 9029d6d2cd7..cf36f931cf8 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 @@ 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.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 void addMethod(String method) { /** * get full qualified class name - * + * * @param className super class name, maybe qualified or not */ protected String getQualifiedClassName(String className) { @@ -144,7 +143,7 @@ public CtClass build(ClassLoader classLoader) throws NotFoundException, CannotCo 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 CtClass build(ClassLoader classLoader) throws NotFoundException, CannotCo 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 177a766d3ae..129d58455cd 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 @@ 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 doCompile(Class neighbor, ClassLoader classLoader, String nam 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 55daa1b8ba4..e7cf1bb9d4b 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.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 doCompile(ClassLoader ignored, String name, String sourceCode) t 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 JavaFileManagerImpl(JavaFileManager fileManager, ClassLoaderImpl classLoa } @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 FileObject getFileForInput(Location location, String packageName, String 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 @@ private URI uri(Location location, String packageName, String relativeName) { } @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 @@ protected Class findClass(final String qualifiedClassName) throws ClassNotFou 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 @@ void add(final String qualifiedClassName, final JavaFileObject javaFile) { } @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 InputStream getResourceAsStream(final String name) { 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 602ba6470d2..e3af1dad5a4 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 3b41942fca0..86fa8985f9f 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 @@ */ 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 CallableSafeInitializer(Callable callable) { * @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 4830b2aefd3..881d5ba009e 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 @@ 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 a7c21772640..26890c646ce 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 1653e961342..1e07e012abf 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 Object getInternalProperty(String key) { 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 7734b5fbbe7..5fa2143fd7c 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 @@ default Integer getInteger(String key, Integer defaultValue) { 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 @@ default Boolean getBoolean(String key, Boolean defaultValue) { 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 @@ default boolean containsKey(String key) { 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 043cdd9e789..4af6922cfe7 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 @@ private ConfigurationUtils() { * @return */ public static Configuration getSystemConfiguration(ScopeModel scopeModel) { - return getScopeModelOrDefaultApplicationModel(scopeModel).modelEnvironment().getSystemConfiguration(); + return getScopeModelOrDefaultApplicationModel(scopeModel) + .modelEnvironment() + .getSystemConfiguration(); } /** @@ -87,7 +88,9 @@ public static Configuration getSystemConfiguration(ScopeModel scopeModel) { * @return */ public static Configuration getEnvConfiguration(ScopeModel scopeModel) { - return getScopeModelOrDefaultApplicationModel(scopeModel).modelEnvironment().getEnvironmentConfiguration(); + return getScopeModelOrDefaultApplicationModel(scopeModel) + .modelEnvironment() + .getEnvironmentConfiguration(); } /** @@ -97,9 +100,10 @@ public static Configuration getEnvConfiguration(ScopeModel scopeModel) { * * @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 static void setExpectedShutdownTime(long expectedShutdownTime) { 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 static Map parseProperties(String content) throws IOExcep } 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; - } - } - if (!deny) { - map.put(k, properties.getProperty(k)); + 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)); + } + }); } 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 static boolean isEmptyValue(Object value) { * @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 static Map getSubProperties(Map 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 += "."; } @@ -278,8 +283,8 @@ private static Map getSubProperties(Map 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()); // convert camelCase/snake_case to kebab-case @@ -318,8 +323,8 @@ public static boolean hasSubProperties(Map configM for (Map.Entry entry : copy.entrySet()) { String key = entry.getKey(); if (StringUtils.startsWithIgnoreCase(key, prefix) - && key.length() > prefix.length() - && !ConfigurationUtils.isEmptyValue(entry.getValue())) { + && key.length() > prefix.length() + && !ConfigurationUtils.isEmptyValue(entry.getValue())) { return true; } } @@ -358,8 +363,8 @@ public static Set getSubIds(Collection 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 +386,10 @@ public static Set getSubIds(Collection * @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 +430,10 @@ public static Configuration getGlobalConfiguration() { */ @Deprecated public static Configuration getDynamicGlobalConfiguration() { - return ApplicationModel.defaultModel().getDefaultModule().modelEnvironment().getDynamicGlobalConfiguration(); + return ApplicationModel.defaultModel() + .getDefaultModule() + .modelEnvironment() + .getDynamicGlobalConfiguration(); } /** @@ -485,5 +495,4 @@ public static String getProperty(String property, String defaultValue) { 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 e20959e3a1d..644ed4a2f95 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 void updateAppConfigMap(Map map) { */ 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 CompositeConfiguration getConfiguration() { * @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 void destroy() throws IllegalStateException { 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 Configuration getDynamicGlobalConfiguration() { 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 92d808de9ff..8179dfc6eab 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 void setProperties(Map properties) { 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 cf516242620..3de18ccbf0f 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 Configuration getDynamicGlobalConfiguration() { 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 b4440a07643..a2838a9d960 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 OrderedPropertiesConfiguration(ModuleModel moduleModel) { 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 void refresh() { 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 ccc0539e160..051104ce4db 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 d8b45881fa3..d16c5d005da 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 Object getInternalProperty(String key) { } 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 8341fd4e156..eaedbda3789 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 afd1cac9894..c9bd32b9f00 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 long getDefaultTimeout() { * @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 @@ private void shutdownWorkersThreadPool() { } } - 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 @@ protected static long getParameter(URL url, String name, long defaultValue) { 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 f7c2ec71baa..405adbb61bd 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 ConfigChangeType getChangeType() { @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 boolean equals(Object o) { 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 ad5aa1bdc20..6acdc7cd515 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 ConfigItem(String content, Object ticket) { 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 fc505d51a62..70d44280265 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 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.Configuration; - /** * Dynamic Configuration *
@@ -48,7 +47,6 @@ default void addListener(String key, ConfigurationListener listener) { addListener(key, getDefaultGroup(), listener); } - /** * {@link #removeListener(String, String, ConfigurationListener)} * @@ -170,7 +168,8 @@ default boolean publishConfig(String key, String group, String content) throws U * @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 a6b6dbc0769..1fb89e4bd1b 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 @@ 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 cee63ea7db9..bea78931776 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 @@ -63,12 +63,13 @@ public TreePathDynamicConfiguration(URL url) { 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/file/FileSystemDynamicConfiguration.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfiguration.java index cf055349aa0..c18bd074e68 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfiguration.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfiguration.java @@ -32,8 +32,6 @@ 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.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 FileSystemDynamicConfiguration(File rootDirectory, String encoding, Strin 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 FileSystemDynamicConfiguration(File rootDirectory, String encoding, 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 FileSystemDynamicConfiguration(File rootDirectory, String encoding, } 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 @@ private void registerDubboShutdownHook() { 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 @@ private static boolean isProcessingWatchEvents() { * @param watchService {@link WatchService} */ private void processWatchEvents(WatchService watchService) { - getWatchEventsLoopThreadPool().execute(() -> { // WatchEvents Loop - while (true) { - WatchKey watchKey = null; - try { - watchKey = watchService.take(); - - 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()); - - if (configChangeType == null) { - continue; - } - - 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; + getWatchEventsLoopThreadPool() + .execute( + () -> { // WatchEvents Loop + while (true) { + WatchKey watchKey = null; + try { + watchKey = watchService.take(); + + 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()); + + if (configChangeType == null) { + continue; + } + + 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; + }); + } + + } 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 @@ protected Collection doGetConfigKeys(String groupPath) { 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 @@ protected V delay(String configFilePath, ThrowableFunction function // 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 @@ private void addProcessing(File configDirectory) { 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 @@ private static WatchEvent.Modifier[] initWatchEventModifiers() { * @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 @@ protected static File initDirectory(URL url) { } 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 @@ protected static String getEncoding(URL url) { } 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-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 b4afd0d46e1..5ff967de41d 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 Set getInnerConfigurations() { return configurations; } - @Override public void addListener(String key, String group, ConfigurationListener listener) { iterateListenerOperation(configuration -> configuration.addListener(key, group, listener)); @@ -92,7 +92,13 @@ public void close() throws Exception { 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 f5f87299c4a..29b6037b148 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 8b96f96b69d..0178a5382c0 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; @@ -266,6 +265,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;"; @@ -306,6 +306,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"; @@ -612,11 +613,11 @@ 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 @@ -624,7 +625,6 @@ public interface CommonConstants { */ 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; @@ -646,5 +646,4 @@ public interface CommonConstants { String DUBBO_MANUAL_REGISTER_KEY = "dubbo.application.manual-register"; String DUBBO2_COMPACT_ENABLE = "dubbo.compact.enable"; - } 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 f4199ffe418..028535bfc6c 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 b129d9d4e41..25a399ab783 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 0a3bfa21257..7bdcdc939aa 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; /** @@ -92,7 +91,6 @@ public interface LoggerCodeConstants { String VULNERABILITY_WARNING = "0-28"; - // Registry module String REGISTRY_ADDRESS_INVALID = "1-1"; 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 01286e6e4f4..3a0460977c4 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 38c7952bd66..74a8f0b4b21 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 { @@ -142,5 +141,4 @@ public interface RegistryConstants { String ENABLE_EMPTY_PROTECTION_KEY = "enable-empty-protection"; boolean DEFAULT_ENABLE_EMPTY_PROTECTION = false; String REGISTER_CONSUMER_URL_KEY = "register-consumer-url"; - } 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 cbdb0bffe16..f02264decb5 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 2e6471dd9d6..1f0ceb2c00c 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.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 3f67fa12001..a69f9e32668 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 @@ 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 bb851399613..300e4c5013a 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.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 7e5c8b65fc8..a6c3c258404 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 @@ 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 ConverterUtil(FrameworkModel frameworkModel) { * @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 9232fedc5f6..6f12b70827c 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 @@ * @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 3e40bf1ed8f..4c58cd1349c 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 char[] convert(String source) { 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 148b2f8b5cd..85aa2201fc8 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 Double convert(String source) { 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 edd1cf297fb..067f5d836c2 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 Duration parse(String value, ChronoUnit unit) { 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 Duration parse(String value, ChronoUnit unit) { throw new IllegalArgumentException("'" + value + "' is not a valid ISO-8601 duration", ex); } } - }; private final Pattern pattern; @@ -237,7 +237,6 @@ public static TimeUnit fromSuffix(String suffix) { } 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 f9ebdcd687f..680298c6468 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 Long convert(String source) { 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 a26fa04b02e..3fbea3c4157 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 Optional convert(String source) { 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 6427b17de43..cd2cef3050e 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 Short convert(String source) { 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 aab20facf36..41b710be95c 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 Object convert(String[] segments, int size, Class targetType, Class 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 ad9fec9eb11..067f1f6118f 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 StringToIterableConverter(FrameworkModel frameworkModel) { converterUtil = frameworkModel.getBeanFactory().getBean(ConverterUtil.class); } - public boolean accept(Class type, Class multiValueType) { return isAssignableFrom(getSupportedType(), multiValueType); } @@ -49,22 +48,23 @@ public final Object convert(String[] segments, int size, Class multiValueType Optional stringConverter = getStringConverter(elementType); - return stringConverter.map(converter -> { - - 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; - } - - return convertedObject; - }).orElse(null); + return stringConverter + .map(converter -> { + 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; + } + + return convertedObject; + }) + .orElse(null); } protected abstract T createMultiValue(int size, Class multiValueType); @@ -80,8 +80,8 @@ protected final Class getSupportedType() { @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 75fefe6a7ea..f59fc5e9062 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 @@ default Object convert(String source, Class multiValueType, Class elementT 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 04ae6826c78..554f7f9c852 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 @@ protected void setStarting() { 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 @@ protected void setStarted() { 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 @@ protected void setStopping() { 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 @@ protected void setStopped() { 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 @@ protected void setFailed(Throwable error) { 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 f045c4259d8..4df97d81213 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 @@ @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 94d31bbd64f..b52455bbc44 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 925747dae47..6a34b7dced3 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 @@ 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 bf76984d25f..06eadd3798f 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 @@ * 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 9b13e7212dc..53344314c70 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 @@ * 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 b209a2f93c8..9e468318884 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 @@ * @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 1c9517f7ae5..fd51fa15cc5 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 @@ private String generateExtNameAssignment(String[] value, boolean hasInvocation) 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 @@ private String generateExtNameAssignment(String[] value, boolean hasInvocation) } 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 @@ private boolean hasInvocationArgument(Method method) { */ 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 @@ private String[] getMethodAdaptiveValue(Adaptive adaptiveAnnotation) { // 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 @@ private String generateUrlAssignmentIndirectly(Method method) { 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 @@ private String generateUrlAssignmentIndirectly(Method method) { 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 577a28df6b4..c207c9028a3 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 @@ @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 be13080d37a..14c4882b60a 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 @@ default T getDefaultExtension(Class type) { 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 b0ca06ec2ff..943cba0773a 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 @@ 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 9790be7ae46..ecf08eb995a 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 ExtensionLoader getExtensionLoader(Class type) { 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 ExtensionDirector getParent() { 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 0441c120f77..d043b5d4dc5 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 bea5d7c4747..bac736fb064 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,14 +105,12 @@ * @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"; + private static final Pattern NAME_SEPARATOR = Pattern.compile("\\s*[,]+\\s*"); + private static final String SPECIAL_SPI_PROPERTIES = "special_spi.properties"; private final ConcurrentMap, Object> extensionInstances = new ConcurrentHashMap<>(64); @@ -124,17 +122,14 @@ 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 ConcurrentMap> cachedInstances = new ConcurrentHashMap<>(); - private final Holder cachedAdaptiveInstance = new Holder<>(); - private volatile Class cachedAdaptiveClass = null; - private String cachedDefaultName; - private volatile Throwable createAdaptiveInstanceError; + 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; + private String cachedDefaultName; + private volatile Throwable createAdaptiveInstanceError; private Set> cachedWrapperClasses; @@ -144,21 +139,22 @@ 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(); /** * Record all unacceptable exceptions when using SPI */ - private final Set unacceptableExceptions = new ConcurrentHashSet<>(); - private final ExtensionDirector extensionDirector; + private final Set unacceptableExceptions = new ConcurrentHashSet<>(); + + private final ExtensionDirector extensionDirector; private final List extensionPostProcessors; - private InstantiationStrategy instantiationStrategy; - private final ActivateComparator activateComparator; - private final ScopeModel scopeModel; - private final AtomicBoolean destroyed = new AtomicBoolean(); + private InstantiationStrategy instantiationStrategy; + private final ActivateComparator activateComparator; + private final ScopeModel scopeModel; + private final AtomicBoolean destroyed = new AtomicBoolean(); public static void setLoadingStrategies(LoadingStrategy... strategies) { if (ArrayUtils.isNotEmpty(strategies)) { @@ -173,8 +169,7 @@ public static void setLoadingStrategies(LoadingStrategy... strategies) { * @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 @@ private static LoadingStrategy[] loadLoadingStrategies() { */ 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 static List getLoadingStrategies() { 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 @@ private static List getIgnoredInjectMethodsDesc() { 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 static ExtensionLoader getExtensionLoader(Class type) { } @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 void destroy() { 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 void destroy() { 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 String getExtensionName(T extensionInstance) { } public String getExtensionName(Class extensionClass) { - getExtensionClasses();// load class + getExtensionClasses(); // load class return cachedNames.get(extensionClass); } @@ -332,8 +325,7 @@ public List getActivateExtension(URL url, String[] values) { */ 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 List getActivateExtension(URL url, String[] values, String group) { 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 List getActivateExtension(URL url, String[] values, String group) { 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 List getActivateExtension(URL url, String[] values, String group) { // 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 List getActivateExtension(URL url, String[] values, String group) { 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 List getActivateExtension(URL url, String[] values, String group) { } 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 @@ private boolean isActive(String[][] keyPairs, URL url) { 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 void addExtension(String name, Class clazz) { 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 void addExtension(String name, Class clazz) { 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 void replaceExtension(String name, Class clazz) { 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 void replaceExtension(String name, Class clazz) { 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 void replaceExtension(String name, Class clazz) { 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 T getAdaptiveExtension() { 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 T getAdaptiveExtension() { 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 T getAdaptiveExtension() { } 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 @@ private IllegalStateException findException(String name) { } 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 @@ private T createExtension(String name, boolean wrap) { 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 @@ private T injectExtension(T instance) { 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 @@ private void initExtension(T instance) { * 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 @@ private String getSetterProperty(Method method) { * 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 @@ private Map> getExtensionClasses() { 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 @@ private Map> loadExtensionClasses() throws InterruptedException 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 @@ private void loadDirectory(Map> extensionClasses, LoadingStrate 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 @@ private void cacheDefaultExtensionName() { 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 @@ private void cacheDefaultExtensionName() { } } - 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 @@ private void loadDirectoryInternal(Map> extensionClasses, 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 @@ private void loadDirectoryInternal(Map> extensionClasses, 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 @@ private void loadDirectoryInternal(Map> extensionClasses, } } - 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); - } - } - - private void loadFromClass(Map> extensionClasses, boolean overridden, - Set urls, ClassLoader classLoader, - String[] includedPackages, String[] excludedPackages, - String[] onlyExtensionClassLoaderPackages) { + 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) { 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 @@ private void loadResource(Map> extensionClasses, ClassLoader cl } else { clazz = line; } - 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); + 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); } } 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 @@ private List getResourceContent(java.net.URL resourceURL) throws IOExcep 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 @@ private boolean isExcluded(String className, String... excludedPackages) { 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 @@ private boolean isExcludedByClassLoader(String className, ClassLoader classLoade 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 @@ private void loadClass(ClassLoader classLoader, Map> extensionC 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 @@ private boolean loadClassIfActive(ClassLoader classLoader, Class clazz) { 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 @@ private void cacheName(Class clazz, String name) { /** * 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 @@ private void cacheActivateClass(Class clazz, String name) { 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 @@ private void cacheAdaptiveClass(Class clazz, boolean overridden) { 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 @@ private T createAdaptiveExtension() { 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 @@ private Class createAdaptiveExtensionClass() { } 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 @@ private static Properties loadProperties(ClassLoader classLoader, String resourc } } } 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 @@ private static Properties loadFromUrl(java.net.URL url) { } 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 fcc48228093..af757e82210 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 @@ default Object postProcessBeforeInitialization(Object instance, String name) thr 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 57a6e1750f2..bbb2f82c5b3 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 @@ default String[] includedPackagesInCompatibleType() { * @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 47cd1fc6468..970b443b967 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 85513380850..5531e8711c4 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 void setExtensionAccessor(final ExtensionAccessor extensionAccessor) { 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 e2bde42e3ce..0350ffe6af0 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 @@ * 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 73016dcae92..400f2ea12b1 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 @@ private ActivateInfo parseActivate(Class clazz) { 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 4fb19bf22b0..6685675068c 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 @@ private OrderInfo parseOrder(Class clazz) { // 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 f78a1ba3b8b..af43c0723d8 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 @@ static Predicate and(Predicate... 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 0c715a54c53..7940d56e3be 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 @@ static T filterFirst(Iterable values, Predicate... predicates) { .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 3784069d618..a30233c56eb 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 @@ * 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 9e3a16a559c..98007dffc7f 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 @@ /** * 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 static short bytes2short(byte[] b) { * @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 static int bytes2int(byte[] b) { * @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 static float bytes2float(byte[] b) { * @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 static long bytes2long(byte[] b) { * @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 static double bytes2double(byte[] b) { * @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 static byte[] base642bytes(final String str, final int off, final int len 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 @@ private static byte[] getMD5(InputStream is, int bs) throws IOException { 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 bc0f9587929..b0badff64ec 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 @@ * 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 df96a1c1d01..7a284224f49 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 void reset() { } @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 8104ecaf9c5..d06cce19dcf 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 String toString(String charset) throws UnsupportedEncodingException { } @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 ad37476bd72..d5be46be20e 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 int read() throws IOException { @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 4ee8a75e186..836a4ff14df 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 void write(char[] cs) throws IOException { @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 Writer append(char c) { } @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 7416aa5628b..e9088a93160 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 @@ 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 static Object fromJson(String json, Type originType) throws RuntimeExcept 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())); } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/AbstractJSONImpl.java b/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/AbstractJSONImpl.java index 2ebec0c9a42..77f4d7d09ec 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/AbstractJSONImpl.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/AbstractJSONImpl.java @@ -51,8 +51,7 @@ public List getList(Map obj, String key) { } 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 List getListOfStrings(Map obj, String key) { 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 Double getNumberAsDouble(Map obj, String key) { 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 Integer getNumberAsInteger(Map obj, String key) { 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 Long getNumberAsLong(Map obj, String key) { 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 String getString(Map obj, String key) { 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 String getString(Map obj, String key) { 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 List checkStringList(List rawList) { 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 88f8920e37c..ef3e783a74e 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 AbstractJSONImpl { @Override public T toJavaObject(String json, Type type) { @@ -37,4 +37,3 @@ public String toJson(Object obj) { 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 9397183f61a..97af77891f3 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 AbstractJSONImpl { @Override @@ -37,5 +37,4 @@ public List toJavaList(String json, Class clazz) { 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 e779be06633..cd4e53a7ad4 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 AbstractJSONImpl { // weak reference of com.google.gson.Gson, prevent throw exception when init private volatile Object gsonCache = null; @@ -33,7 +33,8 @@ public T toJavaObject(String json, Type type) { @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 b33003857d5..28d822f8600 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.json.JsonMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; -import java.lang.reflect.Type; -import java.util.List; - public class JacksonImpl extends AbstractJSONImpl { private final ObjectMapper objectMapper = new ObjectMapper(); @@ -44,7 +43,8 @@ public T toJavaObject(String json, Type type) { @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 @@ private JsonMapper getJackson() { 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 1114492cc1d..09992e79169 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.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 76a6a0b8afa..c392efc5c0e 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 8392f23bdc3..98348842901 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 void destroy() { } 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 72db45e868d..4d40f428db6 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 7e615de436a..321ba7e57e5 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/Logger.java b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/Logger.java index 511dd8a66d7..776688c9b55 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 @@ -167,5 +167,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 02e1cd77442..e52f2f4d628 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 @@ 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 static void setLoggerAdapter(LoggerAdapter loggerAdapter) { * @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 static Logger getLogger(Class key) { * @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 static Logger getLogger(String key) { * @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 static ErrorTypeAwareLogger getErrorTypeAwareLogger(Class key) { * @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 static List getAvailableAdapter() { 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 static String getCurrentAdapter() { } 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 5021b3f7217..93a66922619 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 @@ -131,5 +131,4 @@ public boolean isWarnEnabled() { 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 1751c602e9e..0249bb6c4a4 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.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 File getFile() { 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 5f778885f5e..c75a71f016f 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 @@ -127,5 +127,4 @@ public boolean isWarnEnabled() { 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 43f32b17284..c153db3d144 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 JdkLoggerAdapter() { 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 Logger getLogger(String key) { @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 fad4605fa53..1fdc8ac1bc5 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.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 c8f25d59e52..f30bbcb9fe5 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.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 592c1a6717e..63350f2447c 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 @@ -221,5 +221,4 @@ public static Level getLevel(org.slf4j.Logger 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 47f4c170c39..c249394f66e 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.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 Level getLevel() { @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 8438c0ebfda..c9a9f01bf81 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; @@ -40,11 +39,12 @@ public FailsafeErrorTypeAwareLogger(Logger logger) { 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) { @@ -64,8 +64,9 @@ private String getErrorUrl(String code) { 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 ""; } 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 66e369f83ba..07e61960daf 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 void setLogger(Logger 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 @@ -274,5 +275,4 @@ public boolean isErrorEnabled() { 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 5d2c4201805..d26fc8023f7 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 static void removeBizProfiler() { 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 static List buildDetail(ProfilerEntry entry, long startTime, long 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 2025550b14c..998f92caf56 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 @@ * 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 bc1f1cee880..5bf314a7f1b 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 @@ * 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 final void close() { 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 78c075cdf38..6635af861fc 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 @@ 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 11b8a4556b4..6014f707c45 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 @@ protected T initialize() { } 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 4c265ab9b6f..0d02d09128c 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 @@ */ 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 ExecutorService getExecutorService() { 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 synchronized void destroy() { 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 void removeDisposable(Disposable disposable) { } } - // 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 d906457d669..8bb0c492ec1 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 81b9f9876f4..6f7a95fe331 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 ProviderCert(byte[] keyCertChain, byte[] privateKey, byte[] trustCert, Au 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 b694ee3bef7..23923c45ed3 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 57ae3727e2f..33dc5ca6e71 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 enum Level { */ 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 2ff75cfaa7a..d6b2e5c0c80 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 8c8c65a8d31..ef953b443e0 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 String createConsumptionReport(String interfaceName, String version, Stri 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 293bb491bff..d8eb6ac53d7 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.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 c6a40d2b0a1..a6f7432b7c9 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 Status check() { 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 411fa2f3d9e..a4cd0d3f420 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 Status check() { 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 d70a219f180..18beaf38895 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 static Status getSummaryStatus(Map statuses) { } 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 59d7414f7b4..4b8fc31ab60 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 61c0956b442..cabb9e903d9 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 @@ 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 Object get(String componentName, String key) { @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 void remove(String componentName, String key) { } 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 89d7eed79c1..1b4c2cb2359 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 @@ */ 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 f3de66fa87f..f241d751829 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 @@ */ 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 @@ private static Class loadOne(List classNames) { 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 22fde9a8638..2d0b95144f8 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 InternalRunnable(Runnable runnable){ */ @Override public void run() { - try{ + try { runnable.run(); - }finally { + } finally { InternalThreadLocal.removeAll(); } } @@ -47,7 +45,7 @@ public void run() { /** * 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 e891cd8f7fb..dc6ed89625a 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 0bb305f03f3..7b7f14aae07 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 1be3d6c5a14..474148561aa 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 @@ private static void checkAndScheduleRefresh() { // 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 f64a9f041e5..e394aeb81fd 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 b26e37eb27f..9eb3ac77fba 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 31e24a5b34f..0950362860b 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 MemorySafeLinkedBlockingQueue() { 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 b1ff4a8b08c..d06e8ea5080 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 @@ /** * 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 5ff664bc0b2..85e590ae4ac 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 void execute(Runnable runnable) { /** * 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 9dba74f897f..215e1d139ee 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 @@ 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 static CompletableFuture schedule( } }, 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 ae1c9aaaccb..8bb1460011d 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 @@ * 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 DefaultExecutorRepository(ApplicationModel applicationModel) { @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 @@ private String getExecutorKey(ServiceModel serviceModel) { } 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 ExecutorService getExecutor(URL url) { * 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 ExecutorService getExecutor(ServiceModel serviceModel, URL url) { * 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 ExecutorService getExecutor(ServiceModel serviceModel, URL url) { @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 ScheduledExecutorService getServiceExportExecutor() { 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 ExecutorService getServiceReferExecutor() { 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 @@ private Integer getExportThreadNum() { } } 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 @@ private Integer getExportThreadNum(ModuleModel moduleModel) { } 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 @@ private Integer getReferThreadNum() { } } 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 @@ private Integer getReferThreadNum(ModuleModel moduleModel) { } 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 67ab0cf2ab8..9954937de1a 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 8cbc0b28d9a..e3feee96f36 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.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 ScheduledExecutorService getSharedScheduledExecutor() { return sharedScheduledExecutor; } - public ExecutorService getPoolRouterExecutor() { return poolRouterExecutor; } @@ -206,16 +227,15 @@ public void destroy() { 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 @@ private void shutdownExecutorService(ExecutorService executorService, String nam 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 16c55331b54..223a72419de 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 @@ */ 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 AbortPolicyWithReport(String threadName, URL url) { 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 void dispatchThreadPoolExhaustedEvent(String msg) { 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 @@ private void dumpJStack() { } 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 @@ private void dumpJStack() { } }); } 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 @@ protected String getDumpPath() { 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 90419c4d900..11ee91656ae 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 Executor getExecutor(URL url) { 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 53ee25c0bbe..71e1e096ef9 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 Executor getExecutor(URL url) { // 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 a0d2a349902..69fe89c21c6 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 @@ */ 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 30bb9113928..17b804742b0 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 06acc3961f6..137f6af3629 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 Executor getExecutor(URL url) { 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 de70f3c5121..919056fd261 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 Executor getExecutor(URL url) { 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 1de2dfed4f5..a7e9d9eef0c 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 static DubboServiceAddressURL valueOf(String rawURL, URL consumerURL, Ser 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 String getAnyMethodParameter(String key) { */ @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 boolean equals(Object obj) { 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 e072b61c3c4..ad2c89845c0 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 PathURLAddress(String protocol, String username, String password, String 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 boolean equals(Object obj) { 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 String toString() { 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 String toString() { 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 cfef5228322..811fd4b4ead 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 @@ 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 ServiceAddressURL( 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 String getConcatenatedParameter(String key) { // 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 9b73daf1c6d..b16b5d03250 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 @@ 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 ServiceConfigURL(URLAddress urlAddress, URLParam urlParam, 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 ServiceConfigURL(String protocol, String username, String password, Strin 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 String toParameterString() { return parameter = super.toParameterString(); } - @Override public URL getUrlParameter(String key) { URL u = getUrls().get(key); @@ -527,7 +534,6 @@ public byte getServiceMethodParameter(String service, String method, String key, return b; } - private Map getUrls() { // concurrent initialization is tolerant if (urls == null) { @@ -553,7 +559,8 @@ private Number getCachedNumber(String method, String key) { } 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 @@ protected Map getServiceNumbers(String service) { 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 0362af72de2..bf6417e6b36 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 boolean equals(Object obj) { 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 1500787fdaf..e097ef4e405 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 @@ protected 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 @@ protected URLParam(BitSet key, Map value, Map 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 void clear() { @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 Set keySet() { @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 Collection values() { @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 @@ private URLParam doAddParameters(Map parameters, boolean skipIfP 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 @@ private URLParam doAddParameters(Map parameters, boolean skipIfP } 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 @@ private URLParam doAddParameters(Map parameters, boolean skipIfP 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 String getParameter(String key) { 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 boolean equals(Object o) { } 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 static URLParam parse(String rawParam) { 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 static URLParam parse(Map params, String rawParam) { 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 static URLParam parse(Map params, String rawParam) { } } - 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 @@ private static void addParameter(BitSet keyBit, Map valueMap, 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 b4fc76e10cf..4702976f4f2 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 c023e9c76f9..3b5012e8e32 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 @@ private static void init() { 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 6d6de7f4599..1907da9113c 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 int getIndex(String value) { 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 cfc768f3b31..e6580d45828 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 60c41e5e4a2..e4164175c69 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 c245f39b55e..0d8221a4343 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)) { @@ -159,8 +159,8 @@ static A getAnnotation(AnnotatedElement annotatedElement, * @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(); } @@ -176,8 +176,8 @@ static List getDeclaredAnnotations(AnnotatedElement annotatedElement * @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 { @@ -216,7 +216,6 @@ static List getAllDeclaredAnnotations(Class type, Predicate getAllDeclaredAnnotations(Class type, Predicate 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)); } /** @@ -247,8 +246,8 @@ static List getMetaAnnotations(Class annotatio * @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<>(); @@ -298,8 +297,8 @@ static A findAnnotation(AnnotatedElement annotatedElement * @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)); } @@ -312,8 +311,8 @@ static List findMetaAnnotations(Class List findMetaAnnotations(AnnotatedElement annotatedElement, - Class metaAnnotationType) { + static List findMetaAnnotations( + AnnotatedElement annotatedElement, Class metaAnnotationType) { List metaAnnotations = new LinkedList<>(); for (Annotation annotation : getAllDeclaredAnnotations(annotatedElement)) { @@ -331,8 +330,8 @@ static List findMetaAnnotations(AnnotatedElement annot * @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)); } @@ -346,8 +345,8 @@ static A findMetaAnnotation(AnnotatedElement annotatedEle * 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)); } @@ -373,9 +372,8 @@ static A findMetaAnnotation(AnnotatedElement annotatedEle * @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; @@ -435,8 +433,8 @@ static boolean isAnnotationPresent(AnnotatedElement annotatedElement, Class type, Class * @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 * @@ -498,9 +494,10 @@ static T getDefaultValue(Class annotationType, String * @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 e6485988672..92efcc26196 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 @@ */ 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 9c5ec040ac6..f7a88f033b8 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 static void assertTrue(boolean expression, Supplier messageSuppli 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 7aff6303aa4..da378342685 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 cc81d34d053..b7443a896b0 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 055ba48e0a6..e2bb2d484b2 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 @@ */ 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 fe3a21586f9..0fcb8ca71e6 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 static Class forName(String name) throws ClassNotFoundException { * @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 static Class resolvePrimitiveClassName(String name) { public static String toShortString(Object obj) { return ClassUtils.toShortString(obj); - } public static String simpleClassName(Class clazz) { @@ -136,10 +133,9 @@ public static boolean isPrimitive(Class type) { } 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 static Object convertPrimitive(Class type, String value) { * @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 8328cd727c2..a748b8a9e37 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 @@ -38,7 +38,8 @@ 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 { @@ -46,7 +47,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) { @@ -83,14 +85,21 @@ public static Set loadResources(String fileName, ClassLoader currentClassLo 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); } @@ -112,7 +121,6 @@ private static void setRef(URL url) { } } - // 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 845296e98a1..edea08dd159 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,8 +227,7 @@ public static Class forName(String name) throws ClassNotFoundException { * @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) { @@ -245,8 +246,7 @@ public static Class forName(String name, ClassLoader classLoader) 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); } @@ -289,7 +289,6 @@ public static String toShortString(Object obj) { return "null"; } return obj.getClass().getSimpleName() + "@" + System.identityHashCode(obj); - } public static String simpleClassName(Class clazz) { @@ -304,7 +303,6 @@ public static String simpleClassName(Class clazz) { return className; } - /** * The specified type is primitive type or simple type * @@ -339,14 +337,14 @@ public static Object convertPrimitive(FrameworkModel frameworkModel, Class ty 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. * @@ -355,8 +353,7 @@ public static Object convertPrimitive(FrameworkModel frameworkModel, Class ty * @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; @@ -409,19 +406,14 @@ public static Set> getAllInterfaces(Class type, Predicate>. 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(); } @@ -445,7 +437,6 @@ public static Set> getAllInheritedTypes(Class type, Predicate tClass) { 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; } @@ -572,21 +562,21 @@ private static boolean matchPrimitive(Class from, Class to) { 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; } @@ -600,14 +590,13 @@ public static String[] getDeclaredMethodNames(Class tClass) { 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 52c6f071882..df6388c936d 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 static Map flip(Map map) { 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 static Map objToMap(Object object) throws IllegalAccessExcep 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 static Set toTreeSet(Set set) { } 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 fb4d53ccbdb..3eb4e1860a5 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 static Object compatibleTypeConvert(Object value, Class type) { 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 static Object compatibleTypeConvert(Object value, Class type) { 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 static Object compatibleTypeConvert(Object value, Class type) { } 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 static Object compatibleTypeConvert(Object value, Class type) { 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 static Object compatibleTypeConvert(Object value, Class type) { } 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 static Object compatibleTypeConvert(Object value, Class type) { 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 7e71a1bab02..0800fb9ed3b 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 @@ /** * ConcurrentHashMap util */ - public class ConcurrentHashMapUtils { /** @@ -42,11 +40,11 @@ public static V computeIfAbsent(ConcurrentMap map, K key, Function< // 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 static V computeIfAbsent(ConcurrentMap map, K key, Function< 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 1e8ea4cb534..e527d028de4 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 boolean remove(Object o) { 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 b45a57a2f72..74ad48add58 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 @@ 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 static boolean isNotEmpty(String value) { 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 static boolean isDefault(String value) { * @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 static Properties loadProperties(Set classLoaders, String fi * * @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 static Properties loadProperties(Set classLoaders, String fi 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 static Properties loadProperties(Set classLoaders, String fi 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 static Properties loadProperties(Set classLoaders, String fi 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 static Properties loadProperties(Set classLoaders, String fi 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 static Properties loadProperties(Set classLoaders, String fi } } } 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 static String loadMigrationRule(Set classLoaders, String fil 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 static String loadMigrationRule(Set classLoaders, String fil 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 static String loadMigrationRule(Set classLoaders, String fil } } } 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 @@ private static boolean checkFileNameExist(String fileName) { 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 9c863d717e9..798d3e4d234 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 @@ private static long[] loadPrefix(Set allowedList) { return array; } - /** * Try load class * @@ -103,8 +103,9 @@ private static long[] loadPrefix(Set allowedList) { 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 @@ private Class loadClass0(ClassLoader classLoader, String className) throws Cl } 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 @@ private Class loadClass0(ClassLoader classLoader, String className) throws Cl 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 @@ private Class loadClass0(ClassLoader classLoader, String className) throws Cl 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 @@ private Class loadClass0(ClassLoader classLoader, String className) throws Cl 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 4f9d72b4edc..f9ac324c67c 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 @@ private Log parseLog(LoggingEvent event) { 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 f6e1ce41ca2..a5ca54ff13f 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 @@ 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 99f47d7bd31..cc233eda25c 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 @@ static T setFieldValue(Object object, Field field, T value) { } 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 07c3e32ca41..e14f6e1da9b 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 void set(T value) { 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 2f79f6c1e05..0578feed909 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 static long write(InputStream is, OutputStream os, int bufferSize) throws * @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 static void appendLines(File file, String[] lines) throws IOException { writeLines(new FileOutputStream(file, true), lines); } - /** * use like spring code * @@ -260,8 +259,7 @@ public static URL getURL(String resourceLocation) throws FileNotFoundException { 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 static URL getURL(String resourceLocation) throws FileNotFoundException { 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 f656a6942c6..6897bfae0aa 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 @@ private static JRE getJre() { 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 2e8f9123328..bbd6df09b72 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.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 static void jstack(OutputStream stream) throws Exception { } 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 @@ private static String getThreadDumpString(ThreadInfo threadInfo) { // 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/JsonUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JsonUtils.java index 88fd380b5f5..0d259c6e51b 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 @@ -63,10 +63,7 @@ protected static JSON getJson() { } if (json == 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 { JSON instance = jsonClass.getConstructor().newInstance(); @@ -80,8 +77,9 @@ protected static JSON getJson() { } } if (json == 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."); } } } @@ -101,64 +99,51 @@ public static T toJavaObject(String json, Type type) { 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 dcc6a945b69..1e3965ec69f 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 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 @@ static class CacheNode { V value; CacheDeque owner; - CacheNode() { - } + CacheNode() {} CacheNode(final K key, final V value) { this.key = key; @@ -190,8 +187,7 @@ static class CacheNode { * @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 @@ static CacheNode withdrawNode( } return node; } - } /** @@ -280,7 +275,5 @@ CacheNode pollFirst() { 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 06025364029..2a725e93343 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 void setMaxCapacity(int maxCapacity) { 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 425e06491c2..76d6c19cb71 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 int getMaxCapacity() { 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 7a3d028e7f9..3943b67687d 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 boolean equals(Object obj) { } 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 99ba5ab8282..79855ab882c 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 @@ public class LogHelper { - private LogHelper() { - } + private LogHelper() {} public static void trace(Logger logger, String msg) { if (logger == null) { @@ -172,5 +171,4 @@ public static void error(Logger logger, String msg, Throwable e) { 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 35c609bd114..5319206663d 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 @@ 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 static boolean checkNoError() { } else { return false; } - } public static int findName(String expectedLogName) { @@ -126,6 +125,5 @@ public static void printList(List list) { 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 a79dffe811e..288486da0bb 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 String getMd5(String input) { } 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 daf92730207..a5a1655a611 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 @@ static boolean isPrivate(Member member) { 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 8270c1da675..715100c2abd 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 @@ */ 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 a5ea0d6bffb..a4b829ce455 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 @@ 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 @@ static boolean isSetter(Method method) { 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 @@ static boolean isDeprecated(Method method) { 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 @@ static Predicate excludedDeclaredClass(Class declaredClass) { * @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 @@ static List getAllMethods(Class declaringClass, Predicate... 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 @@ static T invokeMethod(Object object, String methodName, Object... methodPara 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 @@ static T invokeMethod(Object object, String methodName, Object... methodPara return value; } - /** * Tests whether one method, as a member of a given type, * overrides another method. @@ -458,4 +463,3 @@ static long invokeAndReturnLong(Method method, Object targetObj) { } } } - diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NativeUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NativeUtils.java index 5ab9cff6af5..f73659ddb1c 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NativeUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NativeUtils.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 static org.apache.dubbo.common.constants.CommonConstants.NATIVE; @@ -24,5 +23,4 @@ public abstract class NativeUtils { public static boolean isNative() { return Boolean.parseBoolean(System.getProperty(NATIVE, "false")); } - } 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 d33fcea5b05..6a04983b051 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.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 static synchronized int getAvailablePort(int port) { return port; } - /** * Check the port whether is in use in os * @param port port to check @@ -173,9 +173,7 @@ public static boolean isValidAddress(String address) { } 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 static boolean isAnyHost(String host) { 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 static boolean isValidLocalHost(String host) { } 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 @@ static boolean isValidV4Address(InetAddress address) { 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 static String getLocalHostV6() { 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 @@ private static Inet6Address getLocalAddress0V6() { 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 @@ private static boolean isUniqueLocalAddress(InetAddress address) { */ 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 static String getLocalHostName() { 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 static String toURL(String protocol, String host, int port, String path) } @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 static boolean matchIpExpression(String pattern, String host, int port) t */ 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 static boolean matchIpRange(String pattern, String host, int port) throws 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 @@ private static boolean ipPatternContainExpression(String pattern) { 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 @@ private static Integer getNumOfIpSegment(String ipSegment, boolean isIpv4) { 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 static boolean isIPV6URLStdFormat(String ip) { } 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 static String getLegalIP(String ip) { 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 b40e26dceba..5975c8617ec 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 @@ static String buildPath(String rootPath, String... subPaths) { 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 @@ static String normalize(String path) { } 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 8dcea2fcefe..cdf625049b1 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 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 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); public static Object[] generalize(Object[] objs) { Object[] dests = new Object[objs.length]; @@ -137,7 +145,8 @@ private static Object generalize(Object pojo, Map history) { 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 @@ private static Object generalize(Object pojo, Map history) { 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 @@ private static Object generalize(Object pojo, Map history) { 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 @@ private static Map createMap(Map src) { } 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 @@ private static Object realize0(Object pojo, Class type, Type genericType, fin 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 @@ private static Object realize1(Object pojo, Class type, Type genericType, fin } 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 @@ private static Object realize1(Object pojo, Class type, Type genericType, fin } 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 @@ private static Object realize1(Object pojo, Class type, Type genericType, fin 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 @@ private static Object realize1(Object pojo, Class type, Type genericType, fin map.remove("class"); } } catch (Exception e) { - //ignore error + // ignore error map = (Map) pojo; } } else { @@ -475,8 +499,8 @@ private static Object realize1(Object pojo, Class type, Type genericType, fin 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 @@ private static Object realize1(Object pojo, Class type, Type genericType, fin } 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 @@ private static Object realize1(Object pojo, Class type, Type genericType, fin } 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 @@ private static Object realize1(Object pojo, Class type, Type genericType, fin 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 @@ private static Object realize1(Object pojo, Class type, Type genericType, fin 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 @@ private static Object realize1(Object pojo, Class type, Type genericType, fin 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 @@ private static Object newInstance(Class cls) { } 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 @@ declared by the class represented by this Class object. 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 @@ private static Field getAndCacheField(Class cls, String fieldName) { 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 @@ private static Field getField(Class cls, String fieldName) { 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 @@ private static Object getFieldObject(Object mapObject, Type fieldType) throws Re 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 @@ private static Object convertClassType(Object mapObject, Class type) throws R } @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 @@ private static Object convertParameterizedType(Object mapObject, ParameterizedTy 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 @@ private static Object convertParameterizedType(Object mapObject, ParameterizedTy 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 b32cf2d1e46..aa0a04f75d4 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.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 static boolean isPrimitives(Class cls) { } 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 static String getName(Class c) { do { sb.append("[]"); c = c.getComponentType(); - } - while (c.isArray()); + } while (c.isArray()); return c.getName() + sb.toString(); } @@ -910,7 +915,8 @@ public static Method findMethodByMethodSignature(Class clazz, String methodNa 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 static Method findMethodByMethodSignature(Class clazz, String methodNa types[i] = ReflectUtils.name2class(parameterTypes[i]); } method = clazz.getMethod(methodName, types); - } return method; } @@ -944,7 +949,7 @@ public static Method findMethodByMethodName(Class clazz, String methodName) 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 static Constructor findConstructor(Class clazz, Class paramType) */ 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 static boolean isBeanPropertyReadMethod(Method method) { && 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 static Map getBeanPropertyFields(Class cl) { 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 static Type[] getReturnTypes(Method method) { genericReturnType = null; } } - return new Type[]{returnType, genericReturnType}; + return new Type[] {returnType, genericReturnType}; } /** @@ -1212,8 +1217,8 @@ public static Set findParameterizedTypes(Class sourceClass 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 static Set findParameterizedTypes(Class sourceClass .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 static T getProperty(Object bean, String methodName) { try { return method.getMethod().invoke(bean); } catch (Exception e) { - //ignore + // ignore } return null; - }).get(); + }) + .get(); } catch (Exception e) { } @@ -1352,10 +1357,11 @@ public static boolean isJdk(Class clazz) { * @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 bf5ec423e2f..b1fbeb520b9 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 @@ */ public class ReflectionUtils { - private ReflectionUtils() { - } + private ReflectionUtils() {} /** * Retrieves the value of the specified field from the given object. @@ -65,8 +64,8 @@ public static Object getField(Object source, String fieldName) { 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 static boolean match(Class clazz, Class interfaceClass, Object even 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 cb7f24c6c08..e91c91ff43d 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 String getProperty(String key) { } // 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 ba7227a1ac9..f49f7cfbfb7 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 @@ 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 SerializeSecurityConfigurator(ModuleModel moduleModel) { } public void refreshCheck() { - 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)); + 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 @@ private void refreshClassLoader(ClassLoader classLoader) { } private void refreshConfig() { - String allowedClassList = System.getProperty(CLASS_DESERIALIZE_ALLOWED_LIST, "").trim(); - String blockedClassList = System.getProperty(CLASS_DESERIALIZE_BLOCKED_LIST, "").trim(); + String allowedClassList = + System.getProperty(CLASS_DESERIALIZE_ALLOWED_LIST, "").trim(); + String blockedClassList = + System.getProperty(CLASS_DESERIALIZE_BLOCKED_LIST, "").trim(); if (StringUtils.isNotEmpty(allowedClassList)) { String[] classStrings = allowedClassList.trim().split(","); @@ -133,7 +142,12 @@ private void loadAllow(ClassLoader classLoader) { serializeSecurityManager.addToAlwaysAllowed(line); } } catch (IOException e) { - logger.error(COMMON_IO_EXCEPTION, "", "", "Failed to load allow class list! Will ignore allow lis from " + u, e); + logger.error( + COMMON_IO_EXCEPTION, + "", + "", + "Failed to load allow class list! Will ignore allow lis from " + u, + e); } } } @@ -152,14 +166,21 @@ private void loadBlocked(ClassLoader classLoader) { serializeSecurityManager.addToDisAllowed(line); } } catch (IOException e) { - logger.error(COMMON_IO_EXCEPTION, "", "", "Failed to load blocked class list! Will ignore blocked lis from " + u, e); + logger.error( + COMMON_IO_EXCEPTION, + "", + "", + "Failed to load blocked class list! Will ignore blocked lis from " + u, + e); } } } public void refreshStatus() { - Optional 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 @@ private void checkClass(Set markedClass, Class clazz) { return; } String className = clazz.getName(); - if (className.startsWith("java.") || className.startsWith("javax.") || className.startsWith("com.sun.") || - className.startsWith("sun.") || className.startsWith("jdk.")) { + if (className.startsWith("java.") + || className.startsWith("javax.") + || className.startsWith("com.sun.") + || className.startsWith("sun.") + || className.startsWith("jdk.")) { return; } @@ -314,8 +338,11 @@ private void checkClass(Set markedClass, Class clazz) { private void addToAllow(String className) { // ignore jdk - if (className.startsWith("java.") || className.startsWith("javax.") || className.startsWith("com.sun.") || - className.startsWith("sun.") || className.startsWith("jdk.")) { + if (className.startsWith("java.") + || className.startsWith("javax.") + || className.startsWith("com.sun.") + || className.startsWith("sun.") + || className.startsWith("jdk.")) { serializeSecurityManager.addToAllowed(className); return; } @@ -323,9 +350,8 @@ private void addToAllow(String className) { // add group package String[] subs = className.split("\\."); if (subs.length > 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 66158ca0c25..1b07de5392d 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.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 3bc86a869e5..f2efa8ede12 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 @@ private Annotation getServiceAnnotation(Class serviceType) { } 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 58241aadba8..13e7ae4e7d4 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 @@ /** * 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 534a612bfdb..bf671ddd18a 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 static Predicate of(Class targetClass) { 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 31372ca8a37..e46c77e0592 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 @@ /** * 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 static boolean isNumeric(String str, boolean allowDot) { return true; } - /** * @param e * @return string @@ -773,10 +772,7 @@ public static Set splitToSet(String value, char separatorChar, boolean t 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)); } /** @@ -976,9 +972,7 @@ private static boolean isWord(String str) { } 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; @@ -1080,7 +1074,7 @@ public static String[] delimitedListToStringArray(String str, String delimiter, 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; @@ -1224,8 +1218,8 @@ public static byte decodeHexByte(CharSequence s, int pos) { 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 0355b6cf9ad..d6b18476f34 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 507146736a7..0c18a0b1b3c 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 @@ 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 0555602e5c2..7b45759ce3c 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 @@ static List getGenericTypes(Type type, Predicate getAllGenericSuperClasses(Type type, Predicate allGenericSuperClasses = allTypes - .stream() + List allGenericSuperClasses = allTypes.stream() .map(Class::getGenericSuperclass) .filter(TypeUtils::isParameterizedType) .map(ParameterizedType.class::cast) @@ -201,8 +197,7 @@ static List getAllGenericInterfaces(Type type, Predicate allGenericInterfaces = allTypes - .stream() + List allGenericInterfaces = allTypes.stream() .map(Class::getGenericInterfaces) .map(Arrays::asList) .flatMap(Collection::stream) @@ -218,8 +213,6 @@ static String getClassName(Type type) { } 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 0167438a1e3..ec1745e431f 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 static List parseURLs(String address, Map defaults) } 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 static Map> convertRegister(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 static Map convertSubscribe(Map subscribe 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 static Map> revertNotify(Map revertForbid(List forbid, Set subscribed) { if (CollectionUtils.isNotEmpty(forbid)) { List newForbid = new ArrayList<>(); @@ -378,9 +379,9 @@ public static URL getEmptyUrl(String service, String category) { 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 static boolean isMatch(URL consumerUrl, URL providerUrl) { 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 static boolean isMatch(URL consumerUrl, URL providerUrl) { 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 @@ else if (i == 0) { } 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 static List classifyUrls(List urls, Predicate predicate) { } 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 static URL valueOf(String url) { 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 cda3390abd1..054468a54ba 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 @@ -94,7 +94,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"}; /** * The config id @@ -177,11 +177,13 @@ public static void appendAttributes(Map parameters, Object confi 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 @@ private static void appendParameters0(Map parameters, Object con 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,7 @@ private static String calculateAttributeFromGetter(String getter) { private static void invokeSetParameters(Class c, Object o, Map map) { try { - Method method = findMethodByMethodSignature(c, "setParameters", new String[]{Map.class.getName()}); + Method method = findMethodByMethodSignature(c, "setParameters", new String[] {Map.class.getName()}); if (method != null && isParametersSetter(method)) { method.invoke(o, map); } @@ -317,27 +319,29 @@ private static Map invokeGetParameters(Class c, Object o) { 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 +355,11 @@ private static boolean isNestedGetter(Object obj, Method method) { 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 +435,8 @@ public final void setScopeModel(ScopeModel scopeModel) { 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 +461,9 @@ protected void checkScopeModel(ScopeModel scopeModel) { */ 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 +492,11 @@ protected void appendAnnotation(Class annotationClass, Object annotation) { 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 +617,8 @@ public void overrideWithConfig(AbstractConfig newOne, boolean overrideAll) { 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 +667,8 @@ public void overrideWithConfig(AbstractConfig newOne, boolean overrideAll) { } // 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 +681,12 @@ public void overrideWithConfig(AbstractConfig newOne, boolean overrideAll) { } } 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 +702,12 @@ public void refresh() { 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 +746,9 @@ protected void refreshWithPrefixes(List prefixes, ConfigMode configMode) 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 +757,12 @@ protected void refreshWithPrefixes(List prefixes, ConfigMode configMode) 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 +770,8 @@ private void assignProperties(Object obj, Environment environment, Map 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 +786,26 @@ private void assignProperties(Object obj, Environment environment, Map urls = new ArrayList(); + protected final transient List urls = new ArrayList(); @Transient public List getExportedUrls() { @@ -254,8 +252,8 @@ protected void checkRegistry() { 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); } } } @@ -295,7 +293,9 @@ protected void appendMetricsCompatible(Map map) { protected String[] methods(Class interfaceClass) { boolean isNative = getEnvironment().getConfiguration().getBoolean(NATIVE, false); if (isNative) { - 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); } @@ -343,8 +343,8 @@ protected void processExtraRefresh(String preferredPrefix, InmemoryConfiguration // 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); @@ -358,22 +358,24 @@ protected void processExtraRefresh(String preferredPrefix, InmemoryConfiguration List methodConfigs = this.getMethods(); if (methodConfigs != null && methodConfigs.size() > 0) { // whether ignore invalid method config - Object ignoreInvalidMethodConfigVal = getEnvironment().getConfiguration() - .getProperty(ConfigKeys.DUBBO_CONFIG_IGNORE_INVALID_METHOD_CONFIG, "false"); + 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); } } - } /** @@ -386,12 +388,12 @@ protected boolean canSkipInterfaceCheck() { 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; @@ -400,10 +402,11 @@ protected boolean verifyMethodConfig(MethodConfig methodConfig, Class interfa } } - 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; @@ -464,24 +467,25 @@ protected void checkStubAndLocal(Class interfaceClass) { 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()); } } @@ -508,7 +512,6 @@ private void convertRegistryIdsToRegistries() { }); setRegistries(tmpRegistries); } - } protected boolean notHasSelfRegistryProperty() { @@ -723,7 +726,6 @@ public void setRegistryIds(String registryIds) { this.registryIds = registryIds; } - public List getMethods() { return methods; } @@ -840,7 +842,8 @@ public MetadataReportConfig getMetadataReportConfig() { if (metadataReportConfig != null) { return metadataReportConfig; } - Collection metadataReportConfigs = getConfigManager().getMetadataConfigs(); + Collection metadataReportConfigs = + getConfigManager().getMetadataConfigs(); if (CollectionUtils.isNotEmpty(metadataReportConfigs)) { return metadataReportConfigs.iterator().next(); } @@ -895,11 +898,15 @@ protected void initServiceMetadata(AbstractInterfaceConfig interfaceConfig) { } 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() { @@ -934,5 +941,4 @@ public ClassLoader getInterfaceClassLoader() { 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 f0367c6c5df..80ec1b60f31 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 @@ -102,9 +102,7 @@ public abstract class AbstractMethodConfig extends AbstractConfig { */ protected Integer forks; - public AbstractMethodConfig() { - - } + public AbstractMethodConfig() {} public AbstractMethodConfig(ModuleModel moduleModel) { super(moduleModel); @@ -125,7 +123,8 @@ protected ScopeModel getDefaultModel() { @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); } } @@ -246,5 +245,4 @@ public Map getParameters() { 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 058f1d1622f..cf07233b3fe 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 void setSticky(Boolean sticky) { 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 6b5545c62f6..a88bbd83691 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 @@ -155,8 +155,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 f5da6adb77b..3666135ae85 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 @@ -125,6 +125,7 @@ public class ApplicationConfig extends AbstractConfig { * Registry centers */ private List registries; + private String registryIds; /** @@ -255,8 +256,7 @@ public class ApplicationConfig extends AbstractConfig { */ private String executorManagementMode; - public ApplicationConfig() { - } + public ApplicationConfig() {} public ApplicationConfig(ApplicationModel applicationModel) { super(applicationModel); @@ -281,7 +281,7 @@ protected void checkDefault() { try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { - LOGGER.warn(COMMON_UNEXPECTED_EXCEPTION,"","","Failed to get the hostname of current instance.", e); + LOGGER.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "Failed to get the hostname of current instance.", e); hostname = "UNKNOWN"; } } @@ -340,16 +340,18 @@ public String getEnvironment() { } public void setEnvironment(String 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.", - environment, - DEVELOPMENT_ENVIRONMENT, - TEST_ENVIRONMENT, - PRODUCTION_ENVIRONMENT, - PRODUCTION_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.", + environment, + DEVELOPMENT_ENVIRONMENT, + TEST_ENVIRONMENT, + PRODUCTION_ENVIRONMENT, + PRODUCTION_ENVIRONMENT)); } this.environment = environment; } @@ -676,7 +678,6 @@ public void setMetadataServiceProtocol(String metadataServiceProtocol) { this.metadataServiceProtocol = metadataServiceProtocol; } - @Parameter(key = LIVENESS_PROBE_KEY) public String getLivenessProbe() { return livenessProbe; @@ -704,7 +705,6 @@ public void setStartupProbe(String startupProbe) { this.startupProbe = startupProbe; } - public String getSerializeCheckStatus() { return serializeCheckStatus; } 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 74d906cf2ec..399807126aa 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 void setCallback(Boolean callback) { public Boolean isCallback() { return callback; } - } 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 494c8b515d9..8d15f506d97 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 @@ -66,6 +66,7 @@ public class ConfigCenterConfig extends AbstractConfig { * The default value is CommonConstants.DUBBO */ private String group; + private String username; private String password; @@ -112,8 +113,7 @@ public class ConfigCenterConfig extends AbstractConfig { private Map appExternalConfiguration; - public ConfigCenterConfig() { - } + public ConfigCenterConfig() {} public ConfigCenterConfig(ApplicationModel applicationModel) { super(applicationModel); @@ -332,5 +332,4 @@ public void updateParameters(Map parameters) { 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 4e3297bfbb1..a3f20e0dc77 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 ed2e821368f..da6ab9f5d7a 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,5 +151,5 @@ public interface Constants { String CLIENT_THREAD_POOL_NAME = "DubboClientHandler"; - String REST_PROTOCOL="rest"; + String REST_PROTOCOL = "rest"; } 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 10faac70159..b34ee3c1403 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 ConsumerConfig(ModuleModel moduleModel) { 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 ac0506554ec..b2c32fab5a2 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 @@ -123,8 +123,7 @@ public class MetadataReportConfig extends AbstractConfig { private Boolean reportDefinition; - public MetadataReportConfig() { - } + public MetadataReportConfig() {} public MetadataReportConfig(ApplicationModel applicationModel) { super(applicationModel); @@ -155,9 +154,15 @@ public URL toUrl() throws IllegalArgumentException { 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 914002e1a49..000b447cac9 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 @@ private void refreshArgument(ArgumentConfig argument, InmemoryConfiguration subP 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 @@ private void refreshArgument(ArgumentConfig argument, InmemoryConfiguration subP 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 String getName() { 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 d1cf0c1d434..8d7ea993928 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 @@ -114,9 +114,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 859d6678e46..743345394d0 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 @@ protected void checkDefault() { @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 b3755878f8b..551d66cc052 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 @@ -64,8 +64,7 @@ public class MonitorConfig extends AbstractConfig { */ private Map parameters; - public MonitorConfig() { - } + public MonitorConfig() {} public MonitorConfig(ApplicationModel applicationModel) { super(applicationModel); @@ -153,5 +152,4 @@ public void setInterval(String interval) { 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 c6be90b3dbf..5fba5d3020d 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 @@ -95,7 +95,6 @@ public class ProtocolConfig extends AbstractConfig { */ private Integer queues; - /** * Thread pool exhausted listeners */ @@ -206,7 +205,7 @@ public class ProtocolConfig extends AbstractConfig { /** * whether it is a persistent connection */ - //TODO add this to provider config + // TODO add this to provider config private Boolean keepAlive; // TODO add this to provider config @@ -229,8 +228,7 @@ public class ProtocolConfig extends AbstractConfig { */ private String extProtocol; - public ProtocolConfig() { - } + public ProtocolConfig() {} public ProtocolConfig(ApplicationModel applicationModel) { super(applicationModel); @@ -617,20 +615,20 @@ public void mergeProtocol(ProtocolConfig sourceConfig) { 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 497e78b78c9..6d70347197f 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 Boolean getExportBackground() { 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 962b74c2f65..4394f1dfaf1 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 @@ -60,7 +60,6 @@ public abstract class ReferenceConfigBase extends AbstractReferenceConfig { */ protected Class interfaceClass; - /** * The url for peer-to-peer invocation */ @@ -134,8 +133,8 @@ protected void preProcessRefresh() { 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); @@ -228,8 +227,9 @@ public static Class determineInterfaceClass(String generic, String interfaceN 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)) { @@ -260,12 +260,15 @@ public void setInterface(Class interfaceClass) { } 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()); } } @@ -329,9 +332,18 @@ protected void resolveFile() { 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."); } } } @@ -353,7 +365,9 @@ public String getUniqueServiceName() { @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 @@ -384,5 +398,4 @@ public final T get() { 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 91bc4b826eb..294916c8b55 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 @@ -194,8 +194,7 @@ public void setSecure(String secure) { 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 93279cf6571..07b5158ccd0 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 @@ -51,7 +51,6 @@ public abstract class ServiceConfigBase extends AbstractServiceConfig { private static final long serialVersionUID = 3033787999037024738L; - /** * The interface class of the exported service */ @@ -82,7 +81,6 @@ public abstract class ServiceConfigBase extends AbstractServiceConfig { */ protected volatile String generic; - public ServiceConfigBase() { serviceMetadata = new ServiceMetadata(); serviceMetadata.addAttribute("ORIGIN_CONFIG", this); @@ -145,14 +143,15 @@ protected void checkRef() { } 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) { @@ -173,8 +172,8 @@ protected void preProcessRefresh() { 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); @@ -228,8 +227,9 @@ protected void completeCompoundConfigs() { 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)); } } @@ -267,8 +267,8 @@ public Class getInterfaceClass() { } 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); @@ -285,7 +285,6 @@ public void setInterfaceClass(Class interfaceClass) { setInterface(interfaceClass); } - public void setInterface(Class interfaceClass) { // rest protocol allow set impl class if (interfaceClass != null && !interfaceClass.isInterface() && !canSkipInterfaceCheck()) { @@ -393,7 +392,9 @@ public String getGroup() { @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 5bf5a57b037..ba53458d7e3 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 @@ -69,8 +69,7 @@ public class SslConfig extends AbstractConfig { private String caCertPath; private String oidcTokenPath; - public SslConfig() { - } + public SslConfig() {} public SslConfig(ApplicationModel applicationModel) { super(applicationModel); @@ -183,7 +182,8 @@ public void setOidcTokenPath(String oidcTokenPath) { @Transient public InputStream getServerKeyCertChainPathStream() throws IOException { if (serverKeyCertChainPath != null) { - serverKeyCertChainPathStream = IOUtils.getURL(serverKeyCertChainPath).openStream(); + serverKeyCertChainPathStream = + IOUtils.getURL(serverKeyCertChainPath).openStream(); } return serverKeyCertChainPathStream; } @@ -207,7 +207,8 @@ public void setServerPrivateKeyPathStream(InputStream serverPrivateKeyPathStream @Transient public InputStream getServerTrustCertCollectionPathStream() throws IOException { if (serverTrustCertCollectionPath != null) { - serverTrustCertCollectionPathStream = IOUtils.getURL(serverTrustCertCollectionPath).openStream(); + serverTrustCertCollectionPathStream = + IOUtils.getURL(serverTrustCertCollectionPath).openStream(); } return serverTrustCertCollectionPathStream; } @@ -219,7 +220,8 @@ public void setServerTrustCertCollectionPathStream(InputStream serverTrustCertCo @Transient public InputStream getClientKeyCertChainPathStream() throws IOException { if (clientKeyCertChainPath != null) { - clientKeyCertChainPathStream = IOUtils.getURL(clientKeyCertChainPath).openStream(); + clientKeyCertChainPathStream = + IOUtils.getURL(clientKeyCertChainPath).openStream(); } return clientKeyCertChainPathStream; } @@ -243,7 +245,8 @@ public void setClientPrivateKeyPathStream(InputStream clientPrivateKeyPathStream @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 3a7e4e3b917..c8774ed4bac 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; @@ -57,8 +56,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/annotation/Argument.java b/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/Argument.java index 6a0da8ea8d9..238cbbc809d 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 @@ @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/DubboService.java b/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/DubboService.java index d2d3cb69f00..a945909edfd 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/DubboService.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/DubboService.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config.annotation; - import org.apache.dubbo.common.constants.ClusterRules; import org.apache.dubbo.common.constants.LoadbalanceRules; 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 eb4bc74abf9..94f3e78d559 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 @@ * 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/annotation/ProvidedBy.java b/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/ProvidedBy.java index b8c0013bdad..7c8e88f5931 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/ProvidedBy.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/ProvidedBy.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config.annotation; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/Service.java b/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/Service.java index e712e4ab2d7..aba87ddc367 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/Service.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/Service.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config.annotation; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; 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 0f8a0e23d4b..5a15b14ac2f 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,8 +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; @@ -122,14 +123,15 @@ public void initialize() throws IllegalStateException { 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); } @@ -159,7 +161,8 @@ public final T addConfig(AbstractConfig config) { 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)) { @@ -193,8 +196,7 @@ protected boolean isSupportConfigType(Class type) { * @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; @@ -217,9 +219,14 @@ private C addIfAbsent(C config, Map config 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 @@ -250,11 +257,11 @@ protected C getSingleConfig(String configType) throws 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(); } @@ -340,8 +347,8 @@ protected C getConfigByName(Class cls, S .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); } @@ -365,9 +372,7 @@ protected Optional findConfigByValue(Collection } // 2. find equal config - prevConfig = values.stream() - .filter(val -> isEquals(val, config)) - .findFirst(); + prevConfig = values.stream().filter(val -> isEquals(val, config)).findFirst(); return prevConfig; } @@ -395,7 +400,9 @@ protected boolean isEquals(AbstractConfig oldOne, AbstractConfig newOne) { 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; } @@ -409,8 +416,7 @@ static Boolean isDefaultConfig(C config) { 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) { @@ -418,8 +424,7 @@ static List getDefaultConfigs(Map confi } // find isDefault() == null - list = configsMap.values() - .stream() + list = configsMap.values().stream() .filter(c -> AbstractConfigManager.isDefaultConfig(c) == null) .collect(Collectors.toList()); return list; @@ -431,19 +436,25 @@ protected Optional checkUniqueConfig(Map 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); } @@ -451,7 +462,11 @@ protected Optional checkUniqueConfig(Map Optional checkUniqueConfig(Map Optional checkUniqueConfig(Map List loadConfigsOfTypeFromProps(Class cl 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; @@ -508,7 +532,12 @@ public List loadConfigsOfTypeFromProps(Class cl 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) { @@ -528,7 +557,8 @@ public List loadConfigsOfTypeFromProps(Class cl 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); @@ -539,7 +569,8 @@ public List loadConfigsOfTypeFromProps(Class cl 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; @@ -567,7 +598,6 @@ private Set getConfigIdsFromProps(Class clazz) return ConfigurationUtils.getSubIds(environment.getConfigurationMaps(), prefix); } - protected void checkDefaultAndValidateConfigs(Class configType) { try { if (shouldAddDefaultConfig(configType)) { @@ -626,11 +656,11 @@ private ConfigValidator getConfigValidator() { * @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; @@ -644,11 +674,7 @@ private boolean shouldAddDefaultConfig(Class clazz 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 e737e8971e8..58d7abf7cbc 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 @@ -57,15 +57,22 @@ public class ConfigManager extends AbstractConfigManager implements ApplicationE public static final String BEAN_NAME = "dubboConfigManager"; 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)); - } - - -// ApplicationConfig correlative methods + 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 /** * Set application config @@ -135,7 +142,8 @@ public void addConfigCenters(Iterable configCenters) { } public Optional> getDefaultConfigCenter() { - Collection defaults = getDefaultConfigs(getConfigsMap(getTagName(ConfigCenterConfig.class))); + Collection defaults = + getDefaultConfigs(getConfigsMap(getTagName(ConfigCenterConfig.class))); if (CollectionUtils.isEmpty(defaults)) { defaults = getConfigCenters(); } @@ -165,7 +173,8 @@ public Collection getMetadataConfigs() { } public Collection getDefaultMetadataConfigs() { - Collection defaults = getDefaultConfigs(getConfigsMap(getTagName(MetadataReportConfig.class))); + Collection defaults = + getDefaultConfigs(getConfigsMap(getTagName(MetadataReportConfig.class))); if (CollectionUtils.isEmpty(defaults)) { return getMetadataConfigs(); } @@ -201,7 +210,6 @@ public Collection getProtocols() { return getConfigs(getTagName(ProtocolConfig.class)); } - // RegistryConfig correlative methods public void addRegistry(RegistryConfig registryConfig) { @@ -226,7 +234,6 @@ public Collection getRegistries() { return getConfigs(getTagName(RegistryConfig.class)); } - @Override public void refreshAll() { // refresh all configs here @@ -254,7 +261,7 @@ public void loadConfigs() { // load dubbo.metrics.xxx loadConfigsOfTypeFromProps(MetricsConfig.class); - //load dubbo.tracing.xxx + // load dubbo.tracing.xxx loadConfigsOfTypeFromProps(TracingConfig.class); // load multiple config types: @@ -268,7 +275,7 @@ public void loadConfigs() { loadConfigsOfTypeFromProps(MetadataReportConfig.class); // config centers has bean loaded before starting config center - //loadConfigsOfTypeFromProps(ConfigCenterConfig.class); + // loadConfigsOfTypeFromProps(ConfigCenterConfig.class); refreshAll(); @@ -304,8 +311,8 @@ private void checkConfigs() { } 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 7d20b1b6581..ea6b5e6661c 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 @@ 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 0527fdaf183..03e873bd5bd 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 @@ -62,9 +62,15 @@ public class ModuleConfigManager extends AbstractConfigManager implements Module private final Map serviceConfigCache = new ConcurrentHashMap<>(); 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(); } @@ -188,11 +194,11 @@ public void clear() { this.serviceConfigCache.clear(); } - @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) { @@ -230,7 +236,8 @@ private AbstractInterfaceConfig findDuplicatedInterfaceConfig(AbstractInterfaceC 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); @@ -248,10 +255,10 @@ private AbstractInterfaceConfig findDuplicatedInterfaceConfig(AbstractInterfaceC } 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); @@ -273,7 +280,8 @@ private void removeInterfaceConfig(AbstractInterfaceConfig config) { 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); } @@ -295,7 +303,6 @@ public void loadConfigs() { checkDefaultAndValidateConfigs(ModuleConfig.class); } - // // Delegate read application configs // 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 beba9b5ddd2..8b826c299a5 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 @@ -91,6 +91,5 @@ public List getFields() { 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 58de4dcd804..307490f6496 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; 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 53ef9ac9e45..70425869bdc 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 8e523533239..1b231ad33fa 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 @@ -36,5 +36,4 @@ public String getType() { public void setType(String type) { this.type = type; } - } 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 1cab41afc54..bf6ddd9aee8 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,6 +28,4 @@ @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 9091100aa40..217ad69e9f1 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 @@ * 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 e7c18e6f6fe..d54dce60df0 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 MethodDefinition build(Method method) { 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 1367b5d551f..b7c9f511713 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 static String schema(final Class clazz) { 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 a9f9d2d984c..83f592910b5 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.Map; import java.util.Set; - /** * 2015/1/27. */ @@ -66,7 +65,7 @@ private static TypeBuilder getGenericTypeBuilder(Class clazz) { return builder; } } catch (NoClassDefFoundError cnfe) { - //ignore + // ignore logger.info("Throw classNotFound (" + cnfe.getMessage() + ") in " + builder.getClass()); } } @@ -82,5 +81,4 @@ public TypeDefinition build(Type type, Class clazz) { 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 78cc7a5a103..3bac0302a76 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 TypeDefinition build(Type type, Class clazz, Map clazz, Map clazz, Map clazz, Map t 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 ff926ca2978..c107d2d884e 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 @@ * 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 TypeDefinition build(Type type, Class clazz, Map 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 fbebcf1ed6f..d84fb2e38df 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 void setParameters(Map parameters) { @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 305bfc3f0b1..6177ef2b4c4 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 boolean equals(Object o) { 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 a16eb6a2a45..cacd09ddd2f 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 boolean equals(Object o) { 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 4962316daac..5a6ff701690 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 boolean equals(Object o) { 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 c6f13d55601..1115c451b20 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 static String getCanonicalNameForParameterizedType(ParameterizedType para 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 static String getCanonicalNameForParameterizedType(ParameterizedType para 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 static String getCanonicalNameForParameterizedType(ParameterizedType para 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 a21de3f5dc4..4372a40e732 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 static boolean needAnalyzing(Class clazz) { 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 1c78036a919..b188e14775b 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 @@ protected ProviderModel getProviderModel(Object data) { 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 08dd4ebee71..1a33129e753 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 DefaultExecutorSupport(URL url) { 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 b3f4a551d8b..c978052ecfb 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 0544df59ed3..1971cf25e70 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 @@ * 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 @@ protected ApplicationModel(FrameworkModel frameworkModel, boolean isInternal) { 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 @@ protected ApplicationModel(FrameworkModel frameworkModel, boolean isInternal) { 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 @@ protected ApplicationModel(FrameworkModel frameworkModel, boolean isInternal) { 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 @@ protected void onDestroy() { // 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 ModuleModel newModule() { @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 String getApplicationName() { } public String tryGetApplicationName() { - Optional appCfgOptional = getApplicationConfigManager().getApplication(); + Optional appCfgOptional = + getApplicationConfigManager().getApplication(); return appCfgOptional.isPresent() ? appCfgOptional.get().getName() : null; } @@ -268,7 +272,7 @@ public void removeModule(ModuleModel moduleModel) { 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 @@ protected boolean checkIfClassLoaderCanRemoved(ClassLoader classLoader) { } 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 ca27eb7f5b5..5140c06056c 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 @@ 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 7a4427f778b..d002dcafca8 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 @@ 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 Method getMethod() { 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 Object getAttribute(String key) { return this.attributeMap.get(key); } - public Class getReturnClass() { return returnClass; } @@ -79,7 +77,7 @@ public String[] getParameterTypes() { 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 @@ private String[] createParamSignature(Class[] args) { return paramSig; } - public boolean isGeneric() { return generic; } @@ -96,6 +93,4 @@ public boolean isGeneric() { 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 24876bc1965..1a1c5d28970 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 ConsumerModel(String serviceKey, 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 ConsumerModel(String serviceKey, 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 void initMethodModels() { 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 ConsumerMethodModel getMethodModel(Method method) { * @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 ConsumerMethodModel getMethodModel(String method) { */ 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 boolean equals(Object o) { 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 7047eeaa1de..5481c364717 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 09a001f3bbc..e5fb2b52ff4 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 FrameworkModel() { 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 FrameworkModel() { 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 @@ protected void onDestroy() { 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 @@ private void resetDefaultAppModel() { } 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 @@ private static void resetDefaultFrameworkModel() { } 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 FrameworkServiceRepository getServiceRepository() { return serviceRepository; } - @Override protected Lock acquireDestroyLock() { return destroyLock; @@ -373,7 +378,8 @@ public Environment modelEnvironment() { @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 7aff29de0ce..49a6d90185e 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 void registerProvider(ProviderModel providerModel) { // 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 List allProviderModels() { 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 @@ private static String keyWithoutGroup(String serviceKey) { } 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 a9da7f7dd98..2496d2dea31 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 358868af693..9af38b04289 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 @@ protected ModuleModel(ApplicationModel applicationModel, boolean isInternal) { 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 void addClassLoader(ClassLoader classLoader) { @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 ConsumerModel registerInternalConsumer(Class internalService, URL url) 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 c3b1d446c70..5a9092b4d9e 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 ModuleModel getModuleModel() { * @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 ServiceDescriptor registerService(Class interfaceClazz) { } 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 ServiceDescriptor registerService(String path, Class interfaceClass) { 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 void reRegisterProvider(String newServiceKey, String serviceKey) { 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 void unregisterConsumer(ConsumerModel consumerModel) { } 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 ProviderModel lookupExportedService(String serviceKey) { } 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 50f46c5f8bd..340b668e42c 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 a9707bc0731..90c931a7c14 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 @@ default byte[] packResponse(Object response) throws Exception { return getResponsePack().pack(response); } - default boolean needWrapper() { return false; } @@ -59,5 +57,4 @@ default boolean needWrapper() { 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 c3961a78c54..f5ca5ebca34 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 @@ 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 d578cef6fee..bb1f0ed8a00 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 ProviderModel(String serviceKey, 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 ProviderModel(String serviceKey, 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 static class RegisterStatedURL { 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 void setServiceUrls(List urls) { 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 4b447d5fc5b..ea27aad53ca 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.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 ReflectionMethodDescriptor(Method method) { 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 @@ private RpcType determineRpcType() { 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 boolean equals(Object o) { 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 int hashCode() { 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 489f7e4c6cb..dc041469330 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 ReflectionServiceDescriptor(Class interfaceClass) { } 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 @@ private void initMethods() { // 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 boolean equals(Object o) { 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 a96df0eb43e..9e9d494a402 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 @@ protected ScopeModel(ScopeModel parent, ExtensionScope scope, boolean isInternal */ 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 9e9291e24b4..7a213835dcc 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 @@ default ApplicationModel getApplicationModel() { 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 6b60567965a..bd03d97f307 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 2c00989c201..eba83d47026 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 9111f80b512..7784cbfbcde 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 ServiceMetadata(String serviceInterfaceName, String group, String version 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 afbc946abbf..20692a08b68 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 boolean equals(Object o) { 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 204a5180de2..b524b622815 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 ServiceRepository(ApplicationModel applicationModel) { 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 @@ private void initialize() { } public void destroy() { - //TODO destroy application service repository + // TODO destroy application service repository } public Collection allConsumerModels() { @@ -69,5 +70,4 @@ public Collection allProviderModels() { } 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 a98ef742f28..bfe497e2ee4 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 StubMethodDescriptor(String methodName, 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 d2ef41465c0..1041bf7fa8b 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 StubServiceDescriptor(String interfaceName, Class interfaceClass) { 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 boolean equals(Object o) { 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 b214e50ce0f..d3c6b8ac6f3 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 444309689ee..1fd216b8071 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 @@ default Object unpack(byte[] data) throws Exception { } 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 2ad9489e3b7..7e57cd5a4b4 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 @@ 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 592469d5b9f..6e7675fc7eb 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 fe3702aefd0..948e0d9192d 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 39860701f6b..3e1920ac01b 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 String getExceptionMessage() { 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 1f144eac690..888a92f17b4 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 29b950e3c9a..fbd4bcc5325 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 77e55bc7ebb..a0a9eac21a0 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.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 f040f3c9480..9972df84be6 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 7b983beed4b..b8098ea52e6 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 @@ 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 static String serviceKey(int port, String serviceName, String serviceVers 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 9f7f5620b97..3b4d8b537a3 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 ea1f65baff1..1019d8cfe9c 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 3f12cca518d..d5ac7d38d42 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 e306ed1af59..4db43bb8506 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 890f6e2df8c..0cca644b8e1 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 06771c28a4f..a45a26ad7ff 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 b991d5f3e22..8b873d880d1 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 0555fc72071..ae161397ccc 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 e880cfef7e1..c157a53daf6 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 f842b0b4c70..8c6c9adcddf 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 62a11612929..f2aa52110da 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 139fb696249..1a5d631c2a5 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.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 ac2910bf7cd..9106c10e43d 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 3df4506ce38..3378891bbee 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 00b56f7e933..28e61a6edc6 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 a6fca598458..290e651ea4b 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 ea2dd950a71..01e5bc2f7c8 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 4c2b442c55c..b2c6081b411 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 65f81562fd1..adfa677a18a 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 30b8b7922e4..7ebe27fc174 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 6a9ed6e8b1a..cf0082f4110 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 @@ void test() { 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 @@ void test() { 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 010edb1b3fc..a9d78cdd978 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.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 @@ void testGetParameter() { @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 @@ void testURLEquals() { 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 @@ void testURLEquals() { 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 3b7a5fa0570..2514695206d 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 @@ public void setName(String name) { 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 4b20f87d9d7..61cc3b3e93d 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 8d50abbd42b..91ae0eaf669 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 @@ void test() { 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 180a1e21a01..f0c75ed416d 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 d0833c60297..24a47c4dffc 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 @@ void test() { 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 219f9d97597..aa6cc9f6410 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 @@ 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 @@ void testNoArgConstructor() { @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 @@ void shouldAddParameter() { @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 @@ void testDefault() { @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 @@ void shouldSet() { 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 @@ void shouldRemoveParameters() { @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 @@ void shouldAddIfAbsent() { @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 @@ void shouldAddParameters() { 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 67d13caa2b3..4c4c218c35c 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 @@ void testEncoded() { }); errorEncodedCases.forEach(errorCase -> { - Assertions.assertThrows(RuntimeException.class, - () -> URLStrParser.parseEncodedStr(errorCase)); + Assertions.assertThrows(RuntimeException.class, () -> URLStrParser.parseEncodedStr(errorCase)); }); } @@ -78,8 +79,7 @@ void testDecoded() { }); errorDecodedCases.forEach(errorCase -> { - Assertions.assertThrows(RuntimeException.class, - () -> URLStrParser.parseDecodedStr(errorCase)); + Assertions.assertThrows(RuntimeException.class, () -> URLStrParser.parseDecodedStr(errorCase)); }); } @@ -93,5 +93,4 @@ void testDefault() { 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 78c96e2891a..ee03745d3d8 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 @@ 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 @@ void test_valueOf_noHost() throws Exception { 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 @@ void test_valueOf_WithProtocolHost() throws Exception { 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 @@ void test_valueOf_Exception_noProtocol() throws Exception { @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 @@ void test_getAbsolutePath() throws Exception { @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 @@ void test_equals() throws Exception { @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 @@ void test_set_methods() throws Exception { @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 @@ void test_removeParameters() throws Exception { 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 @@ void test_removeParameters() throws Exception { 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 @@ void test_addParameter_sameKv() throws Exception { 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 @@ void test_addParameters_SameKv() throws Exception { 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 @@ void test_windowAbsolutePathBeginWithSlashIsValid() throws Exception { @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 @@ void testUserNamePasswordContainsAt() { 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 @@ void testIpV6Address() { @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 @@ void testGetServiceKey() { 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 @@ void testGetServiceKey() { 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 @@ void testGetColonSeparatedKey() { 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 @@ void testValueOf() { assertURLStrDecoder(url); } - /** * Test {@link URL#getParameters(Predicate)} method * @@ -916,7 +937,8 @@ void testValueOf() { */ @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 @@ void testGetParameter() { @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 @@ void testEqualsWithPort() { @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 @@ void testEqualsWithUser() { @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 @@ void testGetAuthority() { 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 @@ void testGetUserInformation() { 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 @@ void testGetUserInformation() { 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 69ba3846123..cb70b704bf5 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 @@ public ScopeModel getScopeModel() { 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 @@ void testCreateBeanWithScopeModelArgument() throws ReflectiveOperationException 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 0e51c9e609d..10a24286886 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.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 @@ void testInjection() { 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 @@ void testInjection() { 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 @@ void testInjection() { 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 4e32514bea6..a049e63687a 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 eb1118479f1..d5f165623e4 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 @@ 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 64fcf7ade40..65de6beb1c7 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.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.Map; import java.util.UUID; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class JavaBeanSerializeUtilTest { @Test @@ -74,8 +74,8 @@ void testDeserialize_Primitive() { @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 @@ void testDeserialize_Null() { @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 @@ void testDeserialize_containsProperty() { @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 @@ void testSetEnumNameProperty() { @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 @@ void testGetEnumNameProperty() { 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 @@ void testSetClassNameProperty() { @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 @@ void testGetClassNameProperty() { @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 @@ void testSetPrimitiveProperty() { @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 @@ void testSerialize_Array() { 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 @@ void testSerialize_Array() { 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 @@ void testSerialize_Array() { 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 @@ void testDeserialize_Array() { } 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 @@ void testBeanSerialize() { 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 @@ void testBeanSerialize() { 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 @@ void testDeserializeBean() { 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 @@ void testDeserializeBean() { 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 2eed4129aab..9d760b6d907 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.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 @@ public String baseClassMethod() { } } -interface BaseInterface { +interface BaseInterface {} -} class ClassGeneratorTest { @Test @@ -66,19 +63,48 @@ void test() throws Exception { // 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 @@ void test() throws Exception { 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 @@ void test() throws Exception { 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 @@ void test() throws Exception { // 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 @@ void testMain() throws Exception { 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 @@ void testMain0() throws Exception { 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 @@ public void test_getClassPool() throws InterruptedException { 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 2ad7ab35aef..ce81aebf1b1 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 6a6e1df7947..a18a30c988b 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 @@ static String sayBye() { 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 8268494421e..35b7c767c89 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 @@ void testMain() throws Exception { 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 @@ void test_unwantedArgument() throws Exception { 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 @@ void testWrapPrimitive() throws Exception { Wrapper.getWrapper(Byte.TYPE); }); } - + @Test void testInvokeWrapperObject() throws Exception { Wrapper w = Wrapper.getWrapper(Object.class); @@ -120,9 +120,12 @@ void testInvokeWrapperObject() throws Exception { 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 @@ void testOverloadMethod() throws Exception { 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[]{}, Wrapper.getWrapper(Son.class).getDeclaredMethodNames()); - assertArrayEquals(new String[]{}, ClassUtils.getDeclaredMethodNames(Son.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)); } @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 @@ public interface I2 { 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 @@ public static class Impl0 { 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 @@ public Float getFloat2() { } } - 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 8a3cb3255aa..b31c130aa7c 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,25 +16,27 @@ */ 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.net.URISyntaxException; import java.net.URL; import java.nio.file.Paths; +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", store1.getCacheFilePath()); + Assertions.assertEquals( + getDirectoryOfClassPath() + "..%002f..%002f..%002fdubbo.dubbo.cache", store1.getCacheFilePath()); store1.destroy(); FileCacheStore store2 = FileCacheStoreFactory.getInstance(getDirectoryOfClassPath(), "../../../中文"); - Assertions.assertEquals(getDirectoryOfClassPath() + "..%002f..%002f..%002f%4e2d%6587.dubbo.cache", store2.getCacheFilePath()); + Assertions.assertEquals( + getDirectoryOfClassPath() + "..%002f..%002f..%002f%4e2d%6587.dubbo.cache", store2.getCacheFilePath()); store2.destroy(); } @@ -71,4 +73,4 @@ private String getDirectoryOfClassPath() throws URISyntaxException { 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/cache/FileCacheStoreTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/cache/FileCacheStoreTest.java index bdfcc3b0226..fd2798ad330 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 @@ private String getDirectoryOfClassPath() throws URISyntaxException { 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 9edc55804a5..31fb7f07025 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 @@ void testAvailableCompiler() throws Exception { 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 0e7c6b7a734..5023ff76408 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 @@ void testNewInstance() { @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 @@ void testBoxedAndUnboxed() { 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 @@ void testToUri() { void testGetSizeMethod() { Assertions.assertEquals("getLength()", ClassUtils.getSizeMethod(GenericClass3.class)); } - + @Test void testGetSimpleClassName() { Assertions.assertNull(ClassUtils.getSimpleClassName(null)); @@ -143,20 +152,15 @@ void testGetSimpleClassName() { 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 @@ public int getLength() { } 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 ae9c23bd81b..a711a124c28 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 @@ 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 16686cde7f3..1af4ea3b261 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 @@ 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 @@ String getSimpleCode() { 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 @@ String getSimpleCodeWithoutPackage(){ return code.toString(); } - String getSimpleCodeWithSyntax(){ + String getSimpleCodeWithSyntax() { StringBuilder code = new StringBuilder(); code.append("package org.apache.dubbo.common.compiler.support;"); @@ -66,7 +67,7 @@ String getSimpleCodeWithSyntax(){ } // 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 @@ String getSimpleCodeWithWithExtends() { 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 9cfb667b390..18ac8852c33 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 @@ public void testCompileJavaClass0() throws Exception { 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 @@ public void testCompileJavaClass0() throws Exception { 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 @@ void testCompileJavaClass1() { @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 @@ void testCompileJavaClassWithImport() throws Exception { @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 61b8b819670..315c587f138 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 @@ void test_compileJavaClass() throws Exception { 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 @@ void test_compileJavaClass0() { 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 @@ void test_compileJavaClass_java8() throws Exception { 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 @@ void test_compileJavaClass0_java8() { 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 4e37b0bad55..7ba2ae47dba 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 a1a8fd70ae0..92b0a2c123a 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 @@ 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.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.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 @@ void testRunnableResponse() throws ExecutionException, InterruptedException { @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 09d4ca7fa75..e760388abd8 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 @@ void test() { 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 @@ void test() { 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 acf6a3b229f..9db46866fdd 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 @@ void test() { 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 16853eb32ec..4879c9de9d6 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.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 @@ void testCachedProperties() { } @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 @@ void testEscapedNewLine() throws Exception { 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 f6806b7ab4d..7ff12664f67 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 e0a12041933..81e940f95c5 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.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 @@ void testResolvePlaceholders() { 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 50c55c00feb..d5d3cc1cabf 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 @@ 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 @@ void testGetProperties() { 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 @@ void testConversions() { * 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 45525c71910..8fc082de281 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 8f7d89fb0ac..7d6f7da6494 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 @@ void testPrefixedConfiguration() { 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 @@ void testPrefixedConfiguration() { 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 9394a6cacf4..4f0ba077051 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 @@ 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 @@ void test() { 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 39fb0186957..c9aa6583b6c 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 @@ void testGetSysProperty() { */ @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 @@ enum ConfigMock { */ 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 4633dd3ec8b..09535c7caf5 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 @@ void testGetDynamicConfiguration() { 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 15367ec83ce..1429f30eeb8 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 @@ 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 @@ protected String doGetConfig(String key, String group) { } @Override - protected void doClose() { - - } + protected void doClose() {} @Override protected boolean doRemoveConfig(String key, String group) { @@ -98,9 +96,7 @@ protected String doGetConfig(String key, String group) { } @Override - protected void doClose() { - - } + protected void doClose() {} @Override protected boolean doRemoveConfig(String key, String group) { @@ -111,8 +107,7 @@ protected boolean doRemoveConfig(String key, String group) { 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 @@ void testPublishConfig() { 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 8b3224b13e8..b315bf08a06 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 55183f3cd0d..dd298cedd91 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 @@ void testGetter() { @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 @@ void testToString() { 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 c5ef6273797..baeb9fd1188 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/config/configcenter/file/FileSystemDynamicConfigurationFactoryTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfigurationFactoryTest.java index 37c3f22847d..99e954d392a 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfigurationFactoryTest.java +++ b/dubbo-common/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-common/src/test/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfigurationTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfigurationTest.java index 111b71bd449..7b4dfe86034 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfigurationTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfigurationTest.java @@ -20,17 +20,17 @@ 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 @@ public void init() { } 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 @@ void testInit() { 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 @@ void testAddAndRemoveListener() throws InterruptedException { 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 @@ void testAddAndRemoveListener() throws InterruptedException { 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 @@ void testAddAndRemoveListener() throws InterruptedException { 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 @@ void testRemoveConfig() throws Exception { 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-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 7ab68f44b58..694124cc7d1 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 @@ void test() { 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 3a1407c2d6e..c01a5323c5a 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 @@ public void tearDown() { @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 64dbe23e864..8b0c69d0fd9 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 @@ void testConvert() { 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 e05a315b57d..bbc6733c0ed 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 @@ void testAccept() { @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 c5c321397b7..289cd31cf61 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 @@ void testConvert() { 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 ae92ee6151b..586533cf10e 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 @@ void testConvert() { 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 b8fe980dc04..f31f974969f 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 @@ void testConvert() { 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 794e7ca3252..9b2924b8c0c 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 @@ void testConvert() { 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 5a648d9fe10..ddd6d6bfc04 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 @@ void testConvert() { 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 f2edaeac939..1f3cccf10ff 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 @@ void testConvert() { 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 b349d1cef25..4bd74ca69e8 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 @@ void testConvert() { 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 aeada364edc..22a21d751f1 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 @@ void testConvert() { 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 ac904bbc8f1..c15b8403ece 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.BlockingQueue; import java.util.concurrent.TransferQueue; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; /** @@ -69,4 +69,4 @@ void testFind() { 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 0565c290d07..26be6d3e554 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 @@ void testAccept() { @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 @@ void testGetSourceType() { 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 a884972cdfb..d7667db33ba 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 @@ 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.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 @@ void testConvert() throws NoSuchFieldException { 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 @@ void testConvert() throws NoSuchFieldException { assertNull(converter.convert(null, Collection.class, null)); assertNull(converter.convert("", Collection.class, null)); - } @Test @@ -117,7 +117,8 @@ void testGetSourceType() { @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 2c830782eac..294bd47ee4e 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 @@ 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.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 @@ void testConvert() { 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 @@ void testConvert() { assertNull(converter.convert(null, Collection.class, null)); assertNull(converter.convert("", Collection.class, null)); - } @Test @@ -120,4 +120,4 @@ void testGetSourceType() { 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 37a3aa145c5..b70f73390e5 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.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 @@ void testConvert() { assertNull(converter.convert(null, Collection.class, Integer.class)); assertNull(converter.convert("", Collection.class, Integer.class)); - } @Test @@ -113,4 +112,4 @@ void testGetSourceType() { 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 dd1800358be..f6a2e6d1947 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 @@ 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.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 @@ void testGetSourceType() { @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 cf3c4237fa8..d88ad51846f 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 @@ 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.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 @@ void testGetSourceType() { @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 95a7c59ee5f..8f7b9ecde03 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 @@ 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.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 @@ void testGetSourceType() { @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 014b069bfeb..f277cff506d 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 @@ 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.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 @@ void testGetSourceType() { 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 4c1c251ddc3..f1295d2e835 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 @@ 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.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 @@ void testGetSourceType() { 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 2a18ea8e42f..d84eb6a2c48 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 @@ 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.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 @@ void testGetSourceType() { @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 3e46ef1c8cb..c2fc0c6d9ae 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 @@ 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.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 @@ void testGetSourceType() { 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 830e612c614..0cb05ff6783 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 @@ 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 @@ void testGenerate() throws IOException { 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 ad1c7beb956..13f1945d185 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.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 @@ void testInheritanceAndScope() { // 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 @@ void testInheritanceAndScope() { 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 @@ void testInheritanceAndScope() { } @Test - void testPostProcessor() { - - } + void testPostProcessor() {} @Test void testModelAware() { @@ -103,9 +110,12 @@ void testModelAware() { 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 @@ void testModelAware() { 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 @@ void testModelAware() { @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 @@ void testModelDataIsolation() { 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 @@ void testInjection() { // 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 @@ void testInjection() { 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 @@ void testInjection() { 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 bbf27a61e1a..cbcac7c8d76 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.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 @@ void test_getExtensionLoader_Null() { getExtensionLoader(null); fail(); } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage(), - containsString("Extension type == null")); + assertThat(expected.getMessage(), containsString("Extension type == null")); } } @@ -118,8 +117,10 @@ void test_getExtensionLoader_NotInterface() { 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 @@ void test_getExtensionLoader_NotSpiAnnotation() { 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 @@ void test_getExtension_WithWrapper() { 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 @@ void test_getExtension_withWrapperAnnotation() { @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 @@ void test_getExtension_ExceptionNoExtension() { 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 @@ void test_getExtension_ExceptionNoExtension_WrapperNotAffactName() { 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 @@ void test_AddExtension() { 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 @@ void test_AddExtension_ExceptionWhenExistedExtension() { 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 @@ void test_AddExtension_Adaptive_ExceptionWhenExistedAdaptive() { 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 @@ void test_addExtension_with_error_class() { 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 @@ void test_addExtension_with_interface() { 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 @@ void test_addExtension_without_adaptive_annotation() { 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 @@ void test_getLoadedExtensionInstances() { 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 @@ void test_replaceExtension_with_error_class() { 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 @@ void test_replaceExtension_with_interface() { 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 @@ void test_replaceExtension() { 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 @@ void test_replaceExtension_ExceptionWhenNotExistedExtension() { 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 @@ void test_replaceExtension_Adaptive_ExceptionWhenNotExistedExtension() { 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 @@ void test_InitError() { 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 @@ void test_InitError() { 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 @@ void testLoadActivateExtension() { 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 @@ void testLoadActivateExtension() { 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 @@ void testLoadDefaultActivateExtension1() { 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 @@ void testInjectExtension() { @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 @@ void testGetOrDefaultExtension() { 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 @@ void testGetLoadingStrategies() { 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 @@ void testGetLoadingStrategies() { @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 @@ void testLoadByDubboInternalSPI() { 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 5dfe1b79f38..b810b836ed0 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 @@ void test_onClass() throws Exception { 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 52755a8bf4b..dc58d75fccd 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.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 @@ void test_getAdaptiveExtension_customizeAdaptiveKey() throws Exception { @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 @@ void test_getAdaptiveExtension_protocolKey() throws Exception { } { - 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 @@ void test_getAdaptiveExtension_ExceptionWhenNoAdaptiveMethodOnInterface() throws 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 @@ void test_getAdaptiveExtension_ExceptionWhenNotAdaptiveMethod() throws Exception 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 @@ void test_getAdaptiveExtension_ExceptionWhenNoUrlAttribute() throws Exception { 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 @@ void test_urlHolder_getAdaptiveExtension_ExceptionWhenNameNotProvided() throws E 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 @@ void test_getAdaptiveExtension_inject() throws Exception { url = url.addParameters("simple.ext", "impl2"); assertEquals("Ext6Impl1-echo-Ext1Impl2-echo", ext.echo(url, "ha")); - } @Test @@ -320,4 +333,4 @@ void test_getAdaptiveExtension_InjectNotExtFail() throws Exception { 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 0848c01a43f..4e474d79570 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 @@ public static void setUp() throws Exception { 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 83596edb952..5757064aa33 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 @@ void test_getExtension() { 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 b0de9d439a2..2342c2bd243 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 25aa7e7e838..91e097988c8 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 e2ca5bd087e..4c8ad8e5c1d 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 fda49370c83..920808a50ac 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 c00a988577d..e828f7775d2 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 1ae23227c7a..b83d10fb195 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 fe3e082d499..8c62c2462f9 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 8a2558c20bb..b4736ab2502 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 0ff2ef44f4d..41ab1f55b24 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 716d8150403..a9e53c7445b 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 671a3b9c005..70b3c1a60ee 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 89ca54caa07..7593a01490e 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 3af7a39b8d8..b420e7d586f 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 46c7d42b940..13a57a84620 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 85d2e5be592..9194fcfdd6e 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 534edd8690a..e2b462d84f4 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 3f273f55bc1..f55fde545ec 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 @@ @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 27d92a1da63..99bc330b9ad 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 String yell(URL url, String s) { 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 399822a1f68..63aa2b5c79b 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 @@ * * @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 c231495de21..048496faef4 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 @@ * * @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 85f51ab039a..6e27f0472d1 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 @@ * * @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 e88527123c3..52336f7a855 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 194c8182792..a5523d59a0f 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 9d4b81ed8ad..b045d638194 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 87ce080a7ee..5ea8e730500 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 cf60246b2c0..df00aa01302 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 @@ 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 ed5aec4eda9..1670acb011b 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 void setFrameworkProvider(FooFrameworkProvider frameworkProvider) { } @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 25dcb66dcf4..94fce92e86b 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 @@ 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 45b71b1b1b0..ee1db514d69 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 void setModuleProvider(FooModuleProvider moduleProvider) { } @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 604c2919d15..50f897ee21e 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 @@ 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 d7c0ad79b02..3d6bf60bfb1 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 void setAppService(FooAppService appService) { } @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 33e63bb40f9..c8a05597c9b 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 String yell(URL url, String s) { 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 dd78351a2e2..a5051086adb 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 String yell(URL url, String s) { 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 33492ce171e..d849666f904 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 @@ 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 1d7862b94b4..05cfcc53fdd 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 @@ 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 34077b2cfb1..24cae3c383a 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 String echo(UrlHolder holder, String s) { 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 d308b36b4fa..81e883c1114 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 String echo(UrlHolder holder, String s) { 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 539342e89df..667c3c3346d 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 9d024f930f7..eb76e7bdcf6 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 525bba89281..b14f5f3debe 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 2b11b8cc599..bb1d628730a 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 void setExt1(SimpleExt ext1) { 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 b704cde273d..928c393f680 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 void setList(List list) { 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 40b5978dc29..bf0006ac3fe 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 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 f214c5db922..7cf3706355b 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 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 fe64029e5fd..eadb7e2b3ae 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 4b54f649bd5..df5fed6d3ee 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 bea7fa82167..b3b1ba3270f 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 @@ 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 7e3fc696f4c..f24b26551d1 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 @@ void test() { 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 6bf8cdfbf11..9ecb7a1bbac 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 @@ 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 612440894d4..1a088264125 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 @@ 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 5f30dd650e0..b1408919bfd 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 @@ 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 df93fa6eaf8..3b9b9e27c8d 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 @@ 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 c02aaa13c26..38f787a306b 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 @@ 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 353874bc9a7..fdca0bcff55 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 @@ 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 634e92f12f2..c900d474800 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 cf23ffee942..a58500f413f 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 b09ed993a90..99b08f9ebbf 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 f17543d1c44..d1e97a20522 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 @@ void testWrapper() { 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 dd594249b9e..28cb8b0abe1 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 String echo(String msg) { 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 44ec737a1fb..5a9e5b159a3 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 @@ 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 c8e4385474e..25662b02a86 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 @@ 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 b1dc5de7276..2ab493327b0 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 @@ void testOr() { 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 d8fde23d228..6f8973642fb 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 @@ void testFilterSet() { 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 5a608eb3ea0..f31624fa9cc 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 57e515eef00..5d1e24ecab1 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 08b9d72a317..b58f516967c 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 eb075f65ab6..29e6d31fe49 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 @@ void testMain() { @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 @@ void testWrongOffSet() { @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 @@ void testMD5ForString() { @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 21c63cc488f..c2fe38e18c0 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 @@ void testReadWithWrongOffset() { } }); } -} \ 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 a60a6af5851..6192ebfe872 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 @@ void testSkipZero() { 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 ad733e017f0..6cb0be0f36f 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 @@ void testToStringWithCharset() throws IOException { 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 2911c64bfac..160e562e2eb 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 @@ void testWrongLength() throws IOException { 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 bb054b3e509..1cd47768912 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 @@ void testWriteCharWithWrongCombineLength() throws IOException { 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 468374d6bab..c28f4ad8da3 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 @@ void test1() { 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 @@ public void setAge(int age) { 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 bbed68afb1d..a372a2fee3d 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.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 @@ static void teardown() { 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 a3fd701c977..889af34cfad 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 @@ 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.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 @@ void testSupported() { 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 0ebf9cb1ebd..0852c230edf 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.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 @@ void testSupported() { 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 @@ void testSupported() { 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 c65de4d7360..67424e297ab 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 @@ void testConstants() { @Test void testGetPriority() { - assertEquals(Prioritized.NORMAL_PRIORITY, new Prioritized() { - }.getPriority()); + assertEquals(Prioritized.NORMAL_PRIORITY, new Prioritized() {}.getPriority()); } @Test @@ -85,7 +84,6 @@ void testComparator() { copy = asList(1, 2, 3); assertEquals(copy, list); - } public static PrioritizedValue of(int value) { @@ -123,4 +121,4 @@ public int hashCode() { 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 035f1181724..dd38bc770a6 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 @@ void testSingleton() { @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 @@ public void destroy() { 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 afab9e4c7b3..75465b6a3de 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.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 @@ static Stream data() { 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 4b5dc7d9e46..94ff33102dc 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 @@ 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 @@ void shouldReturnSameLogger() { @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 e834433c94d..b30164d6682 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.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 @@ static Stream data() { Arguments.of(JdkLoggerAdapter.class), Arguments.of(Log4jLoggerAdapter.class), Arguments.of(Slf4jLoggerAdapter.class), - Arguments.of(Log4j2LoggerAdapter.class) - ); + Arguments.of(Log4j2LoggerAdapter.class)); } @ParameterizedTest @@ -73,7 +71,8 @@ void testAllLogMethod(Class loggerAdapter) throws Excep @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 931e34313e9..74d9e0615a5 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 @@ -40,8 +40,7 @@ void testLocationAwareLogger() { 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(new Exception("error")); logger.warn(new Exception("warn")); @@ -55,7 +54,7 @@ void testLocationAwareLogger() { 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)); } } 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 78c20457dc1..898d4c44c47 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 @@ void testFailsafeErrorTypeAwareForLoggingMethod() { 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 @@ void testSuccessLogger() { 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 @@ void testInstructionShownOrNot() { 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 52abadc0c7b..df8afe03940 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 @@ void testGetLogger() { 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 1dc2dba7c4d..d331d0fd9c8 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 int hashCode() { @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 730d2cb3193..e5c3e0c3f62 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 int hashCode() { @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 3fca20d6348..b4c850905a7 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 e83b2a7f285..999d9c7d40b 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 void setSize(Size size) { } 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 1ad1744420b..76f01f86d4e 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 @@ @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 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 String copyright; // Can be unset. + + 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) { this.uri = uri; this.title = title; this.width = width; @@ -200,6 +211,7 @@ public void setCopyright(String copyright) { } 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 9a653e29884..15e84765f76 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 int hashCode() { @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 String toString() { + 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 0aaabd87a5e..b98e7b0d16c 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 @@ 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 6d1bed43f37..5c25a474d62 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 FullAddress(String countryId, String provinceName, String cityId, String 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 int hashCode() { @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 String toString() { } 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 15f1238fe85..3b46b3b93c5 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 int hashCode() { @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 String toString() { + 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 2217d6a46e8..7725418eb1a 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 void setPersonName(String personName) { 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 6c25ec89b49..11595ee148a 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 int hashCode() { @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 String toString() { } 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 42c52f85195..6b7bc483488 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 @@ void testBizProfiler() { 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 e163dfbde1a..31c9d378bb3 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 @@ void test() { 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 d586abbfa83..67dab918736 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 @@ 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 99153771e07..76560f961f3 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 f7a1c02ef7e..b5334a5e9cb 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.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 @@ void testGetProviderConnectionConfig() throws IOException { 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 @@ void testGetConsumerConnectionConfig() throws IOException { 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 950b5cb8eec..20c82057b87 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 188b9692b06..1013ef9dfbf 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 @@ void testConstructor3() throws Exception { 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 beb9e25fdea..dfc9534df09 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.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 @@ void test() { 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 @@ void test() { 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 @@ void test() { // 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 @@ void test() { // 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 4d34e69a656..e87337d4727 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 951cae0cc9a..ad5b1938a2a 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 d5c3b39e18d..1857bbf6f8b 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 @@ void testGetSummaryStatus3() throws Exception { 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 7b9e7ca225c..fa9470426cd 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 @@ void testGetComponent() throws Exception { 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 5be0f0b579d..7dd93dbf7bc 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.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 @@ protected Integer initialValue() { 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 @@ void testSetAndGet() { 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 @@ void testOnRemove() { 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 @@ public void run() { } } 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 @@ public void run() { } } 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 @@ public void run() { 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 @@ void testConstructionWithIndex() throws Exception { 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 3d0e34caccc..30364e771a7 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 5b5405f5350..456853c89fb 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 @@ void test() { 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 0722a35346d..b659e4c2b53 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 @@ private static long spend(LinkedBlockingQueue lbq, int length, int time 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 6c726b07023..bd658e3ff72 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 d064730f6b9..edd5c648e83 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 @@ */ class ThreadPoolExhaustedEventListenerTest { - private MyListener listener; @BeforeEach @@ -36,7 +35,8 @@ public void init() { @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 @@ public ThreadPoolExhaustedEvent getThreadPoolExhaustedEvent() { 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 8570b24af85..72f2497b7c9 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 be301d71a6b..2f5b7cb1cda 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.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 @@ void testSharedExecutor() throws Exception { 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 @@ void testSharedExecutor() throws Exception { throw new RuntimeException(e); } }); - sharedExecutor.execute(()->{ + sharedExecutor.execute(() -> { latch.countDown(); try { latch1.await(); @@ -113,7 +113,7 @@ void testSharedExecutor() throws Exception { throw new RuntimeException(e); } }); - sharedExecutor.submit(()->{ + sharedExecutor.submit(() -> { latch.countDown(); try { latch1.await(); @@ -122,10 +122,10 @@ void testSharedExecutor() throws Exception { } }); - 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 7090f1f1574..5414a8f978a 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 @@ 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 @@ void testSharedExecutor() throws Exception { 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 @@ void testSharedExecutor() throws Exception { throw new RuntimeException(e); } }); - sharedExecutor.execute(()->{ + sharedExecutor.execute(() -> { latch.countDown(); try { latch1.await(); @@ -72,7 +72,7 @@ void testSharedExecutor() throws Exception { throw new RuntimeException(e); } }); - sharedExecutor.submit(()->{ + sharedExecutor.submit(() -> { latch.countDown(); try { latch1.await(); @@ -81,10 +81,10 @@ void testSharedExecutor() throws Exception { } }); - 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 660c0c926cc..90afb75155d 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.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 1bf52c2f02f..8179d42f0a0 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.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.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 @@ 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 @@ protected void jstack(FileOutputStream jStackStream) { 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 @@ void jStackDumpTest_dumpDirectoryNotExists_cannotBeCreatedTakeUserHome() { 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 @@ void jStackDumpTest_dumpDirectoryNotExists_cannotBeCreatedTakeUserHome() { 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 @@ void jStackDumpTest_dumpDirectoryNotExists_canBeCreated() { 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 @@ void jStackDumpTest_dumpDirectoryNotExists_canBeCreated() { @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 e85bb6c0c6e..bfec72a233e 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.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.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 @@ 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 03e90eddc10..52db48a824d 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.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.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 @@ void testEagerThreadPool() throws Exception { // 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 @@ void testEagerThreadPoolFast() { // 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 @@ void testEagerThreadPoolFast() { @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 @@ void testEagerThreadPool_rejectExecution1() { // 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 @@ void testEagerThreadPool_rejectExecution1() { executor.execute(runnable); } - @Test void testEagerThreadPool_rejectExecution2() { String name = "eager-tf"; @@ -235,12 +239,14 @@ public boolean retryOffer(Runnable o, long timeout, TimeUnit unit) throws Interr 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 440d0156e6a..ace59c4a40a 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.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 @@ 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 @@ void getExecutor1() throws Exception { 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 @@ void getExecutor2() { 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 42c4bf6c236..a61e59a2184 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 @@ void testRetryOffer1() throws Exception { }); } - @Test void testRetryOffer2() throws Exception { TaskQueue queue = new TaskQueue(1); @@ -90,5 +88,4 @@ void testRetryOffer2() throws Exception { 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 5a10dd934ca..a12bcc0f3f8 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.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.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 @@ 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 @@ void getExecutor2() throws Exception { 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 66ef2cac847..5d562b4cd29 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.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.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 @@ 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 3c3396a1118..46fd9ea0e2a 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,43 +77,25 @@ void constructorTest() { // 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); + 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); + new HashedWheelTimer(new NamedThreadFactory("dubbo-future-timeout", true), 100, null, 8, -1); }); Assertions.assertThrows(RuntimeException.class, () -> { new HashedWheelTimer( - new NamedThreadFactory("dubbo-future-timeout", true), - 100, - TimeUnit.MILLISECONDS, - 0, -1); + 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); + new NamedThreadFactory("dubbo-future-timeout", true), Long.MAX_VALUE, TimeUnit.MILLISECONDS, 8, -1); }); Assertions.assertThrows(RuntimeException.class, () -> { @@ -123,7 +103,8 @@ void constructorTest() { 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 @@ void constructorTest() { @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 @@ void createTaskTest() throws InterruptedException { 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 @@ void stopTaskTest() throws InterruptedException { 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 3c1665cd799..bf8c04157ef 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 @@ 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 @@ void testGetParameter() { URLParam urlParam4 = URLParam.parse("aaa=aaa&side=provider"); Assertions.assertEquals("provider", urlParam4.getParameter("side")); - } @Test @@ -208,8 +207,7 @@ void testAddParameters() { 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 @@ void testURLParamMap() { 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 @@ void testURLParamMap() { 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 ceadeaf4f3e..25114a42916 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.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.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 @@ void testGetAllDeclaredAnnotations() { 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 @@ void testGetAllMetaAnnotations() { 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 @@ void testFindMetaAnnotation() { static class A { @MyAdaptive("e") - public void execute() { - - } - - + public void execute() {} } @Documented @@ -300,40 +300,28 @@ public void execute() { @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 @@ public void execute() { @interface MyAdaptive { String[] value() default {}; - } @Service5 @@ -351,17 +338,11 @@ static class B extends A { @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 @@ private void assertADeclaredAnnotations(List annotations, int offset 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 164329bea0e..364336e4af4 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 c8c9385b05e..d5cfb54a60d 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 @@ void testNotNull1() { @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 @@ void testNotNullString() { @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 bc7b23fca8b..716ac89c770 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 @@ void testSet() { 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 @@ void testGetAndSet() { 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 @@ void testGetAndAnd() { 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 2264cb795a7..83f65d7f736 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 @@ void testIpv6() throws UnknownHostException { 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 09dcfd8e677..cf5b028240c 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.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 @@ void test() throws InterruptedException { 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 @@ void test() throws InterruptedException { 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 2df753bcb4d..36ae28ae5f6 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 @@ void tetForNameWithCallerClassLoader() throws Exception { @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 @@ void testGetClassLoader1() { 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 @@ void testConvertPrimitive() { 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 @@ void testConvertPrimitive() { 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 8df47daf4af..0a23526151f 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 @@ 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.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 @@ void testSplitAll() { 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 @@ void testJoinAll() { 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 @@ void testMapEquals() { 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 @@ void testToMap1() { @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 1599d25a4f8..cf1c4436c06 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.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 @@ void testCompatibleTypeConvert() throws Exception { 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 @@ void testCompatibleTypeConvert() throws Exception { 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 @@ void testCompatibleTypeConvert() throws Exception { 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 66c1ae462df..45ce4e1b09c 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 @@ public void testComputeIfAbsent() { @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 @@ public void issue11986ForJava8Test(){ @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 b63aa5322ed..8905610b80c 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.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 @@ 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 @@ void testIsDefault() throws Exception { @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 @@ void testMergeValuesDeleteDefault_2() { */ @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 @@ void testReplaceProperty2() { 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 @@ void testGetSystemProperty() throws Exception { @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 @@ void testLoadPropertiesOneFileAllowMulti() throws Exception { @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 @@ void testLoadPropertiesOneFileNotRootPath() throws Exception { 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 @@ void testLoadMigrationRule() { 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 72b30db5546..596164adc5b 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 @@ void test() { 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 6998ef010cf..29d116b7d61 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 @@ void tearDown() { @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 @@ void testAddAllow() throws ClassNotFoundException { @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 @@ void testAddBlock() { @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 @@ void testStatus() throws ClassNotFoundException { 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 4528f9ad7ed..8b4d6c4f445 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 4aa272b7e6b..8924f78c1aa 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 8266e70521a..a9a452d0321 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 @@ void setSetFieldValue() { 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 d6fc36bcb6f..653c939cadc 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 @@ void testSetAndGet() throws Exception { 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 c23d3b2427b..1e05c07c9da 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.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 @@ void testWrite5() throws Exception { @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 @@ void testReadLines() throws Exception { @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 @@ void testRead() throws Exception { @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 @@ void testAppendLines(@TempDir Path tmpDir) throws Exception { 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 ec5f34b1c0e..a42e1ae368f 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 @@ void blankSystemVersion() { 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 5276dabf709..93813108bb6 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/JsonUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/JsonUtilsTest.java index d237685eb2e..1b63d217d51 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 @@ -24,12 +24,6 @@ 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.util.Collections; import java.util.HashMap; import java.util.LinkedList; @@ -37,6 +31,12 @@ 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); @@ -72,14 +72,16 @@ void testGetJson1() { 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 JsonUtils.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 @@ -87,7 +89,8 @@ void testGetJson1() { 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 @@ -95,7 +98,8 @@ void testGetJson1() { 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 @@ -103,7 +107,8 @@ void testGetJson1() { 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"); JsonUtils.setJson(null); @@ -208,14 +213,14 @@ void consistentTest() { @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 JsonUtils.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 9dbf00c6d8a..1bfd51d62d3 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 @@ 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 8d03fe30a6a..04fe0f94ed4 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 a5fef528e9a..cbd4bcdad4a 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 0dfede08870..391312dab37 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 @@ void testLogThread() { 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 7183ffd9985..e88e8669569 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 @@ void testFindMessage2() { 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 d5a0a46d0d3..f69b82c9105 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.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 @@ static class Md5Task implements Runnable { 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 @@ public void run() { } } } -} \ 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 6b6b45109ab..13bcd79912b 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 @@ void test() throws NoSuchMethodException { 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 b986c3d6629..702306d3ae1 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 @@ void testIsMetaMethod() { @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 @@ void testGetMethods() throws NoSuchMethodException { 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 @@ public String setFieldName2() { public String isFieldName3() { return ""; } - } public class MethodTestClazz { @@ -169,5 +171,4 @@ public MethodTestClazz get() { 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 2d501e542d2..d24950b5c47 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 @@ * 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 57a0303134c..5498a333cce 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 4e835745ae4..e35933531ce 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 @@ void testIgnoreGivenInterfaceNameWithMetaCharacters() throws Exception { 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 @@ public boolean hasMoreElements() { }; 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 @@ public boolean hasMoreElements() { }; // 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 @@ public boolean hasMoreElements() { } } - 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 f3856f0957f..95eea9bca59 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.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 @@ void testMatchIpRangeMatchWhenIpv6() throws UnknownHostException { @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 @@ void testMatchIpv6WithIpPort() throws UnknownHostException { @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 2066142c11f..67e3584e1ba 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.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.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 @@ void test_Map_List_pojo() throws Exception { @Test void test_PrimitiveArray() throws Exception { - 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 boolean[] {true, false}); + assertObject(new Boolean[] {true, false, true}); - assertObject(new char[]{'a', '中', '无'}); - assertObject(new Character[]{'a', '中', '无'}); + assertObject(new byte[] {1, 12, 28, 78}); + assertObject(new Byte[] {1, 12, 28, 78}); - assertObject(new short[]{37, 39, 12}); - assertObject(new Short[]{37, 39, 12}); + assertObject(new char[] {'a', '中', '无'}); + assertObject(new Character[] {'a', '中', '无'}); - assertObject(new int[]{37, -39, 12456}); - assertObject(new Integer[]{37, -39, 12456}); + assertObject(new short[] {37, 39, 12}); + assertObject(new Short[] {37, 39, 12}); - assertObject(new long[]{37L, -39L, 123456789L}); - assertObject(new Long[]{37L, -39L, 123456789L}); + assertObject(new int[] {37, -39, 12456}); + assertObject(new Integer[] {37, -39, 12456}); - assertObject(new float[]{37F, -3.14F, 123456.7F}); - assertObject(new Float[]{37F, -39F, 123456.7F}); + assertObject(new long[] {37L, -39L, 123456789L}); + assertObject(new Long[] {37L, -39L, 123456789L}); - assertObject(new double[]{37D, -3.14D, 123456.7D}); - assertObject(new Double[]{37D, -39D, 123456.7D}); + 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}); - 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 @@ void testMapToEnum() throws Exception { @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 @@ void testGeneralizeEnumArray() throws Exception { @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 @@ void testJsonObjectToMap() throws Exception { 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 @@ void testListJsonObjectToListMap() throws Exception { 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 @@ public BigPerson returnBigPersonMethod() { 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 @@ void test_total() throws Exception { @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 @@ void test_LoopPojoInMap() throws Exception { 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 @@ void test_LoopPojoInList() throws Exception { 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 @@ void test_PojoInList() throws Exception { 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 @@ void test_realize_LongPararmter_IllegalArgumentException() throws Exception { 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 @@ void testMapField() throws Exception { 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 @@ void testMapField() throws Exception { } 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 @@ void testRealize() throws Exception { 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 @@ void testDateTimeTimestamp() throws Exception { 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 @@ public void testJSONObjectToPersonMapPojo() { assertEquals(PersonMap.class, result.getClass()); } - protected PersonInfo createPersonInfoByName(String name) { PersonInfo dataPerson = new PersonInfo(); dataPerson.setName(name); @@ -830,12 +828,14 @@ public void testPojoGeneric1() throws NoSuchMethodException { 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 @@ public void testPojoGeneric1() throws NoSuchMethodException { 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 @@ public void testPojoGeneric2() throws NoSuchMethodException { 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 @@ public void testPojoGeneric2() throws NoSuchMethodException { 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 @@ public void testPojoGeneric3() throws NoSuchMethodException { 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 @@ public void testPojoGeneric3() throws NoSuchMethodException { } } - 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 @@ public void testPojoGeneric4() throws NoSuchMethodException { 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 @@ void testNameNotMatch() { 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 @@ public int hashCode() { } 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 @@ public int hashCode() { @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 @@ public boolean equals(Object obj) { } 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 2da5fabfb15..c987b81c30b 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.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 @@ void testIsCompatible() { @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 @@ void testGetGenericClassWithIndex() { @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 @@ void testName2Class() throws Exception { @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 @@ void testGetDescConstructor() { @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 @@ void testFindMethodByMethodName2() { Assertions.assertThrows(IllegalStateException.class, () -> { ReflectUtils.findMethodByMethodName(Foo2.class, "hello"); }); - } @Test @@ -309,23 +310,22 @@ void testDesc2Class() throws Exception { 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 @@ void testFindMethodByMethodSignature() throws Exception { @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 @@ void testFindMethodByMethodSignature_override() throws Exception { 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 @@ public static EmptyProperty getProperties() { return null; } - public void isProperty() { - - } + public void isProperty() {} public boolean isSet() { return set; @@ -503,27 +501,20 @@ public void setSet(boolean set) { } } - 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 @@ public String hello(Integer integer) { } 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 @@ public List hello(int[] ints) { } 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 8afcb0dff10..348de678d9f 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 @@ 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 @@ void testGetProperty(){ 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 37397638ebf..1b9e9e3e657 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.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 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 @@ void test() { 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 @@ void testStatus1() { 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 @@ void testStatus2() { 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 @@ void testStatus3() { 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 @@ void testStatus4() { 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 @@ void testStatus5() { 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 @@ void testConfig1() { 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 @@ void testConfig2() { 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 @@ void testConfig3() { 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 @@ void testConfig3() { System.clearProperty(CommonConstants.CLASS_DESERIALIZE_ALLOWED_LIST); System.clearProperty(CommonConstants.CLASS_DESERIALIZE_BLOCK_ALL); frameworkModel.destroy(); - } @Test @@ -232,12 +238,12 @@ void testSerializable1() { 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 @@ void testSerializable2() { 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 @@ void testGeneric() { 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 @@ void testGenericClass() { 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 @@ void testGenericClass() { frameworkModel.destroy(); } - @Test void testRegister1() { FrameworkModel frameworkModel = new FrameworkModel(); @@ -304,7 +311,8 @@ void testRegister1() { 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 @@ void testRegister1() { frameworkModel.destroy(); } - @Test void testRegister2() { FrameworkModel frameworkModel = new FrameworkModel(); @@ -338,7 +345,8 @@ void testRegister2() { 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 @@ void testRegister3() { 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 @@ void testRegister4() { 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 @@ void testRegister5() { 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 80d41099521..3e183d9e213 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 @@ void testIllegalRemoveNegative() throws Exception { 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 c788d8f7e37..b8748971af4 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 @@ void test() { 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 5d46c2ad18b..cca2309da99 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.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 @@ void testIsJavaIdentifier() throws Exception { @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 @@ -275,7 +276,6 @@ void testSplitToSet() { assertEquals(ofSet("1", "2", "3", "4"), values); } - @Test void testTranslate() throws Exception { String s = "16314"; @@ -287,7 +287,7 @@ void testTranslate() throws Exception { 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')); @@ -318,7 +318,6 @@ void testIsNumeric() throws Exception { assertThat(StringUtils.isNumeric("123.", true), is(true)); assertThat(StringUtils.isNumeric(".123", true), is(true)); assertThat(StringUtils.isNumeric("..123", true), is(false)); - } @Test @@ -340,7 +339,7 @@ void testCamelToSplitName() throws Exception { 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", "-")); @@ -348,7 +347,7 @@ void testCamelToSplitName() throws Exception { 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 @@ -381,7 +380,7 @@ void testConvertToSplitName() { @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}")); @@ -463,7 +462,6 @@ void testEncodeParameters() { blankValueMap.put("client", ""); str = StringUtils.encodeParameters(nullValueMap); assertEquals("[]", str); - } private void assertEqualsWithoutSpaces(String expect, String actual) { @@ -500,6 +498,5 @@ void testStartsWithIgnoreCase() { assertTrue(startsWithIgnoreCase("dubbo.application.name", "dubbo.application.")); assertTrue(startsWithIgnoreCase("dubbo.Application.name", "dubbo.application.")); assertTrue(startsWithIgnoreCase("Dubbo.application.name", "dubbo.application.")); - } -} \ No newline at end of file +} 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 c0b2bcd3c8a..38cf84cd9ee 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.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 c51e8786a73..466e6ba9c1e 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 71d10302b89..fbba7a20394 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 @@ 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.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 @@ void testSubscribe2() { 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 @@ void testIsMatchUrlWithDefaultPrefix() { 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 @@ public void testIsConsumer() { assertFalse(UrlUtils.isConsumer(url1)); assertTrue(UrlUtils.isConsumer(url2)); assertTrue(UrlUtils.isConsumer(url3)); - } @Test @@ -416,7 +414,6 @@ public void testPrivateConstructor() throws Exception { }); } - @Test public void testClassifyUrls() { @@ -457,7 +454,6 @@ public void testHasServiceDiscoveryRegistryProtocol() { 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 @@ public void testIsProvider() { 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 @@ public void testIsProvider() { assertFalse(UrlUtils.isProvider(url5)); } - @Test public void testIsRegistry() { String address1 = "http://example.com"; @@ -540,8 +534,6 @@ public void testIsRegistry() { 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/TestEnum.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/TestEnum.java index f00aa81dd9e..80fffb19ed5 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 436d8a12b85..94bdf75bc80 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 e15a9a1e897..16ea006e243 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 f9781e44718..69dd5dbb08d 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 @@ void testIsFramework263OrHigher() { } @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 @@ protected Class findClass(String name) throws ClassNotFoundException { } } - 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 @@ public Enumeration getResources(String name) throws IOException { } @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 336a0562adc..b71b53b8d58 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 UserVo(String name, String addr, int age) { this.age = age; } - public UserVo() { - } + public UserVo() {} public String getName() { return name; @@ -62,11 +61,7 @@ public static UserVo getInstance() { @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 44a330aad18..1d852d32481 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 @@ public static void tearDown() { System.clearProperty(CommonConstants.DUBBO_PROPERTIES_KEY); } - @Test void checkStub1() { Assertions.assertThrows(IllegalStateException.class, () -> { @@ -256,7 +256,5 @@ protected boolean isNeedCheckMethod() { } } - 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 4ee8fc5bd82..a1c1b49837e 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 212758ec0f5..fb8ad262f65 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 e25653c5148..7c48c9fba0f 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 37e2bf9b3d8..87c9cd4de7f 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 826560831f3..58d229c6bb2 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 @@ void test() { 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 5ddd74aad4f..ae74fc11a4c 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.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 @@ void testProtocolConfig() { 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 @@ void testConfigMode() { configManager.addConfig(applicationConfig2); assertEquals(applicationConfig2, configManager.getApplicationOrElseThrow()); - // test ignore mode System.setProperty(DUBBO_CONFIG_MODE, ConfigMode.IGNORE.name()); ApplicationModel.reset(); @@ -332,7 +331,9 @@ void testConfigMode() { 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 @@ void testConfigMode() { 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 @@ void testGetConfigByIdOrName() { 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 @@ void testGetConfigByIdOrName() { 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 @@ void testGetConfigByIdOrName() { 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 @@ void testLoadConfigsOfTypeFromProps() { System.clearProperty("dubbo.applications.app1.name"); System.clearProperty("dubbo.applications.app2.name"); } - } @Test @@ -466,6 +473,5 @@ void testLoadConfig() { 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 d66136ad1cd..77278b6c567 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 @@ void testInnerClassType() { 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 @@ void testRawMap() { 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 @@ void testEnum() { 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 @@ void testExtendsMap() { 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 1fe844ac2cf..16fa17164d2 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.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 @@ void testBuilderComplexObject() { 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 @@ void checkComplexObjectAsParam(FullServiceDefinition fullServiceDefinition) { 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 @@ void checkComplexObjectAsParam(FullServiceDefinition fullServiceDefinition) { } } 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.assertSame("java.lang.String", innerTypeDefinition.getProperties().get("innerA")); + 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("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 e1427861202..ba227891a43 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 @@ 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 393e7734051..5902af8201b 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 @@ 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 eacd1244cf9..cfe413dab03 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 db00d586102..a48e6d05d67 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 07f1711b724..34c152c7fa5 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 b984dee76e1..d1e083fcea2 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 @@ */ 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 ComplexObject(String var1, int var2, long l, String[] var3, List 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 void setMaps(Map maps) { @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 boolean equals(Object o) { 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 int hashCode() { } public enum TestEnum { - VALUE1, VALUE2 + VALUE1, + VALUE2 } - static public class InnerObject { + public static class InnerObject { String innerA; int innerB; @@ -196,10 +195,7 @@ public void setInnerB(int innerB) { @Override public String toString() { - return "InnerObject{" + - "innerA='" + innerA + '\'' + - ", innerB=" + innerB + - '}'; + return "InnerObject{" + "innerA='" + innerA + '\'' + ", innerB=" + innerB + '}'; } @Override @@ -207,8 +203,7 @@ public boolean equals(Object o) { 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 int hashCode() { } } - static public class InnerObject2 { + public static class InnerObject2 { String innerA2; int innerB2; @@ -239,10 +234,7 @@ public void setInnerB2(int innerB2) { @Override public String toString() { - return "InnerObject{" + - "innerA='" + innerA2 + '\'' + - ", innerB=" + innerB2 + - '}'; + return "InnerObject{" + "innerA='" + innerA2 + '\'' + ", innerB=" + innerB2 + '}'; } @Override @@ -250,8 +242,7 @@ public boolean equals(Object o) { 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 int hashCode() { } } - static public class InnerObject3 { + public static class InnerObject3 { String innerA3; public String getInnerA3() { @@ -273,9 +264,7 @@ public void setInnerA3(String innerA3) { @Override public String toString() { - return "InnerObject3{" + - "innerA3='" + innerA3 + '\'' + - '}'; + return "InnerObject3{" + "innerA3='" + innerA3 + '\'' + '}'; } @Override @@ -292,5 +281,3 @@ public int hashCode() { } } } - - 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 cd24b03e62d..4dba2b24c89 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 a0608064ed5..a4c87d6560b 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 @@ 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 6735caa5f54..65ce53287cd 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.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 @@ void testDestroy() { } catch (Exception e) { Assertions.assertEquals("ApplicationModel is destroyed", e.getMessage(), StringUtils.toString(e)); } - } @Test @@ -172,5 +171,4 @@ void testCopyOnWriteArrayListIteratorAndRemove() throws InterruptedException { 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 3359c73525a..73e6f21a427 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 @@ void destroyAll() { 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 408fbc13c57..f67a3479fa7 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.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 @@ void test() { 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 @@ void test() { 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 @@ void test() { 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 4bf1b6f7482..7ba7ccc296b 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 @@ void testDestroy() { // 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 b78e6cbe827..b62ed7f3a7f 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.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 @@ void test() { 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 @@ void test() { 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 @@ void test() { 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 @@ void test() { 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 @@ void test() { 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 d09fcc0a248..a1af12566c2 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 int hashCode() { @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 93462ada31c..352b1ac645a 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 @@ void getMethod() { @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 @@ void getReturnClass() { @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 @@ void addAttribute() { @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 @@ void testEquals() { @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 @@ void testHashCode() { 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 b7011526be8..11ddacfb424 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 @@ 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 @@ void testStreamRpcTypeException() { 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 @@ void getMethod() { @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 @@ void getMethods() { @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 87d0c117715..e1eb6b7a361 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 @@ void testInitialize() { 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 a7f56c40666..c72e3076bf3 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 @@ 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 @@ void testCreateOnDestroy() throws InterruptedException { 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 2e90314da19..b6e4384cb8f 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.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 @@ void test() { 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.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.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)); } - @SPI(scope = ExtensionScope.FRAMEWORK) - interface SPIDemo1 { - - } + interface SPIDemo1 {} @SPI(scope = ExtensionScope.APPLICATION) - interface SPIDemo2 { - - } + interface SPIDemo2 {} @SPI(scope = ExtensionScope.MODULE) - interface SPIDemo3 { - - } - - interface SPIDemo4 { + interface SPIDemo3 {} - } + interface SPIDemo4 {} class MockScopeModel extends ScopeModel { public MockScopeModel(ScopeModel parent, ExtensionScope scope) { @@ -103,9 +108,7 @@ public MockScopeModel(ScopeModel parent, ExtensionScope scope) { } @Override - protected void onDestroy() { - - } + protected void onDestroy() {} @Override public Environment modelEnvironment() { @@ -117,5 +120,4 @@ protected Lock acquireDestroyLock() { 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 6fff76c1337..dc9848ede9a 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 int hashCode() { @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 d7490c0333b..6d29ea5be04 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.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 @@ public void reset() { @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 @@ void test() { 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 68db5a727cf..cf55802c9fd 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 c9df8335558..f9a885cf82a 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 void setSize(Size size) { } 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 7987460a610..59f856f094f 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 @@ @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 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 String copyright; // Can be unset. + + 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) { this.uri = uri; this.title = title; this.width = width; @@ -200,6 +211,7 @@ public void setCopyright(String copyright) { } 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 3c24fd9f952..b80e91ece30 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 int hashCode() { @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 String toString() { + 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 dfbb56fa174..26288df28eb 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 FullAddress(String countryId, String provinceName, String cityId, String 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 int hashCode() { @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 String toString() { } 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 57f156b6604..9b7aaf9d7b9 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 int hashCode() { @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 String toString() { + 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 ee18ade41d6..523fac549c6 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 int hashCode() { @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 String toString() { } 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 19e24c5d71b..ed7a8f2657d 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 025122368fa..1bfbd97e21e 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 7b5ec906fb5..b19852cbe05 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 @@ 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 d0cc3ae95c1..8ea272749f2 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 @@ void testGetServiceKey() { 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 @@ private static String serviceKeyOldImpl(int port, String serviceName, String ser 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 ec42b071f7b..e8059276165 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.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 - - - 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.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 + + + 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 62539d233ee..44a0a67b58a 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 626eed2b4e1..83092a2a22a 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 6ca184c6607..05a9c25d52d 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 Cache getCache(URL url, Invocation invocation) { 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 4ed46e5e23c..9579e26d67f 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.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 2825e89cea7..918b7d8a92f 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 boolean equals(Object obj) { 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 3491c841d5d..4809d5168d2 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 @@ protected 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 URL(String protocol, String username, String password, String host, int p 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 String getProtocol() { @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 String getUsername() { @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 String getPassword() { @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 String getHost() { @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 int getPort() { @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 String getBackupAddress(int defaultPort) { 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 String getPath() { @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 URL setServiceInterface(String service) { } 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 548a6ab9a65..eaac5445e4d 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 875e25b6022..4cf96d7227d 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 @@ * @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 bd98ea2e777..a5efb0e5242 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 @@ @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 ed26a62034a..e8dff684c85 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 a6caf8828e3..c6167fd7ddf 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 5d57dc77624..39c81e807e8 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 dc82b3195f6..45b6bca8680 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 04600acf3c5..f83369a2e4c 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 3f74c133ffa..5c4b4300e17 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 81a25a8c4fc..c08b87fa404 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 da4adf80ba3..6af6fefb20c 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 aec0f871b71..92bb1968c07 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 static URL parseURL(String address, Map defaults) { } 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 static Map> revertNotify(Map 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 static boolean isMatchCategory(String category, String categories) { } 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 static boolean isMatchGlobPattern(String pattern, String value) { } 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 ab5f8c2fa80..ddb4a61d01e 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 2ba33bbdf45..f65bb0c198d 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 3c24db1d2af..6ba119b77a7 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 ff368c70118..528846ef0f2 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 3b122efc562..8472cdd3601 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 0c5d17525b3..fac470dd773 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 3f716c3480b..4cdcb25c6b5 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 ProtocolConfig(String name, int port) { 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 f7ff0c345c6..d6a91e73f96 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 1e40b6f4c9c..35db9e9c68a 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 @@ @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 501f918ba08..4da493f764c 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 e874a59798b..fbd752f3582 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 @@ @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 com.alibaba.dubbo.config.MonitorConfig getMonitor() { 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 ae28c751a15..9cc65f7595d 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 @@ 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 5de941fa33d..84da43fae7b 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 @@ 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 bb13c8732b8..e9d6380c7a3 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.RetentionPolicy; import java.lang.annotation.Target; +import org.springframework.core.annotation.AliasFor; + @Deprecated @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @@ -62,7 +61,6 @@ @AliasFor(annotation = DubboComponentScan.class, attribute = "basePackageClasses") Class[] scanBasePackageClasses() default {}; - /** * It indicates whether {@link AbstractConfig} binding to multiple Spring Beans. * @@ -71,5 +69,4 @@ */ @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 4f236dd93a2..51c50fd36b1 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 fad7b525340..8905faf5b45 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 @@ 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 645f9408bea..e16196dfa81 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 int compare(PageHandler o1, PageHandler o2) { 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 5583912c124..24042939a80 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 Page(String navigation) { 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 List getColumns() { 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 ac8fee7c555..e0528888971 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 040101d2826..25486c07edb 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.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.Random; import java.util.concurrent.ConcurrentHashMap; +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; + /** * PageServlet */ @@ -71,7 +72,8 @@ public void init() throws ServletException { 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 @@ protected final void doPost(HttpServletRequest request, HttpServletResponse resp 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 @@ protected final void doPost(HttpServletRequest request, HttpServletResponse resp 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 @@ protected final void doPost(HttpServletRequest request, HttpServletResponse resp 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 @@ protected final void writeMenu(HttpServletRequest request, PrintWriter writer, S 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 @@ protected final void writeTable(PrintWriter writer, String title, List c writer.println(" "); int j = 0; for (String col : row) { - writer.println(" "); + writer.println(" "); j++; } writer.println(" "); @@ -276,5 +281,4 @@ protected final void writeTable(PrintWriter writer, String title, List c 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 3ffd172869f..62f3da3d8e4 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.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.util.ArrayList; import java.util.List; +import com.alibaba.dubbo.common.Constants; + /** * ResourceServlet */ @@ -63,8 +64,7 @@ public void init(FilterConfig filterConfig) throws ServletException { } } - public void destroy() { - } + public void destroy() {} public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { @@ -138,7 +138,9 @@ private InputStream getInputStream(String uri) { 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 @@ private InputStream getInputStream(String uri) { } 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 f2433458956..306706c22cc 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 @@ 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 Page handle(URL url) { 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 874bdb3dfd3..ee9f3670d53 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.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 Page handle(URL url) { 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 Page handle(URL url) { 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 50e5564c68f..f0fdb34a2ad 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.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 Page handle(URL url) { 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 @@ private String getLevelColor(Status.Level level) { } 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 c4c6308b767..0c8e3c26ec4 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 @@ 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.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 Page handle(URL url) { 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 Page handle(URL url) { 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 6e1ed3767b6..a4205e886f1 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 @@ default void collect(URL statistics) { @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 4f30d1f3c76..9a054c53278 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 e44d92311ad..168b8fd2307 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 6428e1d5fb6..9f474b30b06 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 ae262e1fa76..8c425dd29dd 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 8256b368db8..1394a1c0eef 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 @@ default void unregister(URL url) { @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 e0eaf5c52b8..7cd7e8cbb37 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 48a8cafc184..26cc9de0b81 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 @@ protected void setUrl(com.alibaba.dubbo.common.URL url) { } 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 void unregister(com.alibaba.dubbo.common.URL url) { } 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 void unregister(URL url) { @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 badd9f082ed..4b9218f641c 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 @@ * 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 f50c2c1fb41..ccc1997cf42 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 void removeFailedUnregisteredTask(URL url) { } 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 void unregister(URL url) { @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 @@ protected void recover() throws Exception { @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 List lookup(org.apache.dubbo.common.URL url) 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 void doUnregister(org.apache.dubbo.common.URL url) { @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 void recover() throws Exception { 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 a900047fb98..a3e1192e7f3 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 4be71fe31a0..a5fe7e16b53 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 c398fe7110b..a3759734727 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 5bb4bb25ff0..12645da3661 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 3ec02d45c27..0f146e3c834 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 @@ @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 c863a510347..c86262ff04a 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 RemotingException(Channel channel, String message, Throwable cause) { 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 2ad23d6ad64..c89fb61a19a 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 @@ 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 b34aca3232b..c984a701b73 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 b8f20f65b2b..807b4afcc47 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 30a71afdf14..614bfdc5dfa 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 c7083a6058b..461531e8220 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 6deaab96f39..c0982a08454 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 0cd3e5d1279..81479debf78 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 @@ @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 61252825e8c..25cabd64ce1 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 d89fe3aa5ce..cca7cbd8f15 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 c196baa5171..d21aca9a481 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 85e5cfcfe52..a2dfd103290 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 @@ default void setAttachmentIfAbsent(String key, String value) { } @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 @@ default void setAttachmentIfAbsent(String key, Object value) { setObjectAttachmentIfAbsent(key, value); } - @Override default String getServiceName() { return null; @@ -82,9 +77,7 @@ default String getAttachment(String key, String defaultValue) { } @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 c8b86f98a28..fc4c053ddb6 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 @@ default org.apache.dubbo.rpc.Invoker getOriginal() { // 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 Class getInterface() { } @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 void destroy() { 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 6ba4a37b479..ffca181f1f0 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 ba603d6b1b6..690ee86fe4f 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 @@ default org.apache.dubbo.rpc.Exporter export(org.apache.dubbo.rpc.Invoker } @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 35ff7f0da9a..933541ef113 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 040736647a3..da5bc07608c 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 @@ 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 @@ default Map getObjectAttachments() { } @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 @@ default Object getObjectAttachment(String key, Object defaultValue) { return null; } - /** * @see com.alibaba.dubbo.rpc.Result#getValue() * @deprecated Replace to getValue() @@ -86,7 +76,8 @@ public org.apache.dubbo.rpc.Result getDelegate() { } @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 org.apache.dubbo.rpc.Result get() throws InterruptedException, ExecutionE } @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 cfc5fb4b8bb..6f1b383e629 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.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 static RpcContext getContext() { 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 static RpcContext getClientResponseContext() { 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 static void removeServerResponseContext() { 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 T getRequest(Class clazz) { return newRpcContext.getRequest(clazz); } - public void setRequest(Object request) { newRpcContext.setRequest(request); } @@ -336,9 +337,7 @@ public List> getInvokers() { 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 Future asyncCall(Callable callable) { 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 T get() throws InterruptedException, ExecutionException { @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 1e994019ac3..b01ca571b5d 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 7206210ceb6..d9bc2dd6627 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.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 RpcInvocation(Invocation invocation, Invoker invoker) { } 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 RpcInvocation(String methodName, Class[] parameterTypes, Object[] argu 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 String toString() { + 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 d62eb094189..e383ff24766 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 @@ @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 RpcResult(Object result) { 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 13c9629c362..e92ca0ef1e0 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 @@ @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 69a2f4b7ad3..750a88b6c73 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 d0f978afa60..cec780365f6 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.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 b5f37fbcb23..093ed29eb39 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 2bc4aabd189..94bf7362fce 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.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 @@ List> route(List 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 @@ default int getPriority() { } @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 f57a0023d5e..34160fe846d 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 acf6c8797ba..eb67cdb615d 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 98f9aa78fd4..d2a1a2aec37 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 @@ protected int getWeight(Invoker invoker, Invocation invocation) { } 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 b2bba70b7f9..448d26a4eb0 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.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 void accept(Object obj, Throwable t) { } 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 boolean isDone() { 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 V get() throws InterruptedException, ExecutionException { 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 e47b1ca17f7..ad2508fa6fa 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 470e952b40f..e50733b17db 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 0d5ac6fed24..aa0275df4ae 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 cc3282a7a08..113c9734505 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 378f14adc29..45a333e9dc1 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 static void attachInvocationIdIfAsync(URL url, Invocation inv) { 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 4881f3395a5..673bbefb1b8 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 97719c2c004..fbee29fb737 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 b60f7bf163b..47c6f4a9ae4 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 @@ void testCacheFactory() { 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 @@ public Map getAttributes() { } @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 c7a7528350c..72941d7951e 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 aa22fbe4a74..25560a70de8 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 187c28905a7..0dca5da42b9 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.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 @@ private ExtensionLoader getExtensionLoader(Class type) { @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 732f333c082..5b5e77c897d 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 d2187b9d748..548b5f0b8ab 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 T getExtension(final Class type, final String name) { } 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 c00a988577d..e828f7775d2 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 fe3e082d499..8c62c2462f9 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 1c1cf7dc80d..9ddcd7d19d4 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 @@ 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 612440894d4..1a088264125 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 @@ 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 5f30dd650e0..b1408919bfd 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 @@ 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 df93fa6eaf8..3b9b9e27c8d 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 @@ 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 c02aaa13c26..38f787a306b 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 @@ 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 353874bc9a7..fdca0bcff55 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 @@ 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 c01e4c93b29..ba1be8a1aa9 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 58feca16920..2f1c73170b2 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 634e92f12f2..c900d474800 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 cf23ffee942..a58500f413f 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 b09ed993a90..99b08f9ebbf 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 26b1960f35c..da9d879335b 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.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.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 @@ void testGetAllDeclaredAnnotations() { 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 @@ void testGetAllMetaAnnotations() { 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 @@ void testFindMetaAnnotation() { } @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 @@ public void execute() { @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 @@ public void execute() { @interface MyAdaptive { String[] value() default {}; - } @Service5 @@ -350,17 +338,11 @@ static class B extends A { @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 @@ private void assertADeclaredAnnotations(List annotations, int offset 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 3d35af99844..fb2b13d6eb1 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 ba1ba93a638..2ffa853a0c3 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 2470a2da244..2a4f4af975f 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.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 5dda5ae966e..1e4a51fb1d3 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 f53106d7939..9e4b975adf3 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 @@ void testConvertMethodConfig2AsyncInfo() throws Exception { 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 @@ void testOnreturnMethod() { assertThat(parameters.size(), is(0)); } - //@Test + // @Test void testOnthrow() { MethodConfig method = new MethodConfig(); method.setOnthrow("on-throw-object"); @@ -176,7 +175,7 @@ void testOnthrowMethod() { 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 45c60bbb208..ff52b0aeb10 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 983d2bb43f2..cb31ea9b4b0 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 ccbffaebd38..d88abf52a6b 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 @@ void testContextPath() throws Exception { 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 7eacd6acce4..a4bdd495f25 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 dd42978cfb5..fca18eb1f2c 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 ac1d1647dc3..ffb7d479d53 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 @@ 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 ed168fc37a7..9fc3119aa45 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 @@ 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 84fd9397160..a0314e6f58b 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 3cc54160967..d6e9fbcf64e 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 59f1385a130..358bda2dc65 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 RegistryConfig registryConfig() { * * @return {@link ProtocolConfig} Bean */ - @Bean//("dubbo") + @Bean // ("dubbo") public ProtocolConfig protocolConfig() { ProtocolConfig protocolConfig = new ProtocolConfig(); protocolConfig.setName("dubbo"); @@ -95,15 +94,10 @@ public TransactionStatus getTransaction(TransactionDefinition definition) throws } @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 6ad42e80c79..5f5d4ac3aae 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 @@ public void setUp() { } @AfterEach - public void tearDown() { - } + public void tearDown() {} @Test void test() { @@ -71,7 +70,6 @@ void test() { // Test @Transactional is present or not Assertions.assertNotNull(findAnnotation(beanClass, Transactional.class)); - // consumer app AnnotationConfigApplicationContext consumerContext = new AnnotationConfigApplicationContext(); @@ -121,9 +119,5 @@ void test() { 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 f4b705315e0..69acec2129a 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.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.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.core.io.support.ResourcePropertySource; -import java.io.IOException; - /** * {@link DubboConfigConfiguration} Test * @@ -47,7 +47,6 @@ public void before() throws IOException { context = new AnnotationConfigApplicationContext(); ResourcePropertySource propertySource = new ResourcePropertySource("META-INF/config.properties"); context.getEnvironment().getPropertySources().addFirst(propertySource); - } @AfterEach @@ -90,5 +89,4 @@ void testMultiple() { 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 803241d5355..ba5392a02d5 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.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 @@ public void tearDown() { DubboBootstrap.reset(); } - //@Test + // @Test public void testSingle() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); @@ -88,7 +87,6 @@ public void testSingle() { 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 @@ public void testSingle() { assertFalse(hasAlias(context, "org.apache.dubbo.config.MonitorConfig#0", "zookeeper")); } - //@Test + // @Test public void testMultiple() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); @@ -119,22 +117,17 @@ public void testMultiple() { 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 729d5ec5f08..ebaa0dcded3 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.TransactionException; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.annotation.EnableTransactionManagement; + /** * {@link EnableDubbo} Test * @@ -113,7 +114,6 @@ void testConsumer() { // Test multiple binding Assertions.assertEquals("N/A", registryConfig.getAddress()); - } @EnableDubbo(scanBasePackages = "org.apache.dubbo.config.spring.context.annotation.provider") @@ -134,17 +134,11 @@ public TransactionStatus getTransaction(TransactionDefinition definition) throws } @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 9fd7b2e1b77..5f3aabb3f9c 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.PropertySource; @Configuration("consumerConfiguration") -@DubboComponentScan( - basePackageClasses = ConsumerConfiguration.class -) +@DubboComponentScan(basePackageClasses = ConsumerConfiguration.class) @PropertySource("META-INF/default.properties") public class ConsumerConfiguration { @@ -80,13 +78,12 @@ public void setDemoService(DemoService demoService) { 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 void setDemoServiceFromAncestor(DemoService demoServiceFromAncestor) { } } - public static abstract class Parent extends Ancestor { + public abstract static class Parent extends Ancestor { private DemoService demoServiceFromParent; @@ -112,7 +109,6 @@ public DemoService getDemoServiceFromParent() { public void setDemoServiceFromParent(DemoService demoServiceFromParent) { this.demoServiceFromParent = demoServiceFromParent; } - } public static class Child extends Parent { @@ -123,7 +119,6 @@ public static class Child extends Parent { @Reference(version = "2.5.7", url = remoteURL) private DemoService demoServiceFromChild; - public DemoService getDemoService() { return demoService; } @@ -136,5 +131,4 @@ public void setDemoServiceFromChild(DemoService demoServiceFromChild) { 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 5869d95e899..87a44c7b420 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 void setDemoService(DemoService demoService) { 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 void setDemoServiceFromAncestor(DemoService demoServiceFromAncestor) { } } - public static abstract class Parent extends Ancestor { + public abstract static class Parent extends Ancestor { private DemoService demoServiceFromParent; @@ -98,11 +98,14 @@ public DemoService getDemoServiceFromParent() { 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 c4df6f43408..8b50e8780be 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 8ee2a8a09f6..62f7e24b747 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.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; - /** * {@link DemoService} Service implementation * @@ -34,8 +33,7 @@ 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 59e0cb3d772..d4e103aad7f 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.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.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 @@ protected void doRollback(DefaultTransactionStatus status) throws TransactionExc } }; } - } - 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 9006995903d..c43c9bd1b89 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 @@ /** * 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 d8f6f9cd754..470e50db888 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 @@ /** * 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 e41d734c609..daedbb3990c 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 void setProtocol(Protocol protocol) { 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 74ad8d6cc6d..cdd615874f2 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 @@ void testEcho() { 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 24996c2c323..a66ac4cda88 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 @@ void testInvokeException() { @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 @@ void testDefault() throws Throwable { @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 8495a944e91..cddcb9956b3 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 String getMethodName() { } 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 String getAttachment(String key, String defaultValue) { } @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 328b842321f..8b72325053b 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 Result invoke(Invocation invocation) throws RpcException { } @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 68c5c8786b6..6f9dac39967 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.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 3ec36e00f4c..26f99a6f2d6 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.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 @@ public void beforeEach() { @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 @@ void testGeneric() { @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 @@ void testGeneric2() { @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 @@ void testGenericCompatible() { 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 @@ void testGenericCompatible() { @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 @@ void testGenericComplexCompute4FullServiceMetadata() { 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 @@ void testGenericComplexCompute4FullServiceMetadata() { @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 @@ MethodDefinition getMethod(String methodName, List list) { 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 @@ Map createComplexObject(FullServiceDefinition fullServiceDefinit } } 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.assertSame("java.lang.String", innerTypeDefinition.getProperties().get("innerA")); + 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("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 @@ Map createComplexObject(FullServiceDefinition fullServiceDefinit 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 @@ ComplexObject map2bean(Map map) { 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 abe91275d46..cbb0a5da771 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 @@ 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 a02432711be..4b21c6437ff 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 fe97b4b4b87..44689fe64e1 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 @@ 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 cd84396e6d3..779cbd08b8c 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.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 @@ void testBuild() { 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 e99d4177842..865613a496e 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 @@ 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 @@ protected void addCompiledClasses(Set> classesToBeCompiled) { 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 @@ void testAccept() { @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 49572e708e2..d3a7261f577 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.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 @@ void testBuild() { 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 8ca703aa320..7a930e5924d 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.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 @@ protected void beforeEach() { @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 4f486846063..dd7944c66ec 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.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 @@ protected void beforeEach() { 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 @@ void testAccept() { @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 @@ static void buildAndAssertTypeDefinition(ProcessingEnvironment processingEnv, Va 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 3c9774cf6c7..db714bde3fd 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.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 @@ protected void beforeEach() { 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 @@ void testBuild() { 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 9906f12975d..0f57ba37785 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.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 @@ */ 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 @@ void testBuild() { "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 08f008d394c..10118ee8bdf 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 @@ 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 28bf4f31113..8c8a63a8f54 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 @@ */ 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 e90f1c8926e..f3704322039 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 9fab9df62de..e1fc517bee7 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 @@ * @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 087aa932ed6..fb582960342 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 186b06bb4f3..18814dc2732 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.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.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 @@ void testGetAnnotations() { 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 @@ void testGetAllAnnotations() { 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 @@ void testGetAllAnnotations() { 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 @@ void testFindAnnotation() { @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 @@ void testGetAttribute() { 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 74b69cc72df..d2e5f72e2a1 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.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.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 @@ void testIsField() { 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 59a1b4545a4..7b43a1210e7 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.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 dca4090df5d..ee3ecc4eac1 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.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 @@ void testIsMethod() { @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 @@ void testReturnType() { @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 1bca2bc0275..d7dc3d6771e 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.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 @@ 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 @@ void testConstants() { 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 @@ void testIsServiceAnnotationPresent() { @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 @@ void testGetAnnotation() { @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 04e86e77ff3..282c5c470cb 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.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.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 @@ void testIsClassType() { @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 @@ void testGetHierarchicalTypes() { 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 @@ void testGetHierarchicalTypes() { 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 @@ void testGetHierarchicalTypes() { 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 @@ void testGetHierarchicalTypes() { 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 @@ void testGetHierarchicalTypes() { 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 @@ void testGetHierarchicalTypes() { 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 @@ void testGetHierarchicalTypes() { assertTrue(getHierarchicalTypes((TypeMirror) null).isEmpty()); } - @Test void testGetInterfaces() { TypeElement type = getType(Model.class); @@ -296,7 +328,8 @@ void testGetInterfaces() { 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 @@ void testGetAllInterfaces() { 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 @@ void testGetAllInterfaces() { 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 @@ void testOfTypeElement() { @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 @@ void testListDeclaredTypes() { 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 @@ void testListTypeElements() { 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 65d67ab475d..7b6883780da 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 c2daf9b1045..b475bd53da8 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 @@ 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.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 String param(@RequestParam(defaultValue = "value-param") String param) { @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 String form(@RequestParam("f") String form) { @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 684d76fd3b2..2f7d57e557b 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.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 String params(@QueryParam("a") int a, @QueryParam("b") String b) { @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 String headers(@HeaderParam("h") String header, @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 String form(@FormParam("f") String form) { @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 e2f27dd3064..5874ad05620 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.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 @@ private File javaSourceFile(String sourceClassName) { } 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 071e1b26c8f..762e297d362 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 d7b73c4abcc..9b020d2ca4d 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.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 85bce6924dd..bb2bc21b635 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 @@ * * @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 83cf19ff2cc..637e4d1077f 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 5f0ed6e0931..b8ea68c957f 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.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 ce17abd5921..5871c21fefe 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.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 e55fdf3da4f..84c8199dc7d 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.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 cb8ae82354a..42cdaa1811d 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.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 ProcessingEnvironment getProcessingEnvironment() { 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 83c0ef6affe..83fdf165e8f 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.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 713e8e701b6..fe5f42c496c 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 @@ 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 String echo(String message) { } @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 20c311104e6..27b35778cde 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 2351b214409..af437dc8827 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 13350d4572f..47ec05c0901 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 056bd106fd0..dcd8311e5d4 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 @@ public static void setUp () { } @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 874950ce801..a2dd7d196a5 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 @@ 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 @@ void testInvokeWithException() throws Exception { 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 ed595724f8c..325f1e4fde6 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 22ded467770..b5368d2b38b 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 0e1d96c9e32..925d20b4e84 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 7147515a666..3f0cbed6a3b 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 MyObjectOutput(OutputStream outputStream) { } @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 void writeUTF(String v) throws IOException { } @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 94db7059f94..cc6ee02de16 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 9dcfa9114c2..28a8cb7fff4 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 7941af88ff2..b2dcda7fc98 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 @@ */ 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 ComplexObject(String var1, int var2, long l, String[] var3, List 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 void setMaps(Map maps) { @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 boolean equals(Object o) { 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 int hashCode() { } public enum TestEnum { - VALUE1, VALUE2 + VALUE1, + VALUE2 } - static public class InnerObject { + public static class InnerObject { String innerA; int innerB; @@ -195,10 +195,7 @@ public void setInnerB(int innerB) { @Override public String toString() { - return "InnerObject{" + - "innerA='" + innerA + '\'' + - ", innerB=" + innerB + - '}'; + return "InnerObject{" + "innerA='" + innerA + '\'' + ", innerB=" + innerB + '}'; } @Override @@ -206,8 +203,7 @@ public boolean equals(Object o) { 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 int hashCode() { } } - static public class InnerObject2 { + public static class InnerObject2 { String innerA2; int innerB2; @@ -238,10 +234,7 @@ public void setInnerB2(int innerB2) { @Override public String toString() { - return "InnerObject{" + - "innerA='" + innerA2 + '\'' + - ", innerB=" + innerB2 + - '}'; + return "InnerObject{" + "innerA='" + innerA2 + '\'' + ", innerB=" + innerB2 + '}'; } @Override @@ -249,8 +242,7 @@ public boolean equals(Object o) { 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 int hashCode() { } } - static public class InnerObject3 { + public static class InnerObject3 { String innerA3; public String getInnerA3() { @@ -272,9 +264,7 @@ public void setInnerA3(String innerA3) { @Override public String toString() { - return "InnerObject3{" + - "innerA3='" + innerA3 + '\'' + - '}'; + return "InnerObject3{" + "innerA3='" + innerA3 + '\'' + '}'; } @Override @@ -291,5 +281,3 @@ public int hashCode() { } } } - - 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 220b3f178f1..25696349d7b 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 cdd0d278d5f..3379be21758 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 ea2ac17b3e6..c74dc3ce480 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 @@ /** * DemoServiceImpl */ - public class DemoServiceImpl implements DemoService { public DemoServiceImpl() { super(); @@ -42,25 +41,23 @@ public String getThreadName() { } 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 String complexCompute(String input, ComplexObject co) { } @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 d29e339c1fe..80af8954439 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 String getServiceName() { } 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 Object get(Object key) { } @Override - public void setServiceModel(ServiceModel serviceModel) { - - } + public void setServiceModel(ServiceModel serviceModel) {} @Override public ServiceModel getServiceModel() { @@ -182,9 +180,7 @@ public Object getObjectAttachment(String key, Object defaultValue) { } @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 8bdb392b768..3700bccad50 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-compiler/pom.xml b/dubbo-compiler/pom.xml index 5cb8a9c8a7e..61245b78882 100644 --- a/dubbo-compiler/pom.xml +++ b/dubbo-compiler/pom.xml @@ -1,3 +1,4 @@ + + + 4.0.0 - - 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + + dubbo-compiler + jar - - org.apache.dubbo - dubbo-parent - ${revision} - ../pom.xml - - jar - dubbo-compiler + ${project.artifactId} + Dubbo customized RPC stub compiler. - ${project.artifactId} - Dubbo customized RPC stub compiler. + + false + - - false - + + + com.salesforce.servicelibs + jprotoc + + + io.grpc + grpc-core + + + io.grpc + grpc-stub + + + io.grpc + grpc-protobuf + + + io.grpc + grpc-context + + + com.salesforce.servicelibs + grpc-contrib + + - - - com.salesforce.servicelibs - jprotoc - - - 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 + true + ${java_source_version} + ${java_target_version} + ${file_encoding} + + - - - - org.apache.maven.plugins - maven-compiler-plugin - - -proc:none - true - ${java_source_version} - ${java_target_version} - ${file_encoding} - - + + 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-compiler/src/main/java/org/apache/dubbo/gen/AbstractGenerator.java b/dubbo-compiler/src/main/java/org/apache/dubbo/gen/AbstractGenerator.java index de9e67bd8ca..8a7e3411fcc 100644 --- a/dubbo-compiler/src/main/java/org/apache/dubbo/gen/AbstractGenerator.java +++ b/dubbo-compiler/src/main/java/org/apache/dubbo/gen/AbstractGenerator.java @@ -16,6 +16,14 @@ */ package org.apache.dubbo.gen; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + import com.google.common.base.Strings; import com.google.common.html.HtmlEscapers; import com.google.protobuf.DescriptorProtos.FileDescriptorProto; @@ -23,20 +31,12 @@ 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.CodeGeneratorResponse.Feature; import com.google.protobuf.compiler.PluginProtos; +import com.google.protobuf.compiler.PluginProtos.CodeGeneratorResponse.Feature; import com.salesforce.jprotoc.Generator; import com.salesforce.jprotoc.GeneratorException; import com.salesforce.jprotoc.ProtoTypeMap; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - public abstract class AbstractGenerator extends Generator { private static final int SERVICE_NUMBER_OF_PATHS = 2; @@ -72,39 +72,35 @@ private String getMethodJavaDocPrefix() { } @Override - public List generateFiles( - PluginProtos.CodeGeneratorRequest request) throws GeneratorException { + public List generateFiles(PluginProtos.CodeGeneratorRequest request) + throws GeneratorException { 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 +122,32 @@ private String extractCommonPackageName(FileDescriptorProto proto) { 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 +156,23 @@ private ServiceContext buildServiceContext(ServiceDescriptorProto serviceProto, 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 +198,7 @@ private String lowerCaseFirst(String s) { 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 +218,24 @@ private List buildFile(ServiceContext c 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; @@ -273,20 +253,17 @@ private String getFileName(String dir, String fileName) { } 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; @@ -320,13 +297,15 @@ public List unaryRequestMethods() { } 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() { @@ -334,19 +313,18 @@ public List biStreamingMethods() { } 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; } - } /** @@ -374,8 +352,9 @@ public String methodNameUpperUnderscore() { 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-compiler/src/main/java/org/apache/dubbo/gen/dubbo/Dubbo3Generator.java b/dubbo-compiler/src/main/java/org/apache/dubbo/gen/dubbo/Dubbo3Generator.java index 29a789b22e4..fad97d19841 100644 --- a/dubbo-compiler/src/main/java/org/apache/dubbo/gen/dubbo/Dubbo3Generator.java +++ b/dubbo-compiler/src/main/java/org/apache/dubbo/gen/dubbo/Dubbo3Generator.java @@ -41,16 +41,15 @@ protected String getClassSuffix() { } @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-compiler/src/main/java/org/apache/dubbo/gen/tri/Dubbo3TripleGenerator.java b/dubbo-compiler/src/main/java/org/apache/dubbo/gen/tri/Dubbo3TripleGenerator.java index ae3f8c0539e..827fd119bd7 100644 --- a/dubbo-compiler/src/main/java/org/apache/dubbo/gen/tri/Dubbo3TripleGenerator.java +++ b/dubbo-compiler/src/main/java/org/apache/dubbo/gen/tri/Dubbo3TripleGenerator.java @@ -50,7 +50,6 @@ protected String getInterfaceTemplateFileName() { return "Dubbo3TripleInterfaceStub.mustache"; } - @Override protected String getSingleTemplateFileName() { throw new IllegalStateException("Do not support single template!"); diff --git a/dubbo-compiler/src/main/java/org/apache/dubbo/gen/tri/reactive/ReactorDubbo3TripleGenerator.java b/dubbo-compiler/src/main/java/org/apache/dubbo/gen/tri/reactive/ReactorDubbo3TripleGenerator.java index dfc8d86e612..5f379ff5e7a 100644 --- a/dubbo-compiler/src/main/java/org/apache/dubbo/gen/tri/reactive/ReactorDubbo3TripleGenerator.java +++ b/dubbo-compiler/src/main/java/org/apache/dubbo/gen/tri/reactive/ReactorDubbo3TripleGenerator.java @@ -14,12 +14,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.gen.tri.reactive; -import com.salesforce.jprotoc.ProtocPlugin; import org.apache.dubbo.gen.AbstractGenerator; +import com.salesforce.jprotoc.ProtocPlugin; + public class ReactorDubbo3TripleGenerator extends AbstractGenerator { public static void main(String[] args) { diff --git a/dubbo-config/dubbo-config-api/pom.xml b/dubbo-config/dubbo-config-api/pom.xml index 2e004260fed..55643e4f8fa 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} - - - - org.apache.dubbo - dubbo-metadata-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-registry - ${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-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-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-registry-multicast - ${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.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-redis - ${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-filter-cache - ${project.parent.version} - test - - - - org.apache.dubbo - dubbo-filter-validation - ${project.parent.version} - test - - - - org.testcontainers - testcontainers - 1.19.1 - test - - - - org.jboss.resteasy - resteasy-jackson-provider - test - - - - + + 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-metrics-api + ${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-metadata + ${project.parent.version} + + + + org.apache.dubbo + dubbo-metrics-config-center + ${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-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-registry-multicast + ${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.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-redis + ${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-filter-cache + ${project.parent.version} + test + + + + org.apache.dubbo + dubbo-filter-validation + ${project.parent.version} + test + + + + org.testcontainers + testcontainers + 1.19.1 + 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 8f12d79c766..52fe883d4cc 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 @@ /** * 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 efb779aee71..1d1a534eb06 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 @@ -22,15 +22,10 @@ /** * 2019/12/30 */ - @SPI(scope = ExtensionScope.MODULE) public interface ConfigPostProcessor { - default void postProcessReferConfig(ReferenceConfig referenceConfig) { - - } - - default void postProcessServiceConfig(ServiceConfig serviceConfig) { + default void postProcessReferConfig(ReferenceConfig referenceConfig) {} - } + 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 955da26d234..56fcb2caf0b 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 void initializeApplicationModel(ApplicationModel applicationModel) { // 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 a8dc78d606d..6dc9a0f54a8 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 DubboShutdownHook(ApplicationModel applicationModel) { 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 @@ private void doDestroy() { 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 @@ private void doDestroy() { 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 @@ private void doDestroy() { } 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 void unregister() { 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 void unregister() { 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 ac67102c683..4132922051a 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 @@ -260,7 +260,12 @@ private void logAndCleanup(Throwable t) { 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(); @@ -274,8 +279,8 @@ private void logAndCleanup(Throwable t) { 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); @@ -294,7 +299,12 @@ public synchronized void destroy() { 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; @@ -316,10 +326,9 @@ protected synchronized void init(boolean check) { 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); } @@ -340,10 +349,17 @@ protected synchronized void init(boolean check) { } else { serviceDescriptor = repository.registerService(interfaceClass); } - 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. + 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. consumerModel.setConfig(this); repository.registerConsumer(consumerModel); @@ -411,7 +427,11 @@ private Map appendConfig() { 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)); @@ -428,8 +448,8 @@ private Map appendConfig() { 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); @@ -466,13 +486,18 @@ private T createProxy(Map referenceParameters) { 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")); - } - - URL consumerUrl = new ServiceConfigURL(CONSUMER_PROTOCOL, referenceParameters.get(REGISTER_IP_KEY), 0, - referenceParameters.get(INTERFACE_KEY), referenceParameters); + 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); consumerUrl = consumerUrl.setScopeModel(getScopeModel()); consumerUrl = consumerUrl.setServiceModel(consumerModel); MetadataUtils.publishServiceDefinition(consumerUrl, consumerModel.getServiceModel(), getApplicationModel()); @@ -505,8 +530,12 @@ private void meshModeHandleUrl(Map referenceParameters) { 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 { @@ -517,8 +546,10 @@ private void meshModeHandleUrl(Map referenceParameters) { // 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; @@ -539,7 +570,9 @@ private boolean checkMeshConfig(Map referenceParameters) { 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); @@ -550,7 +583,6 @@ private boolean checkMeshConfig(Map referenceParameters) { return true; } - /** * Parse the directly configured url. */ @@ -567,7 +599,11 @@ private void parseUrl(Map referenceParameters) { 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); } @@ -596,20 +632,20 @@ private void aggregateUrlFromRegistry(Map referenceParameters) { } } 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 */ @@ -619,11 +655,11 @@ private void createInvoker() { 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<>(); @@ -643,9 +679,11 @@ private void createInvoker() { // 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)) { @@ -653,7 +691,8 @@ private void createInvoker() { } 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); } } } @@ -678,25 +717,34 @@ private void checkInvokerAvailable(long timeout) throws IllegalStateException { } 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()); - - logger.error(CLUSTER_NO_VALID_PROVIDER, "provider not started", "", "No provider available.", illegalStateException); + 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); throw illegalStateException; } @@ -724,19 +772,29 @@ protected void checkAndUpdateSubConfigs() { } 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); 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 71ea252ed6b..f63ddc35ce6 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 @@ -159,8 +159,7 @@ public class ServiceConfig extends ServiceConfigBase { private final List serviceListeners = new ArrayList<>(); - public ServiceConfig() { - } + public ServiceConfig() {} public ServiceConfig(ModuleModel moduleModel) { super(moduleModel); @@ -187,7 +186,6 @@ public boolean isExported() { return exported; } - @Override @Parameter(excluded = true, attribute = false) public boolean isUnexported() { @@ -208,7 +206,12 @@ public synchronized void unexport() { 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); } } } @@ -218,7 +221,12 @@ public synchronized void unexport() { 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); } } } @@ -240,10 +248,12 @@ private void waitForIdle() { 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) { @@ -253,8 +263,10 @@ private void waitForIdle() { 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) { @@ -265,7 +277,8 @@ private void waitForIdle() { } // 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) { @@ -318,9 +331,9 @@ public void export(RegisterTypeEnum registerType) { 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 { @@ -341,12 +354,14 @@ public void register(boolean byDeployer) { 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(); } } @@ -354,14 +369,23 @@ public void register(boolean byDeployer) { } 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() { @@ -370,15 +394,18 @@ protected void exported() { 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); } }); onExported(); } - protected void mapServiceName(URL url, ServiceNameMapping serviceNameMapping, ScheduledExecutorService scheduledExecutor) { + protected void mapServiceName( + URL url, ServiceNameMapping serviceNameMapping, ScheduledExecutorService scheduledExecutor) { if (!exported) { return; } @@ -389,20 +416,32 @@ protected void mapServiceName(URL url, ServiceNameMapping serviceNameMapping, Sc 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() { @@ -414,7 +453,7 @@ private void checkAndUpdateSubConfigs() { // 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 @@ -436,7 +475,8 @@ private void checkAndUpdateSubConfigs() { 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); @@ -455,7 +495,8 @@ private void checkAndUpdateSubConfigs() { 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) { @@ -469,7 +510,8 @@ private void checkAndUpdateSubConfigs() { 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); @@ -510,11 +552,13 @@ private void doExportUrls(RegisterTypeEnum registerType) { } 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); @@ -525,9 +569,8 @@ private void doExportUrls(RegisterTypeEnum registerType) { List registryURLs = ConfigValidationUtils.loadRegistries(this, true); 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. @@ -539,7 +582,8 @@ private void doExportUrls(RegisterTypeEnum registerType) { 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 @@ -557,11 +601,25 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r } 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)); }); } @@ -569,8 +627,13 @@ private void processServiceExecutor(URL url) { 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; } /** @@ -614,7 +677,11 @@ private Map buildAttributes(ProtocolConfig protocolConfig) { 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)); @@ -679,7 +746,8 @@ private void appendArgumentConfig(ArgumentConfig argument, Method method, Map or "); + throw new IllegalArgumentException( + "Argument config must set index or type attribute.eg: or "); } } @@ -688,7 +756,10 @@ private boolean hasIndex(ArgumentConfig argument) { } 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) { @@ -700,7 +771,9 @@ private Integer findArgumentIndexIndexWithGivenType(ArgumentConfig argument, Met 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 @@ -709,7 +782,8 @@ private Integer findArgumentIndexIndexWithGivenType(ArgumentConfig argument, Met 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()); } } @@ -730,14 +804,23 @@ private URL buildUrl(ProtocolConfig protocolConfig, Map params) 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); @@ -762,10 +845,10 @@ private void exportUrl(URL url, List registryURLs, RegisterTypeEnum registe if (StringUtils.isNotBlank(extProtocol)) { // export original url - url = URLBuilder.from(url). - addParameter(IS_PU_SERVER_KEY, Boolean.TRUE.toString()). - removeParameter("ext.protocol"). - build(); + url = URLBuilder.from(url) + .addParameter(IS_PU_SERVER_KEY, Boolean.TRUE.toString()) + .removeParameter("ext.protocol") + .build(); } url = exportRemote(url, registryURLs, registerType); @@ -780,12 +863,12 @@ private void exportUrl(URL url, List registryURLs, RegisterTypeEnum registe // export extra protocols for (String protocol : protocols) { if (StringUtils.isNotBlank(protocol)) { - URL localUrl = URLBuilder.from(url). - setProtocol(protocol). - build(); + URL localUrl = + URLBuilder.from(url).setProtocol(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); } @@ -802,7 +885,7 @@ private URL exportRemote(URL url, List registryURLs, RegisterTypeEnum regis 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; } @@ -821,7 +904,8 @@ private URL exportRemote(URL url, List registryURLs, RegisterTypeEnum regis 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); } @@ -839,7 +923,6 @@ private URL exportRemote(URL url, List registryURLs, RegisterTypeEnum regis doExportUrl(url, true, registerType); } - return url; } @@ -848,9 +931,9 @@ private void doExportUrl(URL url, boolean withMetaData, RegisterTypeEnum registe 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); } @@ -859,21 +942,21 @@ private void doExportUrl(URL url, boolean withMetaData, RegisterTypeEnum registe 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); @@ -886,12 +969,12 @@ private void exportLocal(URL url) { */ 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); + .getActivateExtension(URL.valueOf("configPostProcessor://", getScopeModel()), (String[]) null); configPostProcessors.forEach(component -> component.postProcessServiceConfig(this)); } @@ -920,14 +1003,14 @@ protected void onUnexpoted() { * @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 @@ -950,7 +1033,8 @@ private static String findConfiguredHosts(ProtocolConfig protocolConfig, // 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; @@ -961,7 +1045,6 @@ private static String findConfiguredHosts(ProtocolConfig protocolConfig, 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 @@ -971,10 +1054,12 @@ private static String findConfiguredHosts(ProtocolConfig protocolConfig, * @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 @@ -1047,7 +1132,8 @@ private static void putRandomPort(String protocol, Integer port) { 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 f2f33191089..a207606e83b 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 @@ * 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 bfb2278fb6f..abb9327eac9 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 static DubboBootstrap getInstance() { } 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 void onFailure(ApplicationModel scopeModel, Throwable cause) { } 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 ApplicationConfig getApplication() { } public void setTakeoverMode(BootstrapTakeoverMode takeoverMode) { - //TODO this.started.set(false); + // TODO this.started.set(false); this.takeoverMode = takeoverMode; } @@ -367,7 +370,6 @@ public ConfigManager getConfigManager() { return configManager; } - // MetadataReportConfig correlative methods public DubboBootstrap metadataReport(Consumer consumerBuilder) { @@ -433,7 +435,6 @@ public DubboBootstrap application(ApplicationConfig applicationConfig) { return this; } - // {@link RegistryConfig} correlative methods /** @@ -485,7 +486,6 @@ public DubboBootstrap registries(List registryConfigs) { return this; } - // {@link ProtocolConfig} correlative methods public DubboBootstrap protocol(Consumer consumerBuilder) { return protocol(null, consumerBuilder); @@ -704,7 +704,7 @@ public DubboBootstrap metrics(MetricsConfig metrics) { 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 DubboBootstrap endModule() { return this; } - public class Module { private ModuleModel moduleModel; private DubboBootstrap bootstrap; @@ -889,5 +888,4 @@ public Module consumers(List consumerConfigs) { 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 0befe7dad7c..5d326c94699 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 300bdc4cf48..d2a8dd0e57d 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 @@ protected static Map appendParameter(Map paramet return parameters; } - protected static Map 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 7010096fecd..1d43765bfd7 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 @@ * * @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 f1f4e4fd661..219cf1c081c 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 @@ * @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 af37236120c..1bab6fe6a9a 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 @@ public class InternalServiceConfigBuilder { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); - private static final Set UNACCEPTABLE_PROTOCOL = Stream.of("rest", "grpc").collect(Collectors.toSet()); + private static final Set UNACCEPTABLE_PROTOCOL = + Stream.of("rest", "grpc").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 static InternalServiceConfigBuilder newBuilder(ApplicationModel ap return new InternalServiceConfigBuilder<>(applicationModel); } - - public InternalServiceConfigBuilder interfaceClass(Class interfaceClass) { this.interfaceClass = interfaceClass; return getThis(); @@ -104,7 +103,6 @@ public InternalServiceConfigBuilder protocol(String protocol, String key) { return getThis(); } - /** * Get other configured protocol from environment in priority order. If get nothing, use default dubbo. * @@ -115,50 +113,54 @@ private String getRelatedOrDefaultProtocol() { // List moduleModels = applicationModel.getPubModuleModels(); protocol = moduleModels.stream() - .map(ModuleModel::getConfigManager) - .map(ModuleConfigManager::getConsumers) - .filter(CollectionUtils::isNotEmpty) - .flatMap(Collection::stream) - .map(ConsumerConfig::getProtocol) - .filter(StringUtils::isNotEmpty) - .filter(p -> !UNACCEPTABLE_PROTOCOL.contains(p)) - .findFirst() - .orElse(""); - // - if (StringUtils.isEmpty(protocol)) { - Stream providerConfigStream = moduleModels.stream() .map(ModuleModel::getConfigManager) - .map(ModuleConfigManager::getProviders) + .map(ModuleConfigManager::getConsumers) .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(""); - } - }) + .flatMap(Collection::stream) + .map(ConsumerConfig::getProtocol) .filter(StringUtils::isNotEmpty) .filter(p -> !UNACCEPTABLE_PROTOCOL.contains(p)) .findFirst() .orElse(""); - } - // + // if (StringUtils.isEmpty(protocol)) { - Collection protocols = applicationModel.getApplicationConfigManager().getProtocols(); - if (CollectionUtils.isNotEmpty(protocols)) { - protocol = protocols.stream() - .map(ProtocolConfig::getName) + Stream providerConfigStream = moduleModels.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 -> !UNACCEPTABLE_PROTOCOL.contains(p)) .findFirst() .orElse(""); + } + // + if (StringUtils.isEmpty(protocol)) { + Collection protocols = + applicationModel.getApplicationConfigManager().getProtocols(); + if (CollectionUtils.isNotEmpty(protocols)) { + protocol = protocols.stream() + .map(ProtocolConfig::getName) + .filter(StringUtils::isNotEmpty) + .filter(p -> !UNACCEPTABLE_PROTOCOL.contains(p)) + .findFirst() + .orElse(""); } } // @@ -171,7 +173,9 @@ private String getRelatedOrDefaultProtocol() { } } } - return StringUtils.isNotEmpty(protocol) && !UNACCEPTABLE_PROTOCOL.contains(protocol) ? protocol : DUBBO_PROTOCOL; + return StringUtils.isNotEmpty(protocol) && !UNACCEPTABLE_PROTOCOL.contains(protocol) + ? protocol + : DUBBO_PROTOCOL; } public InternalServiceConfigBuilder protocol(String protocol) { @@ -180,13 +184,12 @@ public InternalServiceConfigBuilder protocol(String protocol) { } 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 +206,12 @@ public InternalServiceConfigBuilder port(Integer specPort, String key) { 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 +235,12 @@ public InternalServiceConfigBuilder port(Integer specPort, String key) { } } } 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,20 +250,26 @@ public InternalServiceConfigBuilder port(Integer specPort, String key) { } 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(protocolConfig::mergeProtocol); + applicationModel + .getApplicationConfigManager() + .getProtocol(this.protocol) + .ifPresent(protocolConfig::mergeProtocol); ApplicationConfig applicationConfig = getApplicationConfig(); @@ -289,15 +304,16 @@ public ServiceConfig build(Consumer> configConsumer){ 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() { @@ -307,5 +323,4 @@ protected InternalServiceConfigBuilder getThis() { 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 7b5724dfcfa..cef437808ae 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 generic(String generic) { return getThis(); } -// @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(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"); + // } 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 55662b24b07..3051827ef55 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 @@ -111,7 +111,8 @@ */ 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; @@ -145,13 +146,15 @@ public DefaultApplicationDeployer(ApplicationModel applicationModel) { environment = applicationModel.modelEnvironment(); referenceCache = new CompositeReferenceCache(applicationModel); - frameworkExecutorRepository = applicationModel.getFrameworkModel().getBeanFactory().getBean(FrameworkExecutorRepository.class); + frameworkExecutorRepository = + applicationModel.getFrameworkModel().getBeanFactory().getBean(FrameworkExecutorRepository.class); executorRepository = ExecutorRepository.getInstance(applicationModel); dubboShutdownHook = new DubboShutdownHook(applicationModel); // load spi listener - Set deployListeners = applicationModel.getExtensionLoader(ApplicationDeployListener.class) - .getSupportedExtensionInstances(); + Set deployListeners = applicationModel + .getExtensionLoader(ApplicationDeployListener.class) + .getSupportedExtensionInstances(); for (ApplicationDeployListener listener : deployListeners) { this.addDeployListener(listener); } @@ -220,7 +223,6 @@ public void initialize() { initModuleDeployers(); - initMetricsReporter(); initMetricsService(); @@ -311,12 +313,14 @@ private void startMetadataCenter() { Collection 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)) { @@ -326,7 +330,8 @@ private void startMetadataCenter() { } metadataReportInstance.init(validMetadataReportConfigs); if (!metadataReportInstance.inited()) { - throw new IllegalStateException(String.format("%s MetadataConfigs found, but none of them is valid.", metadataReportConfigs.size())); + throw new IllegalStateException(String.format( + "%s MetadataConfigs found, but none of them is valid.", metadataReportConfigs.size())); } } @@ -350,23 +355,22 @@ private void useRegistryAsConfigCenterIfNecessary() { List defaultRegistries = configManager.getDefaultRegistries(); if (defaultRegistries.size() > 0) { - defaultRegistries - .stream() - .filter(this::isUsedRegistryAsConfigCenter) - .map(this::registryAsConfigCenter) - .forEach(configCenter -> { - if (configManager.getConfigCenter(configCenter.getId()).isPresent()) { - return; - } - configManager.addConfigCenter(configCenter); - logger.info("use registry as config-center: " + configCenter); - - }); + defaultRegistries.stream() + .filter(this::isUsedRegistryAsConfigCenter) + .map(this::registryAsConfigCenter) + .forEach(configCenter -> { + if (configManager.getConfigCenter(configCenter.getId()).isPresent()) { + return; + } + configManager.addConfigCenter(configCenter); + logger.info("use registry as config-center: " + configCenter); + }); } } private void initMetricsService() { - this.metricsServiceExporter = getExtensionLoader(MetricsServiceExporter.class).getDefaultExtension(); + this.metricsServiceExporter = + getExtensionLoader(MetricsServiceExporter.class).getDefaultExtension(); metricsServiceExporter.init(); } @@ -374,19 +378,21 @@ private void initMetricsReporter() { if (!isSupportMetrics()) { return; } - DefaultMetricsCollector collector = - applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class); + DefaultMetricsCollector collector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class); Optional 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(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()); @@ -400,10 +406,12 @@ private void initMetricsReporter() { } metricsReporter.init(); applicationModel.getBeanFactory().registerBean(metricsReporter); - //If the protocol is not the default protocol, the default protocol is also initialized. + // If the protocol is not the default protocol, the default protocol is also initialized. if (!PROTOCOL_DEFAULT.equals(metricsConfig.getProtocol())) { - DefaultMetricsReporterFactory defaultMetricsReporterFactory = new DefaultMetricsReporterFactory(applicationModel); - MetricsReporter defaultMetricsReporter = defaultMetricsReporterFactory.createMetricsReporter(metricsConfig.toUrl()); + DefaultMetricsReporterFactory defaultMetricsReporterFactory = + new DefaultMetricsReporterFactory(applicationModel); + MetricsReporter defaultMetricsReporter = + defaultMetricsReporterFactory.createMetricsReporter(metricsConfig.toUrl()); defaultMetricsReporter.init(); applicationModel.getBeanFactory().registerBean(defaultMetricsReporter); } @@ -415,20 +423,18 @@ public boolean isSupportMetrics() { public static boolean isSupportPrometheus() { return isClassPresent("io.micrometer.prometheus.PrometheusConfig") - && isClassPresent("io.prometheus.client.exporter.BasicAuthHttpConnectionFactory") - && isClassPresent("io.prometheus.client.exporter.HttpConnectionFactory") - && isClassPresent("io.prometheus.client.exporter.PushGateway"); + && isClassPresent("io.prometheus.client.exporter.BasicAuthHttpConnectionFactory") + && isClassPresent("io.prometheus.client.exporter.HttpConnectionFactory") + && isClassPresent("io.prometheus.client.exporter.PushGateway"); } - private static boolean isClassPresent(String className) { return ClassUtils.isPresent(className, DefaultApplicationDeployer.class.getClassLoader()); } - private boolean isUsedRegistryAsConfigCenter(RegistryConfig registryConfig) { - return isUsedRegistryAsCenter(registryConfig, registryConfig::getUseAsConfigCenter, "config", - DynamicConfigurationFactory.class); + return isUsedRegistryAsCenter( + registryConfig, registryConfig::getUseAsConfigCenter, "config", DynamicConfigurationFactory.class); } private ConfigCenterConfig registryAsConfigCenter(RegistryConfig registryConfig) { @@ -469,35 +475,36 @@ private void useRegistryAsMetadataCenterIfNecessary() { return; } - Collection metadataConfigsToOverride = originMetadataConfigs - .stream() - .filter(m -> Objects.isNull(m.getAddress())) - .collect(Collectors.toList()); + Collection metadataConfigsToOverride = originMetadataConfigs.stream() + .filter(m -> Objects.isNull(m.getAddress())) + .collect(Collectors.toList()); if (metadataConfigsToOverride.size() > 1) { return; } - MetadataReportConfig metadataConfigToOverride = metadataConfigsToOverride.stream().findFirst().orElse(null); + MetadataReportConfig metadataConfigToOverride = + metadataConfigsToOverride.stream().findFirst().orElse(null); List defaultRegistries = configManager.getDefaultRegistries(); if (!defaultRegistries.isEmpty()) { - defaultRegistries - .stream() - .filter(this::isUsedRegistryAsMetadataCenter) - .map(registryConfig -> registryAsMetadataCenter(registryConfig, metadataConfigToOverride)) - .forEach(metadataReportConfig -> { - overrideMetadataReportConfig(metadataConfigToOverride, metadataReportConfig); - }); + defaultRegistries.stream() + .filter(this::isUsedRegistryAsMetadataCenter) + .map(registryConfig -> registryAsMetadataCenter(registryConfig, metadataConfigToOverride)) + .forEach(metadataReportConfig -> { + overrideMetadataReportConfig(metadataConfigToOverride, metadataReportConfig); + }); } } - private void overrideMetadataReportConfig(MetadataReportConfig metadataConfigToOverride, MetadataReportConfig metadataReportConfig) { + private void overrideMetadataReportConfig( + MetadataReportConfig metadataConfigToOverride, MetadataReportConfig metadataReportConfig) { if (metadataReportConfig.getId() == null) { Collection 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; } } @@ -505,7 +512,8 @@ private void overrideMetadataReportConfig(MetadataReportConfig metadataConfigToO configManager.removeConfig(metadataConfigToOverride); configManager.addMetadataReport(metadataReportConfig); } else { - Optional configOptional = configManager.getConfig(MetadataReportConfig.class, metadataReportConfig.getId()); + Optional configOptional = + configManager.getConfig(MetadataReportConfig.class, metadataReportConfig.getId()); if (configOptional.isPresent()) { return; } @@ -516,8 +524,8 @@ private void overrideMetadataReportConfig(MetadataReportConfig metadataConfigToO } private boolean isUsedRegistryAsMetadataCenter(RegistryConfig registryConfig) { - return isUsedRegistryAsCenter(registryConfig, registryConfig::getUseAsMetadataCenter, "metadata", - MetadataReportFactory.class); + return isUsedRegistryAsCenter( + registryConfig, registryConfig::getUseAsMetadataCenter, "metadata", MetadataReportFactory.class); } /** @@ -530,26 +538,33 @@ private boolean isUsedRegistryAsMetadataCenter(RegistryConfig registryConfig) { * @return * @since 2.7.8 */ - private boolean isUsedRegistryAsCenter(RegistryConfig registryConfig, Supplier 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; } @@ -570,9 +585,11 @@ private boolean supportsExtension(Class extensionClass, String name) { return false; } - private MetadataReportConfig registryAsMetadataCenter(RegistryConfig registryConfig, MetadataReportConfig originMetadataReportConfig) { - MetadataReportConfig metadataReportConfig = originMetadataReportConfig == null ? - new MetadataReportConfig(registryConfig.getApplicationModel()) : originMetadataReportConfig; + private MetadataReportConfig registryAsMetadataCenter( + RegistryConfig registryConfig, MetadataReportConfig originMetadataReportConfig) { + MetadataReportConfig metadataReportConfig = originMetadataReportConfig == null + ? new MetadataReportConfig(registryConfig.getApplicationModel()) + : originMetadataReportConfig; if (metadataReportConfig.getId() == null) { metadataReportConfig.setId(registryConfig.getId()); } @@ -581,8 +598,11 @@ private MetadataReportConfig registryAsMetadataCenter(RegistryConfig registryCon metadataReportConfig.setParameters(new HashMap<>()); } 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()); @@ -693,30 +713,30 @@ private void doStart() { startModules(); // prepare application instance -// prepareApplicationInstance(); + // prepareApplicationInstance(); // Ignore checking new module after start -// 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); -// } -// }); + // 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() { @@ -759,7 +779,8 @@ public void prepareInternalModule() { } // start internal module - ModuleDeployer internalModuleDeployer = applicationModel.getInternalModule().getDeployer(); + ModuleDeployer internalModuleDeployer = + applicationModel.getInternalModule().getDeployer(); if (!internalModuleDeployer.isStarted()) { Future future = internalModuleDeployer.start(); // wait for internal module startup @@ -767,21 +788,33 @@ public void prepareInternalModule() { future.get(5, TimeUnit.SECONDS); hasPreparedInternalModule = true; } catch (Exception e) { - logger.warn(CONFIG_FAILED_START_MODEL, "", "", "wait for internal module startup failed: " + e.getMessage(), e); + logger.warn( + CONFIG_FAILED_START_MODEL, + "", + "", + "wait for internal module startup failed: " + e.getMessage(), + e); } } } } private void exportMetricsService() { - boolean exportMetrics = applicationModel.getApplicationConfigManager().getMetrics() - .map(MetricsConfig::getExportMetricsService).orElse(true); + boolean exportMetrics = applicationModel + .getApplicationConfigManager() + .getMetrics() + .map(MetricsConfig::getExportMetricsService) + .orElse(true); if (exportMetrics) { try { metricsServiceExporter.export(); } catch (Exception e) { - logger.error(LoggerCodeConstants.COMMON_METRICS_COLLECTOR_EXCEPTION, "", "", - "exportMetricsService an exception occurred when handle starting event", e); + logger.error( + LoggerCodeConstants.COMMON_METRICS_COLLECTOR_EXCEPTION, + "", + "", + "exportMetricsService an exception occurred when handle starting event", + e); } } } @@ -826,7 +859,12 @@ private DynamicConfiguration prepareEnvironment(ConfigCenterConfig configCenter) dynamicConfiguration = getDynamicConfiguration(configCenter.toUrl()); } catch (Exception e) { if (!configCenter.isCheck()) { - logger.warn(CONFIG_FAILED_INIT_CONFIG_CENTER, "", "", "The configuration center failed to initialize", e); + logger.warn( + CONFIG_FAILED_INIT_CONFIG_CENTER, + "", + "", + "The configuration center failed to initialize", + e); configCenter.setInitialized(false); return null; } else { @@ -836,18 +874,25 @@ private DynamicConfiguration prepareEnvironment(ConfigCenterConfig configCenter) ApplicationModel applicationModel = getApplicationModel(); if (StringUtils.isNotEmpty(configCenter.getConfigFile())) { - String configContent = dynamicConfiguration.getProperties(configCenter.getConfigFile(), configCenter.getGroup()); + String configContent = + dynamicConfiguration.getProperties(configCenter.getConfigFile(), configCenter.getGroup()); if (StringUtils.isNotEmpty(configContent)) { - logger.info(String.format("Got global remote configuration from config center with key-%s and group-%s: \n %s", configCenter.getConfigFile(), configCenter.getGroup(), configContent)); + logger.info(String.format( + "Got global remote configuration from config center with key-%s and group-%s: \n %s", + configCenter.getConfigFile(), configCenter.getGroup(), configContent)); } String appGroup = getApplication().getName(); String appConfigContent = null; String appConfigFile = null; if (isNotEmpty(appGroup)) { - appConfigFile = isNotEmpty(configCenter.getAppConfigFile()) ? configCenter.getAppConfigFile() : configCenter.getConfigFile(); + appConfigFile = isNotEmpty(configCenter.getAppConfigFile()) + ? configCenter.getAppConfigFile() + : configCenter.getConfigFile(); appConfigContent = dynamicConfiguration.getProperties(appConfigFile, appGroup); if (StringUtils.isNotEmpty(appConfigContent)) { - logger.info(String.format("Got application specific remote configuration from config center with key %s and group %s: \n %s", appConfigFile, appGroup, appConfigContent)); + logger.info(String.format( + "Got application specific remote configuration from config center with key %s and group %s: \n %s", + appConfigFile, appGroup, appConfigContent)); } } try { @@ -858,11 +903,21 @@ private DynamicConfiguration prepareEnvironment(ConfigCenterConfig configCenter) environment.updateAppExternalConfigMap(appConfigMap); // Add metrics - MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent(applicationModel, configCenter.getConfigFile(), configCenter.getGroup(), - configCenter.getProtocol(), ConfigChangeType.ADDED.name(), configMap.size())); + MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent( + applicationModel, + configCenter.getConfigFile(), + configCenter.getGroup(), + configCenter.getProtocol(), + ConfigChangeType.ADDED.name(), + configMap.size())); if (isNotEmpty(appGroup)) { - MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent(applicationModel, appConfigFile, appGroup, - configCenter.getProtocol(), ConfigChangeType.ADDED.name(), appConfigMap.size())); + MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent( + applicationModel, + appConfigFile, + appGroup, + configCenter.getProtocol(), + ConfigChangeType.ADDED.name(), + appConfigMap.size())); } } catch (IOException e) { throw new IllegalStateException("Failed to parse configurations from Config Center.", e); @@ -883,7 +938,8 @@ private DynamicConfiguration prepareEnvironment(ConfigCenterConfig configCenter) private DynamicConfiguration getDynamicConfiguration(URL connectionURL) { String protocol = connectionURL.getProtocol(); - DynamicConfigurationFactory factory = ConfigurationUtils.getDynamicConfigurationFactory(applicationModel, protocol); + DynamicConfigurationFactory factory = + ConfigurationUtils.getDynamicConfigurationFactory(applicationModel, protocol); return factory.getDynamicConfiguration(connectionURL); } @@ -901,38 +957,57 @@ private void registerServiceInstance() { registered = true; ServiceInstanceMetadataUtils.registerMetadataAndInstance(applicationModel); } catch (Exception e) { - logger.error(CONFIG_REGISTER_INSTANCE_ERROR, "configuration server disconnected", "", "Register instance error.", e); + logger.error( + CONFIG_REGISTER_INSTANCE_ERROR, + "configuration server disconnected", + "", + "Register instance error.", + e); } if (registered) { // scheduled task for updating Metadata and ServiceInstance - asyncMetadataFuture = frameworkExecutorRepository.getSharedScheduledExecutor().scheduleWithFixedDelay(() -> { - - // 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 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); + asyncMetadataFuture = frameworkExecutorRepository + .getSharedScheduledExecutor() + .scheduleWithFixedDelay( + () -> { + + // 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 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); } } @@ -986,7 +1061,6 @@ public void preDestroy() { if (asyncMetadataFuture != null) { asyncMetadataFuture.cancel(true); } - } } @@ -1005,13 +1079,17 @@ private void offline() { } } } 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); @@ -1031,9 +1109,11 @@ public void postDestroy() { executeShutdownCallbacks(); // TODO should we close unused protocol server which only used by this application? - // protocol server will be closed on all applications of same framework are stopped currently, but no associate to application + // protocol server will be closed on all applications of same framework are stopped currently, but no + // associate to application // see org.apache.dubbo.config.deploy.FrameworkModelCleaner#destroyProtocols - // see org.apache.dubbo.config.bootstrap.DubboBootstrapMultiInstanceTest#testMultiProviderApplicationStopOneByOne + // see + // org.apache.dubbo.config.bootstrap.DubboBootstrapMultiInstanceTest#testMultiProviderApplicationStopOneByOne // destroy all executor services destroyExecutorRepository(); @@ -1047,7 +1127,8 @@ public void postDestroy() { } private void executeShutdownCallbacks() { - ShutdownHookCallbacks shutdownHookCallbacks = applicationModel.getBeanFactory().getBean(ShutdownHookCallbacks.class); + ShutdownHookCallbacks shutdownHookCallbacks = + applicationModel.getBeanFactory().getBean(ShutdownHookCallbacks.class); shutdownHookCallbacks.callback(); } @@ -1162,7 +1243,12 @@ private void onInitialize() { try { listener.onInitialize(applicationModel); } 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); } } } @@ -1177,7 +1263,12 @@ private void exportMetadataService() { ((ApplicationDeployListener) listener).onModuleStarted(applicationModel); } } catch (Throwable e) { - logger.error(CONFIG_FAILED_START_MODEL, "", "", getIdentifier() + " an exception occurred when handle starting event", e); + logger.error( + CONFIG_FAILED_START_MODEL, + "", + "", + getIdentifier() + " an exception occurred when handle starting event", + e); } } } @@ -1296,7 +1387,8 @@ private void destroyServiceDiscoveries() { private void destroyMetadataReports() { // only destroy MetadataReport of this application - List metadataReportFactories = getExtensionLoader(MetadataReportFactory.class).getLoadedExtensionInstances(); + List metadataReportFactories = + getExtensionLoader(MetadataReportFactory.class).getLoadedExtensionInstances(); for (MetadataReportFactory metadataReportFactory : metadataReportFactories) { metadataReportFactory.destroy(); } @@ -1305,6 +1397,4 @@ private void destroyMetadataReports() { private ApplicationConfig getApplication() { return configManager.getApplicationOrElseThrow(); } - - } 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 c770e5350aa..a3501102447 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 void init() { } 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 void setApplicationModel(ApplicationModel applicationModel) { 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 MetricsServiceExporter export() { 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 MetricsServiceExporter unexport() { } private MetricsConfig getMetricsConfig() { - Optional metricsConfig = applicationModel.getApplicationConfigManager().getMetrics(); + Optional metricsConfig = + applicationModel.getApplicationConfigManager().getMetrics(); if (metricsConfig.isPresent()) { return metricsConfig.get(); } else { @@ -125,5 +141,4 @@ private MetricsConfig getMetricsConfig() { 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 5694c890dc4..be0b1307e17 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 @@ */ 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<>(); @@ -90,18 +91,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); } @@ -122,7 +127,10 @@ public void initialize() throws IllegalStateException { 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()); @@ -160,7 +168,6 @@ private synchronized Future startSync() throws IllegalStateException { onModuleStarting(); - initialize(); // export services @@ -205,7 +212,12 @@ private synchronized Future startSync() throws IllegalStateException { // 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 @@ -259,13 +271,17 @@ private void offline() { } } } 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); @@ -289,7 +305,12 @@ public synchronized void postDestroy() throws IllegalStateException { 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); } } @@ -300,7 +321,12 @@ public synchronized void postDestroy() throws IllegalStateException { 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(); @@ -313,7 +339,12 @@ private void onInitialize() { 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); } } } @@ -326,11 +357,11 @@ private void onModuleStarting() { } 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) { @@ -421,16 +452,24 @@ private void exportServiceInternal(ServiceConfigBase sc) { } 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 { @@ -482,13 +521,21 @@ private void referServices() { 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 { @@ -496,7 +543,12 @@ private void referServices() { } } } 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; } @@ -525,7 +577,11 @@ private void waitExportFinish() { 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(); @@ -538,7 +594,11 @@ private void waitReferFinish() { 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(); @@ -551,17 +611,15 @@ public boolean isBackground() { } 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 @@ -577,5 +635,4 @@ public void prepare() { applicationDeployer.initialize(); this.initialize(); } - } 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 258181d2f23..2405e6fda03 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 @@ */ 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 @@ private void destroyProtocols(FrameworkModel frameworkModel) { } } } - } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java index dc62bc803e0..6bfa5e3caf7 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java @@ -50,23 +50,27 @@ public class ConfigurableMetadataServiceExporter { private volatile ServiceConfig 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 synchronized ConfigurableMetadataServiceExporter export() { } } 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 f3e34bb4c9a..b5819892bd2 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 @@ private String getMetadataType(ApplicationModel applicationModel) { } 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 void setMetadataServiceExporter(ConfigurableMetadataServiceExporter metad @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 synchronized void onStopped(ApplicationModel scopeModel) { } @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 6e1f677b3c9..6bd1f7d5e48 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 @@ private String resolveMetadataPropertyName(ServiceInstance serviceInstance) { } 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 5ae8f010a66..508ce9ad67d 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 @@ */ 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 CompositeReferenceCache(ApplicationModel applicationModel) { 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 4e9c20d415d..a37044cdca9 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 @@ -220,10 +220,10 @@ public static List loadRegistries(AbstractInterfaceConfig interfaceConfig, 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(SUBSCRIBE_KEY, true)) { registryList.add(url); @@ -242,39 +242,49 @@ private static List genCompatibleRegistries(ScopeModel scopeModel, 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); @@ -324,17 +333,20 @@ public static URL loadMonitor(AbstractInterfaceConfig interfaceConfig, URL regis 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); @@ -367,25 +379,26 @@ public static void checkMock(Class interfaceClass, AbstractInterfaceConfig co 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); } } @@ -397,7 +410,11 @@ public static void validateAbstractInterfaceConfig(AbstractInterfaceConfig confi 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(); @@ -469,8 +486,8 @@ public static void validateApplicationConfig(ApplicationConfig config) { } 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 @@ -500,7 +517,12 @@ private static void checkQosDependency(ApplicationConfig config) { try { ClassUtils.forName("org.apache.dubbo.qos.protocol.QosProtocolWrapper"); } catch (ClassNotFoundException e) { - logger.warn(COMMON_CLASS_NOT_FOUND, "", "", "No QosProtocolWrapper class was found. Please check the dependency of dubbo-qos whether was imported correctly.", e); + logger.warn( + COMMON_CLASS_NOT_FOUND, + "", + "", + "No QosProtocolWrapper class was found. Please check the dependency of dubbo-qos whether was imported correctly.", + e); } } } @@ -518,8 +540,8 @@ public static boolean isValidMetadataConfig(MetadataReportConfig metadataReportC 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; } @@ -535,7 +557,8 @@ public static void validateMetadataConfig(MetadataReportConfig metadataReportCon 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); } } @@ -560,8 +583,8 @@ public static void validateSslConfig(SslConfig sslConfig) { 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()); @@ -575,10 +598,10 @@ public static void validateProtocolConfig(ProtocolConfig config) { 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()); } @@ -637,7 +660,9 @@ public static void validateMethodConfig(MethodConfig config) { } 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) { @@ -647,8 +672,7 @@ private static String getRegistryProtocolType(URL url) { 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()); } } @@ -684,8 +708,8 @@ public static void checkMultiExtension(ScopeModel scopeModel, List> typ } } 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(","))); } } } @@ -761,17 +785,24 @@ public static void checkProperty(String property, String value, int maxlength, P 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 396f6afc492..6bf010c3fca 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 void validate(AbstractConfig config) { 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 7e798004fc9..7b1b26b7f18 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 @@ * 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 static SimpleReferenceCache getCache(String name) { * 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 T get(ReferenceConfigBase rc, boolean check) { 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 void check(String key, Class type, long timeout) { for (ReferenceConfigBase rc : referencesOfKey) { rc.checkOrDestroy(timeout); } - } @Override @@ -240,7 +247,6 @@ public void destroy(String key, Class type) { 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 b315aa2e4ee..b546238ef38 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 9dd67ca5a57..0d07661d134 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 @@ 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 c4ed2aa702b..f4d2b96a452 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 @@ 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 359ca39222e..edaa1955b47 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.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.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 @@ void testAppendParameters4() { @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 @@ void testAppendAttributes1() { 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 @@ void checkParameterName() { } @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 @@ void testRefreshProperties() throws Exception { 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 @@ void testRefreshProperties() throws Exception { 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 @@ void testRefreshParameters() { 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 @@ void testRefreshParametersWithOverrideConfigMode() { 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 @@ void testRefreshParametersWithOverrideConfigMode() { 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 @@ void testOnlyPrefixedKeyTakeEffect() { Assertions.assertEquals("value-from-external", overrideConfig.getNotConflictKey2()); } finally { ApplicationModel.defaultModel().modelEnvironment().destroy(); - } } @@ -570,7 +586,8 @@ void tetMetaData() { 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 @@ private static class OverrideConfig extends AbstractConfig { public String notConflictKey2; protected Map parameters; - public OverrideConfig() { - } + public OverrideConfig() {} public OverrideConfig(ScopeModel scopeModel) { super(scopeModel); @@ -741,14 +757,13 @@ private static class ParameterConfig { 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 @@ void testMetaData() throws Exception { // 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 @@ private static class OuterConfig extends AbstractConfig { @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 4973e1d3d9e..8842e1a2030 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 @@ 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 @@ void testParameters() throws Exception { 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 bc3ffe739aa..c3e13301459 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.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 @@ void testRouter() { 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 @@ void testGenericOverride() { 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 f25a5ed327a..3dc4bd90dd7 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 @@ void testPreferSerializationDefault2() { 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 a6ec4dac6ee..54dacb1a773 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 @@ void testAppendEnvironmentProperties() { 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 @@ void testOverrideEmptyConfig() { 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 @@ void testOverrideConfigById() { 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 @@ void testOverrideConfigByName() { 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 @@ void testLoadConfig() { 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 @@ void testOverrideConfigConvertCase() { 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 @@ void testOverrideConfigConvertCase() { 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 a3007f4503f..9ec261f1350 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 0af13133cad..1c95936ca36 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 @@ void testPrefix() { 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 @@ void testToUrl() { 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 @@ void testOverrideConfig() { 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 @@ void testOverrideConfig() { 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 @@ void testOverrideConfig2() { 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 @@ void testOverrideConfig2() { .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 @@ void testOverrideConfig2() { @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 @@ void testOverrideConfigBySystemProps() { .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 @@ void testOverrideConfigByDubboProps() { 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 @@ void testOverrideConfigByDubboProps() { .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 @@ void testOverrideConfigBySystemPropsWithId() { .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 @@ void testOverrideConfigByDubboPropsWithId() { 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 @@ void testOverrideConfigByDubboPropsWithId() { .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 @@ void testOverrideConfigByDubboPropsWithId() { 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 @@ void testParameters() { 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 @@ void testAttributes() { 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 @@ void testSetAddress() { 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 4946e0b2b27..d1abfb2e4f7 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 @@ public void reset() { } @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 1a303ced7bb..f3a161c01c9 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.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 @@ void testOverrideConfigSingle() { .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 @@ void testOverrideConfigSingle() { 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 @@ void testOverrideConfigByPluralityId() { .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 @@ void testOverrideConfigBySingularId() { .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 @@ void testOverrideConfigBySingularId() { @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 @@ void testOverrideConfigByDubboProps() { .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 @@ void testReferenceAndConsumerConfigOverlay() { 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 @@ void testReferenceAndConsumerConfigOverlay() { 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 fd34d7ac883..56cb1196a63 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.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 void testDestoryNoModuleManagedExternally() { 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 62fb8723f82..73708d73da5 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 @@ void testFile() { 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 d8580388cfb..fe9e5d865d8 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.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.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 @@ public void afterEach() { 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 @@ void testStaticConstructor() throws NoSuchFieldException { 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 @@ void testConvertMethodConfig2AsyncInfo() throws Exception { 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 @@ void testOnReturnMethod() { assertThat(parameters.size(), is(0)); } - //@Test + // @Test void testOnThrow() { MethodConfig method = new MethodConfig(); method.setOnthrow("on-throw-object"); @@ -252,7 +272,7 @@ void testOnThrowMethod() { assertThat(parameters.size(), is(0)); } - //@Test + // @Test void testOnInvoke() { MethodConfig method = new MethodConfig(); method.setOninvoke("on-invoke-object"); @@ -289,10 +309,10 @@ void testReturn() { 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 @@ void testOverrideMethodConfigOfReference() { 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 @@ void testOverrideMethodConfigOfReference() { 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 @@ void testAddMethodConfigOfReference() { 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 @@ void testOverrideMethodConfigOfService() { 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 @@ void testOverrideMethodConfigOfService() { 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 @@ void testAddMethodConfigOfService() { 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 @@ void testAddMethodConfigOfService() { 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 @@ void testVerifyMethodConfigOfService() { 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 @@ void testVerifyMethodConfigOfService() { 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 @@ void testIgnoreInvalidMethodConfigOfService() { 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 @@ void testIgnoreInvalidMethodConfigOfService() { 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 578a6321609..432d4390f44 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 @@ 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 6aeba1bc98d..cb8bb4ebf99 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 @@ void testDefault() throws Exception { 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 0edf1c9b872..d5001a8b306 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 @@ void testInterval() throws Exception { 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 d15052b4ad4..686794ffa68 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 @@ void testExtension() throws Exception { 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 @@ void testOverrideConfigByName() { 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 @@ void testCreateConfigFromPropsWithId() { 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 @@ void testCreateConfigFromPropsWithName() { 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 @@ void testCreateDefaultConfigFromProps() { 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 @@ void testCreateDefaultConfigFromProps() { } } - @Test void testPreferSerializationDefault1() throws Exception { ProtocolConfig protocolConfig = new ProtocolConfig(); @@ -419,6 +414,4 @@ void testPreferSerializationDefault2() throws Exception { 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 dd534342dba..07c3e16693f 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 @@ void testWait() throws Exception { 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 ca1e95d61f6..983c19299a2 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 @@ -49,23 +49,6 @@ 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; @@ -84,6 +67,23 @@ 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; @@ -245,11 +245,12 @@ void testAppendConfig() { 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(); @@ -259,135 +260,200 @@ void testAppendConfig() { 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(); } @@ -410,27 +476,32 @@ void testCreateInvokerForLocalRefer() { 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 = ((MockClusterInvoker) mockInvoker) + .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 +547,7 @@ void testCreateInvokerForRemoteRefer() { 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 +555,6 @@ void testCreateInvokerForRemoteRefer() { dubboBootstrap.destroy(); } - /** * Verify that the remote url is directly configured for remote reference */ @@ -517,18 +584,19 @@ void testCreateInvokerWithRemoteUrlForRemoteRefer() { 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.assertEquals( + Boolean.TRUE, + ((ScopeClusterInvoker) scopeClusterInvoker) + .getInvoker() + .getUrl() + .getAttribute(PEER_KEY)); dubboBootstrap.destroy(); - } /** @@ -560,15 +628,11 @@ void testCreateInvokerWithRegistryUrlForRemoteRefer() { 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 +676,7 @@ void testMultipleRegistryForRemoteRefer() { 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 +714,8 @@ public void testInjvm() throws Exception { 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 +756,16 @@ void test1ReferenceRetry() { 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 +775,9 @@ void test1ReferenceRetry() { rc.destroy(); InjvmProtocol.getInjvmProtocol(FrameworkModel.defaultModel()).destroy(); System.clearProperty("java.net.preferIPv4Stack"); - } Assertions.assertTrue(success); Assertions.assertNotNull(demoService); - } @Test @@ -761,11 +824,9 @@ void test2ReferenceRetry() { rc.destroy(); sc.unexport(); System.clearProperty("java.net.preferIPv4Stack"); - } Assertions.assertTrue(success); Assertions.assertNotNull(demoService); - } @Test @@ -779,13 +840,12 @@ void testMetaData() { 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 +863,6 @@ void testGetPrefixes() { } long end = System.currentTimeMillis(); System.out.println("ReferenceConfig get prefixes cost: " + (end - start)); - } @Test @@ -814,18 +873,20 @@ void testGenericAndInterfaceConflicts() { 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 +911,8 @@ void testLargeReferences() throws InterruptedException { 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 +926,20 @@ void testLargeReferences() throws InterruptedException { 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 +947,12 @@ private void testSearchReferences() { 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 +964,7 @@ private long testInitReferences(int start, int end, ApplicationConfig applicatio referenceConfig.setConfigCenter(configCenterConfig); DubboBootstrap.getInstance().reference(referenceConfig); - //ApplicationModel.defaultModel().getConfigManager().getConfigCenters(); + // ApplicationModel.defaultModel().getConfigManager().getConfigCenters(); } } catch (Throwable e) { e.printStackTrace(); @@ -935,7 +1006,11 @@ void testDifferentClassLoader() throws Exception { 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 +1031,8 @@ void testDifferentClassLoader() throws Exception { 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 +1051,8 @@ void testDifferentClassLoader() throws Exception { 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 +1073,11 @@ void testDifferentClassLoader() throws Exception { @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 +1098,8 @@ public void testDifferentClassLoaderRequest() throws Exception { 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); @@ -1044,11 +1126,13 @@ public void testDifferentClassLoaderRequest() throws Exception { 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()); @@ -1067,8 +1151,7 @@ void testClassLoader() { 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()); @@ -1111,14 +1194,28 @@ private Class compileCustomResult(ClassLoader classLoader) throws NotFoundExc 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; @@ -1145,7 +1242,8 @@ public Class loadClass(String name, boolean resolve) throws ClassNotFoundExce 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); @@ -1160,7 +1258,6 @@ public Class loadClass(String name, boolean resolve) throws ClassNotFoundExce } } - public byte[] loadClassData(String className) throws IOException { className = className.replaceAll("\\.", "/"); String path = basePath + File.separator + className + ".class"; @@ -1216,7 +1313,6 @@ public Class loadClass(String name, boolean resolve) throws ClassNotFoundExce } } - public byte[] loadClassData(String className) throws IOException { className = className.replaceAll("\\.", "/"); String path = basePath + File.separator + className + ".class"; @@ -1269,7 +1365,6 @@ public Class loadClass(String name, boolean resolve) throws ClassNotFoundExce } } - public byte[] loadClassData(String className) throws IOException { className = className.replaceAll("\\.", "/"); String path = basePath + File.separator + className + ".class"; @@ -1283,5 +1378,4 @@ public byte[] loadClassData(String className) throws IOException { 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 572665eac4a..f184d81752a 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.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 @@ void testProtocol() throws Exception { 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 @@ void testOverrideConfigBySystemProps() { 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 @@ void testPreferredWithFalseValue() { 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 fe5a0ad6439..8ef6a355735 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.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.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 @@ public void setUp() throws Exception { } @AfterEach - public void tearDown() { - } + public void tearDown() {} @Test void testExport() throws Exception { @@ -192,7 +190,7 @@ void testExport() throws Exception { @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(); @@ -216,7 +214,6 @@ void testProxy() throws Exception { TestProxyFactory.count = 0; } - @Test void testDelayExport() throws Exception { CountDownLatch latch = new CountDownLatch(1); @@ -229,9 +226,7 @@ public void exported(ServiceConfig sc) { } @Override - public void unexported(ServiceConfig sc) { - - } + public void unexported(ServiceConfig sc) {} }); delayService.export(); assertTrue(delayService.getExportedUrls().isEmpty()); @@ -244,7 +239,7 @@ void testUnexport() throws Exception { try { service.export(); service.unexport(); -// Thread.sleep(1000); + // Thread.sleep(1000); Mockito.verify(exporter, Mockito.atLeastOnce()).unexport(); } finally { System.clearProperty(SHUTDOWN_TIMEOUT_KEY); @@ -323,7 +318,7 @@ void testMetaData() { 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()); @@ -331,7 +326,6 @@ void testMetaData() { Assertions.assertEquals("" + config.isAsync(), metaData.get("async")); } - @Test void testExportWithoutRegistryConfig() { serviceWithoutRegistryConfig.export(); @@ -370,7 +364,6 @@ void testServiceListener() { assertSame(service, serviceConfig); } - @Test void testMethodConfigWithInvalidArgumentConfig() { Assertions.assertThrows(IllegalArgumentException.class, () -> { @@ -378,16 +371,20 @@ void testMethodConfigWithInvalidArgumentConfig() { 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(); @@ -400,18 +397,22 @@ void testMethodConfigWithConfiguredArgumentTypeAndIndex() { 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(); @@ -426,17 +427,21 @@ void testMethodConfigWithConfiguredArgumentIndex() { 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(); @@ -451,17 +456,21 @@ void testMethodConfigWithConfiguredArgumentType() { 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(); @@ -477,17 +486,21 @@ void testMethodConfigWithUnknownArgumentType() { 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(); @@ -501,17 +514,21 @@ void testMethodConfigWithUnmatchedArgument() { 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(); @@ -525,17 +542,21 @@ void testMethodConfigWithInvalidArgumentIndex() { 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(); @@ -592,9 +613,7 @@ public MappingListener stopListen(URL subscribeURL, MappingListener listener) { } @Override - public void putCachedMapping(String serviceKey, Set apps) { - - } + public void putCachedMapping(String serviceKey, Set apps) {} @Override public Set getRemoteMapping(URL consumerURL) { @@ -607,9 +626,7 @@ public Set removeCachedMapping(String serviceKey) { } @Override - public void $destroy() { - - } + public void $destroy() {} }; ApplicationConfig applicationConfig = new ApplicationConfig("app"); applicationConfig.setMappingRetryInterval(10); @@ -650,9 +667,7 @@ public MappingListener stopListen(URL subscribeURL, MappingListener listener) { } @Override - public void putCachedMapping(String serviceKey, Set apps) { - - } + public void putCachedMapping(String serviceKey, Set apps) {} @Override public Set getMapping(URL consumerURL) { @@ -670,9 +685,7 @@ public Set removeCachedMapping(String serviceKey) { } @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 6c3fe4eaaa8..8a09132bea4 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 static void clear() { } 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 e9c87d4f5d8..7937c28d4a8 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 @@ 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 2f32c3f64dd..5324f43a5e8 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 DemoException(String message) { 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 96ff3bb3c3d..7fb348dda56 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 @@ import java.io.Serializable; import java.util.List; - /** * DemoService */ @@ -39,6 +38,5 @@ default InnerClass callInnerClass() { 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 c2afa988755..acdb009e3d2 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 5e55cbbf54e..5f66f79cde5 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 boolean equals(Object obj) { } 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 824de82dae8..c72c843676a 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 static void main(String[] args) throws Exception { 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 ef3894422e5..a08d876eb09 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 static void main(String[] args) { .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 2852bf55d4d..fe791af7c04 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.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.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 @@ void compatibleApplicationShutdown() { 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 @@ void testLoadRegistries() { 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 @@ void testLoadRegistries() { 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 @@ void testLoadUserMonitor_registry() { 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 @@ void testLoadUserMonitor_service_discovery() { 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 @@ void testLoadUserMonitor_user() { 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 @@ void testLoadUserMonitor_user_address() { // 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 @@ void testLoadUserMonitor_user_address() { 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 @@ void testBootstrapStart() { 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 @@ void testBootstrapStart() { 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 @@ void testLocalMetadataServiceExporter() { 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 @@ void testRemoteMetadataServiceExporter() { 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 @@ void testRemoteMetadataServiceExporter() { 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 @@ private void assertMetadataService(DubboBootstrap bootstrap, int availablePort, 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 @@ private void assertMetadataService(DubboBootstrap bootstrap, int availablePort, } } - private void writeDubboProperties(String key, String value) { OutputStream os = null; try { @@ -364,9 +387,5 @@ private void writeDubboProperties(String key, String value) { } } - - 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 ca84218b1eb..28971f1689f 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 static void main(String[] args) throws Exception { .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 static void main(String[] args) throws Exception { 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 6ed451124f5..945d3ba79a0 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 @@ private static void multipleRegistries() { 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 @@ private static void multipleRegistries() { .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 2d705ac09cf..f22154b6832 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 8d6152443f2..729211830a1 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 static void main(String[] args) throws Exception { .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 static void main(String[] args) throws Exception { 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 cbe7b011122..7647448fa31 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 @@ private static void multipleRegistries() { 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 5987b8acf93..1aa652dca67 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.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.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 @@ public void beforeAll() { registryConfig = new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress1()); // pre-check threads - //precheckUnclosedThreads(); + // precheckUnclosedThreads(); } @AfterEach @@ -84,7 +84,7 @@ public void afterAll() throws Exception { FrameworkModel.destroyAll(); // check threads - //checkUnclosedThreads(); + // checkUnclosedThreads(); } private static Map precheckUnclosedThreads() throws IOException { @@ -220,7 +220,7 @@ void testSharedApplications() { @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 @@ void testMultiModuleApplication() throws InterruptedException { 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 @@ void testMultiModuleApplication() throws InterruptedException { 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 @@ void testMultiProviderApplicationsStopOneByOne() { 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 @@ void testMultiProviderApplicationsStopOneByOne() { 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 @@ void testMultiProviderApplicationsStopOneByOne() { // 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 @@ void testMultiProviderApplicationsStopOneByOne() { } } - 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 @@ void testMultiModuleDeployAndReload() throws Exception { 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 @@ void testMultiModuleDeployAndReload() throws Exception { 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 @@ void testMultiModuleDeployAndReload() throws Exception { 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 @@ void testMultiModuleDeployAndReload() throws Exception { 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 @@ void testMultiModuleDeployAndReload() throws Exception { 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 @@ void testMultiModuleDeployAndReload() throws Exception { 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 @@ void testBothStartByModuleAndByApplication() throws Exception { 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 @@ void testBothStartByModuleAndByApplication() throws Exception { 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 @@ void testBothStartByModuleAndByApplication() throws Exception { } } - @Test void testBothStartModuleAndApplicationNoWait() throws Exception { String version1 = "1.0"; @@ -667,17 +672,15 @@ void testBothStartModuleAndApplicationNoWait() throws Exception { 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 @@ void testBothStartModuleAndApplicationNoWait() throws Exception { 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 @@ void testOldApiDeploy() throws Exception { 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 @@ void testOldApiDeploy() throws Exception { // 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 @@ void testOldApiDeploy() throws Exception { // 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 @@ void testAsyncExportAndReferServices() throws ExecutionException, InterruptedExc // 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 @@ void testAsyncExportAndReferServices() throws ExecutionException, InterruptedExc 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 @@ private DubboBootstrap configConsumerApp(DubboBootstrap dubboBootstrap) { 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 @@ private DubboBootstrap configProviderApp(DubboBootstrap dubboBootstrap) { 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 37262e23c2e..98603b8d479 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 static void main(String[] args) throws Exception { .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 72c597ae2f3..ad5911c1822 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 static void main(String[] args) { .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 25093206f56..657120a2114 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 static void main(String[] args) throws Exception { .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 889aae25984..927716f8130 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 428a93306f5..c382ecf9fc8 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 @@ 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 @@ protected Builder getThis() { } } - 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 e865ea46bbb..871e951c564 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.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 @@ void build() { 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 @@ protected InterfaceBuilder getThis() { } } - 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 fb2beb61cbd..02cc967984e 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 @@ 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 @@ void forks() { @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 @@ void build() { Assertions.assertEquals("one", config.getParameters().get("default.num")); Assertions.assertNotSame(config, config2); - } private static class MethodBuilder extends AbstractMethodBuilder { @@ -190,6 +198,5 @@ protected MethodBuilder getThis() { } } - 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 c066a16a31d..d8be34dd4ce 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 @@ void group() { @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 @@ protected ReferenceBuilder getThis() { } } - 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 ef8a9daa482..dbd3608dfe6 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 @@ 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 @@ void build() { 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 @@ protected ServiceBuilder getThis() { } } - 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 f3b5517bd5b..c41be480845 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.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 @@ void build() { 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 @@ void build() { 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 1b6638dd766..3fe6d31c5e0 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 @@ void build() { 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 e07db36fbc5..802e3d64bc4 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 @@ 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 @@ void appendParameters() { @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 @@ void build() { 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 607388c7b27..7aa88fcd8ee 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 @@ void shareConnections() { @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 @@ void build() { 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 9e3e718c6a1..11692fc5a98 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 @@ 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 @@ void syncReport() { @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 @@ void build() { 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 9196c48210c..2c0855ac40c 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 @@ 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 @@ void serviceId() { 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 @@ void build() { 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 bbf7d2eb937..03f48a06d2f 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.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 @@ void build() { 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 @@ void build() { 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 f63fd39d42b..aedbb087006 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 @@ 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 @@ void appendParameters() { @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 @@ void build() { 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 331d228f72a..b5867f19c7a 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 @@ 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 @@ void isDefault() { @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 @@ void build() { 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 f3cc1a6b220..06a8f68b51e 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 @@ void isDefault() { @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 @@ void build() { 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 4d11ef43149..5deba4d4eee 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.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 @@ void build() { 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 eab629d0a5c..05aa52fc8f3 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 @@ 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 @@ void extraKeys() { @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 @@ void build() { 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 cb22a45cdf5..db2ed60a583 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.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 @@ void generic1() throws Exception { 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 @@ void build() { 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 @@ void build() { 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 d9c9c572874..6e559fbea06 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 static void main(String[] args) throws Exception { // 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 static void main(String[] args) throws Exception { 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 cfd52e24577..a1586f9955a 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.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 void setName(String name) { @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 fa5b7ae38d1..53400f292ed 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.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 8cb0bd0d333..6d24d6206df 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 7696b24e701..abf553d4f82 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 @@ 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 14e9ee7d8af..254917ecd5d 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 839b8d3c15d..c264fe1a837 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.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 @@ public void setUp() { @AfterEach public void tearDown() { -// ApplicationModel.defaultModel().getConfigManager().clear(); + // ApplicationModel.defaultModel().getConfigManager().clear(); } private void testCache(String type) throws Exception { @@ -129,16 +129,25 @@ void testCacheThreadlocal() throws Exception { @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); - - Invocation invocation = new RpcInvocation("findCache", CacheService.class.getName(), "", new Class[]{String.class}, new String[]{"0"}, null, null, null); + 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); 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 434fb55f179..e424fb34b28 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; @@ -26,7 +25,8 @@ class DefaultApplicationDeployerTest { @Test void isSupportPrometheus() { - boolean supportPrometheus = new DefaultApplicationDeployer(ApplicationModel.defaultModel()).isSupportPrometheus(); - Assert.assertTrue(supportPrometheus,"DefaultApplicationDeployer.isSupportPrometheus() should return true"); + boolean supportPrometheus = + new DefaultApplicationDeployer(ApplicationModel.defaultModel()).isSupportPrometheus(); + Assert.assertTrue(supportPrometheus, "DefaultApplicationDeployer.isSupportPrometheus() should return true"); } } 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 b62c15f4b6c..e37f92da0c7 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 void exported(Exporter exporter) throws RpcException { 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 Set getFilters() { /** * 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 @@ private Filter getFilter(FilterChainBuilder.CopyOfFilterChainNode filterChainNod /** * 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 c898c918603..337d68d24ce 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 void exported(ServiceConfig sc) { */ @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 2e3067affae..a185231fb82 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 f113cde98f1..a12f4cfb32b 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 cf2d870a067..6a864e030fc 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 @@ * 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 28a644bff70..0cc3aa81c73 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,10 @@ import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; +import java.io.IOException; +import java.util.List; +import java.util.stream.Collectors; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -37,10 +41,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.util.List; -import java.util.stream.Collectors; - import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL; /** @@ -48,7 +48,8 @@ */ 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. @@ -79,7 +80,6 @@ class MultipleRegistryCenterExportMetadataIntegrationTest implements Integration */ private MultipleRegistryCenterExportMetadataExporterListener exporterListener; - @BeforeEach public void setUp() throws Exception { logger.info(getClass().getSimpleName() + " testcase is beginning..."); @@ -93,11 +93,11 @@ public void setUp() throws Exception { // 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())); } /** @@ -112,8 +112,10 @@ public void setUp() throws Exception { */ 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 @@ -148,8 +150,8 @@ private void afterExport() { // 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 @@ -159,11 +161,10 @@ private void afterExport() { // 1. Metadata Service exporter with Injvm protocol // 2. MultipleRegistryCenterExportMetadataService exporter with Injvm protocol Assertions.assertEquals(exporterListener.getExportedExporters().size(), 2); - List> injvmExporters = exporterListener.getExportedExporters() - .stream() - .filter( - exporter -> PROTOCOL_NAME.equalsIgnoreCase(exporter.getInvoker().getUrl().getProtocol()) - ).collect(Collectors.toList()); + List> injvmExporters = exporterListener.getExportedExporters().stream() + .filter(exporter -> PROTOCOL_NAME.equalsIgnoreCase( + exporter.getInvoker().getUrl().getProtocol())) + .collect(Collectors.toList()); // Make sure there two injvmExporters Assertions.assertEquals(injvmExporters.size(), 2); } @@ -178,4 +179,4 @@ public void tearDown() throws IOException { serviceListener = 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/exportprovider/MultipleRegistryCenterExportProviderFilter.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderFilter.java index daf839bc3b8..b00bae913f9 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.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 d2f9b7ee2dc..10395824f57 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.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.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 @@ public void setUp() throws Exception { // 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 @@ public void setUp() throws Exception { * */ 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 @@ private void afterExport() { // 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 @@ private void afterExport() { // 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 @@ private void afterExport() { // 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 8b6c87f985e..ef632ffa34a 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 void onExport(RegistryProtocol registryProtocol, Exporter exporter) { * {@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 cd2e87dfe5b..77ef3f1ada1 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.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 227eaf2718b..3d7315a456f 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.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.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; - import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL; /** @@ -89,11 +89,11 @@ public void setUp() throws Exception { 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 @@ public void setUp() throws Exception { */ 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 @@ private void afterExport() { // 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 @@ private void afterInvoke() { // 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 d0047fe4ceb..1f89b88cc33 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.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.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 @@ */ 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 @@ public void setUp() throws Exception { 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 @@ public void integrate() { 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 @@ private void afterExport() { // 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 @@ private void afterExport() { /** * 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 @@ public void tearDown() throws IOException { 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 f84a9b8765c..2cd8e64b612 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 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 @@ private ServiceDiscoveryRegistryInfoWrapper createServiceDiscoveryRegistryInfoWr /** * 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 09469df5a7b..3ddaad57cde 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 @@ /** * 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 3a615f67093..8bb4736e769 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 @@ /** * 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 b10835de239..5f668f48a2a 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.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.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 @@ public void setUp() throws Exception { 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 @@ private void afterExport() { // 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 @@ private void afterExport() { 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 @@ private void afterExport() { // 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 @@ private void afterExport() { * 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 @@ private void initConsumer() { */ 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 @@ private void afterRefer() { 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 @@ private void afterRefer() { 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 @@ public void tearDown() throws IOException { 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 3178b2e7e96..996e98d8929 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,10 @@ import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; +import java.io.IOException; +import java.util.List; +import java.util.stream.Collectors; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -37,10 +41,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.util.List; -import java.util.stream.Collectors; - import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL; /** @@ -48,7 +48,8 @@ */ 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. @@ -92,9 +93,9 @@ public void setUp() throws Exception { // 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); } @@ -111,8 +112,10 @@ public void setUp() throws Exception { */ 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 @@ -147,19 +150,18 @@ private void afterExport() { // 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 // 1. Metadata Service exporter with Injvm protocol // 2. SingleRegistryCenterExportMetadataService exporter with Injvm protocol Assertions.assertEquals(exporterListener.getExportedExporters().size(), 2); - List> injvmExporters = exporterListener.getExportedExporters() - .stream() - .filter( - exporter -> PROTOCOL_NAME.equalsIgnoreCase(exporter.getInvoker().getUrl().getProtocol()) - ).collect(Collectors.toList()); + List> injvmExporters = exporterListener.getExportedExporters().stream() + .filter(exporter -> PROTOCOL_NAME.equalsIgnoreCase( + exporter.getInvoker().getUrl().getProtocol())) + .collect(Collectors.toList()); // Make sure there are 2 injvmExporters Assertions.assertEquals(injvmExporters.size(), 2); } @@ -174,4 +176,4 @@ public void tearDown() throws IOException { serviceListener = 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/exportprovider/SingleRegistryCenterExportProviderFilter.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportprovider/SingleRegistryCenterExportProviderFilter.java index caf9963de63..299e9c7338f 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.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 41de19efcb3..d866f40d6e1 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.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.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 @@ */ 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 @@ public void setUp() throws Exception { // 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 @@ public void setUp() throws Exception { * */ 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 @@ private void afterExport() { // 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 @@ private void afterExport() { // 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 c7de521d5bb..c67e0981376 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 void onExport(RegistryProtocol registryProtocol, Exporter exporter) { * {@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 48b56df8b8e..06bbdb0f63a 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.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 b313d4461a2..95090fd8ff0 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.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.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; - import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL; /** @@ -89,9 +89,9 @@ public void setUp() throws Exception { // 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 @@ public void setUp() throws Exception { */ 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 @@ private void afterExport() { // 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 de428815680..1abbb660199 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 @@ void testDelegate() { 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 f8361128d5c..185b0f26689 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.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 @@ 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 @@ void test() { 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(); 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 f3d5ee572b8..6b688bf0fa3 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 8cae40684f3..d60a2124178 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 9b14ac6e9ef..ba68d28e257 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/GreetingMock1.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/GreetingMock1.java index 8bfe6e6c076..2a487d8eb72 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/GreetingMock1.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/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.config.mock; -public class GreetingMock1 { -} +public class GreetingMock1 {} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/GreetingMock2.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/GreetingMock2.java index 429bff442af..ca1a8da9275 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/GreetingMock2.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/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, @@ -19,8 +19,7 @@ import org.apache.dubbo.config.api.Greeting; public class GreetingMock2 implements Greeting { - private GreetingMock2() { - } + private GreetingMock2() {} @Override public String hello() { 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 3b5b2cce003..d188a965806 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 c1aac425e50..5de3b545015 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 @@ 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 32fffca968a..60dadb77658 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 fccfd2387f3..729282aeedf 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 b93f44cb62f..f106811a624 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 @@ 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 d51f12318f3..46b570b0f33 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 c929e5443f1..7137edb2d96 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 @@ 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 377f328a3dc..a2f58129e26 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 d09faf8336d..cdea6a2d4d2 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 Result invoke(Invocation invocation) throws RpcException { } @Override - public void destroy() { - - } + public void destroy() {} }; } @@ -84,8 +82,5 @@ public void destroy() { * @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 91653d4dfb0..2f1a31990ca 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 49f05d841ef..215639d90b7 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 735c9427859..f1a461f429f 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 boolean isAvailable() { * @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 void subscribe(URL url, NotifyListener listener) { 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 void subscribe(URL url, NotifyListener listener) { * @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 void unsubscribe(URL url, NotifyListener listener) { 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 1e0e6e7b794..9005378f4f6 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 Registry getRegistry(URL url) { 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 2ab3da8faa2..4217a836d8e 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 694342a7acb..8dc9e8d611e 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 MockServiceDiscovery(String serviceName, URL registryURL) { } @Override - public void doDestroy() throws Exception { - - } + public void doDestroy() throws Exception {} @Override public void doRegister(ServiceInstance serviceInstance) throws RuntimeException { @@ -48,7 +46,8 @@ public void doRegister(ServiceInstance serviceInstance) throws RuntimeException } @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 75e05a84624..a7e8e0cb890 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 void exported(ServiceConfig sc) { } @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 e144c7bc2c0..8683513278c 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 a08160fa798..5738e5276d6 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 fe966899d86..80b327b6ebd 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 28bce33e448..4a1dc835c5b 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 fe22bd13ffe..f18ecb0200a 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 76c9d504a8d..13efc6a5ed0 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 @@ void testTimeWindowSeconds() { 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 50d0f0a6fc9..8ba85b6de1e 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 List getUsers(List users) { 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 c07201b78ee..4a7f225ff55 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 @@ void exporterProviderConfigUrlTest() { @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 @@ protected void verifyExporterUrlGeneration(T config, Object[][] dataTable) { // 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 5994f7e535f..90d3657bb68 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.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", "", "", "", "", ""}, - -// {"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", "", "", "", "", ""}, - //{"", "", "", "", "", "", "", "", "", ""}, + // {"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", "", "", "", "", ""}, + // {"", "", "", "", "", "", "", "", "", ""}, }; - 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 @@ void refConfUrlTest() { 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 @@ private void initRefConf() { 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 @@ private void verifyInvokerUrlGeneration(T config, Object[][] dataTable) { 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 a41988ade08..15dcc0fa618 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 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 RpcConfigGetSetProxy(Object p) { } proxiee = p; - //proxieeClass = c; + // proxieeClass = c; proxieeClass = p.getClass(); isOk = true; - } public static boolean isKindOf(Class c, String type) { @@ -162,5 +159,4 @@ private Method findMethod(String key, Object value, String prefix, Class claz 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 5328bff6b2b..868081c0945 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 @@ protected void fillConfig(T conf, Object[] row, int column) { RpcConfigGetSetProxy proxy = new RpcConfigGetSetProxy(conf); proxy.setValue((String) row[KEY], row[column]); - } @SuppressWarnings("deprecation") @@ -143,7 +158,7 @@ protected void initServConf() { 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 @@ protected void initServConf() { 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 @@ protected String getProviderParamString() { * @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 @@ protected void assertUrlStringWithLocalTable(String paramStringFromDb, 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 af985334960..fb6dae095c6 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 @@ -24,15 +24,15 @@ import org.apache.dubbo.config.mock.GreetingMock1; import org.apache.dubbo.config.mock.GreetingMock2; +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.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_CLASS_NOT_FOUND; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -40,17 +40,14 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; - class ConfigValidationUtilsTest { - @Test void checkMock1() { Assertions.assertThrows(IllegalStateException.class, () -> { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setMock("return {a, b}"); ConfigValidationUtils.checkMock(Greeting.class, interfaceConfig); - }); } @@ -99,8 +96,10 @@ void testValidateMetadataConfig() { @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); @@ -116,15 +115,21 @@ void testValidateApplicationConfig() throws Exception { 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)); } } @@ -141,7 +146,14 @@ void testCheckQosInApplicationConfig() throws Exception { config.setQosEnable(true); mock.validateApplicationConfig(config); - verify(loggerMock).warn(eq(COMMON_CLASS_NOT_FOUND), eq(""), eq(""), eq("No QosProtocolWrapper class was found. Please check the dependency of dubbo-qos whether was imported correctly."), any()); + verify(loggerMock) + .warn( + eq(COMMON_CLASS_NOT_FOUND), + eq(""), + eq(""), + eq( + "No QosProtocolWrapper class was found. Please check the dependency of dubbo-qos whether was imported correctly."), + any()); } private void injectField(Field field, Object newValue) throws Exception { @@ -149,8 +161,5 @@ private void injectField(Field field, Object newValue) throws Exception { 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 22ad45a7aca..c231d892bc6 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 @@ public void setUp() throws Exception { @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 @@ void testGetCacheSameReference() throws Exception { @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 @@ void testGetCacheDiffReference() throws Exception { 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 @@ void testGetCacheDiffReference() throws Exception { @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 @@ void testGetCacheDiffName() throws Exception { @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 @@ void testDestroy() throws Exception { @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 @@ private XxxMockReferenceConfig buildXxxMockReferenceConfig(String service, Strin 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 9526ec1b531..836b1cbf75b 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 @@ /** * */ -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 24bef7689c2..50f3652a6ef 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 @@ /** * */ -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 47641ed235b..e112b48d0c7 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 @@ /** * */ -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 fc8a87b2e94..7db91167bad 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 @@ /** * */ -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 93869ad63d7..00000000000 --- 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 65d3b96f83c..ae060f846d4 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 - - - 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 - - - junit-vintage-engine - org.junit.vintage - - - - org.apache.logging.log4j - log4j-api - - - + + + 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 + + + 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 + + + org.junit.vintage + junit-vintage-engine + + + + org.apache.logging.log4j + log4j-api + + + - - - 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 3126a88a078..888d89c47d2 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.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.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 @@ * 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 void setApplicationContext(ApplicationContext applicationContext) { } @Override - public void destroy() throws Exception { - - } + public void destroy() throws Exception {} @Override public void setEnvironment(Environment environment) { @@ -69,7 +67,11 @@ public void setEnvironment(Environment environment) { // 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 @@ private Map getConfigurations(String key, Environment environmen 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 Boolean getIncludeSpringEnv() { 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 eec610059a2..3846b001a25 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 30790d3fd88..dc474498d6a 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 @@ -36,6 +36,12 @@ 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; @@ -48,16 +54,9 @@ 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 @@ * @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,26 +134,27 @@ 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 private ReferenceBeanManager referenceBeanManager; // Registration sources of this reference, may be xml file or annotation location - private List> sources = new ArrayList<>(); + private List> sources = new ArrayList<>(); public ReferenceBean() { super(); @@ -277,7 +282,6 @@ public void setId(String id) { this.id = id; } - /** * The interface of this ReferenceBean, for injection purpose * @return @@ -336,14 +340,14 @@ public void setKeyAndReferenceConfig(String key, ReferenceConfig referenceConfig */ 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); @@ -363,18 +367,37 @@ private void createLazyProxy() { 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; } } @@ -382,10 +405,18 @@ private void generateFromJavassistFirst(List> interfaces) { 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; } } @@ -393,13 +424,21 @@ private void generateFromJdk(List> interfaces) { 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(); } @@ -414,5 +453,4 @@ public Object getTarget() throws Exception { return getCallProxy(); } } - } 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 8fd1ed9b11c..fa964ab603a 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 @@ -38,9 +38,12 @@ * * @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; @@ -104,7 +107,7 @@ public void afterPropertiesSet() throws Exception { 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 a0750ee19ba..136aed980ea 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 @@ 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/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 ade274d59a0..c287e23ae4b 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.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.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 @@ * 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 @@ protected final Class[] getAnnotationTypes() { @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 void setBeanFactory(BeanFactory beanFactory) throws BeansException { * @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 @@ private List findFiel }); return elements; - } /** @@ -162,12 +173,12 @@ private List findFiel * @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 @@ private List findAnn 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 @@ private List findAnn 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 @@ protected AnnotatedInjectionMetadata findInjectionMetadata(String beanName, Clas // 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 @@ protected AnnotatedInjectionMetadata findInjectionMetadata(String beanName, Clas 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 void destroy() throws Exception { if (logger.isInfoEnabled()) { logger.info(getClass() + " was destroying!"); } - } @Override @@ -280,8 +299,13 @@ protected ConfigurableListableBeanFactory getBeanFactory() { * @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 @@ protected Object getInjectedObject(AnnotationAttributes attributes, Object bean, * @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 @@ protected void prepareInjection(AnnotatedInjectionMetadata metadata) throws Exce * @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 @@ protected static class AnnotatedInjectionMetadata extends InjectionMetadata { 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 Collection ge 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 c0c2e96eb26..fd871607d48 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 @@ 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 84a1eb03a29..d8dc09388b4 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 Object postProcessBeforeInitialization(Object bean, String beanName) thro 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 a36cd6f5662..a4fcb62b930 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.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.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 @@ * @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); private ApplicationContext applicationContext; @@ -128,9 +127,10 @@ public ReferenceAnnotationBeanPostProcessor() { @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 void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) 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 void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) } 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 @@ private void processReferenceAnnotatedBeanDefinition(String beanName, AnnotatedB 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 @@ private void processReferenceAnnotatedBeanDefinition(String beanName, AnnotatedB } 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 @@ private void processReferenceAnnotatedBeanDefinition(String beanName, AnnotatedB // 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 @@ private void processReferenceAnnotatedBeanDefinition(String beanName, AnnotatedB 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); @@ -328,7 +344,7 @@ public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, C * @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); } @@ -338,7 +354,7 @@ public PropertyValues postProcessPropertyValues( */ @Override public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) - throws BeansException { + throws BeansException { try { AnnotatedInjectionMetadata metadata = findInjectionMetadata(beanName, bean.getClass(), pvs); prepareInjection(metadata); @@ -346,8 +362,8 @@ public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, Str } 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; } @@ -358,19 +374,19 @@ private boolean isReferenceBean(BeanDefinition beanDefinition) { 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()) { @@ -379,9 +395,10 @@ protected void prepareInjection(AnnotatedInjectionMetadata metadata) throws Bean } 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); } @@ -390,7 +407,9 @@ protected void prepareInjection(AnnotatedInjectionMetadata metadata) throws Bean } } - 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 @@ -409,7 +428,9 @@ public String registerReferenceBean(String propertyName, Class injectedType, // 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 @@ -424,11 +445,12 @@ public String registerReferenceBean(String propertyName, Class injectedType, } } - //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){ + if (!isContains) { // Look in the alias for the origin bean name String[] aliases = beanDefinitionRegistry.getAliases(referenceBeanName); if (ArrayUtils.isNotEmpty(aliases)) { @@ -446,30 +468,34 @@ public String registerReferenceBean(String propertyName, Class injectedType, 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 @@ -479,10 +505,16 @@ public String registerReferenceBean(String propertyName, Class injectedType, } 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); @@ -508,11 +540,13 @@ public String registerReferenceBean(String propertyName, Class injectedType, beanDefinition.setAttribute(ReferenceAttributes.INTERFACE_CLASS, interfaceClass); beanDefinition.setAttribute(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); @@ -524,11 +558,17 @@ public String registerReferenceBean(String propertyName, Class injectedType, } @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); @@ -537,7 +577,8 @@ protected Object doGetInjectedBean(AnnotationAttributes attributes, Object bean, @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 aa8a52cf935..e187ff3380b 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,18 @@ 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 org.springframework.beans.BeansException; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.BeanClassLoaderAware; @@ -69,18 +81,6 @@ 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 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 +101,34 @@ * @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); } } @@ -183,7 +187,8 @@ public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) Map annotationAttributes = getServiceAnnotationAttributes(beanDefinition); if (annotationAttributes != null) { // process @DubboService at java-config @bean method - processAnnotatedBeanDefinition(beanName, (AnnotatedBeanDefinition) beanDefinition, annotationAttributes); + processAnnotatedBeanDefinition( + beanName, (AnnotatedBeanDefinition) beanDefinition, annotationAttributes); } } @@ -204,7 +209,11 @@ private void scanServiceBeans(Set packagesToScan, BeanDefinitionRegistry 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; } @@ -242,19 +251,28 @@ private void scanServiceBeans(Set packagesToScan, BeanDefinitionRegistry 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()); } } @@ -280,7 +298,8 @@ private BeanNameGenerator resolveBeanNameGenerator(BeanDefinitionRegistry regist 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) { @@ -289,17 +308,14 @@ private BeanNameGenerator resolveBeanNameGenerator(BeanDefinitionRegistry regist 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."); + 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; - } /** @@ -313,7 +329,9 @@ private BeanNameGenerator resolveBeanNameGenerator(BeanDefinitionRegistry regist * @since 2.5.8 */ private Set findServiceBeanDefinitionHolders( - ClassPathBeanDefinitionScanner scanner, String packageToScan, BeanDefinitionRegistry registry, + ClassPathBeanDefinitionScanner scanner, + String packageToScan, + BeanDefinitionRegistry registry, BeanNameGenerator beanNameGenerator) { Set beanDefinitions = scanner.findCandidateComponents(packageToScan); @@ -325,11 +343,9 @@ private Set findServiceBeanDefinitionHolders( String beanName = beanNameGenerator.generateBeanName(beanDefinition, registry); BeanDefinitionHolder beanDefinitionHolder = new BeanDefinitionHolder(beanDefinition, beanName); beanDefinitionHolders.add(beanDefinitionHolder); - } return beanDefinitionHolders; - } /** @@ -359,7 +375,6 @@ private void processScannedBeanDefinition(BeanDefinitionHolder beanDefinitionHol buildServiceBeanDefinition(serviceAnnotationAttributes, serviceInterface, annotatedServiceBeanName); registerServiceBeanDefinition(beanName, serviceBeanDefinition, serviceInterface); - } /** @@ -370,14 +385,16 @@ private void processScannedBeanDefinition(BeanDefinitionHolder beanDefinitionHol * @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)) + 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); @@ -403,7 +420,6 @@ private Class resolveClass(BeanDefinitionHolder beanDefinitionHolder) { BeanDefinition beanDefinition = beanDefinitionHolder.getBeanDefinition(); return resolveClass(beanDefinition); - } private Class resolveClass(BeanDefinition beanDefinition) { @@ -411,7 +427,6 @@ private Class resolveClass(BeanDefinition beanDefinition) { String beanClassName = beanDefinition.getBeanClassName(); return resolveClassName(beanClassName, classLoader); - } private Set resolvePackagesToScan(Set packagesToScan) { @@ -435,9 +450,8 @@ private Set resolvePackagesToScan(Set packagesToScan) { * @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); @@ -446,19 +460,30 @@ private AbstractBeanDefinition buildServiceBeanDefinition(Map se MutablePropertyValues propertyValues = beanDefinition.getPropertyValues(); - String[] ignoreAttributeNames = ObjectUtils.of("provider", "monitor", "application", "module", "registry", "protocol", - "methods", "interfaceName", "parameters", "executor"); - - propertyValues.addPropertyValues(new AnnotationPropertyValuesAdapter(serviceAnnotationAttributes, environment, ignoreAttributeNames)); - - //set config id, for ConfigManager cache key - //builder.addPropertyValue("id", beanName); + String[] ignoreAttributeNames = ObjectUtils.of( + "provider", + "monitor", + "application", + "module", + "registry", + "protocol", + "methods", + "interfaceName", + "parameters", + "executor"); + + propertyValues.addPropertyValues( + new AnnotationPropertyValuesAdapter(serviceAnnotationAttributes, environment, ignoreAttributeNames)); + + // 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()) { @@ -504,7 +529,6 @@ private AbstractBeanDefinition buildServiceBeanDefinition(Map se } return builder.getBeanDefinition(); - } private String[] resolveStringArray(String[] strs) { @@ -547,9 +571,11 @@ private Map getServiceAnnotationAttributes(BeanDefinition beanDe 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 +602,10 @@ private Map getServiceAnnotationAttributes(BeanDefinition beanDe * @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 +618,8 @@ private void processAnnotatedBeanDefinition(String refServiceBeanName, Annotated // 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 +627,8 @@ private void processAnnotatedBeanDefinition(String refServiceBeanName, Annotated 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 +637,12 @@ private void registerServiceBeanDefinition(String serviceBeanName, AbstractBeanD 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 +668,8 @@ public void setBeanClassLoader(ClassLoader classLoader) { @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 +677,8 @@ private class ScanExcludeFilter implements TypeFilter { 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 a3957f6076c..a10c0346298 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 @@ private ServiceBeanNameBuilder(String interfaceClassName, Environment environmen 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 @@ private ServiceBeanNameBuilder(AnnotationAttributes attributes, Class default * @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 75eb6ca2be3..b689e512944 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 @@ private String normalizePackage(String apackage) { } 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 a3599cae3d8..44155ea28c0 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.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.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 @@ protected void processBeforeInitialization(AbstractConfig dubboConfigBean, Strin 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 @@ protected void setPropertyIfAbsent(Object bean, String propertyName, String bean 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 802e32d9d4d..6091656343a 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 @@ private void initDubboConfigBeans() { 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 @@ private void onContextRefreshedEvent(ContextRefreshedEvent event) { 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 void setApplicationContext(ApplicationContext applicationContext) throws } 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 @@ private void checkCallStackAndInit() { // 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 2cdf512053f..fa9d5b2b0b2 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.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 void onApplicationEvent(DubboConfigInitEvent event) { } public void init() { - // It's expected to be notified at org.springframework.context.support.AbstractApplicationContext.registerListeners(), + // It's expected to be notified at + // org.springframework.context.support.AbstractApplicationContext.registerListeners(), // before loading non-lazy singleton beans. At this moment, all BeanFactoryPostProcessor have been processed, if (initialized.compareAndSet(false, true)) { initDubboConfigBeans(); @@ -71,12 +74,14 @@ private void initDubboConfigBeans() { 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 moduleModel.getDeployer().prepare(); } - - } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboConfigBeanInitializer.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboConfigBeanInitializer.java index bf696b69fe6..1a2409eaeb0 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboConfigBeanInitializer.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboConfigBeanInitializer.java @@ -36,6 +36,9 @@ import org.apache.dubbo.config.spring.reference.ReferenceBeanManager; import org.apache.dubbo.rpc.model.ModuleModel; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; + import org.springframework.beans.BeansException; import org.springframework.beans.FatalBeanException; import org.springframework.beans.factory.BeanFactory; @@ -45,10 +48,6 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; - - /** * * Dubbo config bean initializer. @@ -101,7 +100,7 @@ private void init() { private void prepareDubboConfigBeans() { logger.info("loading dubbo config beans ..."); - //Make sure all these config beans are initialed and registered to ConfigManager + // Make sure all these config beans are initialed and registered to ConfigManager // load application config beans loadConfigBeansOfType(ApplicationConfig.class, configManager); loadConfigBeansOfType(RegistryConfig.class, configManager); @@ -128,7 +127,8 @@ private void prepareDubboConfigBeans() { logger.info("dubbo config beans are loaded."); } - private void loadConfigBeansOfType(Class 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); @@ -136,5 +136,4 @@ private void loadConfigBeansOfType(Class configClass, configManager.addConfig(configBean); } } - } 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 73c07c5b299..869e61b9fb4 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.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.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 @@ /** * 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 void setApplicationContext(ApplicationContext applicationContext) throws this.applicationModel = DubboBeanUtils.getApplicationModel(applicationContext); this.moduleModel = DubboBeanUtils.getModuleModel(applicationContext); // listen deploy events and publish DubboApplicationStateEvent - applicationModel.getDeployer().addDeployListener(new DeployListenerAdapter(){ + applicationModel.getDeployer().addDeployListener(new DeployListenerAdapter() { @Override public void onStarting(ApplicationModel scopeModel) { publishApplicationEvent(DeployState.STARTING); @@ -90,7 +92,7 @@ public void onFailure(ApplicationModel scopeModel, Throwable cause) { publishApplicationEvent(DeployState.FAILED, cause); } }); - moduleModel.getDeployer().addDeployListener(new DeployListenerAdapter(){ + moduleModel.getDeployer().addDeployListener(new DeployListenerAdapter() { @Override public void onStarting(ModuleModel scopeModel) { publishModuleEvent(DeployState.STARTING); @@ -160,9 +162,18 @@ private void onContextRefreshedEvent(ContextRefreshedEvent event) { try { future.get(); } catch (InterruptedException e) { - logger.warn(CONFIG_FAILED_START_MODEL, "", "", "Interrupted while waiting for dubbo module start: " + e.getMessage()); + logger.warn( + CONFIG_FAILED_START_MODEL, + "", + "", + "Interrupted while waiting for dubbo module start: " + e.getMessage()); } catch (Exception e) { - logger.warn(CONFIG_FAILED_START_MODEL, "", "", "An error occurred while waiting for dubbo module start: " + e.getMessage(), e); + logger.warn( + CONFIG_FAILED_START_MODEL, + "", + "", + "An error occurred while waiting for dubbo module start: " + e.getMessage(), + e); } } } @@ -178,7 +189,12 @@ private void onContextClosedEvent(ContextClosedEvent event) { moduleModel.destroy(); } } catch (Exception e) { - logger.error(CONFIG_STOP_DUBBO_ERROR, "", "", "Unexpected error occurred when stop dubbo module: " + e.getMessage(), e); + logger.error( + CONFIG_STOP_DUBBO_ERROR, + "", + "", + "Unexpected error occurred when stop dubbo module: " + e.getMessage(), + e); } // remove context bind cache DubboSpringInitializer.remove(event.getApplicationContext()); @@ -188,5 +204,4 @@ private void onContextClosedEvent(ContextClosedEvent event) { public int getOrder() { return LOWEST_PRECEDENCE; } - } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboInfraBeanRegisterPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboInfraBeanRegisterPostProcessor.java index b54b506e551..09bdd7a7d3b 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboInfraBeanRegisterPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboInfraBeanRegisterPostProcessor.java @@ -24,6 +24,8 @@ 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; @@ -32,9 +34,6 @@ import org.springframework.context.ApplicationContextAware; import org.springframework.core.env.ConfigurableEnvironment; -import java.util.SortedMap; - - /** * Register some infrastructure beans if not exists. * This post-processor MUST impl BeanDefinitionRegistryPostProcessor, @@ -43,7 +42,8 @@ * @see org.springframework.context.support.PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors( *org.springframework.beans.factory.config.ConfigurableListableBeanFactory, java.util.List) */ -public class DubboInfraBeanRegisterPostProcessor implements BeanDefinitionRegistryPostProcessor, ApplicationContextAware { +public class DubboInfraBeanRegisterPostProcessor + implements BeanDefinitionRegistryPostProcessor, ApplicationContextAware { /** * The bean name of {@link ReferenceAnnotationBeanPostProcessor} @@ -61,12 +61,14 @@ public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) t @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { - // In Spring 3.2.x, registry may be null because do not call postProcessBeanDefinitionRegistry method before postProcessBeanFactory + // In Spring 3.2.x, registry may be null because do not call postProcessBeanDefinitionRegistry method before + // postProcessBeanFactory if (registry != null) { - // register ReferenceAnnotationBeanPostProcessor early before PropertySourcesPlaceholderConfigurer/PropertyPlaceholderConfigurer + // register ReferenceAnnotationBeanPostProcessor early before + // PropertySourcesPlaceholderConfigurer/PropertyPlaceholderConfigurer // for processing early init ReferenceBean ReferenceAnnotationBeanPostProcessor referenceAnnotationBeanPostProcessor = beanFactory.getBean( - ReferenceAnnotationBeanPostProcessor.BEAN_NAME, ReferenceAnnotationBeanPostProcessor.class); + ReferenceAnnotationBeanPostProcessor.BEAN_NAME, ReferenceAnnotationBeanPostProcessor.class); beanFactory.addBeanPostProcessor(referenceAnnotationBeanPostProcessor); // register PropertySourcesPlaceholderConfigurer bean if not exits @@ -91,7 +93,7 @@ public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) beanFactory.registerSingleton(ConfigManager.BEAN_NAME, applicationModel.getApplicationConfigManager()); // fix https://github.com/apache/dubbo/issues/10278 - if (registry != null){ + if (registry != null) { registry.removeBeanDefinition(BEAN_NAME); } } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitContext.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitContext.java index 71c6f3d6cb6..0d14a1be79f 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitContext.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitContext.java @@ -20,13 +20,13 @@ import org.apache.dubbo.rpc.model.ModelConstants; import org.apache.dubbo.rpc.model.ModuleModel; +import java.util.HashMap; +import java.util.Map; + import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.ApplicationContext; -import java.util.HashMap; -import java.util.Map; - /** * Dubbo spring initialization context object */ diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitCustomizer.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitCustomizer.java index 5d5adab3cbd..b34ae83decf 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitCustomizer.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitCustomizer.java @@ -43,5 +43,4 @@ public interface DubboSpringInitCustomizer { * @param context */ void customize(DubboSpringInitContext context); - } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitCustomizerHolder.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitCustomizerHolder.java index 7d06e284068..9eeb86ad5ae 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitCustomizerHolder.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitCustomizerHolder.java @@ -34,7 +34,8 @@ */ public class DubboSpringInitCustomizerHolder { - private static final ThreadLocal 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 void clearCustomizers() { 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 2c188af0a7c..5fa4f30bb3c 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 @@ -24,6 +24,10 @@ 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; @@ -31,10 +35,6 @@ 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 */ @@ -44,8 +44,7 @@ public class DubboSpringInitializer { private static final Map contextMap = new ConcurrentHashMap<>(); - private DubboSpringInitializer() { - } + private DubboSpringInitializer() {} public static void initialize(BeanDefinitionRegistry registry) { @@ -72,13 +71,12 @@ public static boolean remove(ApplicationContext springContext) { AutowireCapableBeanFactory autowireCapableBeanFactory = springContext.getAutowireCapableBeanFactory(); for (Map.Entry entry : contextMap.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 = contextMap.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; } } @@ -98,8 +96,10 @@ static DubboSpringInitContext findBySpringContext(ApplicationContext application 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); @@ -127,7 +127,8 @@ private static void initContext(DubboSpringInitContext context, BeanDefinitionRe } 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(); @@ -158,12 +159,14 @@ private static ConfigurableListableBeanFactory findBeanFactory(BeanDefinitionReg 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 registerSingleton(beanFactory, context); registerSingleton(beanFactory, context.getApplicationModel()); @@ -187,8 +190,8 @@ private static void customize(DubboSpringInitContext context) { // find initialization customizers Set customizers = FrameworkModel.defaultModel() - .getExtensionLoader(DubboSpringInitCustomizer.class) - .getSupportedExtensionInstances(); + .getExtensionLoader(DubboSpringInitCustomizer.class) + .getSupportedExtensionInstances(); for (DubboSpringInitCustomizer customizer : customizers) { customizer.customize(context); } @@ -201,5 +204,4 @@ private static void customize(DubboSpringInitContext context) { } 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 fc8953bab54..9bc89344264 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 @@ -16,17 +16,17 @@ */ package org.apache.dubbo.config.spring.context.annotation; +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 java.util.Objects; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - import static org.springframework.context.annotation.AnnotationConfigUtils.registerAnnotationConfigProcessors; /** @@ -43,9 +43,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); @@ -54,14 +56,12 @@ public DubboClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, bool setResourceLoader(resourceLoader); 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 82f16ecbb41..31983d466bc 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 @@ 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.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 @@ * @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 59cd3de7d80..101f6862ce4 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,11 @@ import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationPostProcessor; import org.apache.dubbo.config.spring.context.DubboSpringInitializer; +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 +36,6 @@ 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 +75,17 @@ private void registerServiceAnnotationPostProcessor(Set packagesToScan, 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 +94,14 @@ private Set getPackagesToScan(AnnotationMetadata metadata) { 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 +122,4 @@ private Set getPackagesToScan0(AnnotationMetadata metadata, Class annota } 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 9d698a2e97d..2e872c5b78e 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 5e3ef54cac4..860c9445de7 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 @@ 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.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 @@ @AliasFor(annotation = DubboComponentScan.class, attribute = "basePackageClasses") Class[] scanBasePackageClasses() default {}; - /** * It indicates whether {@link AbstractConfig} binding to multiple Spring Beans. * @@ -77,5 +76,4 @@ */ @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 3d5e085b97f..9e1b81e706a 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.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.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 @@ * @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 298e9e00158..10cf5573af8 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.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 void customize(String beanName, AbstractConfig dubboConfigBean) { 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 252b48230ac..28ffa459676 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 DubboConfigInitEvent(ApplicationContext source) { 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 47b3955feaa..4a2f532889d 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 final void setEnvironment(Environment environment) { 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 117207038fb..410e9c3710a 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 @@ 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 void bind(String prefix, C dubboConfig) { 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 @@ private String buildErrorMsg(List errors, String prefix, String conf 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 bf297803b68..d8422dc4aa6 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.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 T getInstance(Class type, String name) { return null; } - //check @SPI annotation + // check @SPI annotation if (type.isInterface() && type.isAnnotationPresent(SPI.class)) { return null; } @@ -66,28 +66,29 @@ public T getInstance(Class type, String name) { 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 efc13f98330..5eeb7889fa0 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 36c74180313..ed0070823eb 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 ReferenceBeanBuilder setInit(Boolean init) { return this; } - //@Deprecated + // @Deprecated public ReferenceBeanBuilder setGeneric(Boolean generic) { attributes.put(ReferenceAttributes.GENERIC, generic); return this; @@ -203,10 +203,10 @@ public ReferenceBeanBuilder setProviderPort(Integer providerPort) { 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 ReferenceBeanBuilder setLayer(String layer) { 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 ReferenceBeanBuilder setParameters(Map parameters) { 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 0e428a8647c..2bdf44362bb 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.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.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 void addReference(ReferenceBean referenceBean) throws Exception { 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 void addReference(ReferenceBean referenceBean) throws Exception { 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 @@ private String getReferenceKeyByBeanName(String referenceBeanName) { } 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 synchronized void initReferenceBean(ReferenceBean referenceBean) throws E 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 synchronized void initReferenceBean(ReferenceBean referenceBean) throws E // 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 97df3b5b787..513ae79d099 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 @@ -25,6 +25,16 @@ 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; @@ -38,23 +48,17 @@ 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) { @@ -95,7 +99,12 @@ public static void convertReferenceProps(Map attributes, Class d 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); } @@ -103,15 +112,16 @@ public static void convertReferenceProps(Map attributes, Class d 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) { @@ -119,10 +129,8 @@ public static void convertReferenceProps(Map attributes, Class d attributes.remove(ReferenceAttributes.REGISTRY); attributes.put(ReferenceAttributes.REGISTRY_IDS, value); } - } - public static String generateReferenceKey(Map attributes, ApplicationContext applicationContext) { String interfaceClass = (String) attributes.get(ReferenceAttributes.INTERFACE); @@ -130,7 +138,7 @@ public static String generateReferenceKey(Map attributes, Applic 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('/'); @@ -142,7 +150,7 @@ public static String generateReferenceKey(Map attributes, Applic // append attributes beanNameBuilder.append('('); - //sort attributes keys + // sort attributes keys List sortedAttrKeys = new ArrayList<>(attributes.keySet()); Collections.sort(sortedAttrKeys); for (String key : sortedAttrKeys) { @@ -152,10 +160,7 @@ public static String generateReferenceKey(Map attributes, Applic 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 ")" @@ -169,8 +174,10 @@ public static String generateReferenceKey(Map attributes, Applic 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; } @@ -180,11 +187,11 @@ private static String convertToString(String key, Object obj) { 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()) { @@ -219,11 +226,13 @@ public static Map convertPropertyValues(MutablePropertyValues pr 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); } @@ -231,16 +240,14 @@ public static Map convertPropertyValues(MutablePropertyValues pr } 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; } @@ -272,7 +279,8 @@ public static Map getReferenceAttributes(ReferenceBean reference 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 0f8e69087d3..2ac029e5466 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.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.StringUtils; import org.springframework.validation.DataBinder; -import java.util.Map; - /** * {@link ReferenceConfig} Creator for @{@link DubboReference} * @@ -52,7 +52,8 @@ 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 @@ private ReferenceCreator(Map attributes, ApplicationContext appl 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 final ReferenceConfig build() throws Exception { 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 @@ protected void configureBean(ReferenceConfig referenceConfig) throws Exception { configureModuleConfig(referenceConfig); configureConsumerConfig(referenceConfig); - } private void configureMonitorConfig(ReferenceConfig configBean) { @@ -147,7 +146,10 @@ private void configureConsumerConfig(ReferenceConfig referenceBean) { 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 @@ protected void populateBean(ReferenceConfig referenceConfig) { // 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 @@ protected void populateBean(ReferenceConfig referenceConfig) { 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 @@ protected void populateBean(ReferenceConfig referenceConfig) { // 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 @@ private MethodConfig createMethodConfig(Map methodAttributes, De 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 ReferenceCreator defaultInterfaceClass(Class interfaceClass) { 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 69911edc93f..c7b8bdd9de0 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,7 +16,6 @@ */ 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.springframework.beans.factory.config.BeanDefinition; @@ -75,5 +74,4 @@ protected boolean shouldGenerateIdAsFallback() { protected Class getBeanClass(Element element) { return ServiceAnnotationPostProcessor.class; } - } 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 9250b272439..dbdfc369ab3 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.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.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 DubboBeanDefinitionParser(Class beanClass) { } @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 @@ private static RootBeanDefinition parse(Element element, ParserContext parserCon } 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 @@ private static RootBeanDefinition parse(Element element, ParserContext parserCon 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 @@ private static RootBeanDefinition parse(Element element, ParserContext parserCon } 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 @@ private static RootBeanDefinition parse(Element element, ParserContext parserCon 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 @@ private static RootBeanDefinition parse(Element element, ParserContext parserCon // 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 @@ private static void parseMetrics(Element element, ParserContext parserContext, R 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 @@ private static void parseMetrics(Element element, ParserContext parserContext, R 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 @@ private static void assignProperties(Object obj, Element ele, ParserContext pars 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 @@ private static void assignProperties(Object obj, Element ele, ParserContext pars } } - 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 @@ private static void configReferenceBean(Element element, ParserContext parserCon // 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 @@ private static void configReferenceBean(Element element, ParserContext parserCon 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 @@ private static void getPropertyMap(Class beanClass, Map beanPr 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 @@ private static String getCompatibleDefaultValue(String property, String value) { } 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 @@ private static void parseNested(Element element, ParserContext parserContext, Cl 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 @@ private static void parseNested(Element element, ParserContext parserContext, Cl } } - 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 @@ private static void parseProperties(NodeList nodeList, RootBeanDefinition beanDe 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 @@ private static void parseProperties(NodeList nodeList, RootBeanDefinition beanDe } 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 @@ private static void parseProperties(NodeList nodeList, RootBeanDefinition beanDe } @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 @@ private static ManagedMap parseParameters(NodeList nodeList, RootBeanDefinition 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 @@ private static ManagedMap parseParameters(NodeList nodeList, RootBeanDefinition } @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 @@ private static void parseMethods(String id, NodeList nodeList, RootBeanDefinitio 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 @@ private static void parseMethods(String id, NodeList nodeList, RootBeanDefinitio addPropertyValue(methodBeanDefinition, "id", beanName); } - BeanDefinitionHolder methodBeanDefinitionHolder = new BeanDefinitionHolder( - methodBeanDefinition, beanName); + BeanDefinitionHolder methodBeanDefinitionHolder = + new BeanDefinitionHolder(methodBeanDefinition, beanName); methods.add(methodBeanDefinitionHolder); } } @@ -540,7 +588,8 @@ private static boolean hasPropertyValue(AbstractBeanDefinition beanDefinition, S 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 @@ private static void addPropertyValue(AbstractBeanDefinition beanDefinition, Stri } @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 @@ private static void parseArguments(String id, NodeList nodeList, RootBeanDefinit 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 BeanDefinition parse(Element element, ParserContext parserContext) { 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 2f2e44fbaca..0b46de0f3a2 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.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 @@ @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 Status check() { 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 Status check() { } 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 4ef77b1aa98..ca42b6ce40e 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.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 Status check() { } } } 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 dcef5825250..713a1918356 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.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 static Map getAttributes(Annotation annotation, PropertyR * @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 static Map getAttributes(Map annotationAt * @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) { - - Map annotationAttributes = org.springframework.core.annotation.AnnotationUtils.getAnnotationAttributes(annotation, classValuesAsString, nestedAnnotationsAsMap); + 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); String[] actualIgnoreAttributeNames = ignoreAttributeNames; @@ -225,8 +234,8 @@ public static T getRequiredAttribute(Map attributes, String * @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 static AnnotationAttributes getAnnotationAttributes(Annotation annotation * @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 static AnnotationAttributes getAnnotationAttributes(Annotation annotation * @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 static AnnotationAttributes getAnnotationAttributes(Annotation annotation * @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 static AnnotationAttributes getAnnotationAttributes(AnnotatedElement anno * @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 static AnnotationAttributes getAnnotationAttributes(AnnotatedElement anno * @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 static AnnotationAttributes getAnnotationAttributes(AnnotatedElement anno * 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 static Annotation tryGetMergedAnnotation(AnnotatedElement annotatedElemen * @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 6a3ffb62c30..08a46a67f44 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.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.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 @@ */ public class DubboAnnotationUtils { - @Deprecated public static String resolveInterfaceName(Service service, Class defaultInterfaceClass) throws IllegalStateException { @@ -56,13 +55,11 @@ public static String resolveInterfaceName(Service service, Class defaultInter } 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 static String resolveInterfaceName(Map attributes, Class< // 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 static String resolveInterfaceName(Map attributes, Class< 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 static String resolveInterfaceName(Map attributes, Class< } } - 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 static String resolveInterfaceName(Reference reference, Class defaultI } 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 static Map convertParameters(String[] parameters) { } 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; - } - - 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); + .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); 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 ae6854142cf..ca935378c39 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 @@ -29,6 +29,9 @@ 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; @@ -42,9 +45,6 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -import java.util.HashMap; -import java.util.Map; - /** * Dubbo Bean utilities class * @@ -69,27 +69,32 @@ static void registerCommonBeans(BeanDefinitionRegistry registry) { registerInfrastructureBean(registry, ReferenceBeanManager.BEAN_NAME, ReferenceBeanManager.class); // Since 2.5.7 Register @Reference Annotation Bean Processor as an infrastructure Bean - registerInfrastructureBean(registry, ReferenceAnnotationBeanPostProcessor.BEAN_NAME, - ReferenceAnnotationBeanPostProcessor.class); + registerInfrastructureBean( + registry, ReferenceAnnotationBeanPostProcessor.BEAN_NAME, ReferenceAnnotationBeanPostProcessor.class); // 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, DubboInfraBeanRegisterPostProcessor.class); + registerInfrastructureBean( + registry, DubboInfraBeanRegisterPostProcessor.BEAN_NAME, DubboInfraBeanRegisterPostProcessor.class); } /** @@ -100,9 +105,8 @@ static void registerCommonBeans(BeanDefinitionRegistry registry) { * @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; @@ -113,8 +117,8 @@ static boolean registerInfrastructureBean(BeanDefinitionRegistry beanDefinitionR 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."); } } @@ -131,25 +135,34 @@ static boolean registerInfrastructureBean(BeanDefinitionRegistry beanDefinitionR * @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()); @@ -165,8 +178,8 @@ static boolean checkBeanExists(ConfigurableListableBeanFactory beanFactory, Clas 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; @@ -175,8 +188,10 @@ static ReferenceAnnotationBeanPostProcessor getReferenceAnnotationBeanPostProces 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) { @@ -202,5 +217,4 @@ static ModuleModel getModuleModel(BeanFactory beanFactory) { } 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 c6bbde0c7c3..38f9b7d6467 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.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 @@ private static Map doExtraProperties(ConfigurableEnvironment env 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 @@ private static Map> doGetPropertySources(ConfigurableE 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 static SortedMap filterDubboProperties(ConfigurableEnviro 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 c7678f8a96d..8defa856571 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 @@ protected T doPostProcessBeforeInitialization(T bean, String beanName) throws Be processBeforeInitialization(bean, beanName); return bean; - } /** @@ -95,7 +94,6 @@ protected T doPostProcessAfterInitialization(T bean, String beanName) throws Bea processAfterInitialization(bean, beanName); return bean; - } /** @@ -107,8 +105,7 @@ protected T doPostProcessAfterInitialization(T bean, String beanName) throws Bea * @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 @@ protected void processBeforeInitialization(T bean, String beanName) throws Beans * @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 043c86a6120..1b3ec0e0b63 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 Object invoke(Object proxy, Method method, Object[] args) throws Throwabl } } } - 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 7b469c5c55a..b11b80b4a69 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 e2f8145711c..15e164b5eee 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.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 static Map getSubProperties(Iterable> p } return getSubProperties(mutablePropertySources, prefix); - } /** @@ -101,7 +100,8 @@ public static Map getSubProperties(PropertySources propertySourc * @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 static Map getSubProperties(PropertySources propertySourc * @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 a6a4d93faa7..26bb02e5650 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,6 +16,10 @@ */ package org.apache.dubbo.config.spring.util; +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; @@ -25,10 +29,6 @@ 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 */ @@ -51,7 +51,7 @@ public static T getPropertyValue(PropertyValues pvs, String propertyName) { 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 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 4a7e85410ea..52fbbb2c2a1 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 @@ private void addListener(final String service, final NotifyListener listener) { 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 @@ private void doNotify(String service, List urls) { 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 @@ protected final void forbid(String service) { } 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 List getNotified(String service) { 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 8eadd486740..cb2211d7b90 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.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.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.assertTrue; import static org.junit.jupiter.api.Assertions.fail; - /** * ConfigTest */ @@ -95,14 +94,15 @@ public void tearDown() { 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 @@ public void testServiceAnnotation() { 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 @@ void testMultiProtocol() { @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 @@ public void testMultiProtocolDefault() { @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 @@ public void testMultiProtocolError() { 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 @@ public void testMultiRegistry() { 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 @@ public void testDelayFixedTime() throws Exception { } 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 @@ public void testDelayFixedTime() throws Exception { 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 @@ void testRmiTimeout() throws Exception { @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 @@ void testAppendFilter() throws Exception { 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 @@ void testAppendFilter() throws Exception { @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 @@ void testInitReference() throws Exception { 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 @@ void testInitReference() throws Exception { 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 @@ void testInitReference() throws Exception { 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 @@ void testInitReference() throws Exception { @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 @@ void test_noMethodInterface_methodsKeyHasValue() throws Exception { @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 @@ void test_RpcContext_getUrls() throws Exception { @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 @@ public void test_retrySettingFail() throws Exception { @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 @@ public void test_returnSerializationFail() throws Exception { @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 @@ public void testApiOverrideProperties() throws Exception { 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 @@ void testSystemPropertyOverrideProtocol() throws Exception { 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 @@ void testSystemPropertyOverrideProtocol() throws Exception { 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 @@ public void testSystemPropertyOverrideXmlDefault() throws Exception { 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 @@ public void testSystemPropertyOverrideXml() throws Exception { 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 @@ void testSystemPropertyOverrideReferenceConfig() throws Exception { // 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 @@ public void testSystemPropertyOverrideApiDefault() throws Exception { 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 @@ public void testAnnotation() { 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 @@ void testDubboProtocolPortOverride() throws Exception { service.setRegistry(registry); service.setProtocol(protocol); - DubboBootstrap.getInstance() .application(application) .registry(registry) @@ -1075,14 +1107,15 @@ public void testProtocolRandomPort() throws Exception { 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 @@ public void testReferGenericExport() throws Exception { 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 @@ void testGenericServiceConfig() throws Exception { 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 @@ void testGenericServiceConfigThroughSpring() throws Exception { 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 6f059143a83..2d2de09b8da 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.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 @@ void testServiceConfig() { 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 b2c33071a68..cb93ece362e 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 @@ 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 769271248a0..25f6f9523f1 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.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.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 @@ void testBean() { 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 @@ void testBean() { 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 @@ static class ConsumerConfiguration { public ReferenceBean demoService() { return new ReferenceBean<>(); } - } @Configuration @@ -178,4 +177,4 @@ public DemoService demoServiceImpl() { 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 804575eac40..3a7755847c5 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 @@ void testGetService() { 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 ab82523300c..4c1a04fb8f6 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 @@ */ 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 static Exporter export(int port) { } 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 static Exporter export(int port, RegistryService registr .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 a8e8d745756..5d0f720fb58 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 @@ */ 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 void subscribe(String service, URL url, NotifyListener listener) { 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 void subscribe(String service, URL url, NotifyListener listener) { } 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 void disconnect() { 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 List getRegistries() { 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 57ec18ab12e..cb4b4d88e1b 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 static void clear() { } 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 1163b860ed8..95022f3150e 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 1e3d762d4ff..e856cbc296a 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 DemoService getDemoService() { 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 a8f3faeec19..2933d92d8ac 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 580edda1d8e..f1c044789ba 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 @@ @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 9d3407782dc..c86649684e9 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 cfe124362cf..a46f062fb4e 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 c5b5ba20c11..17893c7f666 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 String sayName(String name) { 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 ed168fc37a7..9fc3119aa45 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 @@ 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 84fd9397160..a0314e6f58b 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 3cc54160967..d6e9fbcf64e 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 b8c610df354..2d5c74094cd 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 @@ public ApplicationConfig applicationConfig() { 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 3a4f4886b62..15d9999b643 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.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 @@ void testMergedService() { } @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 @@ private static class TestBean2 { @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 01b70a8dc40..907141f2c34 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 @@ @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 @@ public static void afterAll() { @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 @@ void testMethodAnnotationCallBack() { 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 @@ static class MethodCallbackConfiguration { 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 a5bf17bb7c0..eb20030d430 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 @@ 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 @@ void test() { */ 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 a4fbcff02d2..851ebf9a8b4 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.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.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 @@ @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 @@ public static class TestAspect { @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 @@ public Object aroundHelloService(ProceedingJoinPoint pjp) throws Throwable { 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 @@ void testAop() throws Exception { 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 @@ void testAop() throws Exception { 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 @@ void testGetInjectedFieldReferenceBeanMap() { 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 @@ void testGetInjectedMethodReferenceBeanMap() { @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 @@ void testReferenceBeansMethodAnnotation() { 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 @@ public void setDemoServiceFromAncestor(DemoService demoServiceFromAncestor) { public ApplicationContext getApplicationContext() { return applicationContext; } - } private static class ParentBean extends AncestorBean { @@ -330,7 +349,6 @@ private static class ParentBean extends AncestorBean { public DemoService getDemoServiceFromParent() { return demoServiceFromParent; } - } static class TestBean extends ParentBean { @@ -365,6 +383,5 @@ static class MyConfiguration { 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 60533b195d3..cf0e5c73756 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.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.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 @@ void testBuild() throws Exception { // 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 @@ void testBuild() throws Exception { Assertions.assertNotNull(referenceBean.getMonitor()); } - @Configuration public static class ConsumerConfiguration { @@ -241,7 +264,5 @@ public MonitorConfig monitorConfig() { 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 52980c7f658..9c51b1f74ab 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.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.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 @@ @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 @@ void test() { beanFactory.getBeansOfType(ServiceAnnotationPostProcessor.class); Assertions.assertEquals(2, beanPostProcessorsMap.size()); - } @Test @@ -95,15 +95,12 @@ void testMethodAnnotation() { 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 59f1385a130..358bda2dc65 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 RegistryConfig registryConfig() { * * @return {@link ProtocolConfig} Bean */ - @Bean//("dubbo") + @Bean // ("dubbo") public ProtocolConfig protocolConfig() { ProtocolConfig protocolConfig = new ProtocolConfig(); protocolConfig.setName("dubbo"); @@ -95,15 +94,10 @@ public TransactionStatus getTransaction(TransactionDefinition definition) throws } @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 7f9cf28bb05..43093c43a8a 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 @@ * @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 @@ public void prepare() { 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 @@ void testServiceNameBuild() { 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 cdd05ff839c..ddb3af0d7d9 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.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 @@ void test() { 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 b9caff8a848..d78568bd9c5 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 @@ 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.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 @@ void test() { } } } - 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 225bcd1463c..5fb91df0290 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.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 PropertySource createPropertySource(String name, EncodedResource resou @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 a0f6b9eaced..a951db0a114 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 @@ * @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 @@ void testProperty() { 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 468d1e0fd57..ca357c592fb 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 @@ 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.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 @@ void testConsumer() { 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 @@ public String sayHello(String name) { }; } } -} \ 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 04adaba2dc6..bea403d9c9e 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.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.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 @@ void testConsumer() { Assertions.assertNull(helloServiceMap.get("myHelloService")); } - @Order(Integer.MAX_VALUE-2) + @Order(Integer.MAX_VALUE - 2) @Configuration public static class AnnotationBeanConfiguration { @@ -89,20 +82,17 @@ public static class AnnotationBeanConfiguration { 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 d3fa5204e77..2738b55748e 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.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.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 @@ void testConsumer() { Assertions.assertNull(helloServiceMap.get("myHelloService")); } - @Order(Integer.MAX_VALUE-2) + @Order(Integer.MAX_VALUE - 2) @Configuration public static class RawReferenceBeanConfiguration { @@ -91,20 +84,17 @@ public ReferenceBean helloService() { .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 3e01fe07221..4ebe99915ba 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.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.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 void testConsumer() { 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 HelloService helloServiceImpl() { } // 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 cffb7e40c5f..cf42633507f 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.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.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 @@ void testConfigProps() { 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 @@ void testConfigProps() { 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 482cd054cd0..a8022071e67 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.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.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 @@ void testConfigProps() { 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 @@ void testConfigProps() { 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 d116d82f45a..6436cce82fd 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.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 @@ void testConsumer() { 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 789cfaa5a13..097684f955d 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 4e5f5bec5e8..8ad0b82895d 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.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.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 @@ void testProvider() { 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 @@ public void setApplicationContext(ApplicationContext applicationContext) throws 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 f09fa550821..4d1fe654b86 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 @@ 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 @@ void test(){ 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 @@ void test(){ 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 @@ void test(){ // 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 @@ void test(){ } } } -} \ 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 e165f933db6..5f5d4ac3aae 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 @@ public void setUp() { } @AfterEach - public void tearDown() { - } + public void tearDown() {} @Test void test() { @@ -71,7 +70,6 @@ void test() { // Test @Transactional is present or not Assertions.assertNotNull(findAnnotation(beanClass, Transactional.class)); - // consumer app AnnotationConfigApplicationContext consumerContext = new AnnotationConfigApplicationContext(); @@ -121,9 +119,5 @@ void test() { 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 f4b705315e0..69acec2129a 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.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.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.core.io.support.ResourcePropertySource; -import java.io.IOException; - /** * {@link DubboConfigConfiguration} Test * @@ -47,7 +47,6 @@ public void before() throws IOException { context = new AnnotationConfigApplicationContext(); ResourcePropertySource propertySource = new ResourcePropertySource("META-INF/config.properties"); context.getEnvironment().getPropertySources().addFirst(propertySource); - } @AfterEach @@ -90,5 +89,4 @@ void testMultiple() { 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 803241d5355..ba5392a02d5 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.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 @@ public void tearDown() { DubboBootstrap.reset(); } - //@Test + // @Test public void testSingle() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); @@ -88,7 +87,6 @@ public void testSingle() { 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 @@ public void testSingle() { assertFalse(hasAlias(context, "org.apache.dubbo.config.MonitorConfig#0", "zookeeper")); } - //@Test + // @Test public void testMultiple() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); @@ -119,22 +117,17 @@ public void testMultiple() { 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 6230db4822e..b171a6cf0cd 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 @@ void testProvider() { // Test @Transactional is present or not Assertions.assertNotNull(findAnnotation(beanClass, Transactional.class)); - } @Test @@ -119,13 +118,13 @@ void testConsumer() { // 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 @@ void testConsumer() { // Test multiple binding Assertions.assertEquals("N/A", registryConfig.getAddress()); - } @EnableDubbo(scanBasePackages = "org.apache.dubbo.config.spring.context.annotation.provider") @@ -163,17 +161,11 @@ public TransactionStatus getTransaction(TransactionDefinition definition) throws } @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 9fd7b2e1b77..5f3aabb3f9c 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.PropertySource; @Configuration("consumerConfiguration") -@DubboComponentScan( - basePackageClasses = ConsumerConfiguration.class -) +@DubboComponentScan(basePackageClasses = ConsumerConfiguration.class) @PropertySource("META-INF/default.properties") public class ConsumerConfiguration { @@ -80,13 +78,12 @@ public void setDemoService(DemoService demoService) { 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 void setDemoServiceFromAncestor(DemoService demoServiceFromAncestor) { } } - public static abstract class Parent extends Ancestor { + public abstract static class Parent extends Ancestor { private DemoService demoServiceFromParent; @@ -112,7 +109,6 @@ public DemoService getDemoServiceFromParent() { public void setDemoServiceFromParent(DemoService demoServiceFromParent) { this.demoServiceFromParent = demoServiceFromParent; } - } public static class Child extends Parent { @@ -123,7 +119,6 @@ public static class Child extends Parent { @Reference(version = "2.5.7", url = remoteURL) private DemoService demoServiceFromChild; - public DemoService getDemoService() { return demoService; } @@ -136,5 +131,4 @@ public void setDemoServiceFromChild(DemoService demoServiceFromChild) { 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 57b8669fe4a..ca09eedda07 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 void setDemoService(DemoService demoService) { 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 c4df6f43408..8b50e8780be 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 8ee2a8a09f6..62f7e24b747 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.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; - /** * {@link DemoService} Service implementation * @@ -34,8 +33,7 @@ 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 1841abb0755..80cc2cd9fd1 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 @@ 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 59e0cb3d772..d4e103aad7f 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.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.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 @@ protected void doRollback(DefaultTransactionStatus status) throws TransactionExc } }; } - } - 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 4662a62acc1..b2810064fa1 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 @@ void testReloadSpringContext() { 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 @@ void testReloadSpringContext() { 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 @@ void testReloadSpringContext() { 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 73240d56f91..f0ec93a8ded 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 @@ void testBinder() { 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 c27f07595c5..463727c70f9 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 @@ public void init() { } @AfterEach - public void destroy() { - } + public void destroy() {} @Test void testSpringInjector() { @@ -55,8 +54,9 @@ void testSpringInjector() { 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 @@ void testSpringInjector() { 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 @@ public HelloService helloService() { 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 9006995903d..c43c9bd1b89 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 @@ /** * 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 d8f6f9cd754..470e50db888 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 @@ /** * 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 e41d734c609..daedbb3990c 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 void setProtocol(Protocol protocol) { 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 04133146302..12e7c385ced 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 String getPrefix() { 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 f97d3b307ab..5b979abbd66 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 String getPrefix() { 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 a8fe9bc23ad..6edac1b8791 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 @@ 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 @@ private void checkTranscation() { 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 14df2a0dff2..e681335a77c 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 String sayName(String name) { 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 ec728db29a6..c9cbcdd9bac 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.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 static void afterAll() throws Exception { 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 void test() throws Exception { 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 @@ private void rpcInvoke(DubboBootstrap consumerBootstrap) { 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 eb6c121c8f4..80afe78b5f5 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.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 @@ private void rpcInvoke(DemoService demoServiceV1, HelloService helloServiceV2, H 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 3a994e937a5..eda4503d08f 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.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 void test() throws Exception { // 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 9c40bb19539..a63144fbf2a 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 @@ 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 a70b7884e6f..09da5a46dca 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 @@ 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 e807ffeab21..b1585801038 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 @@ 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 cd8131f7177..7f65b50fbcb 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 @@ 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 6c3c4c2dad1..44a6619318c 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 @@ 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 61812f868cc..acd6eed5fef 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 @@ 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 1d23403c775..a9e6769e625 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 @@ 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 a99bf247541..0bb66f96e55 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 @@ 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 099b51db02d..6ad5560f34e 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 @@ 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 1ba6eca5c46..27b7e7bd5b4 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 @@ 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 61d5ed3fb38..08297c0a3ee 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 @@ 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 @@ private void setServiceConfig(ClassPathXmlApplicationContext providerContext) { 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 b71662cd3bd..92b3baeebbd 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 @@ void test() { 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 @@ void test() { 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 b3c996b36a3..d4fcf9e0edd 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 @@ void test() { 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 84f7cb494ce..4872370a777 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.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.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 @@ void test() { 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 @@ void test() { } } - @Component static class ClassA { @DubboReference(group = "demo", version = "1.2.3", check = false) private HelloService helloService; - } @Component @@ -88,6 +89,5 @@ static class ClassB { @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 716ba61a81e..4e1249296bb 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 @@ void test() { 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 @@ void test() { } } - @EnableDubbo(scanBasePackages = "") @PropertySource("classpath:/META-INF/issues/issue9172/consumer.properties") static class ConsumerConfiguration { @@ -84,7 +87,6 @@ static class ConsumerConfiguration { @DubboReference(consumer = "consumer-two") private DemoService demoServiceTwo; - } @EnableDubbo(scanBasePackages = "") @@ -103,4 +105,4 @@ public DemoService demoServiceTwo() { 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 7d086cd199c..3f3777cec2f 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.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.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 @@ void testConfigCenterBeanFromProps() throws IOException { 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 @@ void testConfigCenterBeanFromProps() throws IOException { applicationContext.close(); } } - } @EnableDubbo(scanBasePackages = "") @@ -93,17 +95,18 @@ public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) 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 3f667bd65ea..8f7fc61e7f8 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.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 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 void testMetrics() { 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 77e757c84db..bab9652a35d 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.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.ImportResource; import org.springframework.context.support.ClassPathXmlApplicationContext; -import java.net.InetSocketAddress; - class PropertyConfigurerTest { @BeforeAll @@ -48,25 +48,29 @@ public static void afterAll() { @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 @@ public DemoBeanFactoryPostProcessor bizBeanFactoryPostProcessor(HelloService ser 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 4dcb6b29b96..dee638e1453 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.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.ImportResource; import org.springframework.context.support.ClassPathXmlApplicationContext; -import java.net.InetSocketAddress; - class PropertySourcesConfigurerTest { @BeforeAll @@ -49,19 +49,24 @@ public static void afterAll() { @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 @@ public DemoBeanFactoryPostProcessor bizBeanFactoryPostProcessor(HelloService ser 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 b8128b3044c..f7556f57f20 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.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.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 @@ void testImportPropertySource() { 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 @@ void testImportPropertySource() { 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 @@ void testCustomPropertySourceBean() { 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 @@ void testCustomPropertySourceBean() { 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 @@ public DemoBeanFactoryPostProcessor bizBeanFactoryPostProcessor(HelloService ser @Configuration @PropertySource("classpath:" + PACKAGE_PATH + "/app.properties") - static class ImportPropertyConfiguration { - - } + static class ImportPropertyConfiguration {} @Configuration static class PropertyBeanConfiguration { @@ -149,4 +155,4 @@ protected String convertProperty(String propertyName, String propertyValue) { 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 ef58855ceb9..c1b6809245c 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 9afc815496b..97d1df45c1f 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.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.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 @@ public static void afterAll() { DubboBootstrap.reset(); } - @Autowired private FooService fooService; @@ -97,17 +92,19 @@ void test() { // 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 @@ static class FooService { @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 69fe8211b2e..f2a0537b1c3 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.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.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 @@ void testReferenceKey() throws Exception { 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 @@ void testReferenceKey() throws Exception { 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 @@ void testConfig4() { @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 @@ void testConfig5() { @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 @@ void testConfig6() { } @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 @@ private String getStackTrace(Throwable ex) { 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 @@ static class ReferenceConfiguration { @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 @@ static class ConsumerConfiguration3 { } @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 @@ public 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 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 @@ public HelloService 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 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 @@ static class ConsumerConfiguration7 { @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 2d020d8c8b1..9e472f5a5ab 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.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.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 @@ public void tearDown() { @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 @@ void testAnnotationAtField() { 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 @@ public void testAnnotationAtField2() { 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 @@ void testLazyProxy1() { 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 @@ void testLazyProxy2() { 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 @@ private String getStackTrace(Throwable ex) { @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 @@ void testAnnotationBean() { @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 @@ void testGenericServiceAnnotationBean() { 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 @@ void testReferenceBean() { @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 @@ void testGenericServiceReferenceBean() { 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 @@ void testGenericServiceReferenceBean() { 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 @@ void testRawReferenceBean() { context.close(); } } - } @Test @@ -299,7 +304,9 @@ void testInconsistentBean() { 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 @@ void testInconsistentBean() { 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 @@ void testMissingGenericTypeBean() { 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 @@ public GenericService localMissClassGenericServiceImpl() { } } - @Configuration public static class LazyProxyConfiguration1 { @@ -415,7 +423,6 @@ public static class AnnotationAtFieldConfiguration { @DubboReference(group = "${myapp.group}") private HelloService helloService; - } @Configuration @@ -423,7 +430,6 @@ public static class AnnotationAtFieldConfiguration2 { @DubboReference(group = "${myapp.group}", timeout = 2000) private HelloService helloService; - } @Configuration @@ -434,7 +440,6 @@ public static class AnnotationBeanConfiguration { public ReferenceBean helloService() { return new ReferenceBean(); } - } @Configuration @@ -447,7 +452,10 @@ public ReferenceBean genericHelloService() { } @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 @@ public static class ReferenceBeanConfiguration { @Bean public ReferenceBean helloService() { - return new ReferenceBeanBuilder() - .setGroup("${myapp.group}") - .build(); + return new ReferenceBeanBuilder().setGroup("${myapp.group}").build(); } @Bean @@ -475,9 +481,9 @@ public static class GenericServiceReferenceBeanConfiguration { @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 @@ public static class ReferenceBeanWithoutGenericTypeConfiguration { @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 @@ public ReferenceBean helloService() { 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 235e432ef6d..5af4ada5eab 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 @@ 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.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 @@ public static void afterAll() { private HelloService helloService; @Autowired - //@Qualifier("localHelloService") + // @Qualifier("localHelloService") private HelloService localHelloService; @Test @@ -61,11 +64,11 @@ void testLocalCall() { // 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 4b76ad623c3..fc845ba80c3 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.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.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 void testLocalCall() { // 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 08fad7451cd..e46581f728f 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 9c3edd00fe6..9c4bd6ae45f 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.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.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 @@ void testLocalCall() { // 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 @@ public static class LocalCallConfiguration { 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 f579e000760..f253ab00a53 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.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.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 @@ void testLocalCall() { // 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 @@ public static class LocalCallConfiguration { @DubboReference(group = "${biz.group}", version = "${biz.version}") private HelloService helloService3; - } @Configuration @@ -105,7 +111,6 @@ public static class LocalCallConfiguration2 { @DubboReference(group = "${biz.group}", version = "2.0.0") private HelloService demoHelloService; - } @Configuration @@ -113,14 +118,14 @@ public static class LocalCallConfiguration3 { @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 @@ public String sayHello(String name) { 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 e05ef64b991..90c08561f0a 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.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.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 @@ void testLocalCall() { // 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 @@ public static class LocalCallConfiguration { 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 af17e997cc4..b3a78647673 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 b45a649901e..ef7b1005fe0 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 @@ 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 @@ void testProvider() { @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 bf6a7865f42..d587f00d562 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 boolean isAvailable() { } @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 3e4608768b2..416c4e4f084 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 MockServiceDiscovery(String serviceName, URL registryURL) { } @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 9fefd1c27ed..23273aa6078 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.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 3d096030603..58c3fcda1c8 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 @@ 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 52d1bf8cd2d..e81b357a381 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 @@ 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 ac5300d2a20..05ef4e68e9d 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 405e58906ac..aa5213e8313 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.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 f685f3d2688..5a1eea55aec 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 @@ 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 58714a50e82..f4d424d998c 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 @@ void testIsConcrete() { name.setGroup(null); name.setVersion(null); assertTrue(name.isConcrete()); - } @Test @@ -122,4 +121,4 @@ void testIsCompatible() { 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 33efb6f9e49..cbc1accd2df 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.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.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 @@ public void tearDown() { @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 @@ void testProviderXmlOnConfigurationClass() { @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 @@ private void testProviderXml(ApplicationContext context) { 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 @@ void testMultiProtocol() { @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 @@ void testDefaultProtocol() { @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 @@ void testCustomParameter() { 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 @@ void testDelayFixedTime() { @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 @@ void testTimeoutConfig() { 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 @@ void testModuleInfo() { @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 @@ void testProperty() { @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 @@ void testMetricsAggregation() { 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 4103f9c569f..25e932fb092 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 @@ void testGeneric() { 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 8fbb4508170..6d74fab5414 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 @@ public static void afterAll() { 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 b17e04a7f23..7edf41135d4 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 @@ 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.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 @@ void testWithoutApplicationContext() { @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 @@ void testWithDatasourceHasNextResult() throws SQLException { 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 @@ void testWithDatasourceNotHasNextResult() throws SQLException { 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 da3fe0061ba..4678e41fb8f 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 @@ 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 @@ void testWithoutApplicationContext() { @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 @@ void testGenericWebApplicationContext() { 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 96f995bba3a..6782a4f5ae0 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.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 @@ void testExtraProperties() { } finally { System.clearProperty(key); } - } @Test @@ -83,6 +82,5 @@ void testFilterDubboProperties() { 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/pom.xml b/dubbo-config/pom.xml index dcbb5355ebb..c9ccf7b371d 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 - - - dubbo-config-api - dubbo-config-spring - + + 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 - - + + + org.apache.dubbo + dubbo-test-check + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-test-common + ${project.parent.version} + test + + diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml b/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml index fb39e096c2d..d561592e9c6 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 75b6973f1fa..b9506d3fe34 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.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 @@ * 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 void close() { 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 @@ private String getAddressWithProtocolPrefix(URL url) { 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 String getProperties(String key, String group, long timeout) throws Illeg 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 ApolloListener implements ConfigChangeListener { 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 @@ boolean hasInternalListener() { 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 64331d886b0..64c93f65c4c 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 @@ 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 07aa131e671..3558272881a 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 @@ 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.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 @@ void testAddListener() throws Exception { 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 @@ private static void putData(String key, String value) { } 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 @@ private static void putMockData(String key, String value, String fileName) { * 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 1bb7f5527a7..e234150ff61 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.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 @@ private String loadConfigFor(String namespace) { } 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-nacos/pom.xml b/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml index 730c695b318..e3cce7faf9d 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 1c1e2afda43..74c530e2b07 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.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.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 @@ private NacosConfigServiceWrapper buildConfigService(URL url) { 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 @@ private NacosConfigServiceWrapper buildConfigService(URL url) { } 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 @@ private Properties buildNacosProperties(URL url) { } 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 void close() throws Exception { @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 Executor getExecutor() { @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 void innerReceive(String dataId, String group, String configInfo) { } 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 5d2196726dc..762b0161b37 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 @@ 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 bba7741e645..399401865a2 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 String getConfig(String dataId, String group, long timeoutMs) throws Naco } @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 boolean publishConfigCas(String dataId, String group, String content, Str } @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 boolean removeConfig(String dataId, String group) throws NacosException { } @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 String getServerStatus() { } @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 831c74c833e..58fc5707405 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 @@ void testGetConfig() throws Exception { 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 @@ void testAddListener() throws Exception { 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 @@ void testAddListener() throws Exception { 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 @@ private void put(String key, String group, String value) { 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 @@ void testPublishConfig() { } @AfterAll - public static void tearDown() { - - } + public static void tearDown() {} private class TestListener implements ConfigurationListener { private CountDownLatch latch; @@ -183,5 +183,4 @@ public String getValue() { 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 32116ba247e..a2ba32785cb 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 org.apache.dubbo.common.URL; +import org.apache.dubbo.rpc.model.ApplicationModel; + import java.util.Properties; import java.util.concurrent.atomic.AtomicInteger; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.rpc.model.ApplicationModel; +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 com.alibaba.nacos.api.NacosFactory; -import com.alibaba.nacos.api.config.ConfigService; -import com.alibaba.nacos.api.exception.NacosException; - 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 @@ public String getServerStatus() { 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 @@ public String getServerStatus() { 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 @@ public String getServerStatus() { 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 c0689824df8..c1deb8c3e5b 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} + + + + + + curator5 + + [17,) + + - 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.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 df596926b77..ba3fc4a0b2d 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 void clear() { 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 df22f5de0f8..5ec5a3cd574 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 void dataChanged(String path, Object value, EventType eventType) { 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 e0bc325c4c8..f29671f0c64 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.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.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 @@ protected void doAddListener(String pathKey, ConfigurationListener listener, Str 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 99e7674ba14..dddd710d4b0 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.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.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 @@ public static void setUp() throws Exception { 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 @@ private static void setData(String path, String data) throws Exception { 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 @@ void testAddListener() throws Exception { 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 @@ void testPublishConfigCas() { 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); -// } - -} \ No newline at end of file + // + // @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); + // } + +} diff --git a/dubbo-configcenter/pom.xml b/dubbo-configcenter/pom.xml index b27bae411f7..bbba673be37 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-zookeeper + dubbo-configcenter-apollo + dubbo-configcenter-nacos + + + 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 00e2fc3e455..709aa14dd45 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 66b76b496ee..00e3daee7d2 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 da558f5f72a..c9eca15c10e 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.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 void run() { 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 void run() { 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 880f041e326..9060de5408a 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-api - test - - - log4j - log4j - 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-api + test + + + log4j + log4j + 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 94e094e6a4b..0adb7986584 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 void stop() { 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 9673770c845..b1ea0747c95 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 ec2cab09c43..a104376e7f6 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 217f3edbc25..d8e0fe734dd 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 718921c0991..8f6d2e9c7dc 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 static void main(String[] args) { @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 fbfcd9ebd9e..93d1eca356e 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 @@ 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 120bb535060..cde2ee0d587 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,106 +17,105 @@ ~ 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 - 1.7.33 - + + true + 1.7.33 + - - - 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.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - ${slf4j-log4j12.version} - - - log4j - log4j - - + + + 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.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + ${slf4j-log4j12.version} + + + log4j + log4j + + 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 3062d247273..56fe623cc90 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 @@ 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 8983ed287b4..8b4f9446500 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.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 54f08b5b408..891cfabbf86 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 28b830c4922..41b30699d54 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,88 +17,87 @@ ~ 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-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-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 e655d4a637d..07cbefed293 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 @@ private static void runWithBootstrap() { 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 @@ private static void runWithBootstrap() { // 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 be8bacd43d0..6fb83b1dcff 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,90 +17,88 @@ ~ 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 + 1.7.33 + - - true - 1.7.33 - + + + 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 b80bfbfd3b1..d6f70a57a1a 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 @@ private static void startWithBootstrap() { 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 ae1faf86ab8..e7760f53a73 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 @@ 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 de47d5770f8..c469ffdef5b 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 4891a1e5779..53925c9f369 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 7aceba49a07..9b8a2210cb4 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 static void main(String[] args) { runWithBootstrap(args); } - private static void runWithBootstrap(String[] args) { ReferenceConfig reference = new ReferenceConfig<>(); reference.setInterface("org.apache.dubbo.demo.DemoService"); @@ -52,18 +51,19 @@ private static void runWithBootstrap(String[] args) { 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 @@ private static void runWithBootstrap(String[] args) { } } } - } diff --git a/dubbo-demo/dubbo-demo-interface/pom.xml b/dubbo-demo/dubbo-demo-interface/pom.xml index 802bea76a31..1f2776d88c5 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 - - true - + 4.0.0 + + org.apache.dubbo + dubbo-demo + ${revision} + ../pom.xml + + dubbo-demo-interface + jar + ${project.artifactId} + The demo module of dubbo project + + 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 09bdafa1f6b..26f1ac524aa 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 8caa8ccebcf..f12536bfd10 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 09a202ab585..b77cded2f57 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 0ef70bf2932..478b3e6dc20 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 313159be0a6..277693d9155 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 ebbc1b10f3e..db1a815d46d 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.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 e1df730e204..4e925b386d8 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 368489f1cf6..9b61aa54521 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.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 @@ * * 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 d5da64403ed..ef726b5e2d3 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.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 4cd1df96d8b..29a139f08ab 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 TestPO(String name, String address, int age) { this.age = age; } - public TestPO() { - } + public TestPO() {} public String getName() { return name; @@ -60,10 +59,6 @@ public static TestPO getInstance() { @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 2c58d9d3f20..d5a6326c900 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 @@ 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 int hashCode() { @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 b0480058fd3..5f7b2e594b3 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 - - dubbo-demo-native-consumer - - - true - 5.1.0 - 3.8.3 - - - - + + + 4.0.0 + + org.apache.dubbo + dubbo-demo-native + ${revision} + ../pom.xml + + + dubbo-demo-native-consumer + + + 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-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} + + + + log4j + log4j + 1.2.17 + compile + + + * + * + + + + + org.slf4j + slf4j-api + 1.7.36 + compile + + + org.slf4j + slf4j-log4j12 + 1.7.33 + compile + + + * + * + + + + + + + + native + + native + + + + org.apache.dubbo - dubbo-demo-native-interface + dubbo-maven-plugin ${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} - - - - log4j - log4j - 1.2.17 - compile - - - * - * - - - - - org.slf4j - slf4j-api - 1.7.36 - compile - - - org.slf4j - slf4j-log4j12 - 1.7.33 - compile - - - * - * - - - - - - - - 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.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 + + + + + + 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 f430cfd7b97..77d77635f2b 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 @@ private static void runWithBootstrap() { 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 f7476d2cb9f..2184cc8e123 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 06097a6c1f7..8e338c4bacb 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 @@ 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 e75659d564d..c68dcba0473 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 - - dubbo-demo-native-provider - - - 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-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} - - + + + 4.0.0 + + org.apache.dubbo + dubbo-demo-native + ${revision} + ../pom.xml + + + dubbo-demo-native-provider + + + 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-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} + + + + log4j + log4j + 1.2.17 + compile + + + * + * + + + + + org.slf4j + slf4j-api + 1.7.36 + compile + + + org.slf4j + slf4j-log4j12 + 1.7.33 + compile + + + * + * + + + + + + + + native + + native + + + + + org.apache.dubbo - dubbo-serialization-fastjson2 + dubbo-maven-plugin ${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} - - - - log4j - log4j - 1.2.17 - compile - - - * - * - - - - - org.slf4j - slf4j-api - 1.7.36 - compile - - - org.slf4j - slf4j-log4j12 - 1.7.33 - compile - - - * - * - - - - - - - - - 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.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 f324635955e..bfe638da2fe 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 @@ private static void startWithBootstrap() { 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 38c9d1b45f7..a360f6a5d91 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 0601a5dac1f..4cf4a6654e8 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 8a4c9ee64e6..996190443ad 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 - - dubbo-demo-spring-boot-consumer - - - 8 - 8 - 1.7.33 - 2.7.17 - true - - - - - org.apache.dubbo - dubbo-demo-spring-boot-interface - ${project.parent.version} - - - - org.apache.dubbo - dubbo-spring-boot-starter - ${project.version} - - - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.version} - - - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.version} - - - - org.apache.dubbo - dubbo-metadata-report-zookeeper - ${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.springframework.boot - spring-boot-starter - ${spring-boot.version} - - - - org.springframework.boot - spring-boot-autoconfigure - ${spring-boot.version} - - - - org.springframework.boot - spring-boot-starter-logging - ${spring-boot.version} - - - - org.apache.logging.log4j - log4j-api - - - - - - org.slf4j - slf4j-api - - - - org.slf4j - slf4j-log4j12 - ${slf4j-log4j12.version} - - - - log4j - log4j - - - - org.apache.dubbo - dubbo-spring-boot-tracing-otel-zipkin-starter - ${project.version} - - - - org.apache.dubbo - dubbo-qos - ${project.version} - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot-maven-plugin.version} - - - - repackage - - - - - - + + 4.0.0 + + org.apache.dubbo + dubbo-demo-spring-boot + ${revision} + ../pom.xml + + + dubbo-demo-spring-boot-consumer + + + 8 + 8 + 1.7.33 + 2.7.17 + true + + + + + org.apache.dubbo + dubbo-demo-spring-boot-interface + ${project.parent.version} + + + + org.apache.dubbo + dubbo-spring-boot-starter + ${project.version} + + + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.version} + + + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.version} + + + + org.apache.dubbo + dubbo-metadata-report-zookeeper + ${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.springframework.boot + spring-boot-starter + ${spring-boot.version} + + + + org.springframework.boot + spring-boot-autoconfigure + ${spring-boot.version} + + + + org.springframework.boot + spring-boot-starter-logging + ${spring-boot.version} + + + + org.apache.logging.log4j + log4j-api + + + + + + org.slf4j + slf4j-api + + + + org.slf4j + slf4j-log4j12 + ${slf4j-log4j12.version} + + + + log4j + log4j + + + + org.apache.dubbo + dubbo-spring-boot-tracing-otel-zipkin-starter + ${project.version} + + + + org.apache.dubbo + dubbo-qos + ${project.version} + + + + + + + + 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 0b509c1003b..61be9906e57 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 bf209049680..0b8e551562a 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 - - 8 - 8 - true - + + 8 + 8 + 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 328be3a469d..5a638404050 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 abf77aeb06b..93d24ea333f 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 - - dubbo-demo-spring-boot-provider - - - 8 - 8 - 1.7.33 - 2.7.17 - true - - - - - org.apache.dubbo - dubbo-demo-spring-boot-interface - ${project.parent.version} - - - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.version} - - - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.version} - - - - org.apache.dubbo - dubbo-metadata-report-zookeeper - ${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.springframework.boot - spring-boot-starter - ${spring-boot.version} - - - - org.springframework.boot - spring-boot-autoconfigure - ${spring-boot.version} - - - org.springframework.boot - spring-boot-starter-logging - ${spring-boot.version} - - - - org.apache.logging.log4j - log4j-api - - - - - - org.slf4j - slf4j-api - - - - org.slf4j - slf4j-log4j12 - ${slf4j-log4j12.version} - - - - log4j - log4j - - - - - org.apache.dubbo - dubbo-spring-boot-tracing-otel-zipkin-starter - ${project.version} - - - - org.apache.dubbo - dubbo-qos - ${project.version} - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot-maven-plugin.version} - - - - repackage - - - - - - + + 4.0.0 + + org.apache.dubbo + dubbo-demo-spring-boot + ${revision} + ../pom.xml + + + dubbo-demo-spring-boot-provider + + + 8 + 8 + 1.7.33 + 2.7.17 + true + + + + + org.apache.dubbo + dubbo-demo-spring-boot-interface + ${project.parent.version} + + + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.version} + + + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.version} + + + + org.apache.dubbo + dubbo-metadata-report-zookeeper + ${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.springframework.boot + spring-boot-starter + ${spring-boot.version} + + + + org.springframework.boot + spring-boot-autoconfigure + ${spring-boot.version} + + + org.springframework.boot + spring-boot-starter-logging + ${spring-boot.version} + + + + org.apache.logging.log4j + log4j-api + + + + + + org.slf4j + slf4j-api + + + + org.slf4j + slf4j-log4j12 + ${slf4j-log4j12.version} + + + + log4j + log4j + + + + + org.apache.dubbo + dubbo-spring-boot-tracing-otel-zipkin-starter + ${project.version} + + + + org.apache.dubbo + dubbo-qos + ${project.version} + + + + + + + + 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 f0c1aecc3e4..6468826fd00 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 @@ 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 94062920862..db237d38bac 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 7c10fbd9d2f..9e271e88d21 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 + - - 8 - 8 - true - 2.7.17 - 2.7.17 - 1.11.5 - - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - io.micrometer - micrometer-core - ${micrometer-core.version} - - - - + + 8 + 8 + true + 2.7.17 + 2.7.17 + 1.11.5 + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + 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 7a204a368b8..2970acd5830 100644 --- a/dubbo-demo/dubbo-demo-triple/pom.xml +++ b/dubbo-demo/dubbo-demo-triple/pom.xml @@ -17,181 +17,179 @@ ~ 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 - 1.8 - 1.8 - 3.11.0 - + + true + 1.8 + 1.8 + 3.11.0 + - - - 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-java_version}:exe:${os.detected.classifier} - triple-java - build/generated/source/proto/main/java - - - - - compile - test-compile - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${source.level} - ${target.level} - - - - org.codehaus.mojo - build-helper-maven-plugin - - - generate-sources - - add-source - - - - build/generated/source/proto/main/java - - - - - - - + + + + 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-java_version}:exe:${os.detected.classifier} + triple-java + build/generated/source/proto/main/java + + + + + compile + test-compile + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${source.level} + ${target.level} + + + + org.codehaus.mojo + build-helper-maven-plugin + + + + add-source + + generate-sources + + + build/generated/source/proto/main/java + + + + + + + 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 40492a31b2a..2506a5da749 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 284afef7390..36cc07f3eeb 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 6f44f06f89d..90cbfc49e3b 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 static void main(String[] args) throws InterruptedException, IOException 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 a67136b161c..52bb6406909 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 static void main(String[] args) throws IOException { 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 fd422d7ac67..d2c680a87e7 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 static void main(String[] args) throws InterruptedException { 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 3a78d7d56b1..c874960d35d 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 static void main(String[] args) throws IOException { 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 4e76a827908..6c9b32cf362 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,153 +15,151 @@ 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 - 1.7.33 - - - - org.springframework - spring-context - - - org.springframework - spring-web - + + true + 1.7.33 + + + + 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.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - ${slf4j-log4j12.version} - - - log4j - log4j - + + 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-api + + + org.slf4j + slf4j-log4j12 + ${slf4j-log4j12.version} + + + log4j + log4j + - - 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 1977f19efa5..4b3b306d33b 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 static void main(String[] args) { } 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 @@ private static void jaxRsRestDemoServiceTest(ClassPathXmlApplicationContext cont 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 @@ private static void assertEquals(Object returnStr, Object exception) { 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 bda52812311..dc8f6a5e69d 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 @@ 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 a5d0edfacfa..0d9eab4ecb0 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 @@ 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 eb0aa9aa8f3..06f9c5d344d 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,153 +15,151 @@ 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 - 1.7.33 - - - - org.springframework - spring-context - - - org.springframework - spring-web - + + true + 1.7.33 + + + + 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.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - ${slf4j-log4j12.version} - - - log4j - log4j - + + 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-api + + + org.slf4j + slf4j-log4j12 + ${slf4j-log4j12.version} + + + log4j + log4j + - - 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 ebc2ccfe736..d4cdbe038bf 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 @@ 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 a5d0edfacfa..0d9eab4ecb0 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 @@ 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 49099a606ad..2fe7fe3641a 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 64dacac29fe..dcb3b535583 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 @@ 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 26a69ff7fbb..d8a84cc9324 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 String exception(String message) { 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 cc1e832ca1e..24fc704becd 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 String sayHelloOptions(String hello) { 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 0aa6d69e6e4..8c12038cf44 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 List httpResponseHeader(String hello) { 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 ad177d09406..06ec4fdbb9a 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 org.springframework.stereotype.Service; -import po.User; import javax.ws.rs.core.MultivaluedMap; + import java.util.List; import java.util.Map; + +import org.springframework.stereotype.Service; +import po.User; + @Service("jaxRsRestDemoService") public class JaxRsRestDemoServiceImpl implements JaxRsRestDemoService { @@ -42,7 +44,6 @@ public User testJavaBeanBody(User user) { return user; } - @Override public int primitiveInt(int a, int b) { return a + b; @@ -63,8 +64,6 @@ public long primitiveShort(short a, Long b, int c) { return a + b; } - - @Override public String testMapParam(Map params) { return params.get("param"); @@ -90,16 +89,13 @@ 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-spring-mvc-rest-consumer/pom.xml b/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/pom.xml index 6d9d97a3337..cdd8217331c 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,154 +15,151 @@ 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 - 1.7.33 - - - - org.springframework - spring-context - - - org.springframework - spring-web - + + true + 1.7.33 + + + + 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.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - ${slf4j-log4j12.version} - - - log4j - log4j - + + 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-api + + + org.slf4j + slf4j-log4j12 + ${slf4j-log4j12.version} + + + log4j + log4j + - - 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 43e1dc58548..e64117cce0a 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 static void main(String[] args) { } 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 static void consumerService() { } 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 @@ private static void springMvcRestDemoServiceTest(ClassPathXmlApplicationContext 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 @@ private static void assertEquals(Object returnStr, Object exception) { 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 9710c76921f..0d9eab4ecb0 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 @@ 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 180947cd2dc..fbedf5decde 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 @@ 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 60219544e08..6dae77e64da 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,153 +15,151 @@ 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 - 1.7.33 - - - - org.springframework - spring-context - - - org.springframework - spring-web - + + true + 1.7.33 + + + + 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.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - ${slf4j-log4j12.version} - - - log4j - log4j - + + 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-api + + + org.slf4j + slf4j-log4j12 + ${slf4j-log4j12.version} + + + log4j + log4j + - - 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 70b2fe9a41f..81bc1024812 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 @@ 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 a5d0edfacfa..0d9eab4ecb0 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 @@ 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 2798e89aa39..6cdaede32f0 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 User testJavaBeanBody(User user) { return user; } - @Override public int primitiveInt(int a, int b) { return a + b; @@ -64,7 +63,6 @@ public long primitiveShort(short a, Long b, int c) { return a + b; } - @Override public String testMapParam(Map params) { return params.get("param"); @@ -80,22 +78,18 @@ public List testMapForm(MultiValueMap params) { 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 b614dd66759..4060ae76c58 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 b32502fcc3e..2960b8d50e9 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.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 static void main(String[] args) throws Exception { 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 static void main(String[] args) throws Exception { 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 612da3c0f97..b47dc410b07 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 - - true - 1.7.33 - + + 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 + 1.7.33 + - - - 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.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - ${slf4j-log4j12.version} - - - log4j - log4j - - - 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.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + ${slf4j-log4j12.version} + + + log4j + log4j + + + 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 8b36c989696..3467051454e 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 @@ 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 c0864c7a1bb..37155fa436e 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 String sayHello(String name) { return "Hello, " + name; } - public boolean isCalled() { return called; } @@ -83,12 +83,10 @@ public TestPO testBody5(TestPO testPO) { 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 75c27f87843..f1861454d1b 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 3e36fbd8fb3..f24ac41aa63 100644 --- a/dubbo-demo/dubbo-demo-xml/pom.xml +++ b/dubbo-demo/dubbo-demo-xml/pom.xml @@ -17,49 +17,47 @@ ~ specific language governing permissions and limitations ~ under the License. --> - - - org.apache.dubbo - dubbo-demo - ${revision} - ../pom.xml - - 4.0.0 - pom - - dubbo-demo-xml + 4.0.0 + + org.apache.dubbo + dubbo-demo + ${revision} + ../pom.xml + - - true - 2.7.17 - + dubbo-demo-xml + pom - - 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 a5d6123dba8..4c981202a2b 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 - - true - + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + + dubbo-demo + pom + ${project.artifactId} + The demo module of dubbo project - - 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 + diff --git a/dubbo-dependencies-bom/pom.xml b/dubbo-dependencies-bom/pom.xml index 302db996a9e..5b76dcbf954 100644 --- a/dubbo-dependencies-bom/pom.xml +++ b/dubbo-dependencies-bom/pom.xml @@ -15,997 +15,999 @@ See the License for the specific language governing permissions and limitations under the License. --> - - 4.0.0 - - - org.apache - apache - 27 - - - - org.apache.dubbo - dubbo-dependencies-bom - ${revision} - pom - - dubbo-dependencies-bom - Dubbo dependencies BOM + + 4.0.0 + + + org.apache + apache + 27 + + + + org.apache.dubbo + dubbo-dependencies-bom + ${revision} + pom + + 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/ - - - - - The Apache Software Foundation - http://www.apache.org/ - - - - Github Issues - https://github.com/apache/dubbo/issues - - - - - - 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.1.6 - 3.3 - 0.16.0 - 1.0.4 - 3.5.11 - 2.2.21 - 3.14.9 - - 2.1.1 - 3.15.6.Final - 1.9.13 - 8.5.87 - 0.7.6 - 2.2.4 - 1.59.0 - 0.8.1 - 1.2.2 - - 1.7.36 - 1.2 - 1.2.17 - 1.2.11 - - 2.20.0 - 2.11.0 - - 0.13.0 - - - 1.10.18 - - - 6.9.1 - - - 1.0.11 - - 2.2.7 - 1.2.0 - 1.19.1 - 0.7.6 - 3.2.13 - 1.6.12 - - 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.2.8-SNAPSHOT - - - - - - - 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.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} - - - io.netty - 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.alibaba.spring - spring-context-support - ${alibaba_spring_context_support_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} - - - - - javax.annotation - javax.annotation-api - ${javax_annotation-api_version} - - - - javax.servlet - javax.servlet-api - ${servlet_version} - - - - com.squareup.okhttp3 - okhttp - ${okhttp_version} - - - com.squareup.okhttp3 - mockwebserver - ${okhttp_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} - - - commons-logging - commons-logging - ${jcl_version} - - - commons-io - commons-io - ${commons_io_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} - - - - - 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} - - - - - io.swagger - swagger-annotations - ${swagger_version} - - - io.swagger - swagger-jaxrs - ${swagger_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.alibaba.middleware - metrics-rest - ${metrics_version} - - - - - com.alipay.sofa - registry-client-all - ${sofa_registry_version} - - - com.alipay.sofa - registry-test - ${sofa_registry_version} - test - - - - - com.github.codemonstur - embedded-redis - ${embedded_redis_version} - test - - - org.springframework - spring-test - ${spring_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} - - - - 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} - - - 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} - - - - - + + + + Github Issues + https://github.com/apache/dubbo/issues + + + + + + 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.1.6 + 3.3 + 0.16.0 + 1.0.4 + 3.5.11 + 2.2.21 + 3.14.9 + + 2.1.1 + 3.15.6.Final + 1.9.13 + 8.5.87 + 0.7.6 + 2.2.4 + 1.59.0 + 0.8.1 + 1.2.2 + + 1.7.36 + 1.2 + 1.2.17 + 1.2.11 + + 2.20.0 + 2.11.0 + + 0.13.0 + + + 1.10.18 + + + 6.9.1 + + + 1.0.11 + + 2.2.7 + 1.2.0 + 1.19.1 + 0.7.6 + 3.2.13 + 1.6.12 + + 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.2.8-SNAPSHOT + + + + + + + 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.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} + + + io.netty + 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.alibaba.spring + spring-context-support + ${alibaba_spring_context_support_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} + + + + + javax.annotation + javax.annotation-api + ${javax_annotation-api_version} + + + + javax.servlet + javax.servlet-api + ${servlet_version} + + + + com.squareup.okhttp3 + okhttp + ${okhttp_version} + + + com.squareup.okhttp3 + mockwebserver + ${okhttp_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} + + + commons-logging + commons-logging + ${jcl_version} + + + commons-io + commons-io + ${commons_io_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} + + + + + 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} + + + + + io.swagger + swagger-annotations + ${swagger_version} + + + io.swagger + swagger-jaxrs + ${swagger_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.alibaba.middleware + metrics-rest + ${metrics_version} + + + + + com.alipay.sofa + registry-client-all + ${sofa_registry_version} + + + com.alipay.sofa + registry-test + ${sofa_registry_version} + test + + + + + com.github.codemonstur + embedded-redis + ${embedded_redis_version} + test + + + org.springframework + spring-test + ${spring_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} + + + + 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} + + + 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.codehaus.mojo + flatten-maven-plugin + ${maven_flatten_version} + + true + bom + + + + flatten + + flatten + + process-resources + + + flatten.clean + + clean + + clean + + + + + + + + + release + - - org.codehaus.mojo - flatten-maven-plugin - ${maven_flatten_version} - - true - bom - - - - flatten - process-resources - - flatten - - - - flatten.clean - clean - - clean - - - - + + org.apache.maven.plugins + maven-gpg-plugin + + + + sign + + verify + + + + + + + + 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 + + + - - - - - 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 - - - - - - - + + + diff --git a/dubbo-dependencies/dubbo-dependencies-zookeeper-curator5/pom.xml b/dubbo-dependencies/dubbo-dependencies-zookeeper-curator5/pom.xml index ef72c10c0b2..a2e9c4950e6 100644 --- a/dubbo-dependencies/dubbo-dependencies-zookeeper-curator5/pom.xml +++ b/dubbo-dependencies/dubbo-dependencies-zookeeper-curator5/pom.xml @@ -15,209 +15,211 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> - - 4.0.0 - - - org.apache - apache - 27 - - - - org.apache.dubbo - dubbo-dependencies-zookeeper-curator5 - ${revision} - pom - - - 3.2.8-SNAPSHOT - 1.5.0 - 5.1.0 - 3.8.1 - 2.40.0 - check - 1.0.0 - - - - - - org.apache.zookeeper - parent - ${zookeeper_version} - pom - import - - - - + 4.0.0 + + + org.apache + apache + 27 + + + + org.apache.dubbo + dubbo-dependencies-zookeeper-curator5 + ${revision} + pom + + + 3.2.8-SNAPSHOT + 1.5.0 + 5.1.0 + 3.8.1 + 2.40.0 + check + 1.0.0 + 2.38.0 + + + - - org.apache.curator - curator-x-discovery - ${curator5_version} - - - org.apache.zookeeper - zookeeper - ${zookeeper_version} - - - io.netty - netty-handler - - - io.netty - netty-transport-native-epoll - - - - - - com.github.spotbugs - spotbugs-annotations - true - - - - commons-cli - commons-cli - - - - org.eclipse.jetty - jetty-server - - - - org.eclipse.jetty - jetty-servlet - - - - org.eclipse.jetty - jetty-client - - - - jline - jline - - - - io.dropwizard.metrics - metrics-core - - - - org.xerial.snappy - snappy-java - + + org.apache.zookeeper + parent + ${zookeeper_version} + pom + import + - - + + + + + org.apache.curator + curator-x-discovery + ${curator5_version} + + + org.apache.zookeeper + zookeeper + ${zookeeper_version} + + + io.netty + netty-handler + + + io.netty + netty-transport-native-epoll + + + + + + com.github.spotbugs + spotbugs-annotations + true + + + + commons-cli + commons-cli + + + + org.eclipse.jetty + jetty-server + + + + org.eclipse.jetty + jetty-servlet + + + + org.eclipse.jetty + jetty-client + + + + jline + jline + + + + io.dropwizard.metrics + metrics-core + + + + org.xerial.snappy + snappy-java + + + + + + + org.codehaus.mojo + flatten-maven-plugin + ${maven_flatten_version} + + true + resolveCiFriendliesOnly + + + + flatten + + flatten + + process-resources + + + flatten.clean + + clean + + clean + + + + + + + + + release + - - org.codehaus.mojo - flatten-maven-plugin - ${maven_flatten_version} - - true - resolveCiFriendliesOnly - - - - 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 68d1f1908f7..fb872eaf117 100644 --- a/dubbo-dependencies/dubbo-dependencies-zookeeper/pom.xml +++ b/dubbo-dependencies/dubbo-dependencies-zookeeper/pom.xml @@ -15,146 +15,148 @@ ~ 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.2.8-SNAPSHOT + 1.5.0 + 4.3.0 + 3.4.14 + 2.40.0 + check + 1.0.0 + 2.38.0 + - - 3.2.8-SNAPSHOT - 1.5.0 - 4.3.0 - 3.4.14 - 2.40.0 - check - 1.0.0 - + + + org.apache.curator + curator-x-discovery + ${curator_version} + + + org.apache.zookeeper + zookeeper + ${zookeeper_version} + + - - - org.apache.curator - curator-x-discovery - ${curator_version} - - - org.apache.zookeeper - zookeeper - ${zookeeper_version} - - + + + + org.codehaus.mojo + flatten-maven-plugin + ${maven_flatten_version} + + true + resolveCiFriendliesOnly + + + + flatten + + flatten + + process-resources + + + flatten.clean + + clean + + clean + + + + + - + + + release + - - org.codehaus.mojo - flatten-maven-plugin - ${maven_flatten_version} - - true - resolveCiFriendliesOnly - - - - 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 9aee5b19e74..441adfdb68d 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.38.0 + - - 2.40.0 - check - 1.0.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/pom.xml b/dubbo-distribution/pom.xml index 9a7edc14f45..5eb97e30eb7 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 + 2.38.0 + - - 2.40.0 - check - 1.0.0 - - - - - release - - dubbo-all - dubbo-apache-release - dubbo-bom - dubbo-core-spi - - - - dubbo-all - - true - - - dubbo-all - dubbo-bom - - - - dubbo-core-spi - - dubbo-core-spi - - - - 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-apache-release + dubbo-bom + dubbo-core-spi + + + + dubbo-all + + true + + + dubbo-all + dubbo-bom + + + + dubbo-core-spi + + dubbo-core-spi + + + + 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-filter/dubbo-filter-cache/pom.xml b/dubbo-filter/dubbo-filter-cache/pom.xml index 8241d23f457..50f2a7b015a 100644 --- a/dubbo-filter/dubbo-filter-cache/pom.xml +++ b/dubbo-filter/dubbo-filter-cache/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-filter - ${revision} - - dubbo-filter-cache - jar - ${project.artifactId} - The cache module of dubbo project - - false - - - - org.apache.dubbo - dubbo-rpc-api - ${project.parent.version} - - - javax.cache - cache-api - - - com.hazelcast - hazelcast - test - ${hazelcast_version} - - - \ No newline at end of file + 4.0.0 + + org.apache.dubbo + dubbo-filter + ${revision} + + dubbo-filter-cache + jar + ${project.artifactId} + The cache module of dubbo project + + false + + + + org.apache.dubbo + dubbo-rpc-api + ${project.parent.version} + + + javax.cache + cache-api + + + com.hazelcast + hazelcast + ${hazelcast_version} + test + + + diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/Cache.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/Cache.java index 69ae6710eec..898905af846 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/Cache.java +++ b/dubbo-filter/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-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/CacheFactory.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/CacheFactory.java index 66b5b59e2ca..ed36b408519 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/CacheFactory.java +++ b/dubbo-filter/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-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java index 209776d3a5d..b22eaec6586 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java @@ -64,7 +64,9 @@ * @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 void setCacheFactory(CacheFactory cacheFactory) { */ @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 Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept } 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 @@ static class ValueWrapper implements Serializable { private final Object value; - public ValueWrapper (Object value) { + public ValueWrapper(Object value) { this.value = value; } diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java index 2d716a32078..00276dda8c1 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java @@ -85,5 +85,4 @@ public Cache getCache(URL url, Invocation invocation) { * @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-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringCache.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringCache.java index afaf8c6135e..c8d1fd1bed4 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringCache.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringCache.java @@ -68,10 +68,8 @@ public void put(Object key, Object value) { * @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-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringCacheFactory.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringCacheFactory.java index 5259d74b6eb..bb0553f0741 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringCacheFactory.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringCacheFactory.java @@ -20,7 +20,6 @@ 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 @@ * @see ExpiringCache * @see Cache */ - public class ExpiringCacheFactory extends AbstractCacheFactory { /** diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringMap.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringMap.java index 3516b0a214d..cec8854d7d7 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringMap.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringMap.java @@ -194,10 +194,9 @@ public void setTimeToLive(int timeToLive) { @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 int hashCode() { @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 ExpireThread implements Runnable { @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 void setExpirationInterval(long expirationInterval) { } } } - - - diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCache.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCache.java index 7972a9dd9a2..291962617e0 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCache.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCache.java @@ -27,6 +27,7 @@ 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 JCache(URL url) { // 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 void put(Object key, Object value) { public Object get(Object key) { return store.get(key); } - } diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCacheFactory.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCacheFactory.java index aba9a2f9c45..43186f510e0 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCacheFactory.java +++ b/dubbo-filter/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-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lfu/LfuCache.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lfu/LfuCache.java index f505c16b1d7..b59c647177a 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lfu/LfuCache.java +++ b/dubbo-filter/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 void put(Object key, Object value) { public Object get(Object key) { return store.get(key); } - } diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lfu/LfuCacheFactory.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lfu/LfuCacheFactory.java index f04edca4290..0ecc8cf9675 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lfu/LfuCacheFactory.java +++ b/dubbo-filter/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-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCache.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCache.java index 5b7c2564f4b..b84bebb0afd 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCache.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCache.java @@ -76,5 +76,4 @@ public void put(Object key, Object value) { public Object get(Object key) { return store.get(key); } - } diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCacheFactory.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCacheFactory.java index 9ec94862a5f..3954cd4c195 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCacheFactory.java +++ b/dubbo-filter/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-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCache.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCache.java index 12b3b5ca03b..8627f239242 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCache.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCache.java @@ -73,5 +73,4 @@ public void put(Object key, Object value) { public Object get(Object key) { return store.get().get(key); } - } diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactory.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactory.java index cdda6cf3e4c..cee476890bd 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactory.java +++ b/dubbo-filter/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-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/filter/CacheFilterTest.java b/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/filter/CacheFilterTest.java index f420f3fa040..03bc486da2e 100644 --- a/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/filter/CacheFilterTest.java +++ b/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/filter/CacheFilterTest.java @@ -27,13 +27,13 @@ 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 @@ static Stream cacheFactories() { 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 @@ public void setUp(String cacheType, CacheFactory cacheFactory) { 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 @@ public void setUp(String cacheType, CacheFactory cacheFactory) { 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 @@ public void testNonArgsMethod(String cacheType, CacheFactory cacheFactory) { 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 @@ public void testMethodWithArgs(String cacheType, CacheFactory cacheFactory) { 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 @@ public void testException(String cacheType, CacheFactory cacheFactory) { 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 @@ public void testNull(String cacheType, CacheFactory cacheFactory) { Assertions.assertNull(result1.getValue()); Assertions.assertNull(result2.getValue()); } -} \ No newline at end of file +} diff --git a/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/AbstractCacheFactoryTest.java b/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/AbstractCacheFactoryTest.java index f93a453eebf..8887bdd9527 100644 --- a/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/AbstractCacheFactoryTest.java +++ b/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/AbstractCacheFactoryTest.java @@ -30,4 +30,4 @@ protected Cache constructCache() { } protected abstract AbstractCacheFactory getCacheFactory(); -} \ No newline at end of file +} diff --git a/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/expiring/ExpiringCacheFactoryTest.java b/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/expiring/ExpiringCacheFactoryTest.java index bedb6a9d2ab..70bfc06ad90 100644 --- a/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/expiring/ExpiringCacheFactoryTest.java +++ b/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/expiring/ExpiringCacheFactoryTest.java @@ -23,10 +23,10 @@ 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 @@ protected Cache constructCache() { protected AbstractCacheFactory getCacheFactory() { return new ExpiringCacheFactory(); } -} \ No newline at end of file +} diff --git a/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/lru/LruCacheFactoryTest.java b/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/lru/LruCacheFactoryTest.java index 131defdd416..47c92249e9f 100644 --- a/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/lru/LruCacheFactoryTest.java +++ b/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/lru/LruCacheFactoryTest.java @@ -25,7 +25,7 @@ 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 @@ void testLruCacheFactory() throws Exception { protected AbstractCacheFactory getCacheFactory() { return new LruCacheFactory(); } -} \ No newline at end of file +} diff --git a/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactoryTest.java b/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactoryTest.java index 31184ec142c..b2999f42d1a 100644 --- a/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactoryTest.java +++ b/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactoryTest.java @@ -36,4 +36,4 @@ void testThreadLocalCacheFactory() throws Exception { protected AbstractCacheFactory getCacheFactory() { return new ThreadLocalCacheFactory(); } -} \ No newline at end of file +} diff --git a/dubbo-filter/dubbo-filter-validation/pom.xml b/dubbo-filter/dubbo-filter-validation/pom.xml index e3027062a91..19637eeb1f4 100644 --- a/dubbo-filter/dubbo-filter-validation/pom.xml +++ b/dubbo-filter/dubbo-filter-validation/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-filter - ${revision} - - dubbo-filter-validation - jar - ${project.artifactId} - The validation module of dubbo project - - false - - - - org.apache.dubbo - dubbo-rpc-api - ${project.parent.version} - - - jakarta.validation - jakarta.validation-api - - - javax.validation - validation-api - - - org.hibernate - hibernate-validator - test - ${hibernate_validator_version} - - - 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} - - - \ No newline at end of file + 4.0.0 + + org.apache.dubbo + dubbo-filter + ${revision} + + dubbo-filter-validation + jar + ${project.artifactId} + The validation module of dubbo project + + false + + + + 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-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validation.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validation.java index 73c4cd8cdc8..54469c921ea 100644 --- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validation.java +++ b/dubbo-filter/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-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validator.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validator.java index c78c62a1167..f60f31bc2eb 100644 --- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validator.java +++ b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validator.java @@ -23,5 +23,4 @@ public interface Validator { void validate(String methodName, Class[] parameterTypes, Object[] arguments) throws Exception; - } diff --git a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java index ab742d3561c..849cf658394 100644 --- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java +++ b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java @@ -59,7 +59,10 @@ * @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 Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept 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 Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept } 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-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/AbstractValidation.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/AbstractValidation.java index a6f9c8eda35..0b91b60c1db 100644 --- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/AbstractValidation.java +++ b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/AbstractValidation.java @@ -47,5 +47,4 @@ public Validator getValidator(URL url) { } protected abstract Validator createValidator(URL url); - } diff --git a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidation.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidation.java index 6b4b71f9c63..6a8890fbb8f 100644 --- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidation.java +++ b/dubbo-filter/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-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidationNew.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidationNew.java index 32cec169276..a1dccd2e4f7 100644 --- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidationNew.java +++ b/dubbo-filter/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-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java index b55fb9a0d98..e19904ac168 100644 --- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java +++ b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java @@ -25,6 +25,26 @@ 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.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 JValidator(URL url) { 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 @@ private static Class generateMethodParameterClass(Class clazz, Method meth 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 @@ private static Class generateMethodParameterClass(Class clazz, Method meth 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 @@ private static Class generateMethodParameterClass(Class clazz, Method meth 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 @@ private static Class generateMethodParameterClass(Class clazz, Method meth } 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 void validate(String methodName, Class[] parameterTypes, Object[] argu } 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 @@ private Class methodClass(String methodName) { 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 @@ private void validate(Set> violations, Object arg, Class< } } } - } diff --git a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidatorNew.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidatorNew.java index b217131c827..9e6f4017c9e 100644 --- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidatorNew.java +++ b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidatorNew.java @@ -25,12 +25,19 @@ 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.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 JValidatorNew(URL url) { 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 @@ private static Class generateMethodParameterClass(Class clazz, Method meth 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 @@ private static Class generateMethodParameterClass(Class clazz, Method meth 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 @@ private static Class generateMethodParameterClass(Class clazz, Method meth 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 @@ private static Class generateMethodParameterClass(Class clazz, Method meth } 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 void validate(String methodName, Class[] parameterTypes, Object[] argu } 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 @@ private Class methodClass(String methodName) { 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 @@ private void validate(Set> violations, Object arg, Class< } } } - } diff --git a/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/filter/ValidationFilterTest.java b/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/filter/ValidationFilterTest.java index 4260d76e508..2bdb65602eb 100644 --- a/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/filter/ValidationFilterTest.java +++ b/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/filter/ValidationFilterTest.java @@ -55,14 +55,13 @@ void testItWithNotExistClass() { 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 @@ void testItWithExistClass() { 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 @@ void testItWithoutUrlParameters() { 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 @@ void testItWhileMethodNameStartWithDollar() { 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 @@ void testItWhileThrowoutRpcException() { 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-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/JValidationTest.java b/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/JValidationTest.java index c016cbbf278..5e6e8377036 100644 --- a/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/JValidationTest.java +++ b/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/JValidationTest.java @@ -20,11 +20,11 @@ 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 @@ void testReturnTypeWithDefaultValidatorProvider() { Validator validator = jValidation.getValidator(url); assertThat(validator instanceof JValidator, is(true)); } -} \ No newline at end of file +} diff --git a/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/JValidatorTest.java b/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/JValidatorTest.java index a434b6d7ddb..de9f87cdcff 100644 --- a/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/JValidatorTest.java +++ b/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/JValidatorTest.java @@ -20,16 +20,17 @@ 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 @@ void testItWithPrimitiveArgWithProvidedMessage() { @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 @@ void testItWithPartialParameterValidation() { @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 @@ void testItWithNestedParameterValidationWithNullNestedParam() { @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 @@ void testItWithNestedParameterValidationWithNullNestedParams() { assertThat(e1.getMessage(), containsString("name must not be null")); } } - } diff --git a/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/mock/JValidatorTestTarget.java b/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/mock/JValidatorTestTarget.java index 9cf5dec6f3e..cc288eb2bcc 100644 --- a/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/mock/JValidatorTestTarget.java +++ b/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/mock/JValidatorTestTarget.java @@ -18,13 +18,14 @@ 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 void setName(String name) { this.name = name; } } - } diff --git a/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/mock/ValidationParameter.java b/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/mock/ValidationParameter.java index 0b54a047ae1..fb4b598dbdf 100644 --- a/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/mock/ValidationParameter.java +++ b/dubbo-filter/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-filter/pom.xml b/dubbo-filter/pom.xml index 4da7c40f595..6fecdc892b7 100644 --- a/dubbo-filter/pom.xml +++ b/dubbo-filter/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-parent - ${revision} - ../pom.xml - - dubbo-filter - pom - ${project.artifactId} - The filter module of dubbo project - - false - - - dubbo-filter-cache - dubbo-filter-validation - + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + + dubbo-filter + pom + ${project.artifactId} + The filter module of dubbo project + + dubbo-filter-cache + dubbo-filter-validation + + + 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-kubernetes/pom.xml b/dubbo-kubernetes/pom.xml index 39fa870d340..8f5a0e1acb1 100644 --- a/dubbo-kubernetes/pom.xml +++ b/dubbo-kubernetes/pom.xml @@ -15,62 +15,59 @@ 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 - - - - - 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} - - - 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 - - - - + 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} + + + 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 e35419f8c74..43e79862fe6 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.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.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 @@ private void subscribeVs(String appName) { 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 void onClose(WatcherException cause) { vsAppWatch.put(appName, watch); try { GenericKubernetesResource vsRule = kubernetesClient - .genericKubernetesResources( - MeshConstant.getVsDefinition()) + .genericKubernetesResources(MeshConstant.getVsDefinition()) .inNamespace(namespace) .withName(appName) .get(); @@ -140,15 +140,15 @@ private void subscribeDr(String appName) { 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 void onClose(WatcherException cause) { 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 b221c89c2bc..2d51c1bfa2a 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 boolean isAvailable() { } @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 739a5e0584c..7792abdd2b1 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.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 KubernetesServiceDiscovery(ApplicationModel applicationModel, URL registr 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 void doRegister(ServiceInstance serviceInstance) throws RuntimeException .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 void doRegister(ServiceInstance serviceInstance) throws RuntimeException * 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 void doUnregister(ServiceInstance serviceInstance) throws RuntimeExceptio .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 List getInstances(String serviceName) throws NullPointer } @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 @@ private void watchEndpoints(ServiceInstancesChangedListener listener, String ser @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 void onAdd(Endpoints endpoints) { @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 void onUpdate(Endpoints oldEndpoints, Endpoints newEndpoints) { @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 @@ private void watchPods(ServiceInstancesChangedListener listener, String serviceN @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 void onUpdate(Pod oldPod, Pod newPod) { @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 @@ private void watchService(ServiceInstancesChangedListener listener, String servi .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 @@ private void notifyServiceChanged(String serviceName, ServiceInstancesChangedLis } 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 URL getUrl() { } 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 @@ private List toServiceInstance(Endpoints endpoints, String serv 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 @@ private List toServiceInstance(Endpoints endpoints, String serv 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 813bdd82596..e8b8f8407fd 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 1238efb579a..818b8df64d4 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 boolean isEnable() { } @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 d4591a249e5..b7ace538947 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 4b54b4c6b03..332bb6e7333 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 @@ 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 static Config createKubernetesConfig(URL url) { .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 @@ private static String buildMasterUrl(URL url) { 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 5341c0cb749..6f47be60152 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.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.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 @@ public void setUp() { 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 @@ void testEndpointsUpdate() { 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 @@ void testEndpointsUpdate() { 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 @@ void testPodsUpdate() throws Exception { 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 @@ void testPodsUpdate() throws Exception { 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 @@ void testServiceUpdate() { 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 @@ void testServiceUpdate() { 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 @@ void testGetInstance() { 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 0b3302d763d..a8efbe56d2e 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 - - - Dubbo Maven Plugin - 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 + + + + + + maven-plugin-plugin + 3.8.1 + + + default-addPluginArtifactMetadata + + addPluginArtifactMetadata + + package + + + default-descriptor + + descriptor + + process-classes + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 8 + 8 + + + - - commons-io - commons-io - 2.11.0 - - - - - - - maven-plugin-plugin - 3.8.1 - - - default-addPluginArtifactMetadata - package - - addPluginArtifactMetadata - - - - default-descriptor - process-classes - - descriptor - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 8 - 8 - - - - - + 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 fbcc05a466c..c871e3f19a6 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 @@ private String[] getAotArguments(String applicationClass) { } 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-metadata/dubbo-metadata-api/pom.xml b/dubbo-metadata/dubbo-metadata-api/pom.xml index c951e1d36b3..99868033549 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} + - - - 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.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 + - + 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 4a367c812a8..33441157516 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 @@ protected void init(boolean enableFileCache, String filePath, String fileName, i } // 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 void destroy() { 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 static class CacheRefreshTask implements Runnable { 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 6ed85622eeb..d26684a512c 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 void setApplicationModel(ApplicationModel applicationModel) { * * @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 Set getAndListen(URL registryURL, URL subscribedURL, MappingListe 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 Set getAndListen(URL registryURL, URL subscribedURL, MappingListe 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 MappingListener stopListen(URL subscribeURL, MappingListener listener) { 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 MappingListener stopListen(URL subscribeURL, MappingListener listener) { } 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 @@ protected void putCachedMappingIfAbsent(String serviceKey, Set apps) { @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 Set call() throws Exception { 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 Set call() throws Exception { } } } 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 241ba8c8396..7f6aab282bc 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 4af42d4a3fd..ca23dbf178d 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 MappingCacheManager(boolean enableFileCache, String name, ScheduledExecut 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 a1c40f0f91d..3a81cd7bf12 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 Set getApps() { @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 0ec12681abc..8b808d7b240 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 f2b2bed500a..0d805f8e5be 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 @@ -59,19 +59,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; @@ -93,11 +95,17 @@ public MetadataInfo(String app, String revision, Map servic 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); @@ -105,8 +113,10 @@ private MetadataInfo(String app, String revision, Map servi 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; } @@ -120,11 +130,13 @@ public void init() { 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); }); } @@ -188,7 +200,9 @@ public synchronized String calAndGetRevision() { 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); @@ -240,7 +254,7 @@ public ServiceInfo getNoProtocolServiceInfo(String serviceKeyWithoutProtocol) { } Set subServices = subscribedServices.get(serviceKeyWithoutProtocol); if (CollectionUtils.isNotEmpty(subServices)) { - return subServices.iterator().next(); + return subServices.iterator().next(); } return null; } @@ -257,10 +271,9 @@ public ServiceInfo getValidServiceInfo(String serviceKey) { } 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() { @@ -324,9 +337,9 @@ public Set collectExportedURLSet() { 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) { @@ -368,11 +381,11 @@ public boolean equals(Object obj) { 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) { @@ -418,27 +431,23 @@ private void extractInstanceParams(URL url, List filters) 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) { @@ -451,7 +460,17 @@ private String getSimplifiedServices(Map services) { @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() { @@ -469,26 +488,33 @@ public static class ServiceInfo 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. @@ -496,7 +522,14 @@ public ServiceInfo(URL url, List filters) { 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; @@ -588,7 +621,7 @@ protected void init() { 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 } @@ -616,7 +649,7 @@ public ProtocolServiceKey getProtocolServiceKey() { if (protocolServiceKey != null) { return protocolServiceKey; } - protocolServiceKey = new ProtocolServiceKey(name, version, group, protocol); + protocolServiceKey = new ProtocolServiceKey(name, version, group, protocol); return protocolServiceKey; } @@ -695,7 +728,8 @@ public void setParams(Map params) { @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; @@ -742,7 +776,7 @@ public boolean hasMethodParameter(String method, String key) { public boolean hasMethodParameter(String method) { return (consumerMethodParams != null && consumerMethodParams.containsKey(method)) - || (methodParams != null && methodParams.containsKey(method)); + || (methodParams != null && methodParams.containsKey(method)); } public String toDescString() { @@ -808,11 +842,11 @@ public boolean equals(Object obj) { * 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 @@ -826,14 +860,13 @@ public String toString() { } 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 18e7105715a..6bd42d386c7 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 @@ @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 a992cdc586d..ff9b0167011 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 35527d0356c..ecc4d29618b 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 int hashCode() { 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 a1c9e19169b..9284289f59d 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 89872490532..e2c58e69eb0 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 @@ static String buildMappingKey(URL url) { } 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 @@ static Set getAppNames(String content) { 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/report/MetadataReport.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReport.java index b871dc7424e..b4668948d2f 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 @@ default ConfigItem getConfigItem(String key, String group) { 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 @@ default boolean registerServiceAppMapping(String serviceKey, String application, return false; } - default void removeServiceAppMappingListener(String serviceKey, MappingListener listener) { - - } + default void removeServiceAppMappingListener(String serviceKey, MappingListener listener) {} /** * Service<-->Application Mapping -- START @@ -99,5 +95,4 @@ default Set getServiceAppMapping(String serviceKey, URL url) { 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 a0e1bb2e2a7..44340244e08 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 264d6a18f96..3fd14dff0bd 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 void init(List metadataReportConfigs) { 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 @@ private void init(MetadataReportConfig config, MetadataReportFactory metadataRep .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 c88eaf774ad..ce16b2b95fc 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 @@ 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 void initializeApplicationModel(ApplicationModel applicationModel) { } @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 591a1a70b9d..3838e439269 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 @@ protected String getUniqueKey(KeyTypeEnum keyType, String... params) { } 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 @@ private String getFilePathKey(String pathTag, String... params) { 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 dded259cddb..496d69fb609 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 3253f85a73e..cb9c0aa463c 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 @@ * 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 String build(String one, String... others) { * @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 1e5b8919f07..b5501ae6a31 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 MetadataIdentifier(String serviceInterface, String version, String group, this.application = application; } - public MetadataIdentifier(URL url) { this.serviceInterface = url.getServiceInterface(); this.version = url.getVersion(); @@ -103,12 +101,11 @@ public String getUniqueServiceName() { @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 100d8442197..4fd036b97c0 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 ServiceMetadataIdentifier(String serviceInterface, String version, String this.protocol = protocol; } - public ServiceMetadataIdentifier(URL url) { this.serviceInterface = url.getServiceInterface(); this.version = url.getVersion(); @@ -70,13 +69,13 @@ public void setProtocol(String protocol) { @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 e375593047c..12993f66f15 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 String getRevision() { 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 1c26581a956..a1575f00f1f 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 @@ 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 AbstractMetadataReport(URL reportServerURL) { 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 AbstractMetadataReport(URL reportServerURL) { 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 @@ private void doSaveProperties(long version) { 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 @@ private void doSaveProperties(long version) { } 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 void run() { } @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 void storeProviderMetadata(MetadataIdentifier providerMetadataIdentifier, } } - 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); + 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); + } + 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 @@ protected void storeConsumerMetadataTask(MetadataIdentifier consumerMetadataIden // 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 void saveSubscribedData(SubscriberMetadataIdentifier subscriberMetadataId 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 @@ private boolean doHandleMetadataCollection(Map metad 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 @@ private boolean doHandleMetadataCollection(Map metad } else if (CONSUMER_SIDE.equals(item.getKey().getSide())) { this.storeConsumerMetadata(item.getKey(), (Map) item.getValue()); } - } return false; } @@ -448,13 +483,16 @@ long calculateStartTime() { 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 @@ void startRetryTask() { 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 @@ private void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadat 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 @@ private void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadat 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 7ac9aabdcae..e0d156773dc 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 @@ 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 406df6c4187..4c1fa597ec4 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 e42ae2744fc..ef900bd793f 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.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 String getServiceDefinition(MetadataIdentifier metadataIdentifier) { } @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 List getExportedURLs(ServiceMetadataIdentifier metadataIdentifier } @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/main/java/org/apache/dubbo/metadata/rest/AbstractAnnotatedMethodParameterProcessor.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/AbstractAnnotatedMethodParameterProcessor.java index 71d47cfda6c..d7f9a32bc39 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/AbstractAnnotatedMethodParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-api/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 @@ 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 void process(Annotation annotation, Parameter parameter, int parameterInd 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 @@ protected String getAnnotationValue(Annotation annotation, Parameter parameter, protected String getDefaultValue(Annotation annotation, Parameter parameter, int parameterIndex) { return AnnotatedMethodParameterProcessor.buildDefaultValue(parameterIndex); } - } diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/AbstractNoAnnotatedParameterProcessor.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/AbstractNoAnnotatedParameterProcessor.java index b4975dc0c6d..23cdd4cbf3f 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/AbstractNoAnnotatedParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/AbstractNoAnnotatedParameterProcessor.java @@ -41,7 +41,7 @@ private boolean contentTypeSupport(RestMethodMetadata restMethodMetadata, MediaT // @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 @@ protected boolean isFormContentType(RestMethodMetadata restMethodMetadata) { 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-api/src/main/java/org/apache/dubbo/metadata/rest/AbstractServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/AbstractServiceRestMetadataResolver.java index 9d9cbfd4832..0506d762b26 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/AbstractServiceRestMetadataResolver.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/AbstractServiceRestMetadataResolver.java @@ -93,8 +93,8 @@ protected final boolean isImplementedInterface(Class serviceType) { 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 final ServiceRestMetadata resolve(Class serviceType) { return resolve(serviceType, serviceRestMetadata); } - @Override public final ServiceRestMetadata resolve(Class serviceType, ServiceRestMetadata serviceRestMetadata) { serviceRestMetadata.setCodeStyle(this.getClass()); @@ -159,10 +158,19 @@ protected void processAllRestMethodMetadata(ServiceRestMetadata serviceRestMetad // 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 @@ protected void processAllRestMethodMetadata(ServiceRestMetadata serviceRestMetad 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 @@ protected Map resolveServiceMethodsMap(Class serviceType, Cla List serviceMethods = new ArrayList<>(getAllMethods(serviceType, excludedDeclaredClass(Object.class))); - // sort methods sort(declaredServiceMethods, MethodComparator.INSTANCE); sort(serviceMethods, MethodComparator.INSTANCE); @@ -204,8 +212,8 @@ protected Map resolveServiceMethodsMap(Class serviceType, Cla 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 @@ protected Class resolveServiceInterfaceClass(ServiceRestMetadata serviceRestM * @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 @@ protected boolean processRestMethodMetadata(Method serviceMethod, Class servi // process the annotated method parameters processAnnotatedMethodParameters(serviceMethod, serviceType, serviceInterfaceClass, metadata); - // Post-Process postResolveRestMethodMetadata(serviceMethod, serviceType, serviceInterfaceClass, metadata); @@ -317,8 +328,8 @@ protected boolean processRestMethodMetadata(Method serviceMethod, Class servi * @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 @@ protected abstract boolean isRestCapableMethod(Method serviceMethod, Class se * @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 @@ protected abstract String resolveRequestMethod(Method serviceMethod, Class se * @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 @@ protected abstract String resolveRequestPath(Method serviceMethod, Class serv * @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 @@ private void processAnnotatedMethodParameters(Method serviceMethod, Class ser } } - private void processAnnotatedMethodParameter(Parameter parameter, int parameterIndex, Method serviceMethod, - Class serviceType, Class serviceInterfaceClass, - RestMethodMetadata metadata) { + private 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 @@ private void processAnnotatedMethodParameter(Parameter parameter, int parameterI 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-api/src/main/java/org/apache/dubbo/metadata/rest/AnnotatedMethodParameterProcessor.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/AnnotatedMethodParameterProcessor.java index 506b6cf6651..b05bd4b48e2 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/AnnotatedMethodParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/AnnotatedMethodParameterProcessor.java @@ -21,6 +21,7 @@ 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 @@ void process(Annotation annotation, Parameter parameter, int parameterIndex, Met static String buildDefaultValue(int parameterIndex) { return "{" + parameterIndex + "}"; } - } diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/ArgInfo.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/ArgInfo.java index 9c8a96550cb..dc2f7001f8a 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/ArgInfo.java +++ b/dubbo-metadata/dubbo-metadata-api/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 ArgInfo(int index, Parameter parameter) { this.actualType = parameter.getParameterizedType(); } - public ArgInfo() { - } + public ArgInfo() {} public int getIndex() { return index; @@ -115,7 +113,6 @@ public void setParamType(Class paramType) { this.paramType = paramType; } - public int getUrlSplitIndex() { return urlSplitIndex; } @@ -165,15 +162,14 @@ public Type actualReflectType() { @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-api/src/main/java/org/apache/dubbo/metadata/rest/DefaultServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/DefaultServiceRestMetadataResolver.java index 926fc64d4c8..41a4e1bec99 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/DefaultServiceRestMetadataResolver.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/DefaultServiceRestMetadataResolver.java @@ -21,7 +21,6 @@ import java.lang.reflect.Method; import java.util.Set; - /** * The default implementation {@link ServiceRestMetadataResolver} * @@ -53,12 +52,10 @@ protected String resolveRequestPath(Method serviceMethod, Class serviceType, } @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-api/src/main/java/org/apache/dubbo/metadata/rest/JAXRSClassConstants.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/JAXRSClassConstants.java index 0c78eec52a6..47c9149ff40 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/JAXRSClassConstants.java +++ b/dubbo-metadata/dubbo-metadata-api/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-api/src/main/java/org/apache/dubbo/metadata/rest/ParamType.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/ParamType.java index d37b0a641f6..33f0cfc7474 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/ParamType.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/ParamType.java @@ -23,35 +23,42 @@ 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)), EMPTY(addSupportTypes()); private List annotationClasses; - ParamType(List annotationClasses) { this.annotationClasses = annotationClasses; } - public boolean supportAnno(Class anno) { if (anno == null) { return false; @@ -79,9 +86,5 @@ private static List addSupportTypes(Class... classes) { } return types; - - } - - } diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/PathMatcher.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/PathMatcher.java index e08e0733b2b..2e526d19a64 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/PathMatcher.java +++ b/dubbo-metadata/dubbo-metadata-api/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 @@ 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 void setPort(Integer port) { 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 static PathMatcher getInvokeCreatePathMatcher(Method serviceMethod) { } 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 boolean equals(Object o) { 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 @@ && httpMethodMatch(that) // http method compare * @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 @@ private boolean pathEqual(PathMatcher pathMatcher) { return false; } - // no place hold if (!pathMatcher.hasPathVariable) { return this.path.equals(pathMatcher.path); @@ -213,7 +211,6 @@ private boolean pathEqual(PathMatcher pathMatcher) { String[] pathSplits = pathMatcher.pathSplits; String[] thisPathSplits = this.pathSplits; - if (thisPathSplits.length != pathSplits.length) { return false; } @@ -232,7 +229,6 @@ private boolean pathEqual(PathMatcher pathMatcher) { } return true; - } private boolean placeHoldCompare(String pathSplit, String pathToCompare) { @@ -257,15 +253,12 @@ private boolean isPlaceHold(String pathSplit) { 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 @@ private String pathFormat(String path) { } } - @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-api/src/main/java/org/apache/dubbo/metadata/rest/PathUtil.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/PathUtil.java index f105461268b..90cc7cd8fad 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/PathUtil.java +++ b/dubbo-metadata/dubbo-metadata-api/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 static String resolvePathVariable(String rawPath, List argInfos, } } - 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 static String resolvePathVariable(String rawPath, List argInfos, } return pat; - } - /** * parse pathVariable index from url by annotation info * @@ -107,7 +102,6 @@ public static void setArgInfoSplitIndex(String rawPath, List argInfos) } } } - } public static class PathPair { @@ -116,7 +110,6 @@ public static class PathPair { ArgInfo argInfo; - public PathPair(ArgInfo argInfo) { this.argInfo = argInfo; this.value = argInfo.getAnnotationNameAttribute(); @@ -135,11 +128,10 @@ public String getRightPatten() { } 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 void setArgInfoSplitIndex(int urlSplitIndex) { } } } - - diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/RequestMetadata.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/RequestMetadata.java index e7f825d26a0..bdac2575e4f 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/RequestMetadata.java +++ b/dubbo-metadata/dubbo-metadata-api/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 void setPath(String path) { if (!path.startsWith(SLASH)) { this.path = SLASH + path; } - } public Map> getParams() { @@ -100,8 +96,8 @@ private static void add(Map> multiValueMap, String key, Str 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 Set getHeaderNames() { 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 @@ private > RequestMetadata headers(Map(); } - 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 boolean equals(Object o) { 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-api/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadataReader.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadataReader.java index de5207a9dde..6a590260c32 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadataReader.java +++ b/dubbo-metadata/dubbo-metadata-api/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-api/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadataResolver.java index 492dc942fbf..b36ba51decd 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadataResolver.java +++ b/dubbo-metadata/dubbo-metadata-api/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-api/src/main/java/org/apache/dubbo/metadata/rest/SpringMvcClassConstants.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/SpringMvcClassConstants.java index bd3cabf4db2..d16ba215234 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/SpringMvcClassConstants.java +++ b/dubbo-metadata/dubbo-metadata-api/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-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/BodyParameterProcessor.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/BodyParameterProcessor.java index 98895534707..2ee067091b6 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/BodyParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/BodyParameterProcessor.java @@ -40,13 +40,15 @@ public String getAnnotationName() { } @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-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/DefaultValueParameterProcessor.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/DefaultValueParameterProcessor.java index 475fbe9cd1f..5b3a4ee2a26 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/DefaultValueParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/DefaultValueParameterProcessor.java @@ -29,7 +29,6 @@ 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 String getAnnotationName() { } @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-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/FormBodyParameterProcessor.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/FormBodyParameterProcessor.java index 057623acf22..26483885bf1 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/FormBodyParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/FormBodyParameterProcessor.java @@ -40,15 +40,21 @@ public String getAnnotationName() { } @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-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/HeaderParamParameterProcessor.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/HeaderParamParameterProcessor.java index 216f1091f20..9fc5299e831 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/HeaderParamParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/HeaderParamParameterProcessor.java @@ -41,8 +41,14 @@ public String getAnnotationName() { } @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-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/JAXRSServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/JAXRSServiceRestMetadataResolver.java index 40341672b1a..48a53fd6010 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/JAXRSServiceRestMetadataResolver.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/JAXRSServiceRestMetadataResolver.java @@ -48,8 +48,8 @@ public JAXRSServiceRestMetadataResolver(ApplicationModel applicationModel) { @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 @@ -84,16 +84,16 @@ private String resolveRequestPathFromMethod(Method serviceMethod) { } @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-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/ParamAnnotationParameterProcessor.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/ParamAnnotationParameterProcessor.java index d7dd5c05c98..e2feefb9cb1 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/ParamAnnotationParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/ParamAnnotationParameterProcessor.java @@ -31,8 +31,14 @@ 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-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/PathParamParameterProcessor.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/PathParamParameterProcessor.java index 3ab3b8591dc..478182312ee 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/PathParamParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-api/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-api/src/main/java/org/apache/dubbo/metadata/rest/media/MediaType.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/media/MediaType.java index 2414e4ffae7..df59aa4961b 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/media/MediaType.java +++ b/dubbo-metadata/dubbo-metadata-api/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 static String getAllContentType() { } 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-api/src/main/java/org/apache/dubbo/metadata/rest/springmvc/PathVariableParameterProcessor.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/springmvc/PathVariableParameterProcessor.java index a1eccd888b9..fe239f62215 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/springmvc/PathVariableParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/springmvc/PathVariableParameterProcessor.java @@ -34,10 +34,8 @@ public String getAnnotationName() { 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-api/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestHeaderParameterProcessor.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestHeaderParameterProcessor.java index 3eaae48e4fc..1edb86fc050 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestHeaderParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestHeaderParameterProcessor.java @@ -36,9 +36,14 @@ public String getAnnotationName() { } @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-api/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestParamParameterProcessor.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestParamParameterProcessor.java index 7549196fe40..ad457d3c94c 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestParamParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestParamParameterProcessor.java @@ -36,8 +36,14 @@ public String getAnnotationName() { } @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-api/src/main/java/org/apache/dubbo/metadata/rest/springmvc/SpringMvcServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/springmvc/SpringMvcServiceRestMetadataResolver.java index f0b1681e5a7..813fdb12b52 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/springmvc/SpringMvcServiceRestMetadataResolver.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/springmvc/SpringMvcServiceRestMetadataResolver.java @@ -58,9 +58,9 @@ public SpringMvcServiceRestMetadataResolver(ApplicationModel applicationModel) { protected boolean supports0(Class serviceType) { // class @Controller or @RequestMapping return isAnnotationPresent(serviceType, CONTROLLER_ANNOTATION_CLASS) - || isAnnotationPresent(serviceType, REQUEST_MAPPING_ANNOTATION_CLASS) - // method @RequestMapping - || isServiceMethodAnnotationPresent(serviceType, REQUEST_MAPPING_ANNOTATION_CLASS_NAME); + || isAnnotationPresent(serviceType, REQUEST_MAPPING_ANNOTATION_CLASS) + // method @RequestMapping + || isServiceMethodAnnotationPresent(serviceType, REQUEST_MAPPING_ANNOTATION_CLASS_NAME); } @Override @@ -92,14 +92,16 @@ protected String resolveRequestPath(Method serviceMethod, Class serviceType, } @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); @@ -153,10 +155,12 @@ private Annotation getRequestMapping(AnnotatedElement annotatedElement) { // 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-api/src/main/java/org/apache/dubbo/metadata/rest/tag/BodyTag.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/tag/BodyTag.java index a1038c8718b..c308bcee0ba 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/tag/BodyTag.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/tag/BodyTag.java @@ -19,5 +19,4 @@ /** * for @RequestBody class no found */ -public interface BodyTag { -} +public interface BodyTag {} diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/tag/ParamTag.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/tag/ParamTag.java index 66249b43aa2..cfc16e36642 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/tag/ParamTag.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/tag/ParamTag.java @@ -19,5 +19,4 @@ /** * for @RequestParam or @QueryParam class no found */ -public interface ParamTag { -} +public interface ParamTag {} 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 14432ee0a17..3cd01884d85 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 @@ 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 @@ void testGetServices() { 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 @@ void testGetAndListener() { 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 @@ public Set getAndListen(URL url, MappingListener mappingListener) { } @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 @@ public Set getAndListen(URL url, MappingListener mappingListener) { } @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 @@ public boolean hasValidMetadataCenter() { 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 index 3de6ab8bfb3..826baae4aa2 100644 --- 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 @@ -20,7 +20,6 @@ import java.util.List; - /** * DemoService */ @@ -33,5 +32,4 @@ public interface DemoService { 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 d9f3f82b9de..8c483739fc5 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 @@ 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.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 @@ * 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 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 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 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 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"); @Test void testEmptyRevision() { @@ -175,7 +176,6 @@ void testJsonFormat() { metadataInfo2.addService(url); metadataInfo2.addService(url2); System.out.println(JsonUtils.toJson(metadataInfo2)); - } @Test @@ -198,7 +198,7 @@ void testJdkSerialize() throws IOException, ClassNotFoundException, NoSuchFieldE 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 @@ void testCal() { 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/PathMatcherTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/PathMatcherTest.java index b46675c3bf8..875b589b2bf 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/PathMatcherTest.java +++ b/dubbo-metadata/dubbo-metadata-api/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 @@ void testEqual() { pathMatherMeta1.setContextPath("context"); - Assertions.assertEquals(pathMatherMeta, pathMatherMeta1); Assertions.assertEquals(pathMatherMeta.toString(), pathMatherMeta1.toString()); } @@ -84,20 +83,15 @@ void testMethodCompare() { 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-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 322359fa00b..00000000000 --- 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/TestMediaType.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/TestMediaType.java index f81509e0ca8..1a6fbad425e 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/TestMediaType.java +++ b/dubbo-metadata/dubbo-metadata-api/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-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 ac1b22d7f1f..d6fe8a2feb6 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 d0e0de43d65..14075ffeed6 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 String[] serviceParamsIncluded() { @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 ac347fd5f79..8fe4c177f42 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 String[] serviceParamsIncluded() { @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 0f2d3cb4b61..226bd62f3a1 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.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 @@ public void setUp() { 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 @@ public void setUp() { 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 @@ void test() { 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 90950b50e85..6e9743431b4 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 @@ void getUniqueKey() { @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 3b6ce9103cc..c21dd934b10 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 @@ void getUniqueKey() { @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 810c668a626..476623e4ea6 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 @@ void testGetUniqueKey() { 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 71727034484..f8c3dae0d9a 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.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 @@ protected MetadataReport createMetadataReport(URL url) { 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 @@ public List getExportedURLs(ServiceMetadataIdentifier metadataIdentifier } @Override - public void destroy() { - - } + public void destroy() {} @Override public List getSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) { @@ -80,9 +74,7 @@ public List getSubscribedURLs(SubscriberMetadataIdentifier subscriberMet } @Override - public void removeServiceAppMappingListener(String serviceKey, MappingListener listener) { - - } + public void removeServiceAppMappingListener(String serviceKey, MappingListener listener) {} @Override public boolean shouldReportDefinition() { @@ -100,20 +92,20 @@ public String getServiceDefinition(MetadataIdentifier consumerMetadataIdentifier } @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 @@ void testGetOneMetadataReport() { 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 @@ void testGetOneMetadataReportForIpFormat() { @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 @@ void testGetForDiffService() { @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 a64ab817a7b..66bbf796467 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.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.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 @@ public void before() { // 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 @@ public void reset() { @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 @@ void testStoreProviderUsual() throws ClassNotFoundException { 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 @@ void testStoreProviderSync() throws ClassNotFoundException { 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 @@ void testFileExistAfterPut() throws ClassNotFoundException { 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 @@ void testRetry() throws ClassNotFoundException { 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 @@ void testRetryCancel() throws ClassNotFoundException { 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 @@ void testRetryCancel() throws ClassNotFoundException { 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"); - - MetadataIdentifier providerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE, application); + 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); 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 @@ void testPublishAll() throws ClassNotFoundException { 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 @@ void testCalculateStartTime() { } } - private void checkParam(Map map, String application, String version) { assertEquals(map.get("application"), application); assertEquals(map.get("version"), version); @@ -306,48 +348,54 @@ public NewMetadataReport(URL metadataReportURL, ApplicationModel applicationMode } @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 @@ public RetryMetadataReport(URL metadataReportURL, int needRetryTimes, Applicatio } @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 @@ protected void doStoreProviderMetadata(MetadataIdentifier providerMetadataIdenti } @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 @@ protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdenti @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/rest/DefaultRestService.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/DefaultRestService.java index fd0f36cc62c..56075447d5d 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/DefaultRestService.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/DefaultRestService.java @@ -64,19 +64,13 @@ public Map requestBodyUser(User user) { } @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-api/src/test/java/org/apache/dubbo/metadata/rest/NoAnnotationApiDemoResolverTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/NoAnnotationApiDemoResolverTest.java index ad51ea27409..44e378e338c 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/NoAnnotationApiDemoResolverTest.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/NoAnnotationApiDemoResolverTest.java @@ -19,18 +19,21 @@ import org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver; import org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; + public class NoAnnotationApiDemoResolverTest { - private JAXRSServiceRestMetadataResolver jaxrsServiceRestMetadataResolver = new JAXRSServiceRestMetadataResolver(ApplicationModel.defaultModel()); - private SpringMvcServiceRestMetadataResolver springMvcServiceRestMetadataResolver = new SpringMvcServiceRestMetadataResolver(ApplicationModel.defaultModel()); + private JAXRSServiceRestMetadataResolver jaxrsServiceRestMetadataResolver = + new JAXRSServiceRestMetadataResolver(ApplicationModel.defaultModel()); + private SpringMvcServiceRestMetadataResolver springMvcServiceRestMetadataResolver = + new SpringMvcServiceRestMetadataResolver(ApplicationModel.defaultModel()); @Test void testNoAnnotationApiResolver() { @@ -60,5 +63,3 @@ interface NoAnnotationApiDemo { String test(String test); } - - diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/RestService.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/RestService.java index 60c78cf3ae4..049335e0f54 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/RestService.java +++ b/dubbo-metadata/dubbo-metadata-api/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-api/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java index de26899585e..05c3fea7ef6 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java @@ -18,17 +18,17 @@ 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.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.PostMapping; import org.springframework.web.bind.annotation.RequestBody; - -import java.util.HashMap; -import java.util.Map; +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 String param(@RequestParam(defaultValue = "value-param") String param) { @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 String form(@RequestParam("f") String form) { @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 Map requestBodyUser(@RequestBody User user) { @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-api/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java index 44ee3514c6d..45b84b9ce34 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java @@ -28,14 +28,17 @@ 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 String params(@QueryParam("a") int a, @QueryParam("b") String b) { @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 String headers(@HeaderParam("h") String header, @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 String form(@FormParam("f") String form) { @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 Map requestBodyUser(User user) { @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-api/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestDoubleCheckContainsPathVariableService.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestDoubleCheckContainsPathVariableService.java index 8f5e7c1e112..324ba19adeb 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestDoubleCheckContainsPathVariableService.java +++ b/dubbo-metadata/dubbo-metadata-api/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-api/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestDoubleCheckService.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestDoubleCheckService.java index ad0b3658c9d..389af5e78c9 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestDoubleCheckService.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestDoubleCheckService.java @@ -23,6 +23,7 @@ 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-api/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestService.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestService.java index ff9909ddb28..3cc8416fbdc 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestService.java +++ b/dubbo-metadata/dubbo-metadata-api/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-api/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestServiceImpl.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestServiceImpl.java index 62cf3578ef5..2f309e28c05 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestServiceImpl.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestServiceImpl.java @@ -22,7 +22,6 @@ public class JaxrsRestServiceImpl implements JaxrsRestService { - @Override public String param(String param) { return param; diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsUsingService.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsUsingService.java index 7490c753414..4bcc761f1d9 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsUsingService.java +++ b/dubbo-metadata/dubbo-metadata-api/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-api/src/test/java/org/apache/dubbo/metadata/rest/api/SpringControllerService.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/SpringControllerService.java index dfea0209051..479714a4d46 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/SpringControllerService.java +++ b/dubbo-metadata/dubbo-metadata-api/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 @@ @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-api/src/test/java/org/apache/dubbo/metadata/rest/api/SpringRestService.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/SpringRestService.java index 3a6e591df17..8a8c727553f 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/SpringRestService.java +++ b/dubbo-metadata/dubbo-metadata-api/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-api/src/test/java/org/apache/dubbo/metadata/rest/api/SpringRestServiceImpl.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/SpringRestServiceImpl.java index 3176f158b87..a9cfb9c3080 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/SpringRestServiceImpl.java +++ b/dubbo-metadata/dubbo-metadata-api/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 int noAnnoNumber(Integer b) { public int noAnnoPrimitive(int c) { return c; } - } diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/jaxrs/JAXRSServiceRestMetadataResolverTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/jaxrs/JAXRSServiceRestMetadataResolverTest.java index 32643ebab7f..e68b995e84e 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/jaxrs/JAXRSServiceRestMetadataResolverTest.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/jaxrs/JAXRSServiceRestMetadataResolverTest.java @@ -31,15 +31,15 @@ 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 @@ */ class JAXRSServiceRestMetadataResolverTest { - private JAXRSServiceRestMetadataResolver instance = new JAXRSServiceRestMetadataResolver(ApplicationModel.defaultModel()); - + private JAXRSServiceRestMetadataResolver instance = + new JAXRSServiceRestMetadataResolver(ApplicationModel.defaultModel()); @Test void testSupports() { @@ -72,7 +72,8 @@ void testSupports() { @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 @@ void testResolve() { assertTrue(CollectionUtils.equals(expectedServiceRestMetadata.getMeta(), serviceRestMetadata.getMeta())); assertEquals(expectedServiceRestMetadata, serviceRestMetadata); - } @Test @@ -90,25 +90,21 @@ void testResolves() { 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 @@ public int compare(String o1, String o2) { 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 @@ void testJaxrsPathPattern() { } } - - 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-api/src/test/java/org/apache/dubbo/metadata/rest/jaxrs/JaxrsRestDoubleCheckTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/jaxrs/JaxrsRestDoubleCheckTest.java index 3e8f129f204..362e7f3acbd 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/jaxrs/JaxrsRestDoubleCheckTest.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/jaxrs/JaxrsRestDoubleCheckTest.java @@ -23,14 +23,15 @@ 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 @@ void testDoubleCheckException() { resolve.setServiceInterface(JaxrsRestDoubleCheckContainsPathVariableService.class.getName()); instance.resolve(JaxrsRestDoubleCheckContainsPathVariableService.class, resolve); }); - - } @Test @@ -63,14 +62,12 @@ void testSameHttpMethodException() { 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-api/src/test/java/org/apache/dubbo/metadata/rest/springmvc/SpringMvcServiceRestMetadataResolverTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/springmvc/SpringMvcServiceRestMetadataResolverTest.java index a79c6e50610..4c96e383345 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/springmvc/SpringMvcServiceRestMetadataResolverTest.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/springmvc/SpringMvcServiceRestMetadataResolverTest.java @@ -30,16 +30,16 @@ 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 @@ */ class SpringMvcServiceRestMetadataResolverTest { - private SpringMvcServiceRestMetadataResolver instance = new SpringMvcServiceRestMetadataResolver(ApplicationModel.defaultModel()); + private SpringMvcServiceRestMetadataResolver instance = + new SpringMvcServiceRestMetadataResolver(ApplicationModel.defaultModel()); @Test void testSupports() { @@ -71,7 +72,8 @@ void testSupports() { @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 @@ void testResolve() { assertTrue(CollectionUtils.equals(expectedServiceRestMetadata.getMeta(), serviceRestMetadata.getMeta())); assertEquals(expectedServiceRestMetadata, serviceRestMetadata); - } @Test @@ -92,23 +93,19 @@ void testResolves() { 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 @@ public int compare(String o1, String o2) { 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 @@ void testDoubleCheck() { 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/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 ad4f052954f..fc26020f2a3 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 @@ */ 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 @@ public JTestMetadataReport4Test(URL url) { 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 @@ protected void doStoreProviderMetadata(MetadataIdentifier providerMetadataIdenti } @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 @@ public String getServiceDefinition(MetadataIdentifier consumerMetadataIdentifier } @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 6e264083008..cf29a350315 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 eb248b434c6..486601be2b5 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 a6b4850ad6c..18ba0a37a3c 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.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.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 @@ private GeneratedMessageV3.Builder getMessageBuilder(Class requestType) throw 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 @@ private TypeDefinition buildProtobufTypeDefinition(Class clazz, GeneratedMess 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 @@ private TypeDefinition buildProtobufTypeDefinition(Class clazz, GeneratedMess 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 @@ private String generateListFieldName(String methodName) { 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 @@ private boolean isSimplePropertySettingMethod(Method method) { return !methodName.endsWith("Value") || types[0] != int.class; } - /** * judge List property
* proto3 grammar ex: repeated string names;
@@ -276,7 +277,6 @@ boolean isListPropertyGettingMethod(Method method) { 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 559d313f46c..f3d1921efa0 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.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 @@ void testProtobufBuilder() { 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 22a45ad5ae9..a70d0aff240 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) {} + + 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), + ; + + /** + * 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; + } + + /** + * @deprecated Use {@link #forNumber(int)} instead. + */ + @java.lang.Deprecated + public static PhoneType valueOf(int value) { + return forNumber(value); + } + + 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 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< + 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 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; + } + 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_; + } + + 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< + ? extends org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumberOrBuilder> + 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 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 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 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; + } + } + + 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; + } + 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(); + } + } + + 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; + } + } + /** + * 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); + } -package org.apache.dubbo.metadata.definition.protobuf.model; + 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 final class GooglePB { - private GooglePB() {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistryLite registry) { - } - - 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 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); + } - /** - * 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 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 final int getNumber() { - return value; - } + 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); + } - /** - * @deprecated Use {@link #forNumber(int)} instead. - */ - @java.lang.Deprecated - public static PhoneType valueOf(int value) { - return forNumber(value); - } + public Builder newBuilderForType() { + return newBuilder(); + } - 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 Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } - 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 static Builder newBuilder( + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } - 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); - } + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } - private static final PhoneType[] VALUES = values(); + @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; + } - 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()]; - } + 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 final int value; + // Construct using org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } - private PhoneType(int value) { - this.value = value; - } + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } - // @@protoc_insertion_point(enum_scope:org.apache.dubbo.metadata.definition.protobuf.model.PhoneType) - } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { + getCDubboPBRequestTypeFieldBuilder(); + } + } - public interface PBRequestTypeOrBuilder extends - // @@protoc_insertion_point(interface_extends:org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType) - com.google.protobuf.MessageOrBuilder { + public Builder clear() { + super.clear(); + msg_ = ""; + bitField0_ = (bitField0_ & ~0x00000001); + if (cDubboPBRequestTypeBuilder_ == null) { + cDubboPBRequestType_ = null; + } else { + cDubboPBRequestTypeBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000002); + return this; + } - /** - * optional double money = 1; - */ - boolean hasMoney(); - /** - * optional double money = 1; - */ - double getMoney(); + 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; + } - /** - * optional float cash = 2; - */ - boolean hasCash(); - /** - * optional float cash = 2; - */ - float getCash(); + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType + getDefaultInstanceForType() { + return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType.getDefaultInstance(); + } - /** - * optional int32 age = 3; - */ - boolean hasAge(); - /** - * optional int32 age = 3; - */ - int getAge(); + 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; + } - /** - * optional int64 num = 4; - */ - boolean hasNum(); - /** - * optional int64 num = 4; - */ - long getNum(); + 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; + } - /** - * optional bool sex = 5; - */ - boolean hasSex(); - /** - * optional bool sex = 5; - */ - boolean getSex(); + public Builder clone() { + return (Builder) super.clone(); + } - /** - * optional string name = 6; - */ - boolean hasName(); - /** - * optional string name = 6; - */ - java.lang.String getName(); - /** - * optional string name = 6; - */ - com.google.protobuf.ByteString - getNameBytes(); + public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.setField(field, value); + } - /** - * optional bytes msg = 7; - */ - boolean hasMsg(); - /** - * optional bytes msg = 7; - */ - com.google.protobuf.ByteString getMsg(); + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } - /** - * 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); + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } - /** - * 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; - */ + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } - 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; - */ + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); + } - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDoubleMapOrThrow( - java.lang.String key); + 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; + } + } - /** - * 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); + 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; + } - /** - * 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; - */ + public final boolean isInitialized() { + if (hasCDubboPBRequestType()) { + if (!getCDubboPBRequestType().isInitialized()) { + return false; + } + } + return true; + } - com.google.protobuf.ByteString getBytesMapOrDefault( - java.lang.String key, - com.google.protobuf.ByteString defaultValue); - /** - * map<string, bytes> bytesMap = 11; - */ + 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; + } - 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(); - } + private int bitField0_; - @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; - } - } - } - } 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 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; - } + 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; + } - @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 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_; + } - 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 final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFields(unknownFields); + } - 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 final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } - 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_; - } + // @@protoc_insertion_point(builder_scope:org.apache.dubbo.metadata.definition.protobuf.model.PBResponseType) + } - 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_; - } + // @@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; - 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_; - } + static { + DEFAULT_INSTANCE = new org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType(); + } - 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; - } - 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 org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType getDefaultInstance() { + return DEFAULT_INSTANCE; + } - 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_; - } + @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 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 com.google.protobuf.Parser parser() { + return PARSER; + } - 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_; - } + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } - public int getDoubleMapCount() { - return internalGetDoubleMap().getMap().size(); + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } } - /** - * 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 interface PhoneNumberOrBuilder + extends + // @@protoc_insertion_point(interface_extends:org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber) + com.google.protobuf.MessageOrBuilder { - public java.util.Map getDoubleMapMap() { - return internalGetDoubleMap().getMap(); - } - /** - * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; - */ + /** + * required string number = 1; + */ + boolean hasNumber(); + /** + * required string number = 1; + */ + java.lang.String getNumber(); + /** + * required string number = 1; + */ + com.google.protobuf.ByteString getNumberBytes(); - 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; + /** + * 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(); } /** - * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; + * 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; + } + 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 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 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; + } - 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); - } + 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); + } + + 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; + } + 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 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 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 int getBytesMapCount() { - return internalGetBytesMap().getMap().size(); - } - /** - * map<string, bytes> bytesMap = 11; - */ + private byte memoizedIsInitialized = -1; - 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 final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; - public java.util.Map getBytesMapMap() { - return internalGetBytesMap().getMap(); - } - /** - * map<string, bytes> bytesMap = 11; - */ + if (!hasNumber()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; + return true; + } - 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 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 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 int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; - 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; - } + 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; + } - 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); - } + @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; - 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)); - } - 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; - } + 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 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 (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; + } - @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.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.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 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 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); - } + 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); + } - @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(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 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 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_; - } - - 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) - } + 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); + } - // @@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.PhoneNumber parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType getDefaultInstance() { - return DEFAULT_INSTANCE; - } + 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); + } - @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; - } + 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); + } - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } + 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 org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } + 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 interface PBResponseTypeOrBuilder extends - // @@protoc_insertion_point(interface_extends:org.apache.dubbo.metadata.definition.protobuf.model.PBResponseType) - com.google.protobuf.MessageOrBuilder { + 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); + } - /** - * optional string msg = 1; - */ - boolean hasMsg(); - /** - * optional string msg = 1; - */ - java.lang.String getMsg(); - /** - * optional string msg = 1; - */ - com.google.protobuf.ByteString - getMsgBytes(); + 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); + } - /** - * 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_ = ""; - } + public Builder newBuilderForType() { + return newBuilder(); + } - @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; - } - 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(); - } - } - 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; - } + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } - 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); - } + public static Builder newBuilder( + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } - 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; - } - } - /** - * 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 Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } - 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_; - } + @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; + } - private byte memoizedIsInitialized = -1; - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) return true; - if (isInitialized == 0) return false; + 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); + } - if (hasCDubboPBRequestType()) { - if (!getCDubboPBRequestType().isInitialized()) { - memoizedIsInitialized = 0; - return false; - } - } - memoizedIsInitialized = 1; - return true; - } + // Construct using org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } - 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); - } + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } - 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; - } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} + } - @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; - } + public Builder clear() { + super.clear(); + number_ = ""; + bitField0_ = (bitField0_ & ~0x00000001); + type_ = 1; + bitField0_ = (bitField0_ & ~0x00000002); + return this; + } - @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 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 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 org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber + getDefaultInstanceForType() { + return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.getDefaultInstance(); + } - 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); - } + 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; + } - @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; - 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) - } + 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; + } - // @@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 Builder clone() { + return (Builder) super.clone(); + } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType getDefaultInstance() { - return DEFAULT_INSTANCE; - } + public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.setField(field, value); + } - @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; - } + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } + 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 interface PhoneNumberOrBuilder extends - // @@protoc_insertion_point(interface_extends:org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber) - com.google.protobuf.MessageOrBuilder { + 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; + } + } - /** - * required string number = 1; - */ - boolean hasNumber(); - /** - * required string number = 1; - */ - java.lang.String getNumber(); - /** - * required string number = 1; - */ - com.google.protobuf.ByteString - getNumberBytes(); + 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; + } - /** - * 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; - } + public final boolean isInitialized() { + if (!hasNumber()) { + return false; + } + return true; + } - @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; - } - 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 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; - } + 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; + } - 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); - } + private int bitField0_; - 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; - } - 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; - } - } + 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; + } - 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; - } + 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; + } - private byte memoizedIsInitialized = -1; - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) return true; - if (isInitialized == 0) return false; - - if (!hasNumber()) { - memoizedIsInitialized = 0; - return false; - } - memoizedIsInitialized = 1; - return true; - } + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFields(unknownFields); + } - 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 final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } - 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; - } + // @@protoc_insertion_point(builder_scope:org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber) + } - @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; - } + // @@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; - @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; - } + static { + DEFAULT_INSTANCE = new org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber(); + } - 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 static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDefaultInstance() { + return DEFAULT_INSTANCE; + } - 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.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); + } + }; - @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) - } + public static com.google.protobuf.Parser parser() { + return PARSER; + } - // @@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(); - } + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDefaultInstance() { - return DEFAULT_INSTANCE; + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDefaultInstanceForType() { + 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; - } + 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; - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; + public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { + return descriptor; } - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } + private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - } - - 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; - } + 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 - .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) + 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) } diff --git a/dubbo-metadata/dubbo-metadata-processor/pom.xml b/dubbo-metadata/dubbo-metadata-processor/pom.xml index 0cb2c9139d5..32ae35bf52e 100644 --- a/dubbo-metadata/dubbo-metadata-processor/pom.xml +++ b/dubbo-metadata/dubbo-metadata-processor/pom.xml @@ -15,150 +15,148 @@ ~ 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-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-rpc-api - - - org.apache.dubbo - dubbo-cluster - - - + + + org.apache.dubbo + dubbo-metadata-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-rpc-api + + + org.apache.dubbo + dubbo-cluster + + + - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - javax.annotation - javax.annotation-api - + + org.apache.dubbo + dubbo-common + ${project.parent.version} + + + javax.annotation + javax.annotation-api + - - org.slf4j - slf4j-api - + + org.slf4j + slf4j-api + - - commons-logging - commons-logging - - - log4j - log4j - + + commons-logging + commons-logging + + + log4j + log4j + - - org.apache.logging.log4j - log4j-api - + + org.apache.logging.log4j + log4j-api + - - org.apache.logging.log4j - log4j-core - - - org.javassist - javassist - - - com.alibaba - hessian-lite - - - com.esotericsoftware - kryo - - - de.javakaffee - kryo-serializers - - - de.ruedigermoeller - fst - - - commons-io - commons-io - - + + org.apache.logging.log4j + log4j-core + + + org.javassist + javassist + + + com.alibaba + hessian-lite + + + com.esotericsoftware + kryo + + + de.javakaffee + kryo-serializers + + + de.ruedigermoeller + fst + + + commons-io + commons-io + + - + - - - 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 d65c6ba7e8a..c5c64e8e474 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.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 static String getMethodSignature(ExecutableElement method) { 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 9e1032c590d..a40a3404395 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 @@ private boolean exists(String resourceName) { } 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 @@ private Optional getResource(String resourceName) { 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 cf8b45695eb..244cde36afc 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.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 boolean process(Set annotations, RoundEnvironment 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 26aa10dfcca..e1ed3677d63 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 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 boolean accept(ProcessingEnvironment processingEnv, TypeMirror type) { } @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 7f7be241857..21c3e927fdd 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.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 boolean accept(ProcessingEnvironment processingEnv, DeclaredType type) { } @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 bc3b05cbba9..51bf9c8d840 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.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 boolean accept(ProcessingEnvironment processingEnv, DeclaredType type) { } @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 1e907e72454..c64d8005088 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 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 boolean accept(ProcessingEnvironment processingEnv, DeclaredType type) { } @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 TypeDefinition build(ProcessingEnvironment processingEnv, DeclaredType ty 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 1045fcb27d4..e58a43f9882 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.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 boolean accept(ProcessingEnvironment processingEnv, DeclaredType type) { } @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 c91f96f208f..0fa96c3ffe2 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 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 @@ */ 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 @@ static MethodDefinition build(ProcessingEnvironment processingEnv, ExecutableEle 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 6153917f84d..e8577723ddd 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 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 boolean accept(ProcessingEnvironment processingEnv, TypeMirror type) { } @Override - public TypeDefinition build(ProcessingEnvironment processingEnv, PrimitiveType type, Map 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 4fe27b5ce80..669945a56d2 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 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 @@ static ServiceDefinition build(ProcessingEnvironment processingEnv, TypeElement .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 172d8aa3ab9..d133fe2aee2 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 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 boolean accept(ProcessingEnvironment processingEnv, DeclaredType type) { } @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 1df9dcd2f12..6feefaf6c36 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 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 b7170371451..f7dcf08035f 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 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 @@ static TypeDefinition build(ProcessingEnvironment processingEnv, Element element * @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 df79c4fbdbb..142429e0f3d 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 @@ 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 a52bd25710b..a2a388d34da 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.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 @@ */ 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 final ServiceRestMetadata resolve(ProcessingEnvironment processingEnv, 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 final ServiceRestMetadata resolve(ProcessingEnvironment processingEnv, 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 @@ protected Optional resolveRestMethodMetadata(ProcessingEnvir * @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 @@ private ExecutableElement findRestCapableMethod(ProcessingEnvironment processing * @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 @@ protected abstract boolean supports(ProcessingEnvironment processingEnv, * @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 @@ protected void processAnnotatedMethodParameters(ExecutableElement method, TypeEl } } - 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 @@ protected static final V computeIfAbsent(String name, Function> 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 85f0f8a87da..dd97c2dbd35 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 21289678786..24875726827 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.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 @@ protected String resolveRequestPath(ProcessingEnvironment processingEnv, TypeEle 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 @@ private boolean supportsPathVariableType(TypeMirror parameterType) { 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 @@ private boolean supportsPathVariableType(TypeMirror parameterType) { } @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 @@ protected void processProduces(ProcessingEnvironment processingEnv, TypeElement } @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 e4d904a1cbc..e9f0c8bed51 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.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 boolean process(Set annotations, RoundEnvironment 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 9e431f1f16e..ed29a2d909d 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 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 a24f6b789fd..14a14c24eb8 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.rest.ServiceRestMetadata; import javax.annotation.processing.ProcessingEnvironment; + import java.io.IOException; import java.util.Set; @@ -40,18 +41,19 @@ public ServiceRestMetadataStorage(ProcessingEnvironment processingEnv) { 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 void write(Set serviceRestMetadata) throws IOExcepti } 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 f5c5a6235cd..213d2647b40 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 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 String getAnnotationType() { } @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 f4ccddf2d63..5579904e702 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 String getAnnotationType() { } @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 02e52a2f64f..fcfc9f341fb 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.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 static boolean supports(TypeElement serviceType) { } @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 d615cdcb33f..8052fc91237 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 @@ */ 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 1fa5285ef20..2d9cf8dfb51 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 @@ */ 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 c28b88083e8..49a5f747e8f 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 String getAnnotationType() { } @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 e589c0d7dba..f881f1ca12b 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 String getAnnotationType() { } @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 e33fdb3f1d0..bcf1d6edd79 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.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 boolean supports(ProcessingEnvironment processingEnvironment, TypeElement } @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 @@ protected String resolveRequestPath(ProcessingEnvironment processingEnv, TypeEle 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 @@ private AnnotationMirror getRequestMapping(Element element) { } @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 @@ private void addMediaTypes(ExecutableElement method, String annotationAttributeN } 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 176043be902..5a8f0254073 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.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 @@ */ 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 @@ static AnnotationMirror getAnnotation(AnnotatedConstruct annotatedConstruct, Cha 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 @@ static List getAnnotations(AnnotatedConstruct annotatedConstru 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 @@ static List getAllAnnotations(TypeMirror type, Class 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 @@ static List getAllAnnotations(TypeMirror type, CharSequence an } 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 @@ static List getAllAnnotations(TypeMirror type, Predicate 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 @@ static List getAllAnnotations(ProcessingEnvironment processing 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 @@ static AnnotationMirror findAnnotation(Element element, Class 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 @@ static AnnotationMirror findMetaAnnotation(Element annotatedConstruct, CharSeque } 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 31603faabef..362c572bf97 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 javax.lang.model.element.ExecutableElement; import javax.lang.model.element.VariableElement; + import java.util.Comparator; import java.util.List; @@ -36,10 +37,9 @@ */ 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 int compare(ExecutableElement e1, ExecutableElement e2) { if (value == 0) { // Step 3 for (int i = 0; i < ps1.size(); i++) { - value = CharSequenceComparator.INSTANCE.compare(ps1.get(i).getSimpleName(), ps2.get(i).getSimpleName()); + value = CharSequenceComparator.INSTANCE.compare( + ps1.get(i).getSimpleName(), ps2.get(i).getSimpleName()); if (value != 0) { break; } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/FieldUtils.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/FieldUtils.java index b0b2b3ef0b0..b56c082ef46 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/FieldUtils.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/FieldUtils.java @@ -20,6 +20,7 @@ import javax.lang.model.element.Modifier; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; + import java.util.Collection; import java.util.List; import java.util.function.Predicate; @@ -71,8 +72,7 @@ static List getAllDeclaredFields(Element element) { } static List 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 @@ static VariableElement getDeclaredField(Element element, String fieldName) { } 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 @@ static List getAllNonStaticFields(Element element) { } 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 9bac9d65dcf..b8a6b440513 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 800b4ba1fd8..5b5cbdf2a3d 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.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 @@ static List getDeclaredMembers(TypeMirror type) { } 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 0bd2ae900e0..6aa5c9b180a 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 @@ static List getDeclaredMethods(TypeMirror type, Predicate getAllDeclaredMethods(TypeElement type, Predicate... methodFilters) { + static List getAllDeclaredMethods( + TypeElement type, Predicate... methodFilters) { return type == null ? emptyList() : getAllDeclaredMethods(type.asType(), methodFilters); } @@ -67,9 +68,9 @@ static List getAllDeclaredMethods(TypeElement type) { 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 @@ static List getAllDeclaredMethods(TypeElement type, Type... e } 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 @@ static boolean isPublicNonStaticMethod(ExecutableElement method) { 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 @@ static ExecutableElement findMethod(TypeElement type, String methodName, CharSeq } 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 @@ static String getReturnType(ExecutableElement method) { } 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 6f0010b5500..ffda6e42b2d 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 @@ 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 @@ static AnnotationMirror getAnnotation(Iterable annot } 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 2f877e6bc59..0e85171fdac 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.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 @@ */ 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 @@ static Set getHierarchicalTypes(TypeMirror type, Predicate 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 @@ static Set getHierarchicalTypes(TypeElement type, 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 @@ static TypeElement ofTypeElement(TypeMirror type) { } 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 @@ static Set ofDeclaredTypes(Iterable elements) { } 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 @@ static URL getResource(ProcessingEnvironment processingEnv, CharSequence type) { 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 fb0421eb91b..cbb0a5da771 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 @@ 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 a02432711be..4b21c6437ff 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 fe97b4b4b87..44689fe64e1 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 @@ 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 cd84396e6d3..779cbd08b8c 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.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 @@ void testBuild() { 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 e99d4177842..865613a496e 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 @@ 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 @@ protected void addCompiledClasses(Set> classesToBeCompiled) { 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 @@ void testAccept() { @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 49572e708e2..d3a7261f577 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.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 @@ void testBuild() { 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 8ca703aa320..7a930e5924d 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.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 @@ protected void beforeEach() { @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 4f486846063..dd7944c66ec 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.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 @@ protected void beforeEach() { 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 @@ void testAccept() { @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 @@ static void buildAndAssertTypeDefinition(ProcessingEnvironment processingEnv, Va 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 3c9774cf6c7..db714bde3fd 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.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 @@ protected void beforeEach() { 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 @@ void testBuild() { 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 9906f12975d..0f57ba37785 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.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 @@ */ 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 @@ void testBuild() { "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 08f008d394c..10118ee8bdf 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 @@ 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 28bf4f31113..8c8a63a8f54 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 @@ */ 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 e90f1c8926e..f3704322039 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 9fab9df62de..e1fc517bee7 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 @@ * @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 087aa932ed6..fb582960342 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 79a50e304c6..1bb202d91d4 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.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.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 @@ void testGetAnnotations() { 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 @@ void testGetAllAnnotations() { 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 @@ void testGetAllAnnotations() { 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 @@ void testFindAnnotation() { @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 @@ void testGetAttribute() { 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 @@ void testGetValue() { @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 74b69cc72df..d2e5f72e2a1 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.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.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 @@ void testIsField() { 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 59a1b4545a4..7b43a1210e7 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.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 dca4090df5d..ee3ecc4eac1 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.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 @@ void testIsMethod() { @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 @@ void testReturnType() { @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 309956ba501..4cab1c49c9d 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.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 @@ 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 @@ void testConstants() { 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 @@ void testIsServiceAnnotationPresent() { @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 @@ void testGetAnnotation() { @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 04e86e77ff3..282c5c470cb 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.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.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 @@ void testIsClassType() { @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 @@ void testGetHierarchicalTypes() { 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 @@ void testGetHierarchicalTypes() { 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 @@ void testGetHierarchicalTypes() { 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 @@ void testGetHierarchicalTypes() { 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 @@ void testGetHierarchicalTypes() { 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 @@ void testGetHierarchicalTypes() { 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 @@ void testGetHierarchicalTypes() { assertTrue(getHierarchicalTypes((TypeMirror) null).isEmpty()); } - @Test void testGetInterfaces() { TypeElement type = getType(Model.class); @@ -296,7 +328,8 @@ void testGetInterfaces() { 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 @@ void testGetAllInterfaces() { 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 @@ void testGetAllInterfaces() { 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 @@ void testOfTypeElement() { @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 @@ void testListDeclaredTypes() { 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 @@ void testListTypeElements() { 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 65d67ab475d..7b6883780da 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 c2daf9b1045..b475bd53da8 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 @@ 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.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 String param(@RequestParam(defaultValue = "value-param") String param) { @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 String form(@RequestParam("f") String form) { @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 684d76fd3b2..2f7d57e557b 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.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 String params(@QueryParam("a") int a, @QueryParam("b") String b) { @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 String headers(@HeaderParam("h") String header, @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 String form(@FormParam("f") String form) { @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 e2f27dd3064..5874ad05620 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.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 @@ private File javaSourceFile(String sourceClassName) { } 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 071e1b26c8f..762e297d362 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 d7b73c4abcc..9b020d2ca4d 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.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 85bce6924dd..bb2bc21b635 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 @@ * * @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 c6f540347b6..40187adfc35 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 @@ * * @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 5f0ed6e0931..b8ea68c957f 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.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 ce17abd5921..5871c21fefe 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.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 e55fdf3da4f..84c8199dc7d 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.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 cb8ae82354a..42cdaa1811d 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.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 ProcessingEnvironment getProcessingEnvironment() { 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 83c0ef6affe..83fdf165e8f 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.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 7bb1bf0c061..f9745473e50 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 @@ 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 String echo(String message) { } @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 2c07e58543e..9b716b33adf 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 3fb52fbc700..a7125260121 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 @@ private String handleInnerSymbol(String data) { } 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 c3a16d4c432..bdd5e83006b 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.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 @@ private NacosConfigServiceWrapper buildConfigService(URL url) { 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 @@ private NacosConfigServiceWrapper buildConfigService(URL url) { } 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 @@ private Properties buildNacosProperties(URL url) { } 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 @@ private static void putPropertyIfAbsent(URL url, Properties properties, String p 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 @@ private String getConfig(String dataId, String group) { } 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 @@ private void removeCasServiceMappingListener(String serviceKey, String group, Ma 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 @@ private String buildListenerKey(String key, String group) { 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 @@ private void deleteMetadata(BaseMetadataIdentifier identifier) { 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 @@ private String getConfig(BaseMetadataIdentifier identifier) { 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 Executor getExecutor() { @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 2cff74c9a1b..a858a0a1b1b 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 a2970e282ee..e362a88a5f2 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 String getConfigAndSignListener(String dataId, String group, long timeout } @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 boolean removeConfig(String dataId, String group) { } @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 String getServerStatus() { } @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 8ff2d826f3a..ce4a6b514a8 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,19 +16,19 @@ */ 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 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 com.alibaba.nacos.api.NacosFactory; -import com.alibaba.nacos.api.config.ConfigService; -import com.alibaba.nacos.api.exception.NacosException; - 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; @@ -45,12 +45,13 @@ public String getServerStatus() { 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 @@ public String getServerStatus() { } } } + @Test void testDisable() { try (MockedStatic nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) { @@ -69,13 +71,14 @@ public String getServerStatus() { 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 @@ public String getServerStatus() { 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 708178b432e..e35b79374aa 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 47097f22142..453aee6f48f 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.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.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 @@ private void storeMetadata(BaseMetadataIdentifier metadataIdentifier, String v) } 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 @@ private void deleteMetadata(BaseMetadataIdentifier metadataIdentifier) { } 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 @@ private String getMetadata(BaseMetadataIdentifier metadataIdentifier) { } 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 @@ private String getMetadataStandalone(BaseMetadataIdentifier metadataIdentifier) 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 bd0887753fa..d871877f6b7 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 @@ */ 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 0a8d51ba6a3..357b2175457 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 @@ */ 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 0306e960503..ebfce5de95e 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.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.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 @@ 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 @@ public void constructor(final TestInfo testInfo) { 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 @@ public void constructor(final TestInfo testInfo) { 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 @@ void testSyncStoreProvider() throws ClassNotFoundException { 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 @@ void testSyncStoreConsumer() throws ClassNotFoundException { 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 @@ private void testStoreConsumer(RedisMetadataReport redisMetadataReport, String v } } - 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 @@ private MetadataIdentifier storePrivider(RedisMetadataReport redisMetadataReport 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 @@ void testWrongAuthRedisMetadata() throws ClassNotFoundException { 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 6df0fc86cc9..7a344bdfdde 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 + + + + + + curator5 + + [17,) + + - org.apache.curator - curator-framework - test - - - org.apache.curator - curator-recipes - test - - - org.apache.zookeeper - zookeeper + 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 a7cfa56dbeb..ce01bf0d7c8 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.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.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 @@ */ 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 c628fc858d9..42270d863e3 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 void setZookeeperTransporter(ZookeeperTransporter zookeeperTransporter) { 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 388f32d81fc..cfa83a9ff02 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.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.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 @@ public void setUp() throws Exception { 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 @@ void testStoreProvider() throws ClassNotFoundException, InterruptedException { 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 @@ void testStoreProvider() throws ClassNotFoundException, InterruptedException { 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 @@ void testDoSaveMetadata() throws ExecutionException, InterruptedException { 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 @@ void testDoRemoveMetadata() throws ExecutionException, InterruptedException { 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 @@ void testDoGetExportedURLs() throws ExecutionException, InterruptedException { 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 @@ void testDoSaveSubscriberData() throws ExecutionException, InterruptedException 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 @@ void testDoGetSubscribedURLs() throws ExecutionException, InterruptedException { 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)); - - MetadataIdentifier providerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE, application); + 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); 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)); - - MetadataIdentifier consumerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, CONSUMER_SIDE, application); + 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); Class interfaceClass = Class.forName(interfaceName); Map tmp = new HashMap<>(); @@ -271,13 +299,13 @@ private String waitSeconds(String value, long moreTime, String path) throws Inte } 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 @@ void testMapping() throws InterruptedException { 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(); - } - - @Override - public void stop() { - - } - }, url); + 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); 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 @@ void testAppMetadata() { 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 @@ void testAppMetadata() { appMetadata = zookeeperMetadataReport.getAppMetadata(identifier, Collections.emptyMap()); Assertions.assertNotNull(appMetadata); Assertions.assertEquals(appMetadata.calAndGetRevision(), metadataInfo.calAndGetRevision()); - } } diff --git a/dubbo-metadata/pom.xml b/dubbo-metadata/pom.xml index 2eec45ed63a..81af6197aa6 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-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-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 a35c2383950..15886bd542b 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-rpc-api - ${project.parent.version} - - - io.micrometer - micrometer-core - - - com.tdunning - t-digest - - - io.micrometer - micrometer-tracing-integration-test - test - - + + 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-rpc-api + ${project.parent.version} + + + io.micrometer + micrometer-core + + + com.tdunning + t-digest + + + io.micrometer + micrometer-tracing-integration-test + test + + diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/MetricsConstants.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/MetricsConstants.java index 232de1fa59a..bcc3f1b3843 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/MetricsConstants.java +++ b/dubbo-metrics/dubbo-metrics-api/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"; @@ -31,5 +30,4 @@ public interface MetricsConstants { String ATTACHMENT_DIRECTORY_MAP = "dirNum"; int SELF_INCREMENT_SIZE = 1; - } 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 af7908d026b..a7717c022f3 100755 --- 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 d4e222b9705..8c3fad51dbe 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 b8208bf3ee8..6f5d013a6a0 100755 --- 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 Pane currentPane(long timeMillis) { 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 082f563ebd6..8dface2fbad 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 SampleAggregatedEntry get() { 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 long getCount() { 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 8cf70c7fed7..702e799cea3 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 double get() { } 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 10828a91904..040f543cbdd 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 cac0635f6fc..63c996d0c2a 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 181d51e106b..f3b9b475aba 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 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; } @@ -85,7 +84,6 @@ public void increment(MethodMetric methodMetric, MetricsKeyWrapper wrapper, int this.stats.incrementMethodKey(wrapper, methodMetric, size); } - @Override public void init(Invocation invocation, MetricsKeyWrapper wrapper) { this.stats.initMethodKey(wrapper, invocation); @@ -104,7 +102,6 @@ public void onEvent(TimeCounterEvent event) { eventMulticaster.publishEvent(event); } - @Override public void onEventFinish(TimeCounterEvent event) { eventMulticaster.publishFinishEvent(event); @@ -119,4 +116,3 @@ protected BaseStatComposite getStats() { 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 db07746bc86..03f1becd04c 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 19bd58bba9f..0d61468f045 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 @@ default boolean isCollectEnabled() { */ 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 fc269b87ab7..699236f3fb0 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 95567945d46..049d6b73135 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 d0bfe24bb2f..72e79a94f31 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 @@ */ public class ApplicationStatComposite extends AbstractMetricsExport { - public ApplicationStatComposite(ApplicationModel applicationModel) { super(applicationModel); } @@ -66,7 +64,6 @@ public void incrementSize(MetricsKey metricsKey, int size) { applicationNumStats.get(metricsKey).getAndAdd(size); } - public List export(MetricsCategory category) { List list = new ArrayList<>(); for (MetricsKey type : applicationNumStats.keySet()) { @@ -77,14 +74,14 @@ public List export(MetricsCategory category) { @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 f3fcd2d9974..99b35b135f7 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.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 BaseStatComposite(ApplicationModel applicationModel) { init(new RtStatComposite(applicationModel)); } - protected void init(ApplicationStatComposite applicationStatComposite) { this.applicationStatComposite = applicationStatComposite; } @@ -73,11 +69,13 @@ protected void init(RtStatComposite rtStatComposite) { } 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 void incrementServiceKey(MetricsKeyWrapper metricsKeyWrapper, String attS 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 1e26b7e25c0..a06751553e1 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 void initMethodKey(MetricsKeyWrapper wrapper, Invocation invocation) { 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 void incrementMethodKey(MetricsKeyWrapper wrapper, MethodMetric methodMet } 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 List export(MetricsCategory category) { 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 878349542bb..8ac99e16673 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 void init(MetricsPlaceValue... placeValues) { 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 void init(MetricsPlaceValue... placeValues) { 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 void calcServiceKeyRt(String registryOpType, Long responseTime, Metric ke 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 void calcMethodKeyRt(Invocation invocation, String registryOpType, Long r 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 List export(MetricsCategory category) { 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 List> getRtStats() { 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 1cf214293e0..0a63ad87eee 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 ServiceStatComposite(ApplicationModel applicationModel) { 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 void incrementServiceKey(MetricsKeyWrapper wrapper, String serviceKey, in 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 void incrementExtraServiceKey(MetricsKeyWrapper wrapper, String serviceKe 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 List export(MetricsCategory category) { 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 eebe2011f31..1a976cf8753 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 MetricsDispatcher(ApplicationModel applicationModel) { 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/MetricsEvent.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsEvent.java index 3b22dfa818b..09f590dc037 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsEvent.java +++ b/dubbo-metrics/dubbo-metrics-api/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; @@ -35,7 +34,8 @@ public abstract class MetricsEvent { /** * Metric object. (eg. {@link MethodMetric}) */ - protected transient final ApplicationModel source; + protected final transient ApplicationModel source; + private boolean available = true; private final TypeWrapper typeWrapper; private final String appName; @@ -47,7 +47,8 @@ public MetricsEvent(ApplicationModel source, TypeWrapper typeWrapper) { this(source, null, null, typeWrapper); } - public MetricsEvent(ApplicationModel source, String appName, MetricsDispatcher metricsDispatcher, TypeWrapper typeWrapper) { + public MetricsEvent( + ApplicationModel source, String appName, MetricsDispatcher metricsDispatcher, TypeWrapper typeWrapper) { this.typeWrapper = typeWrapper; if (source == null) { this.source = ApplicationModel.defaultModel(); @@ -106,10 +107,7 @@ public boolean isAvailable() { return available; } - - public void customAfterPost(Object postResult) { - - } + public void customAfterPost(Object postResult) {} public ApplicationModel getSource() { return source; @@ -161,7 +159,6 @@ public final String getNameByType(String type) { return String.format(name, type); } - Type(String name) { this.name = name; } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsEventBus.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsEventBus.java index 74ef55e4c7e..93efea83ef1 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsEventBus.java +++ b/dubbo-metrics/dubbo-metrics-api/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 static void publish(MetricsEvent event) { */ public static T post(MetricsEvent event, Supplier targetSupplier) { return post(event, targetSupplier, null); - } /** diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsEventMulticaster.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsEventMulticaster.java index 459b0744e30..2f1381a7265 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsEventMulticaster.java +++ b/dubbo-metrics/dubbo-metrics-api/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-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 bb01c88d7ef..864cc3c1740 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.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 static MetricsInitEvent toMetricsInitEvent(ApplicationModel applicationMo 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 ed172de6eec..bfc8ae2b91e 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/event/TimeCounterEvent.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEvent.java index 69e7e429251..72bbf0049c3 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEvent.java +++ b/dubbo-metrics/dubbo-metrics-api/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,8 @@ public TimeCounterEvent(ApplicationModel source, TypeWrapper typeWrapper) { this.timePair = TimePair.start(); } - public TimeCounterEvent(ApplicationModel source, String appName, MetricsDispatcher metricsDispatcher, TypeWrapper typeWrapper) { + public TimeCounterEvent( + ApplicationModel source, String appName, MetricsDispatcher metricsDispatcher, TypeWrapper typeWrapper) { super(source, appName, metricsDispatcher, typeWrapper); this.timePair = TimePair.start(); } @@ -41,5 +41,4 @@ public TimeCounterEvent(ApplicationModel source, String appName, MetricsDispatch public TimePair getTimePair() { return timePair; } - } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/exception/MetricsNeverHappenException.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/exception/MetricsNeverHappenException.java index 1f5336611b9..e1969f10a2a 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/exception/MetricsNeverHappenException.java +++ b/dubbo-metrics/dubbo-metrics-api/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-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 2ba791e0e1f..516ce04ae4c 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 @@ * 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 boolean isSupport(MetricsEvent event) { } @Override - public void onEvent(TimeCounterEvent event) { - - } + public void onEvent(TimeCounterEvent event) {} public static AbstractMetricsKeyListener onEvent(MetricsKey metricsKey, Consumer postFunc) { @@ -79,6 +77,4 @@ public void onEventError(TimeCounterEvent event) { } }; } - - } 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 7dc5ed2f777..dce4a8b207a 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 96891e6bb02..018889ec2a8 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 MetricsApplicationListener(MetricsKey metricsKey) { * @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 static AbstractMetricsKeyListener onPostEventBuild(MetricsKey metricsKey, * @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 294be1885a5..67dd2ad8fd6 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 @@ */ 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/MetricsListener.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsListener.java index 3411e6f046b..048625fb02f 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsListener.java +++ b/dubbo-metrics/dubbo-metrics-api/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-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 40f27b18ca3..49fa8c783f1 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 MetricsServiceListener(MetricsKey metricsKey) { 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 c6d2734a8aa..85041ebf932 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 Map hostTags(Map tags) { return MetricsSupport.hostTags(tags); } - public Map getExtraInfo() { return extraInfo; } @@ -69,7 +67,8 @@ public boolean equals(Object o) { 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 int hashCode() { } 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 a6f9987e03d..b778e2efc4c 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 boolean equals(Object o) { 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/MethodMetric.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MethodMetric.java index 6f4ddfffcf1..6d3238d15aa 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 MethodMetric(ApplicationModel applicationModel, Invocation invocation, bo 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 void setSide(String side) { @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 boolean equals(Object o) { 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 c9baa9c0da0..891bd356f16 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 0eecdda807e..e68d127f696 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 ed723192e54..dc7b9e5aa28 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.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 static Map applicationTags(ApplicationModel applicationMo } 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 static String getSide(Invocation invocation) { 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 static String getVersion(Invocation invocation) { /** * 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 static void fillZero(Map> data) { 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 361fd9f06e0..133be3bcbdb 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 boolean equals(Object o) { return serviceKey.equals(that.serviceKey) && Objects.equals(extraInfo, that.extraInfo); } - private volatile int hashCode = 0; @Override @@ -67,9 +65,8 @@ public int hashCode() { @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 002653359b4..0899b66086b 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.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 boolean equals(Object o) { 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 @@ -88,7 +86,7 @@ public int hashCode() { 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); @@ -111,12 +109,11 @@ public double getActiveCount() { 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 87060708477..ce1d35e271b 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; private String threadPoolName; @@ -60,8 +61,8 @@ public boolean equals(Object o) { 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 @@ -72,11 +73,10 @@ public int hashCode() { 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/TimePair.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/TimePair.java index 70e0aba1d67..c00e96bbb74 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/TimePair.java +++ b/dubbo-metrics/dubbo-metrics-api/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-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 73ba419ce8c..f3dcfa6256d 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 AtomicLongContainer(MetricsKeyWrapper metricsKeyWrapper) { 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 1c6952dafd8..adb76e70227 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 dad8fce4bf9..81086448853 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 void setValueSupplier(Function valueSupplier) { @Override public String toString() { - return "LongContainer{" + - "metricsKeyWrapper=" + metricsKeyWrapper + - '}'; + return "LongContainer{" + "metricsKeyWrapper=" + metricsKeyWrapper + '}'; } @Override diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/CategoryOverall.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/CategoryOverall.java index 6afec481060..a0c63100655 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/CategoryOverall.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/CategoryOverall.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.key; - import org.apache.dubbo.common.lang.Nullable; /** @@ -33,7 +31,11 @@ public class CategoryOverall { * @param placeType When placeType is null, it means that placeType is obtained dynamically * @param post Statistics of the number of events, as long as it occurs, it will take effect, so it cannot be null */ - public CategoryOverall(@Nullable MetricsPlaceValue placeType, MetricsCat post, @Nullable MetricsCat finish, @Nullable MetricsCat error) { + public CategoryOverall( + @Nullable MetricsPlaceValue placeType, + MetricsCat post, + @Nullable MetricsCat finish, + @Nullable MetricsCat error) { this.post = post.setPlaceType(placeType); if (finish != null) { this.finish = finish.setPlaceType(placeType); diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsCat.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsCat.java index d085aa7ee98..555cf29ad4d 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsCat.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsCat.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.metrics.collector.CombMetricsCollector; @@ -38,14 +37,17 @@ public class MetricsCat { * @param metricsKey The key corresponding to the listening event, not necessarily the export key(export key may be dynamic) * @param biFunc Binary function, corresponding to MetricsKey with less content, corresponding to post event */ - public MetricsCat(MetricsKey metricsKey, BiFunction biFunc) { + public MetricsCat( + MetricsKey metricsKey, BiFunction biFunc) { this.eventFunc = collector -> biFunc.apply(metricsKey, collector); } /** * @param tpFunc Ternary function, corresponding to finish and error events, because an additional record rt is required, and the type of metricsKey is required */ - public MetricsCat(MetricsKey metricsKey, TpFunction tpFunc) { + public MetricsCat( + MetricsKey metricsKey, + TpFunction tpFunc) { this.eventFunc = collector -> tpFunc.apply(metricsKey, placeType, collector); } @@ -58,7 +60,6 @@ public Function getEventFunc() return eventFunc; } - @FunctionalInterface public interface TpFunction { R apply(T t, U u, K k); diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsKey.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsKey.java index 6b5329edc29..e12b8e5ed7f 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsKey.java +++ b/dubbo-metrics/dubbo-metrics-api/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,7 +130,8 @@ 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"), ; private String name; diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsKeyWrapper.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsKeyWrapper.java index 095cc5f3057..236d7e8052c 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsKeyWrapper.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsKeyWrapper.java @@ -14,14 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.model.key; -import io.micrometer.common.lang.Nullable; import org.apache.dubbo.metrics.model.sample.MetricSample; import java.util.Objects; +import io.micrometer.common.lang.Nullable; + /** * Let {@link MetricsKey MetricsKey} output dynamic, custom string content */ diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsLevel.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsLevel.java index 9a81e17ef8e..2f255c7032f 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsLevel.java +++ b/dubbo-metrics/dubbo-metrics-api/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-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsPlaceValue.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsPlaceValue.java index 30542f73bbd..93197349ea6 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsPlaceValue.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsPlaceValue.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; /** diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/TypeWrapper.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/TypeWrapper.java index 76c37a5899d..803900821f7 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/TypeWrapper.java +++ b/dubbo-metrics/dubbo-metrics-api/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 boolean isAssignableFrom(Object type) { 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-api/src/main/java/org/apache/dubbo/metrics/model/sample/CounterMetricSample.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/sample/CounterMetricSample.java index 860f1f63b7d..cf71fd3079a 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/sample/CounterMetricSample.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/sample/CounterMetricSample.java @@ -25,13 +25,14 @@ public class CounterMetricSample extends MetricSample { private final T value; - public CounterMetricSample(String name, String description, Map tags, - MetricsCategory category, T value) { + public CounterMetricSample( + String name, String description, Map tags, MetricsCategory category, T value) { super(name, description, tags, Type.COUNTER, category); this.value = value; } - public CounterMetricSample(MetricsKeyWrapper metricsKeyWrapper, Map tags, MetricsCategory category, T value) { + public CounterMetricSample( + MetricsKeyWrapper metricsKeyWrapper, Map tags, MetricsCategory category, T value) { this(metricsKeyWrapper.targetKey(), metricsKeyWrapper.targetDesc(), tags, category, value); } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/sample/GaugeMetricSample.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/sample/GaugeMetricSample.java index 5a3401d282e..bc17fd511af 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/sample/GaugeMetricSample.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/sample/GaugeMetricSample.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.sample; import org.apache.dubbo.metrics.model.MetricsCategory; @@ -34,19 +33,42 @@ public class GaugeMetricSample extends MetricSample { private final ToDoubleFunction apply; - public GaugeMetricSample(MetricsKey metricsKey, Map tags, MetricsCategory category, T value, ToDoubleFunction apply) { + public GaugeMetricSample( + MetricsKey metricsKey, + Map tags, + MetricsCategory category, + T value, + ToDoubleFunction apply) { this(metricsKey.getName(), metricsKey.getDescription(), tags, category, null, value, apply); } - public GaugeMetricSample(MetricsKeyWrapper metricsKeyWrapper, Map tags, MetricsCategory category, T value, ToDoubleFunction apply) { + public GaugeMetricSample( + MetricsKeyWrapper metricsKeyWrapper, + Map tags, + MetricsCategory category, + T value, + ToDoubleFunction apply) { this(metricsKeyWrapper.targetKey(), metricsKeyWrapper.targetDesc(), tags, category, null, value, apply); } - public GaugeMetricSample(String name, String description, Map tags, MetricsCategory category, T value, ToDoubleFunction apply) { + public GaugeMetricSample( + String name, + String description, + Map tags, + MetricsCategory category, + T value, + ToDoubleFunction apply) { this(name, description, tags, category, null, value, apply); } - public GaugeMetricSample(String name, String description, Map tags, MetricsCategory category, String baseUnit, T value, ToDoubleFunction apply) { + public GaugeMetricSample( + String name, + String description, + Map tags, + MetricsCategory category, + String baseUnit, + T value, + ToDoubleFunction apply) { super(name, description, tags, Type.GAUGE, category, baseUnit); this.value = Objects.requireNonNull(value, "The GaugeMetricSample value cannot be null"); this.apply = Objects.requireNonNull(apply, "The GaugeMetricSample apply cannot be null"); diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/sample/MetricSample.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/sample/MetricSample.java index 826ade67ddd..6ee3153cece 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/sample/MetricSample.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/sample/MetricSample.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.sample; import org.apache.dubbo.metrics.model.MetricsCategory; @@ -33,11 +32,18 @@ public class MetricSample { private MetricsCategory category; private String baseUnit; - public MetricSample(String name, String description, Map 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 boolean equals(Object o) { 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 int hashCode() { @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/observation/AbstractDefaultDubboObservationConvention.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/AbstractDefaultDubboObservationConvention.java index 410af9d6744..5dd21e7dc4e 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/AbstractDefaultDubboObservationConvention.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/AbstractDefaultDubboObservationConvention.java @@ -32,7 +32,9 @@ 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 @@ protected KeyValues appendNonNull(KeyValues keyValues, KeyName keyName, @Nullabl } 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-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DefaultDubboClientObservationConvention.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DefaultDubboClientObservationConvention.java index 91e88da2a35..772eb458b74 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DefaultDubboClientObservationConvention.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DefaultDubboClientObservationConvention.java @@ -21,17 +21,18 @@ import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcContextAttachment; -import io.micrometer.common.KeyValues; - import java.util.List; +import io.micrometer.common.KeyValues; + import static org.apache.dubbo.metrics.observation.DubboObservationDocumentation.LowCardinalityKeyNames.NET_PEER_NAME; import static org.apache.dubbo.metrics.observation.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}. */ @@ -76,7 +77,9 @@ private int remotePort(RpcContextAttachment rpcContextAttachment, URL url) { 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-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DefaultDubboServerObservationConvention.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DefaultDubboServerObservationConvention.java index adcebdbdac8..79e57455d1b 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DefaultDubboServerObservationConvention.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DefaultDubboServerObservationConvention.java @@ -21,7 +21,8 @@ /** * 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-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DubboClientContext.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DubboClientContext.java index 910d6f74c0d..a350524c7e3 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DubboClientContext.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DubboClientContext.java @@ -19,10 +19,10 @@ import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; -import io.micrometer.observation.transport.SenderContext; - import java.util.Objects; +import io.micrometer.observation.transport.SenderContext; + /** * Provider context for RPC. */ diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DubboObservationDocumentation.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DubboObservationDocumentation.java index 855a2e01e18..db8f04e8353 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DubboObservationDocumentation.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/DubboObservationDocumentation.java @@ -40,7 +40,6 @@ public Class> get public KeyName[] getLowCardinalityKeyNames() { return LowCardinalityKeyNames.values(); } - }, /** @@ -56,7 +55,6 @@ public Class> get public KeyName[] getLowCardinalityKeyNames() { return LowCardinalityKeyNames.values(); } - }; @NonNullApi @@ -117,5 +115,4 @@ public String asString() { } } } - } 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 94acf74de9c..7ea0c64bd8d 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 7eed65e340b..9da4eb13192 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 3b1b9f34599..afb4b57b7f0 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 50770e249fe..cffd93135f0 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 21efe4762f4..4fd9f21a5a4 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 2b28a0790fe..7a04d14ce50 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 boolean equals(Object o) { 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 edad533812f..c1f8029b529 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 4632a2cdfed..69deb73c524 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/test/java/org/apache/dubbo/metrics/MetricsSupportTest.java b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/MetricsSupportTest.java index 7bc12d6a497..5ea95fdff7b 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.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 @@ void testFillZero() { 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 bbce54ec846..0427bf73351 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 efcaef6af8f..4cf179df22a 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 @@ void setup() { @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 e0db96730fc..80195cf3b5c 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,20 +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.Test; import org.junit.jupiter.api.Assertions; -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); @@ -40,7 +39,7 @@ public void testTimeWindowAggregator() { 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) { @@ -58,8 +57,7 @@ public void testTimeWindowAggregator() { 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); @@ -78,10 +76,3 @@ public void testTimeWindowAggregator() { 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 c1b68979442..e7f98512996 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 170efd61f94..fc1e5b09c9e 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 @@ void testMulti() { 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 ef2e1739943..b101d944e43 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 void onEvent(MetricsEvent event) { 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 boolean isSupport(MetricsEvent event) { } @Override - public void onEvent(TimeCounterEvent event) { - - } + public void onEvent(TimeCounterEvent event) {} @Override public void onEventFinish(TimeCounterEvent event) { @@ -84,13 +79,9 @@ public void onEventFinish(TimeCounterEvent event) { } @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 c6717d9fea1..ec2a71597fc 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 @@ 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 @@ void getApplicationModel() { 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 @@ void getTags() { 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 @@ void gitTags() { 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 @@ void hostTags() { } @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-api/src/test/java/org/apache/dubbo/metrics/observation/DefaultDubboClientObservationConventionTest.java b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/observation/DefaultDubboClientObservationConventionTest.java index ce83f9e886f..164f64878bd 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/observation/DefaultDubboClientObservationConventionTest.java +++ b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/observation/DefaultDubboClientObservationConventionTest.java @@ -24,10 +24,10 @@ 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() { @@ -49,7 +49,8 @@ void testGetLowCardinalityKeyValues() throws NoSuchFieldException, IllegalAccess 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")); } @@ -67,6 +68,4 @@ void testGetContextualName() { String contextualName = convention.getContextualName(context); Assertions.assertEquals("com.example.TestService/testMethod", contextualName); } - - } diff --git a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/observation/DefaultDubboServerObservationConventionTest.java b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/observation/DefaultDubboServerObservationConventionTest.java index 7ca6398c9ef..2f2b2e4fc0f 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/observation/DefaultDubboServerObservationConventionTest.java +++ b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/observation/DefaultDubboServerObservationConventionTest.java @@ -27,7 +27,8 @@ @SuppressWarnings("deprecation") public class DefaultDubboServerObservationConventionTest { - static DubboServerObservationConvention dubboServerObservationConvention = DefaultDubboServerObservationConvention.getInstance(); + static DubboServerObservationConvention dubboServerObservationConvention = + DefaultDubboServerObservationConvention.getInstance(); @Test void testGetName() { @@ -49,7 +50,8 @@ void testGetLowCardinalityKeyValues() throws NoSuchFieldException, IllegalAccess 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-metrics-api/src/test/java/org/apache/dubbo/metrics/observation/utils/ObservationConventionUtils.java b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/observation/utils/ObservationConventionUtils.java index e6de96f069f..2dbb4ac4cd3 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/observation/utils/ObservationConventionUtils.java +++ b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/observation/utils/ObservationConventionUtils.java @@ -19,24 +19,25 @@ 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-metrics-config-center/pom.xml b/dubbo-metrics/dubbo-metrics-config-center/pom.xml index aa65f3aef02..d69c48b57e7 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 8a7d22c7624..157df551d40 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 a86f97695ee..3840862f68e 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 static org.apache.dubbo.metrics.model.MetricsCategory.CONFIGCENTER; - /** * Config center implementation of {@link MetricsCollector} */ @@ -77,7 +75,8 @@ public void increase(String key, String group, String protocol, String changeTyp if (!isCollectEnabled()) { return; } - ConfigCenterMetric metric = new ConfigCenterMetric(applicationModel.getApplicationName(), key, group, protocol, changeTypeName); + ConfigCenterMetric metric = + new ConfigCenterMetric(applicationModel.getApplicationName(), key, group, protocol, changeTypeName); AtomicLong metrics = updatedMetrics.get(metric); if (metrics == null) { metrics = updatedMetrics.computeIfAbsent(metric, k -> new AtomicLong(0L)); @@ -86,7 +85,6 @@ public void increase(String key, String group, String protocol, String changeTyp metrics.addAndGet(size); } - @Override public List collect() { // Add metrics to reporter @@ -94,7 +92,8 @@ public List collect() { if (!isCollectEnabled()) { return list; } - updatedMetrics.forEach((k, v) -> 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 ddf4f88fdb3..58e9979f70b 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 @@ */ 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 ConfigCenterEvent(ApplicationModel applicationModel, TypeWrapper typeWrap } } - - 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 1604cb3b621..49eab005783 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.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 boolean isSupport(MetricsEvent event) { @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 f20c0478717..35c44a94cad 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.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 @@ void increaseUpdated() { 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 71be413c6a1..8cced701056 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} - - - io.micrometer - micrometer-test - test - - - io.micrometer - micrometer-tracing-integration-test - test - - + + 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} + + + io.micrometer + micrometer-test + test + + + io.micrometer + micrometer-tracing-integration-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 a59832fd0c6..bf65f6fcd6c 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 6a69e4ed803..37b76505fc2 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 660fcc835d9..01e174ad0b3 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 @@ 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 void initializeApplicationModel(ApplicationModel applicationModel) { } @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/collector/AggregateMetricsCollector.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollector.java index f70e3bc0fd1..25ad926a6cc 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 AggregateMetricsCollector(ApplicationModel applicationModel) { 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 void setCollectEnabled(Boolean collectEnabled) { } } - @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 void onEvent(RequestEvent event) { 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 void onEventError(RequestEvent event) { } 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 @@ private void onRTEvent(RequestEvent event) { 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 @@ private void collectBySide(List list, String side) { } 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_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_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_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 void initMethodMetric(MetricsEvent event) { } 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 f1fd60d91a9..96502f90fb5 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; @@ -85,8 +84,9 @@ protected void init(MethodStatComposite methodStatComposite) { @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)); @@ -168,14 +168,14 @@ public boolean isSupport(MetricsEvent event) { @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); @@ -183,35 +183,44 @@ public void onEvent(TimeCounterEvent event) { @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); - } - - 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 - public boolean calSamplesChanged() { - return false; - } - }; + 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; + } + + @Override + protected void countConfigure( + MetricsCountSampleConfigurer sampleConfigure) { + sampleConfigure.configureMetrics(configure -> new ApplicationMetric(applicationModel)); + } + + @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 a7169ba12ae..807e31b2515 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.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 HistogramMetricsCollector(ApplicationModel applicationModel) { ConfigManager configManager = applicationModel.getApplicationConfigManager(); MetricsConfig config = configManager.getMetrics().orElse(null); - if (config == null || config.getHistogram() == null || config.getHistogram().getEnabled() == null || Boolean.TRUE.equals(config.getHistogram().getEnabled())) { + if (config == null + || config.getHistogram() == null + || config.getHistogram().getEnabled() == null + || Boolean.TRUE.equals(config.getHistogram().getEnabled())) { registerListener(); HistogramConfig histogram; @@ -70,19 +73,22 @@ public HistogramMetricsCollector(ApplicationModel applicationModel) { histogram.setBucketsMs(DEFAULT_BUCKETS_MS); } - metricRegister = new HistogramMetricRegister(MetricsGlobalRegistry.getCompositeRegistry(applicationModel), histogram); + metricRegister = new HistogramMetricRegister( + MetricsGlobalRegistry.getCompositeRegistry(applicationModel), histogram); this.serviceLevel = MethodMetric.isServiceLevel(applicationModel); } } private void registerListener() { - applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class).getEventMulticaster().addListener(this); + applicationModel + .getBeanFactory() + .getBean(DefaultMetricsCollector.class) + .getEventMulticaster() + .addListener(this); } @Override - public void onEvent(RequestEvent event) { - - } + public void onEvent(RequestEvent event) {} @Override public void onEventFinish(RequestEvent event) { @@ -96,11 +102,15 @@ public void onEventError(RequestEvent event) { private void onRTEvent(RequestEvent event) { if (metricRegister != null) { - 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(); - HistogramMetricSample sample = new HistogramMetricSample(MetricsKey.METRIC_RT_HISTOGRAM.getNameByType(metric.getSide()), - MetricsKey.METRIC_RT_HISTOGRAM.getDescription(), metric.getTags(), RT); + HistogramMetricSample sample = new HistogramMetricSample( + MetricsKey.METRIC_RT_HISTOGRAM.getNameByType(metric.getSide()), + MetricsKey.METRIC_RT_HISTOGRAM.getDescription(), + metric.getTags(), + RT); Timer timer = ConcurrentHashMapUtils.computeIfAbsent(rt, metric, k -> 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/MetricThreadPoolExhaustedListener.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricThreadPoolExhaustedListener.java index 4b45ba1dd95..f7278e172b1 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 0bb41f0a03d..54267e2d34e 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 S getSource() { 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 fe746a941b0..4b02dcd3653 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/MetricsSampler.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricsSampler.java index 52578d627d5..d6d813b7079 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 bbb1224a105..b6071c56885 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 @@ * @param metricsName * @param metric */ - -public abstract class SimpleMetricsCountSampler - implements MetricsCountSampler { +public abstract class SimpleMetricsCountSampler implements MetricsCountSampler { private final ConcurrentMap EMPTY_COUNT = new ConcurrentHashMap<>(); private final Map> metricCounter = new ConcurrentHashMap<>(); @@ -45,13 +42,11 @@ public void inc(S source, K metricName) { @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 void initMetricsCounter(S source, K metricsName){ - getAtomicCounter(source,metricsName); + protected void initMetricsCounter(S source, K metricsName) { + getAtomicCounter(source, metricsName); } protected abstract void countConfigure(MetricsCountSampleConfigurer sampleConfigure); @@ -77,7 +72,5 @@ private AtomicLong getAtomicCounter(S source, K metricsName) { 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 9ccb55f8db9..d39e2fa2db7 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 @@ -62,12 +62,14 @@ public ThreadPoolMetricsSampler(DefaultMetricsCollector 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 @@ -83,14 +85,44 @@ public List sample() { 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; } @@ -102,14 +134,21 @@ public void registryDefaultSampleThreadPoolExecutor() { } 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.dataStore == null) { - this.dataStore = collector.getApplicationModel().getExtensionLoader(DataStore.class).getDefaultExtension(); + this.dataStore = collector + .getApplicationModel() + .getExtensionLoader(DataStore.class) + .getDefaultExtension(); } if (dataStore != null) { @@ -128,13 +167,19 @@ public void registryDefaultSampleThreadPoolExecutor() { } } - 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); + } + }); } if (this.frameworkExecutorRepository != null) { this.addExecutors("sharedExecutor", frameworkExecutorRepository.getSharedExecutor()); 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 2c0cbcd5182..f405c635451 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.common.utils.ConcurrentHashSet; @@ -47,47 +46,50 @@ public ThreadRejectMetricsCountSampler(DefaultMetricsCollector collector) { this.collector.addSampler(this); } - public void addMetricName(String name){ + public void addMetricName(String name) { this.metricNames.add(name); - this.initMetricsCounter(name,name); + this.initMetricsCounter(name, name); samplesChanged.set(true); } @Override public List sample() { List metricSamples = new ArrayList<>(); - metricNames.stream().forEach(name->collect(metricSamples,name)); + metricNames.stream().forEach(name -> collect(metricSamples, name)); return metricSamples; } - private void collect(List list, String metricName) { count(list, metricName, MetricsKey.THREAD_POOL_THREAD_REJECT_COUNT); } private void count(List list, String metricName, MetricsKey metricsKey) { - getCount(metricName).filter(e -> !e.isEmpty()) - .ifPresent(map -> map.forEach((k, v) -> - list.add(getGaugeMetricSample(metricsKey, k, THREAD_POOL, v, AtomicLong::get)))); + getCount(metricName) + .filter(e -> !e.isEmpty()) + .ifPresent(map -> map.forEach( + (k, v) -> list.add(getGaugeMetricSample(metricsKey, k, THREAD_POOL, v, AtomicLong::get)))); } - private GaugeMetricSample getGaugeMetricSample(MetricsKey metricsKey, - ThreadPoolRejectMetric methodMetric, - MetricsCategory metricsCategory, - T value, - ToDoubleFunction apply) { + private GaugeMetricSample getGaugeMetricSample( + MetricsKey metricsKey, + ThreadPoolRejectMetric methodMetric, + MetricsCategory metricsCategory, + T value, + ToDoubleFunction apply) { return new GaugeMetricSample<>( - metricsKey.getNameByType(methodMetric.getThreadPoolName()), - metricsKey.getDescription(), - methodMetric.getTags(), - metricsCategory, - value, - apply); + metricsKey.getNameByType(methodMetric.getThreadPoolName()), + metricsKey.getDescription(), + methodMetric.getTags(), + metricsCategory, + value, + apply); } @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())); } @Override 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 807736709b6..ca84829f9ef 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 boolean isSupport(MetricsEvent event) { 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,21 +93,32 @@ private CategoryOverall initMethodRequest() { 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 4773ce158af..732aab1dce4 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 @@ * 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 RequestEvent(ApplicationModel applicationModel, String appName, MetricsDi 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 void customAfterPost(Object postResult) { 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 void customAfterPost(Object postResult) { /** * 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 0496443732b..900dc7002b9 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 Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept 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 void onError(Throwable t, Invoker invoker, Invocation invocation, bool } } } - } 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 68502bdfba3..4e651a192ab 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 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/observation/ObservationReceiverFilter.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/observation/ObservationReceiverFilter.java index 5a33ced4373..07df3ef75f1 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/observation/ObservationReceiverFilter.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/observation/ObservationReceiverFilter.java @@ -45,7 +45,8 @@ public ObservationReceiverFilter(ApplicationModel applicationModel) { applicationModel.getApplicationConfigManager().getTracing().ifPresent(cfg -> { if (Boolean.TRUE.equals(cfg.getEnabled())) { observationRegistry = applicationModel.getBeanFactory().getBean(ObservationRegistry.class); - serverObservationConvention = applicationModel.getBeanFactory().getBean(DubboServerObservationConvention.class); + serverObservationConvention = + applicationModel.getBeanFactory().getBean(DubboServerObservationConvention.class); } }); } @@ -59,7 +60,8 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept 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-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 04a173cdee0..b501da23292 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.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 Timer register(HistogramMetricSample sample) { tags.add(Tag.of(k, v)); }); - Timer.Builder builder = Timer.builder(sample.getName()).description(sample.getDescription()).tags(tags); + Timer.Builder builder = Timer.builder(sample.getName()) + .description(sample.getDescription()) + .tags(tags); if (Boolean.TRUE.equals(config.getEnabledPercentiles())) { builder.publishPercentileHistogram(true); @@ -60,8 +62,8 @@ public Timer register(HistogramMetricSample sample) { } if (config.getBucketsMs() != null) { - builder.serviceLevelObjectives(Arrays.stream(config.getBucketsMs()) - .map(Duration::ofMillis).toArray(Duration[]::new)); + builder.serviceLevelObjectives( + Arrays.stream(config.getBucketsMs()).map(Duration::ofMillis).toArray(Duration[]::new)); } if (config.getMinExpectedMs() != null) { diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/register/MetricRegister.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/register/MetricRegister.java index fbf6c5eeb02..37d4fae2318 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/register/MetricRegister.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/register/MetricRegister.java @@ -14,14 +14,13 @@ * 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.Meter; import org.apache.dubbo.metrics.model.sample.MetricSample; +import io.micrometer.core.instrument.Meter; + public interface 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 ac0700221f0..b9494bb735b 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.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.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 @@ protected void addMeterRegistry(MeterRegistry registry) { compositeRegistry.add(registry); } - protected ApplicationModel getApplicationModel() { return applicationModel; } @@ -115,7 +114,8 @@ private void addJvmMetrics() { 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 @@ private void scheduleMetricsCollectorSyncJob() { 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 void resetIfSamplesChanged() { 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 @@ private void registerSample(MetricSample sample) { @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 88e16ec56c1..7d018ddf2ed 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 String getResponseWithName(String metricsName) { 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 @@ protected void doInit() { } @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 504d964db68..e64a7adf059 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 f326f5467cc..9d6952c1915 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 @@ */ 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 28980e4ef93..50e781bf208 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 8f8149c1b5c..b9f2281659e 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 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 eeb07827ca2..2548bb81048 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 Map> getMetricsByCategories(List> 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/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java index 5bb8c014b7a..c61fd486209 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.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 void setUp() { 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 void setUp() { @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 a9edf9507a8..5b53eaa0872 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 Result invoke(Invocation invocation) throws RpcException { @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 boolean isAvailable() { } @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 ce34ce01fdf..ef049eb49c6 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.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.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 @@ public void setup() { 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 @@ void testRequestsMetrics() { 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 @@ void testRequestsMetrics() { 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 @@ public void testQPS() { } @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 @@ public void testQPS() { Assertions.assertEquals(10000, ((TimeWindowCounter) ((GaugeMetricSample) sample).getValue()).get()); } - @Test public void testRtAggregation() { metricsDispatcher.addListener(collector); @@ -248,9 +262,17 @@ public void testRtAggregation() { 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 @@ public void testRtAggregation() { 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 @@ void testP95AndP99() throws InterruptedException { 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 @@ void testP95AndP99() throws InterruptedException { 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 @@ void testP95AndP99() throws InterruptedException { @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 @@ public void setRt(long rt) { public TimePair getTimePair() { return new TestTimePair(rt); } - } public static class TestTimePair extends TimePair { @@ -375,4 +405,3 @@ public long calc() { } } } - 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 88fac20a709..0a8910dd7bd 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; @@ -43,16 +42,16 @@ 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; @@ -63,7 +62,6 @@ 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; @@ -103,7 +101,8 @@ public void setup() { 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); @@ -112,8 +111,22 @@ public void setup() { @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)); @@ -131,7 +144,8 @@ public void teardown() { void testRequestEventNoRt() { applicationModel.getBeanFactory().getOrRegisterBean(MetricsDispatcher.class); - DefaultMetricsCollector collector = applicationModel.getBeanFactory().getOrRegisterBean(DefaultMetricsCollector.class); + DefaultMetricsCollector collector = + applicationModel.getBeanFactory().getOrRegisterBean(DefaultMetricsCollector.class); collector.setCollectEnabled(true); metricsFilter.invoke(new TestMetricsInvoker(side), invocation); @@ -141,7 +155,7 @@ void testRequestEventNoRt() { 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); @@ -150,13 +164,19 @@ void testRequestEventNoRt() { // push finish rt +1 List metricSamples = collector.collect(); - //num(total+success+processing) + rt(5) = 8 + // num(total+success+processing) + rt(5) = 8 Assertions.assertEquals(8, metricSamples.size()); - List metricsNames = metricSamples.stream().map(MetricSample::getName).collect(Collectors.toList()); + 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)); @@ -167,10 +187,12 @@ void testRequestEventNoRt() { 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 { @@ -187,7 +209,8 @@ void testRequestEventNoRt() { } 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(); @@ -195,28 +218,38 @@ void testRequestEventNoRt() { // num(total+success+error+total_error+processing) + rt(5) = 5 Assertions.assertEquals(10, 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 { @@ -227,20 +260,40 @@ void testRequestEventNoRt() { } } - // 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 eff1d0bc8f5..f036eb7dfa2 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.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 @@ public void setup() { 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 @@ public void setup() { 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 @@ public void teardown() { 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()); - - 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(); + 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(); Assertions.assertTrue(metricsNames.contains(REQUESTS)); Assertions.assertTrue(metricsNames.contains(PROCESSING)); for (MetricSample metricSample : metricSamples) { @@ -133,21 +140,18 @@ void testMetricsInitEvent() { } } - 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 2c8e2f984d8..6b20d6c69d5 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.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.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 void testRegistryDefaultSampleThreadPoolExecutor() throws NoSuchFieldExce Field f = ThreadPoolMetricsSampler.class.getDeclaredField("sampleThreadPoolExecutor"); f.setAccessible(true); - Map executors = (Map) f.get(sampler2); + Map executors = (Map) f.get(sampler2); Assertions.assertEquals(3, 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 358c4872d30..b668c770245 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.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.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 @@ public void setup() { 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 @@ void testCollectDisabled() { Assertions.assertTrue(metricsMap.isEmpty()); } - @Test void testUnknownFailedRequests() { collector.setCollectEnabled(true); @@ -167,7 +165,6 @@ void testBusinessFailedRequests() { Assertions.assertEquals(tags.get(TAG_VERSION_KEY), VERSION); } - @Test void testTimeoutRequests() { collector.setCollectEnabled(true); @@ -192,7 +189,8 @@ void testTimeoutRequests() { 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 @@ void testMissingGroup() { 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 @@ public void testErrors() { 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 @@ private void testFilterError(int errorCode, MetricsKey metricsKey) { Assertions.assertSame(((CounterMetricSample) sample).getValue().longValue(), count); - Assertions.assertFalse(metricsMap.containsKey(metricsKey.getName())); Map tags = sample.getTags(); @@ -316,7 +313,7 @@ void testMissingVersion() { 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 @@ void testMissingGroupAndVersion() { 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 @@ void testGenericCall() { 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 @@ void testGenericCall() { 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 @@ private Map getMetricsMap() { 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 93f1c6593f7..0218d872e4d 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.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 @@ public static void setup() { 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 @@ void testServiceMetrics() { 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/GaugeMetricSampleTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model/sample/GaugeMetricSampleTest.java index d43e9693704..b2a0aa369fc 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 @@ public static void setup() { @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 b7bc85662b3..4901ad5dff4 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 19285ad59fd..39f52c40fc0 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/metrics/observation/AbstractObservationFilterTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/observation/AbstractObservationFilterTest.java index 31715ca94b0..b3d6d0fa1d8 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/observation/AbstractObservationFilterTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/observation/AbstractObservationFilterTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.observation; import org.apache.dubbo.config.ApplicationConfig; @@ -81,5 +80,4 @@ private void initParam() { invocation.setMethodName(METHOD_NAME); invocation.setParameterTypes(new Class[] {String.class}); } - } diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/observation/MockInvocation.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/observation/MockInvocation.java index 8cb43471d83..c5c06c98789 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/observation/MockInvocation.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/observation/MockInvocation.java @@ -119,9 +119,7 @@ public Invoker getInvoker() { } @Override - public void setServiceModel(ServiceModel serviceModel) { - - } + public void setServiceModel(ServiceModel serviceModel) {} @Override public ServiceModel getServiceModel() { @@ -164,5 +162,4 @@ public Object getObjectAttachment(String key, Object defaultValue) { } return result; } - } diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/observation/ObservationReceiverFilterTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/observation/ObservationReceiverFilterTest.java index 91101e1aa08..2b2d2cc3c56 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/observation/ObservationReceiverFilterTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/observation/ObservationReceiverFilterTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.observation; import org.apache.dubbo.common.URL; @@ -48,22 +47,32 @@ public SampleTestRunnerConsumer yourCode() { 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 @@ public boolean isAvailable() { } @Override - public void destroy() { - - } + public void destroy() {} @Override public Class getInterface() { @@ -110,11 +117,11 @@ public Class getInterface() { 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-metrics-metadata/pom.xml b/dubbo-metrics/dubbo-metrics-metadata/pom.xml index f454e9558ed..d6cf291fdc0 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 14fc3b8dab9..9f3a43db2f3 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 82b5e689d39..82dcc7cd97d 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_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 2222bda1629..a14c6690526 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 MetadataEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper) } 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 ebbe20f8a8b..bc7ec7fa0f1 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 MetadataSubDispatcher(MetadataMetricsCollector collector) { 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 @@ interface CategorySet { */ 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 564b0ba9c57..8ee31a9e795 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.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 @@ public void setup() { @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 @@ public void teardown() { @Test void testPushMetrics() { -// MetadataMetricsCollector collector = getCollector(); + // MetadataMetricsCollector collector = getCollector(); MetadataEvent pushEvent = MetadataEvent.toPushEvent(applicationModel); - 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; - } - ); + 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 finish rt +1 List metricSamples = collector.collect(); @@ -108,16 +104,17 @@ void testPushMetrics() { 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 @@ void testPushMetrics() { } @SuppressWarnings("rawtypes") - 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); + 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); } @Test void testSubscribeMetrics() { -// MetadataMetricsCollector collector = getCollector(); + // MetadataMetricsCollector collector = getCollector(); MetadataEvent subscribeEvent = MetadataEvent.toSubscribeEvent(applicationModel); - 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; - } - ); + 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; + }); long c1 = subscribeEvent.getTimePair().calc(); // push finish rt +1 @@ -166,16 +173,17 @@ void testSubscribeMetrics() { 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 @@ void testSubscribeMetrics() { } @SuppressWarnings("rawtypes") - 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); + 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); } - @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(); - - // 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; - } - ); + 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; + }); // push finish rt +1 List metricSamples = collector.collect(); @@ -227,23 +244,24 @@ void testStoreProviderMetadataMetrics() { 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 @@ void testStoreProviderMetadataMetrics() { } @SuppressWarnings("rawtypes") - 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); + 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); } @Test @@ -266,10 +300,10 @@ void testMetadataPushNum() { 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 @@ void testMetadataPushNum() { 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 7e7292b7212..eb6efba201d 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.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 @@ protected void init(RtStatComposite rtStatComposite) { @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 @@ void testInit() { 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-prometheus/pom.xml b/dubbo-metrics/dubbo-metrics-prometheus/pom.xml index 27f8fc35819..1a88d4951b2 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 a5bf1a94d93..f0211ba3966 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 @@ 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 111f56634ab..96948e15317 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.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 @@ private void schedulePushJob() { 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 @@ private void schedulePushJob() { 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 @@ protected void push(PushGateway pushGateway, String job) { 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 c5df78394c3..0626b6380be 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 @@ @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 @@ private String specifyApplication(String appName, List models) } 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 @@ private String getResponseByApplication(ApplicationModel applicationModel) { 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 @@ private static long getLineNumber(String content) { } 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 c549d6688b7..fcad830e1e8 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 @@ */ 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 MetricsReporter createMetricsReporter(URL url) { } 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 50725ca82f1..88646278ffe 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 8badfebab7d..5304963a042 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.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.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 @@ void testJvmMetrics() { 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 @@ void testJvmMetrics() { @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 @@ void testExporter() { 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 @@ void testExporter() { 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 @@ void testPushgateway() { Assertions.assertTrue(executor.isTerminated() || executor.isShutdown()); } - private void exportHttpServer(PrometheusMetricsReporter reporter, int port) { try { @@ -158,5 +162,4 @@ private void exportHttpServer(PrometheusMetricsReporter reporter, int port) { 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 4b30009cf14..5591cd8c54c 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.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.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.utils.NetUtils.getLocalHost; import static org.apache.dubbo.common.utils.NetUtils.getLocalHostName; - public class PrometheusMetricsThreadPoolTest { private ApplicationModel applicationModel; @@ -95,20 +94,22 @@ void testExporterThreadpoolName() { 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 @@ void testExporterThreadpoolName() { } } - private void exportHttpServer(PrometheusMetricsReporter reporter, int port) { try { HttpServer prometheusExporterHttpServer = HttpServer.create(new InetSocketAddress(port), 0); @@ -137,17 +137,16 @@ private void exportHttpServer(PrometheusMetricsReporter reporter, int port) { } } - - @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 @@ void testThreadPoolRejectMetrics() { Assertions.assertEquals(gaugeSample.applyAsLong(), 1); } } - } diff --git a/dubbo-metrics/dubbo-metrics-registry/pom.xml b/dubbo-metrics/dubbo-metrics-registry/pom.xml index 86f190ff766..f03625270a8 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 18dac35bc69..da52afe33ba 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 6559a49ed2b..c10bca41ddd 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_SUBSCRIBE; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_SUBSCRIBE_SERVICE; - /** * Registry implementation of {@link MetricsCollector} */ @@ -77,7 +75,12 @@ protected void init(ServiceStatComposite serviceStatComposite) { @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); } }); super.setEventMulticaster(new RegistrySubDispatcher(this)); @@ -100,7 +103,6 @@ public boolean isCollectEnabled() { return Optional.ofNullable(collectEnabled).orElse(true); } - @Override public List collect() { List list = new ArrayList<>(); @@ -116,33 +118,40 @@ public void incrMetricsNum(MetricsKey metricsKey, List registryClusterNa registryClusterNames.forEach(name -> 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 68bbd2fcba1..567b6d6ee06 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 List export(MetricsCategory category) { 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 void incrMetricsNum(MetricsKey metricsKey, String name) { 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 97b9bac1ac2..d122ecabc38 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_SERVICE; import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_SIZE; - /** * Registry related events */ @@ -50,7 +48,11 @@ public RegistryEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper) } } - 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 static RegistryEvent toRegisterEvent(ApplicationModel applicationModel, L 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 void customAfterPost(Object postResult) { }; } - 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 static RegistryEvent toRsEvent(ApplicationModel applicationModel, String 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 static RegistryEvent toSsEvent(ApplicationModel applicationModel, String 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 6e44fea1b1f..a28ec570f18 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 static int getSize(MetricsEvent event) { 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 27cbcb4f617..458ed9d7afc 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 @@ 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 RegistrySubDispatcher(RegistryMetricsCollector collector) { * 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); - - List ALL = Arrays.asList(APPLICATION_REGISTER, APPLICATION_SUBSCRIBE, APPLICATION_NOTIFY, SERVICE_DIRECTORY, SERVICE_REGISTER, SERVICE_SUBSCRIBE); + 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); } - /** * {@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 ff289caca33..442b9a7142c 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.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.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_SUBSCRIBE_SERVICE; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.REGISTER_LEVEL_KEYS; - class RegistryMetricsCollectorTest { private ApplicationModel applicationModel; @@ -78,16 +77,16 @@ public void teardown() { 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 @@ void testRegisterMetrics() { 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 @@ void testRegisterMetrics() { } @SuppressWarnings("rawtypes") - 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); + 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); } - @Test void testServicePushMetrics() { @@ -140,17 +148,20 @@ void testServicePushMetrics() { List rcNames = Lists.newArrayList("demo1"); RegistryEvent registryEvent = RegistryEvent.toRsEvent(applicationModel, serviceName, 2, rcNames); - 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; - } - ); + 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 finish rt +1 List metricSamples = collector.collect(); @@ -160,16 +171,17 @@ void testServicePushMetrics() { 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 @@ void testServicePushMetrics() { } @SuppressWarnings("rawtypes") - 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); + 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); } - @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 @@ void testServiceSubscribeMetrics() { 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 @@ void testServiceSubscribeMetrics() { } @SuppressWarnings("rawtypes") - 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); + 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); } - @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 bd59ab5dae8..1138b85c8b2 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.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 @@ public void teardown() { } @Test - void testRegisterMetrics() { - } + void testRegisterMetrics() {} @Test void testRTMetrics() { @@ -75,13 +73,19 @@ void testRTMetrics() { } @SuppressWarnings("rawtypes") - 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); + 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); } @Test @@ -90,5 +94,4 @@ void testListener() { 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 5610bef2321..db06191028c 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.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.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 @@ void testRegisterRequestsCount() { } 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 @@ void testServiceRegisterCount() { } 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 @@ void testServiceSubscribeCount() { 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 @@ RegistryMetricsCollector getTestCollector(ApplicationModel applicationModel) { return new RegistryMetricsCollector(applicationModel); } - /** * make the control of thread sleep time more precise */ @@ -360,5 +362,4 @@ public static void sleep(long milliseconds) { } } } - } 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 3c0d00826e8..c7af23b7926 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.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_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 @@ protected void init(ServiceStatComposite serviceStatComposite) { @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 @@ protected void init(RtStatComposite rtStatComposite) { @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 @@ void testInit() { 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 @@ void testCalcServiceKeyRt() { 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 @@ void testCalcServiceKeyRt() { Assertions.assertEquals(responseTime2, maxSample.applyAsLong()); Assertions.assertEquals((responseTime1 + responseTime2) / 2, avgSample.applyAsLong()); } - - } diff --git a/dubbo-metrics/pom.xml b/dubbo-metrics/pom.xml index 04abd6e0777..ae8143d5e2b 100644 --- a/dubbo-metrics/pom.xml +++ b/dubbo-metrics/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - dubbo-metrics-api - dubbo-metrics-default - dubbo-metrics-registry - dubbo-metrics-metadata - dubbo-metrics-prometheus - dubbo-metrics-config-center - - - 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-default + dubbo-metrics-registry + dubbo-metrics-metadata + dubbo-metrics-prometheus + dubbo-metrics-config-center + + + 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 f7fc8dd3035..293acf1a6a3 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-rpc-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-api + jar + ${project.artifactId} + The monitor module of dubbo project + + false + + + + org.apache.dubbo + dubbo-rpc-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-cluster + ${project.parent.version} + - - 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 + + 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 6670c852998..94c7f9dc3fb 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 d6fd2fd018b..85abadd878f 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 @@ * * @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 0571d97323a..45403bc3bc1 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 31ecbb03a8f..bc14cb9ebc3 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-api/src/main/java/org/apache/dubbo/monitor/support/AbstractMonitorFactory.java b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/AbstractMonitorFactory.java index c26c09cceb5..0e774cc0182 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/AbstractMonitorFactory.java +++ b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/AbstractMonitorFactory.java @@ -42,7 +42,8 @@ * 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 Monitor getMonitor(URL url) { 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 Monitor getMonitor(URL url) { } protected abstract Monitor createMonitor(URL url); - } diff --git a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/CallbackConsumerContextFilter.java b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/CallbackConsumerContextFilter.java index ab76f628d50..47194623bbb 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/CallbackConsumerContextFilter.java +++ b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/CallbackConsumerContextFilter.java @@ -30,7 +30,7 @@ */ @Activate(group = CALLBACK, order = Integer.MIN_VALUE) public class CallbackConsumerContextFilter extends ConsumerContextFilter implements Filter { - + public CallbackConsumerContextFilter(ApplicationModel applicationModel) { super(applicationModel); } diff --git a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MetricsServiceDetector.java b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MetricsServiceDetector.java index 0eb6406bc3b..a357b8b344a 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MetricsServiceDetector.java +++ b/dubbo-monitor/dubbo-monitor-api/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-api/src/main/java/org/apache/dubbo/monitor/support/MonitorClusterFilter.java b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorClusterFilter.java index 06ea364db6c..e6e9e3c061d 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorClusterFilter.java +++ b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorClusterFilter.java @@ -22,5 +22,4 @@ 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-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java index 2d0ec9823b2..08d4d2738ce 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java +++ b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java @@ -82,7 +82,6 @@ public void setMonitorFactory(MonitorFactory monitorFactory) { 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 void setMonitorFactory(MonitorFactory monitorFactory) { 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 void onResponse(Result result, Invoker invoker, Invocation invocation) 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 void onError(Throwable t, Invoker invoker, Invocation invocation) { * @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 @@ private void collect(Invoker invoker, Invocation invocation, Result result, S 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 @@ private void collect(Invoker invoker, Invocation invocation, Result result, S * @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 @@ private URL createStatisticsUrl(Invoker invoker, Invocation invocation, Resul 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-api/src/main/java/org/apache/dubbo/monitor/support/MonitorServiceDetector.java b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorServiceDetector.java index 3ae4e104ddb..0b8cd37f632 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorServiceDetector.java +++ b/dubbo-monitor/dubbo-monitor-api/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-api/src/test/java/org/apache/dubbo/monitor/support/AbstractMonitorFactoryTest.java b/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/AbstractMonitorFactoryTest.java index 821ab638140..7b32aef7255 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/AbstractMonitorFactoryTest.java +++ b/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/AbstractMonitorFactoryTest.java @@ -21,11 +21,11 @@ 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 @@ public boolean isAvailable() { } @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 @@ void testMonitorFactoryGroupCache() throws Exception { } Assertions.assertNotSame(monitor1, monitor2); } - -} \ No newline at end of file +} diff --git a/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java b/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java index 6a644a5fec6..d32f5658722 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java +++ b/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java @@ -29,13 +29,13 @@ 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 @@ public Class getInterface() { } 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 @@ public Result invoke(Invocation invocation) throws RpcException { } @Override - public void destroy() { - } + public void destroy() {} }; private MonitorFactory monitorFactory = url -> new Monitor() { @@ -101,8 +100,7 @@ public boolean isAvailable() { } @Override - public void destroy() { - } + public void destroy() {} public void collect(URL statistics) { MonitorFilterTest.this.lastStatistics = statistics; @@ -117,8 +115,11 @@ public List lookup(URL query) { 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 @@ void testSkipMonitorIfNotHasKey() { 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 @@ void testSkipMonitorIfNotHasKey() { 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 @@ void testSafeFailForMonitorCollectFail() { 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 @@ void testOnResponseWithoutStartTime() { 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 @@ void testOnErrorWithoutStartTime() { 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 43d4f0044e5..5946a35014f 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-api - ${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 - - + + 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-api + ${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 + + 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 e66fd5f4855..215ba5daa5d 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 void send() { 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 @@ DEFAULT_PROTOCOL, getUrl().getParameter(DEFAULT_PROTOCOL) 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 void collect(URL url) { 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 void destroy() { 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 3ca881f4da0..1bffa1a2007 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 @@ protected Monitor createMonitor(URL url) { } 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 9ee73d03de7..1b45878253b 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.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.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 void setApplicationModel(ApplicationModel applicationModel) { @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 @@ private String buildMethodName(Invocation invocation) { 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 @@ private void setCompassQuantity(String groupName, String result, long duration, } 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 @@ private List getThreadPoolMessage() { 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 @@ private MetricObject value2MetricObject(String metric, Integer value, MetricLeve 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 Result invoke(Invocation invocation) throws RpcException { 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 Result invoke(Invocation invocation) throws RpcException { @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 boolean isAvailable() { } @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 a4a0ef5fa69..7c859aeb8de 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 boolean equals(Object obj) { 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 17a6e38f8d5..c33d0035805 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 d5fdb3b4a6d..c676528cc3c 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 @@ class DubboMonitorFactoryTest { private DubboMonitorFactory dubboMonitorFactory; + @Mock private ProxyFactory proxyFactory; @@ -66,4 +67,4 @@ void testCreateMonitor() { 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 df40e976275..891a45e1072 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.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 @@ public Result invoke(Invocation invocation) throws RpcException { } @Override - public void destroy() { - } + public void destroy() {} }; private volatile URL lastStatistics; private final MonitorService monitorService = new MonitorService() { @@ -103,24 +102,23 @@ public void collect(URL statistics) { 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 @@ void testCount() { 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(); - - Exporter exporter = protocol.export(proxyFactory.getInvoker(monitorService, MonitorService.class, URL.valueOf("dubbo://127.0.0.1:17979/" + MonitorService.class.getName()))); + 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()))); try { Monitor monitor = null; long start = System.currentTimeMillis(); @@ -171,15 +174,15 @@ void testMonitorFactory() { } 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 @@ void testAvailable() { @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 @@ void testSum() { 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 508f3d3b10a..864d52fe238 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.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.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 @@ private void onInvokeReturns(Invoker invoker, AppResponse response) } 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 @@ private void testConsumerSuccess() { 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 @@ private void testConsumerTimeout() { 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 @@ private void testProviderSuccess() { 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 @@ private void testInvokeMetricsService() { 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 @@ private void testInvokeMetricsService() { 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 @@ private void testInvokeMetricsService() { } 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 @@ private void testInvokeMetricsMethodService() { 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 @@ private void testInvokeMetricsMethodService() { } 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 @@ private void testInvokeMetricsMethodService() { 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 7c1a1b093fe..ba435e70d19 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 List getStatistics() { 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 ca2b2b869d0..ac418773824 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 @@ void testToString() { 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 a2fb2d11782..ac0e13c81d7 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 735bf3743e7..246c96bf7b3 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-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-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-native-plugin/pom.xml b/dubbo-native-plugin/pom.xml index f3bf948f03c..e41dad1eb99 100644 --- a/dubbo-native-plugin/pom.xml +++ b/dubbo-native-plugin/pom.xml @@ -1,3 +1,4 @@ + - - - dubbo-parent - org.apache.dubbo - ${revision} - - 4.0.0 - - dubbo-native-plugin - - - 11 - 11 - - maven-plugin - - - - - org.apache.maven - maven-plugin-api - 3.9.1 - - - - org.apache.maven - maven-core - 3.9.1 - provided - - - - - org.apache.maven.plugin-tools - maven-plugin-annotations - 3.8.1 - provided - - - - org.apache.dubbo - dubbo-common - ${project.version} - - - - - commons-io - commons-io - 2.11.0 - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - - - - - - - - - maven-plugin-plugin - 3.8.1 - - - default-addPluginArtifactMetadata - package - - addPluginArtifactMetadata - - - - default-descriptor - process-classes - - descriptor - - - - - - - + + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + + + dubbo-native-plugin + maven-plugin + + + 11 + 11 + + + + + org.apache.maven + maven-plugin-api + 3.9.1 + + + + org.apache.maven + maven-core + 3.9.1 + provided + + + + org.apache.maven.plugin-tools + maven-plugin-annotations + 3.8.1 + provided + + + + org.apache.dubbo + dubbo-common + ${project.version} + + + + commons-io + commons-io + 2.11.0 + + + org.apache.dubbo + dubbo-metrics-default + ${project.parent.version} + + + + + + + + + maven-plugin-plugin + 3.8.1 + + + default-addPluginArtifactMetadata + + addPluginArtifactMetadata + + package + + + default-descriptor + + descriptor + + process-classes + + + + + + diff --git a/dubbo-native-plugin/src/main/java/org/apache/dubbo/maven/plugin/CodeGenerator.java b/dubbo-native-plugin/src/main/java/org/apache/dubbo/maven/plugin/CodeGenerator.java index e3f02a68579..2f90da4a0f1 100644 --- a/dubbo-native-plugin/src/main/java/org/apache/dubbo/maven/plugin/CodeGenerator.java +++ b/dubbo-native-plugin/src/main/java/org/apache/dubbo/maven/plugin/CodeGenerator.java @@ -21,10 +21,6 @@ import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.common.utils.StringUtils; -import org.apache.commons.io.FileUtils; -import org.apache.maven.plugin.logging.Log; -import org.apache.maven.plugin.logging.SystemStreamLog; - import java.io.File; import java.lang.annotation.Annotation; import java.lang.reflect.Method; @@ -38,85 +34,97 @@ import java.util.regex.Matcher; import java.util.stream.Collectors; +import org.apache.commons.io.FileUtils; +import org.apache.maven.plugin.logging.Log; +import org.apache.maven.plugin.logging.SystemStreamLog; + /** * generate related self-adaptive code (native image does not support dynamic code generation. Therefore, code needs to be generated before compilation) */ public class CodeGenerator { - public static void execute(String p, Log log) { log.info("Start generating code:" + p); - List> classes = new ClassFinder().findClassSet("org.apache.dubbo", msg -> { - log.info(msg); - }).stream().map(it -> { - try { - return Class.forName(it); - } catch (Throwable e) { - } - return null; - }).collect(Collectors.toList()); - new ArrayList<>(classes).stream().filter(it -> { - if (null == it) { - return false; - } - Annotation anno = it.getAnnotation(SPI.class); - if (null == anno) { - return false; - } - try { - Optional optional = Arrays.stream(it.getMethods()).filter(it2 -> it2.getAnnotation(Adaptive.class) != null).findAny(); - return optional.isPresent(); - } catch (Throwable ex) { - log.warn(ex.getMessage()); - return false; - } - }).forEach(it -> { - try { - SPI spi = it.getAnnotation(SPI.class); - String value = spi.value(); - if (StringUtils.isEmpty(value)) { - value = "adaptive"; - } - AdaptiveClassCodeGenerator codeGenerator = new AdaptiveClassCodeGenerator(it, value); - String code = codeGenerator.generate(); - String file = p + File.separator + it.getName().replaceAll("\\.", Matcher.quoteReplacement(File.separator)); - String dir = Paths.get(file).getParent().toString(); - FileUtils.forceMkdir(new File(dir)); - code = licensedStr + code + "\n"; - File tmpFile = new File(file + "$Adaptive.java"); - FileUtils.write(tmpFile, code, Charset.defaultCharset()); - log.info("Generate file:" + tmpFile); - } catch (Throwable e) { - log.error("error:" + it.getPackage()); - } - }); + List> classes = new ClassFinder() + .findClassSet("org.apache.dubbo", msg -> { + log.info(msg); + }) + .stream() + .map(it -> { + try { + return Class.forName(it); + } catch (Throwable e) { + } + return null; + }) + .collect(Collectors.toList()); + new ArrayList<>(classes) + .stream() + .filter(it -> { + if (null == it) { + return false; + } + Annotation anno = it.getAnnotation(SPI.class); + if (null == anno) { + return false; + } + try { + Optional optional = Arrays.stream(it.getMethods()) + .filter(it2 -> it2.getAnnotation(Adaptive.class) != null) + .findAny(); + return optional.isPresent(); + } catch (Throwable ex) { + log.warn(ex.getMessage()); + return false; + } + }) + .forEach(it -> { + try { + SPI spi = it.getAnnotation(SPI.class); + String value = spi.value(); + if (StringUtils.isEmpty(value)) { + value = "adaptive"; + } + AdaptiveClassCodeGenerator codeGenerator = new AdaptiveClassCodeGenerator(it, value); + String code = codeGenerator.generate(); + String file = p + + File.separator + + it.getName().replaceAll("\\.", Matcher.quoteReplacement(File.separator)); + String dir = Paths.get(file).getParent().toString(); + FileUtils.forceMkdir(new File(dir)); + code = licensedStr + code + "\n"; + File tmpFile = new File(file + "$Adaptive.java"); + FileUtils.write(tmpFile, code, Charset.defaultCharset()); + log.info("Generate file:" + tmpFile); + } catch (Throwable e) { + log.error("error:" + it.getPackage()); + } + }); log.info("End of code generation"); } - public static void main(String[] args) { URL r = Thread.currentThread().getContextClassLoader().getResource(""); String targetClassPath = new File(r.getFile()).getAbsolutePath(); - String p = Paths.get(targetClassPath).getParent().getParent().toString() + File.separator + "src" + File.separator + "main" + File.separator + "java"; + String p = Paths.get(targetClassPath).getParent().getParent().toString() + File.separator + "src" + + File.separator + "main" + File.separator + "java"; execute(p, new SystemStreamLog()); } - - private static String licensedStr = "/*\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 String licensedStr = + "/*\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-native-plugin/src/main/java/org/apache/dubbo/maven/plugin/DubboNativeCodeGeneratorMojo.java b/dubbo-native-plugin/src/main/java/org/apache/dubbo/maven/plugin/DubboNativeCodeGeneratorMojo.java index 76e7c27d78d..5c98dbb2fb7 100644 --- a/dubbo-native-plugin/src/main/java/org/apache/dubbo/maven/plugin/DubboNativeCodeGeneratorMojo.java +++ b/dubbo-native-plugin/src/main/java/org/apache/dubbo/maven/plugin/DubboNativeCodeGeneratorMojo.java @@ -14,21 +14,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.maven.plugin; -import org.apache.commons.io.FileUtils; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.logging.Log; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.project.MavenProject; - import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.List; +import org.apache.commons.io.FileUtils; +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugin.logging.Log; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.project.MavenProject; + /** * generate related self-adaptive code (native image does not support dynamic code generation. Therefore, code needs to be generated before compilation) */ @@ -50,7 +49,8 @@ public void execute() { private void generateCode(Log log, MavenProject project) throws IOException { String baseDir = project.getBasedir().getPath(); - File source = new File(baseDir + File.separator + "src" + File.separator + "main" + File.separator + "generated"); + File source = + new File(baseDir + File.separator + "src" + File.separator + "main" + File.separator + "generated"); FileUtils.forceMkdir(source); project.addCompileSourceRoot(source.getAbsolutePath()); log.info("Source directory: " + source + " added."); @@ -60,18 +60,21 @@ private void generateCode(Log log, MavenProject project) throws IOException { } private void copyNativeConfigFile(Log log, MavenProject project) { - String[] nativeFiles = {"META-INF/native-image/reflect-config.json", + String[] nativeFiles = { + "META-INF/native-image/reflect-config.json", "META-INF/native-image/jni-config.json", "META-INF/native-image/proxy-config.json", "META-INF/native-image/resource-config.json", - "META-INF/native-image/serialization-config.json"}; + "META-INF/native-image/serialization-config.json" + }; Arrays.stream(nativeFiles).forEach(nativeFile -> { InputStream is = DubboNativeCodeGeneratorMojo.class.getClassLoader().getResourceAsStream(nativeFile); project.getResources().stream().findFirst().ifPresent(resource -> { String directory = resource.getDirectory(); try { - FileUtils.forceMkdir(new File(directory + File.separator + "META-INF" + File.separator + "native-image" + File.separator)); + FileUtils.forceMkdir(new File(directory + File.separator + "META-INF" + File.separator + + "native-image" + File.separator)); File file = new File(directory + File.separator + nativeFile); if (!file.exists()) { FileUtils.copyInputStreamToFile(is, file); diff --git a/dubbo-native-plugin/src/main/java/org/apache/dubbo/maven/plugin/Test.java b/dubbo-native-plugin/src/main/java/org/apache/dubbo/maven/plugin/Test.java index 29fc80089e8..d6f9a0293a9 100644 --- a/dubbo-native-plugin/src/main/java/org/apache/dubbo/maven/plugin/Test.java +++ b/dubbo-native-plugin/src/main/java/org/apache/dubbo/maven/plugin/Test.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.maven.plugin; import java.util.Set; @@ -23,8 +22,7 @@ public class Test { public static void main(String[] args) { ClassFinder finder = new ClassFinder(); - Set set = finder.findClassSet("org.apache.dubbo", msg -> { - }); + Set set = finder.findClassSet("org.apache.dubbo", msg -> {}); System.out.println(set.size()); } } diff --git a/dubbo-native/pom.xml b/dubbo-native/pom.xml index 449148f20ae..90bad192f08 100644 --- a/dubbo-native/pom.xml +++ b/dubbo-native/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-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-native/src/main/java/org/apache/dubbo/aot/generate/AotProcessor.java b/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/AotProcessor.java index c375c0934fc..479410b41fe 100644 --- a/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/AotProcessor.java +++ b/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/AotProcessor.java @@ -34,21 +34,21 @@ public static void main(String[] args) { 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()); + .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()); writer.writeReflectionConfig(reflectRepository); - - } - - } diff --git a/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ClassSourceScanner.java b/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ClassSourceScanner.java index b3fda54d4a9..6653a254733 100644 --- a/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ClassSourceScanner.java +++ b/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 List> spiClassesWithAdaptive() { * @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 Map> adaptiveClasses() { * @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 Map> distinctSpiExtensionClasses(Set spiResource * 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 @@ private Map> loadResource(URL resourceUrl) { 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 @@ private List getResourceContent(URL resourceUrl) throws IOException { } return newContentList; } - - } diff --git a/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ConditionalDescriber.java b/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ConditionalDescriber.java index bf158f05008..c392d6eeddb 100644 --- a/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ConditionalDescriber.java +++ b/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ConditionalDescriber.java @@ -22,5 +22,4 @@ public interface ConditionalDescriber { String getReachableType(); - } diff --git a/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ExecutableDescriber.java b/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ExecutableDescriber.java index 3423a50e007..19cc334c2b9 100644 --- a/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ExecutableDescriber.java +++ b/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ExecutableDescriber.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.aot.generate; - import java.lang.reflect.Constructor; import java.lang.reflect.Executable; import java.util.Arrays; @@ -33,9 +32,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) { @@ -44,7 +47,6 @@ public ExecutableDescriber(String name, List parameterTypes, ExecutableM this.mode = mode; } - public List getParameterTypes() { return parameterTypes; } diff --git a/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/JarScanner.java b/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/JarScanner.java index e39da4818ce..78d1a783f44 100644 --- a/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/JarScanner.java +++ b/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 @@ protected Map> forNames(Collection classNames) { return classes; } - private void scanURL(String prefixName) { try { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); @@ -127,7 +125,6 @@ private void scanJar(JarFile jar) { } else { resourcePathCache.add(name); } - } } @@ -142,5 +139,4 @@ private boolean matchedDubboClasses(String path) { private String toClassName(String path) { return path.substring(0, path.length() - 6).replace(File.separator, "."); } - } diff --git a/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/NativeClassSourceWriter.java b/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/NativeClassSourceWriter.java index 2e727fc0d12..042d5ff3311 100644 --- a/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/NativeClassSourceWriter.java +++ b/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.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 void writeTo(List> classes, String generatedSources) { 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 void writeTo(List> classes, String generatedSources) { }); } - 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-native/src/main/java/org/apache/dubbo/aot/generate/NativeConfigurationWriter.java b/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/NativeConfigurationWriter.java index 86299d02af6..afeb22c3ff2 100644 --- a/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/NativeConfigurationWriter.java +++ b/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/NativeConfigurationWriter.java @@ -49,8 +49,7 @@ protected void writeTo(String fileName, Consumer writer) { try (FileWriter out = new FileWriter(file)) { writer.accept(createJsonWriter(out)); } - } - catch (IOException ex) { + } catch (IOException ex) { throw new IllegalStateException("Failed to write native configuration for " + fileName, ex); } } @@ -66,20 +65,15 @@ private File createIfNecessary(String filename) throws IOException { 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)); } private BasicJsonWriter createJsonWriter(Writer out) { return new BasicJsonWriter(out); } - - } diff --git a/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ReflectConfigMetadataRepository.java b/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ReflectConfigMetadataRepository.java index 1a22d35e33f..77fa888d486 100644 --- a/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ReflectConfigMetadataRepository.java +++ b/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ReflectConfigMetadataRepository.java @@ -35,27 +35,41 @@ public ReflectConfigMetadataRepository() { } public 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; } public 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; } public 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; } public 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-native/src/main/java/org/apache/dubbo/aot/generate/ReflectionConfigWriter.java b/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ReflectionConfigWriter.java index 16ad5cb2110..97ae80d157d 100644 --- a/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ReflectionConfigWriter.java +++ b/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ReflectionConfigWriter.java @@ -55,7 +55,10 @@ private void handleCondition(Map attributes, TypeDescriber descr } 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) { @@ -65,12 +68,20 @@ private Map toAttributes(FieldDescriber describer) { } 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) { @@ -82,48 +93,47 @@ private Map toAttributes(ExecutableDescriber describer) { 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-native/src/main/java/org/apache/dubbo/aot/generate/ResourceBundleDescriber.java b/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceBundleDescriber.java index 35fab65e49a..e50bb8605a3 100644 --- a/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceBundleDescriber.java +++ b/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/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-native/src/main/java/org/apache/dubbo/aot/generate/ResourceConfigMetadataRepository.java b/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceConfigMetadataRepository.java index 372d6c40baf..907a6c1065d 100644 --- a/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceConfigMetadataRepository.java +++ b/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceConfigMetadataRepository.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.aot.generate; - import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; @@ -38,7 +37,7 @@ public 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-native/src/main/java/org/apache/dubbo/aot/generate/ResourceConfigWriter.java b/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceConfigWriter.java index 6d1b551dd6f..03b12903d87 100644 --- a/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceConfigWriter.java +++ b/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceConfigWriter.java @@ -38,15 +38,26 @@ public void write(BasicJsonWriter writer, ResourceConfigMetadataRepository repos 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-native/src/main/java/org/apache/dubbo/aot/generate/ResourcePatternDescriber.java b/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourcePatternDescriber.java index 1e557c7330a..edd0c1e92b1 100644 --- a/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourcePatternDescriber.java +++ b/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourcePatternDescriber.java @@ -47,12 +47,9 @@ public Pattern toRegex() { 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-native/src/main/java/org/apache/dubbo/aot/generate/ResourceScanner.java b/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceScanner.java index a2191caf488..bbfebbf5089 100644 --- a/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceScanner.java +++ b/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 @@ private boolean matchedSecurityResource(String path) { 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-native/src/main/java/org/apache/dubbo/aot/generate/TypeDescriber.java b/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/TypeDescriber.java index a41f0bb2b88..dbf451f155f 100644 --- a/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/TypeDescriber.java +++ b/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/TypeDescriber.java @@ -35,9 +35,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; @@ -46,7 +50,6 @@ public TypeDescriber(String name, String reachableType, Set fiel this.memberCategories = memberCategories; } - public String getName() { return name; } diff --git a/dubbo-native/src/test/java/org/apache/dubbo/aot/generate/ResourcePatternDescriberTest.java b/dubbo-native/src/test/java/org/apache/dubbo/aot/generate/ResourcePatternDescriberTest.java index dd4e489efc9..603f9a7d032 100644 --- a/dubbo-native/src/test/java/org/apache/dubbo/aot/generate/ResourcePatternDescriberTest.java +++ b/dubbo-native/src/test/java/org/apache/dubbo/aot/generate/ResourcePatternDescriberTest.java @@ -22,7 +22,10 @@ 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-auth/pom.xml b/dubbo-plugin/dubbo-auth/pom.xml index 5ae1d98ac07..979aede2be3 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 - - UTF-8 - false - + + UTF-8 + false + - - - org.apache.dubbo - dubbo-common - ${project.version} - - - org.apache.dubbo - dubbo-rpc-api - ${project.version} - - - \ No newline at end of file + + + 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 875a3c33044..0b642b5e61a 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 AccessKeyAuthenticator(ApplicationModel applicationModel) { 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 void authenticate(Invocation invocation, URL url) throws RpcAuthenticatio } 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 @@ AccessKeyPair getAccessKeyPair(Invocation invocation, URL url) { } 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 307cd18fcc6..f331c0444ac 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 c6d8abfb12f..3bae5f1e714 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 5b53db2d175..526c7a5dff8 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 @@ 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 9e0f5cf298b..8dd5b208fd8 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 fea562fde2f..9356e472065 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 Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept 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 fb76cdfdf44..79dc883ecd6 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 Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept 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 Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept } 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 212f609c419..aff0c94db4c 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 void setOptions(String options) { @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 b7d15eb796b..19ffbdc2bc0 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.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 45fd9138e41..c8b61057b71 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 babe23c6b96..3267835bb36 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 @@ 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 @@ private static String sign(byte[] data, String key) throws RuntimeException { 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 @@ private static String sign(byte[] data, String key) throws RuntimeException { } 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 163ca15d888..e886d6e83db 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.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.mock; import static org.mockito.Mockito.when; - class AccessKeyAuthenticatorTest { @Test @@ -52,7 +51,8 @@ void testSignForRequest() { 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 @@ void testAuthenticateRequest() throws RpcAuthenticationException { 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 @@ void testAuthenticateRequestNoSignature() { @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 @@ void testGetSignatureWithParameter() { 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 1e0603a0d4b..567e43fe1b6 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.assertNotNull; import static org.mockito.Mockito.mock; - class DefaultAccessKeyStorageTest { @Test @@ -40,4 +39,4 @@ void testGetAccessKey() { 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 0dafb77c9f4..2bf31d74b95 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.verify; import static org.mockito.Mockito.when; - class ConsumerSignFilterTest { @Test @@ -61,4 +60,4 @@ void testAuthEnabled() { 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 e6f614afe8d..e0c2b5c9063 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.verify; import static org.mockito.Mockito.when; - class ProviderAuthFilterTest { @Test void testAuthDisabled() { @@ -67,7 +66,6 @@ void testAuthEnabled() { verify(invocation, atLeastOnce()).getAttachment(anyString()); } - @Test void testAuthFailed() { URL url = URL.valueOf("dubbo://10.10.10.10:2181") @@ -83,7 +81,6 @@ void testAuthFailed() { ProviderAuthFilter providerAuthFilter = new ProviderAuthFilter(ApplicationModel.defaultModel()); Result result = providerAuthFilter.invoke(invoker, invocation); assertTrue(result.hasException()); - } @Test @@ -126,7 +123,7 @@ void testAuthFailedWhenNoAccessKeyPair() { 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 @@ void testAuthFailedWhenParameterError() { 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 @@ void testAuthSuccessfully() { 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 @@ void testAuthSuccessfully() { 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 ef5c1a9f26f..b8e014d527d 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 @@ void testEncryptWithObject() { 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-qos-api/pom.xml b/dubbo-plugin/dubbo-qos-api/pom.xml index 0e16ca8a173..37395a8bdc8 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 ad890d3c819..c7c680461f9 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 @@ * @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 3c9351d9baa..bb8b3332e0a 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 QosConfiguration getQosConfiguration() { 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 0d97638673f..e76f6801b94 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 int getLevel() { 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 69f9b10e191..580c88381e4 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 QosConfiguration(Builder builder) { 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 static Builder builder() { return new Builder(); } - public static class Builder { private String welcome; private boolean acceptForeignIp; @@ -113,8 +113,7 @@ public static class Builder { 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 6463faf5c25..36b569735ea 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-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-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 5dcbd6f6f4a..58125556bae 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 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-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 441381941dd..b959577602b 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.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 DefaultCommandExecutor(FrameworkModel frameworkModel) { @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 String execute(CommandContext commandContext) throws NoSuchCommandExcepti 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 String execute(CommandContext commandContext) throws NoSuchCommandExcepti 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 e111e48fab1..77e7fa8928e 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.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 static CommandContext decode(HttpRequest request) { 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 static CommandContext decode(HttpRequest request) { 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 a43220f7528..371aafc24f6 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.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 static final CommandContext decode(String str) { 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 static final CommandContext decode(String str) { 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 0e21d2c4290..292d0005a2b 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 @@ protected boolean doExecute(String servicePattern) { 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 boolean offline(String servicePattern) { } 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 62e85b74bce..51551c0e7e5 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 boolean online(String servicePattern) { 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 @@ protected boolean doExecute(String servicePattern) { } 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 08628239738..e16d7e41b62 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 @@ 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 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 String execute(CommandContext commandContext, String[] args) { 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 ef8538f87b3..9d89c983063 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 @@ 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.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 CountTelnet(FrameworkModel frameworkModel) { 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 String execute(CommandContext commandContext, String[] args) { 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 String execute(CommandContext commandContext, String[] args) { 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) { + 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 { - Thread.sleep(1000); - } catch (InterruptedException ignored) { + send(channel, "\r\n" + PROMPT); + } catch (RemotingException ignored) { } - } - } - try { - send(channel, "\r\n" + PROMPT); - } catch (RemotingException ignored) { - } - }, "TelnetCount"); + }, + "TelnetCount"); thread.setDaemon(true); thread.start(); } @@ -134,11 +136,19 @@ public void send(Channel channel, Object message) throws RemotingException { 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 @@ private String count(Invoker invoker, String method) { 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 ceb4d5756b8..2d630f7230f 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 @@ private String specifyApplication(String appName, List models, 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 @@ private String getResponseByApplication(ApplicationModel applicationModel, Strin 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 058349e0187..5383ec3038a 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.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 61f6acd5b6d..edb9655d2cd 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 String execute(CommandContext commandContext, String[] args) { 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 3aace5d25c8..b8dfa9c9fb4 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.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 f6dac6e3ece..09f47294b89 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.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 47b58ee12c8..80ea67581b3 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 String execute(CommandContext commandContext, String[] args) { 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 2d93efda243..5c3ddedb730 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.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 8be7fbd9f23..dd466612d8b 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.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 String execute(CommandContext commandContext, String[] args) { } } - 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 @@ private static void appendConsumer(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 @@ private static void appendInvokers(StringBuilder plainOutput, Map 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 74f08ba729b..a3025147df9 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.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.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 @@ private void appendFrameworkConfig(String[] args, StringBuilder plainOutput, Map 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 @@ private void appendFrameworkConfig(String[] args, StringBuilder plainOutput, Map } } - 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 @@ private static void appendApplicationConfigs(String[] args, StringBuilder plainO } 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 @@ private static void appendApplicationConfigs(String[] args, StringBuilder plainO } 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 @@ private static void appendApplicationConfigs(String[] args, StringBuilder plainO } } - 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 @@ private static void appendModuleConfigs(String[] args, StringBuilder plainOutput } 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 @@ private static void appendModuleConfigs(String[] args, StringBuilder plainOutput } @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 a71be3cdba0..826cfaa6b35 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 57bd6c058ba..8177ad3289f 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.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 GetRecentRouterSnapshot(FrameworkModel frameworkModel) { @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 46d5bef84ba..5857f49df51 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 @@ 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 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 String execute(CommandContext commandContext, String[] args) { 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 f21e6473f8e..fe330d2df03 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.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 GracefulShutdown(FrameworkModel frameworkModel) { @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 60365cd665e..25e6c7752c0 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 @@ 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.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 String execute(CommandContext commandContext, String[] args) { } } - private String commandHelp(String commandName) { if (!commandHelper.hasCommand(commandName)) { @@ -65,9 +64,8 @@ private String commandHelp(String commandName) { 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 @@ private String drawExample(Cmd cmd) { */ 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 int compare(Class o1, Class o2) { final Integer o2s = o2.getAnnotation(Cmd.class).sort(); return o1s.compareTo(o2s); } - }); for (Class clazz : classes) { @@ -115,7 +111,6 @@ public int compare(Class o1, Class o2) { 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 3e7400ff051..5abc2f10458 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.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.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.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 InvokeTelnet(FrameworkModel frameworkModel) { @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 String execute(CommandContext commandContext, String[] args) { } 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 String execute(CommandContext commandContext, String[] args) { } 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 String execute(CommandContext commandContext, String[] args) { } } - if (!StringUtils.isEmpty(service)) { buf.append("Use default service ").append(service).append('.'); } @@ -144,12 +147,15 @@ public String execute(CommandContext commandContext, String[] args) { 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 String execute(CommandContext commandContext, String[] args) { 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 String execute(CommandContext commandContext, String[] args) { 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 cebd23f2b7e..e02f6df76ba 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.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 Live(FrameworkModel frameworkModel) { @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 13a14875e29..e9404ee304b 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 @@ 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 bc1d18178ab..b9043ecc5c7 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 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 String execute(CommandContext commandContext, String[] args) { 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 String listProvider() { 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 3ad503e63cc..6b679b47f22 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.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 57303a0def4..441e838d04b 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.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 e98abab82f5..9a37353d513 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.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 5fab71e8474..328e30b07ca 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 @@ 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 540e7279d67..3dfbf355ba7 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 a46b1163791..35dd3e01c72 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.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 5a2299410da..e4231eb8e2d 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 @@ 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 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 String execute(CommandContext commandContext, String[] args) { 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 30075490a70..f583c7768d2 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.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 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 String execute(CommandContext commandContext, String[] args) { 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 06d4a0a38b6..f93ebfdd41b 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 @@ 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 793bcc744d3..3bac6a06d3a 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 ca1eecf4705..c745c4f005d 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.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 Ready(FrameworkModel frameworkModel) { @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 String execute(CommandContext commandContext, String[] args) { 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 9d7ca8cdeaa..069ad0c7de6 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.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 String execute(CommandContext commandContext, String[] args) { } 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 9c8ac498a0e..2405c6dae39 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 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.api.CommandContext; import org.apache.dubbo.qos.command.util.SerializeCheckUtils; import org.apache.dubbo.rpc.model.FrameworkModel; -@Cmd(name = "serializeCheckStatus",summary = "get serialize check status") +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; + +@Cmd(name = "serializeCheckStatus", summary = "get serialize check status") public class SerializeCheckStatus implements BaseCommand { private final SerializeCheckUtils serializeCheckUtils; @@ -47,14 +47,15 @@ public String execute(CommandContext commandContext, String[] args) { 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 a3668d78a40..ae797dd6bd2 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 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.api.CommandContext; import org.apache.dubbo.qos.command.util.SerializeCheckUtils; import org.apache.dubbo.rpc.model.FrameworkModel; -@Cmd(name = "serializeWarnedClasses",summary = "get serialize warned classes") +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; + +@Cmd(name = "serializeWarnedClasses", summary = "get serialize warned classes") public class SerializeWarnedClasses implements BaseCommand { private final SerializeCheckUtils serializeCheckUtils; @@ -43,9 +43,9 @@ public String execute(CommandContext commandContext, String[] args) { 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 f71fba40c8f..0a8478e3be6 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.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 String execute(CommandContext commandContext, String[] args) { 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 07089481e75..96a80aaad4e 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 @@ 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 String execute(CommandContext commandContext, String[] args) { 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 ce3f7f1ca48..8459e819a6b 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.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 Startup(FrameworkModel frameworkModel) { @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 f65fe01e6e1..887c2c1a511 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 @@ 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 bae3d44de9c..89b283a6eb5 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 @@ 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 907702d1cc9..8231e5eb7a3 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 String execute(CommandContext commandContext, String[] args) { 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 926a462b61c..faad6041de8 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 boolean hasCommand(String commandName) { } 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 91f34a55e93..0125e36027b 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 c876c0ccdb1..749271c63d2 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 static String getRegisterStatus(ProviderModel providerModel) { 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 static String getConsumerAddressNum(ConsumerModel consumerModel) { 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 96bd7866933..73f84dacbcc 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/ChangeTelnetHandler.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/legacy/ChangeTelnetHandler.java index dd570a15186..b2adaf0592d 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/legacy/ChangeTelnetHandler.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/legacy/ChangeTelnetHandler.java @@ -55,12 +55,13 @@ public String telnet(Channel channel, String message) { } 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-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 958c3696c98..6cfcdc0fa25 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 String telnet(Channel channel, String message) { 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 String telnet(Channel channel, String message) { 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 String telnet(Channel channel, String message) { } } } - 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/legacy/TraceTelnetHandler.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/legacy/TraceTelnetHandler.java index d4d6397dd12..b4d6b2a01ae 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/legacy/TraceTelnetHandler.java +++ b/dubbo-plugin/dubbo-qos/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 String telnet(Channel channel, String message) { 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 String telnet(Channel channel, String message) { } } 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 String telnet(Channel channel, String message) { } return null; } - } 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 61736f2247d..d3644e338cc 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.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 boolean access(CommandContext commandContext, PermissionLevel defaultCmdR // 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 9f848b2e898..4121c399a73 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 boolean check() { } 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 653d2b9e35c..2a5afacf468 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 boolean check() { 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 a39e5557064..d33ad307925 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 @@ private void startQosServer(URL url, boolean isServer) throws RpcException { 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 @@ private void startQosServer(URL url, boolean isServer) throws RpcException { 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 9ef98b37a13..e640e655018 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 @@ 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 12c02ccea7b..c7db1f3b74a 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.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.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 void start() throws Throwable { @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 b9e86242a39..b33803a9883 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 void handlerAdded(ChannelHandlerContext ctx) throws Exception { 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 ef2ec861dd6..d23a4acd3a4 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 @@ 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.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 HttpProcessHandler(FrameworkModel frameworkModel, QosConfiguration qosCon } 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 @@ private static FullHttpResponse http(int httpCode, String result) { } 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 @@ protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws E 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 40739f80229..93b9f1d663e 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.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.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 QosProcessHandler(FrameworkModel frameworkModel, QosConfiguration qosConf @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 c12f738d59b..8927d8cd741 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 void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc 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 e2b240cc480..3759e80634b 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.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.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 @@ protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Except } 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 @@ protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Except 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 12aca73c128..3af0cdd2d40 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 483b3f63dbf..7deed677172 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 0f0ef480fcb..f89996d0efb 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 String rendering() { // 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 TLadder addItem(String item) { 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 b3bd54450a7..f96e8571844 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 TTable(int columnNum) { } } - @Override public String rendering() { final StringBuilder tableSB = new StringBuilder(); @@ -74,34 +71,27 @@ public String rendering() { 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 @@ private String drawRow(int[] widthCacheArray, int rowIndex) { 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 @@ private String drawRow(int[] widthCacheArray, int rowIndex) { } segmentSB.append(System.lineSeparator()); } - } if (hasNextLine) { @@ -176,13 +161,10 @@ private String drawRow(int[] widthCacheArray, int rowIndex) { } } } - } 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 @@ private String drawSeparationLine(final int[] widthCacheArray) { 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 TTable addRow(Object... columnDataArray) { 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 TTable addRow(Object... columnDataArray) { return this; } - /** * alignment */ @@ -376,7 +352,6 @@ public int getWidth() { public int getRowCount() { return rows.size(); } - } /** @@ -398,7 +373,6 @@ public int getColumnCount() { return columnDefineArray.length; } - /** * replace tab to four spaces * @@ -476,7 +450,8 @@ public class Border { /** * 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 Border add(int border) { 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 static String wrap(String string, int width) { } 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 274d0be8d75..6b599da45a7 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 void callback(int deep, boolean isLast, String prefix, Node node) { 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 void callback(int deep, boolean isLast, String prefix, Node node) { } } } - } - }); return treeSB.toString(); @@ -112,13 +109,7 @@ private void recursive(int deep, boolean isLast, String prefix, Node node, Callb 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 TTree end() { return this; } - /** * tree node */ @@ -250,17 +240,13 @@ Node markEnd() { 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 31ae32f3d73..fd75d83e84e 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 13d2cce945c..a3ae96b5b9d 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 @@ 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 @@ void test() { 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 aa2d727f24c..24305ce9727 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.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 @@ void testExecute1() { @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 @@ void testExecute2() throws Exception { @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 @@ void shouldNotThrowPermissionDenyException_GivenPermissionConfigAndMatchDefaultP @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 6ad804bfc68..9780dfb6424 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 58100090e49..a0a8dc9bf91 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 @@ 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.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 b761a62aebb..6a8b67531d0 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 @@ public void beforeEach() { 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 @@ public void afterEach() { @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 @@ void testChangeMessageNull() { @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 6e32cb3dd4f..0777e395464 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.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 @@ public void setUp() { given(mockCommandContext.getRemote()).willReturn(mockChannel); given(mockInvoker.getInterface()).willReturn(DemoService.class); given(mockInvoker.getUrl()).willReturn(url); - } @AfterEach @@ -77,9 +76,11 @@ public void tearDown() { @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 @@ void test() throws Exception { 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 @@ public static String buildTable(String methodName, long averageElapsed, 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 77dbf926958..0d1c2edd190 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 @@ 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 @@ void testAll(){ } @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 @@ void testFilter1(){ 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 @@ void testFilter2(){ 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 e5db43ec08f..913a252e9dc 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 @@ void testMainHelp() { @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 bb534ae6a25..84b0cc076ad 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 @@ public void after() { @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 @@ void testInvokeWithSpecifyService() throws RemotingException { 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 @@ void testInvokeWithSpecifyService() throws RemotingException { 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 @@ void testInvokeByPassingEnumValue() 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[]{"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 @@ void testInvokeByPassingEnumValue() throws RemotingException { 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 @@ void testInvokeOverriddenMethodBySelect() throws RemotingException { 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 @@ void testInvokeMethodWithMapParameter() 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 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 @@ void testInvokeMultiJsonParamMethod() 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 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 @@ void testMessageNull() throws RemotingException { 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 @@ void testInvalidMessage() throws RemotingException { 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 @@ void testInvalidMessage() throws RemotingException { 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 6cb56e4259d..369008d7c0a 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.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 @@ void testExecute() { 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 @@ private void registerProvider() { 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 @@ private void registerConsumer() { 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 7196e36e387..c523dc92051 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 @@ public void reset() { @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 @@ private void registerProvider() { 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 ef13b34b1d4..27f60e88341 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 @@ public void reset() { @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 @@ private void registerProvider() { 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 72bd1f71e53..ac4fee23ac2 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 @@ public void before() { 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 @@ void testListClient() throws Exception { 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 @@ void testListClient() throws Exception { @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 @@ void testListAllPort() throws RemotingException { @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 ebd54524df7..e4e621b6501 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 @@ public void setUp() throws Exception { ApplicationModel applicationModel = frameworkModel.newApplication(); applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("APP_" + i)); } - } @AfterEach @@ -50,22 +49,20 @@ void testExecute() { 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 21ca70c9f23..e8ab984a31f 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 @@ public void setUp() { 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 @@ public void tearDown() { @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 @@ void testSlash() throws RemotingException { @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 01152d9ef31..0be0567b12f 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.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 @@ public void setUp() { 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 b18b6ebfd71..0138eed7142 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.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 @@ void testInvokeWithoutMethodList() throws RemotingException { 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 @@ void testInvokeWithIllegalMessage() throws RemotingException { 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 @@ void testInvokeWithNull() throws RemotingException { 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 @@ void testInvokeWithNull() throws RemotingException { 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 162c7a80408..3ef5d01ab6a 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 @@ void testNotify() { 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 91b88a5113f..9c2b5cfdb7f 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 @@ void test() { 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.assertFalse(serializeWarnedClasses.execute(commandContext1, null).contains("Test4321")); - Assertions.assertFalse(serializeWarnedClasses.execute(commandContext2, null).contains("Test4321")); + 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")); 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 7d93525da26..25fb868c5dd 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 @@ void testInvoke() throws RemotingException { 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 0676e0ab19b..b653e1d2657 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.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 @@ public void setUp() { 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 38a7b0c47e6..c58ecaa56fb 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 @@ 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.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 Void get() throws InterruptedException, ExecutionException { } @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 d5b82d11345..b2443ec9bfb 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.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 90cbc0f7691..268ee97b4be 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.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 @@ */ 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 @@ void testIsRegistered() { 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 @@ void testGetConsumerAddressNum() { 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 @@ void testGetConsumerAddressNum() { 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/ChangeTelnetHandlerTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/ChangeTelnetHandlerTest.java index e42fce162d0..338c8c359dd 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/ChangeTelnetHandlerTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/ChangeTelnetHandlerTest.java @@ -47,16 +47,15 @@ class ChangeTelnetHandlerTest { private Invoker mockInvoker; @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"); @@ -69,9 +68,7 @@ public void setUp() { given(mockInvoker.getUrl()).willReturn(URL.valueOf("dubbo://127.0.0.1:20884/demo")); } - private void givenLastCall() { - - } + private void givenLastCall() {} @AfterEach public void after() { @@ -81,22 +78,29 @@ public void after() { @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); } @@ -124,4 +128,4 @@ void testChangeCancel2() throws RemotingException { String result = change.telnet(mockChannel, "/"); assertEquals("Cancelled default service org.apache.dubbo.rpc.protocol.dubbo.support.DemoService.", result); } -} \ 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 2bd4561a337..c3559f7e99a 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 @@ void testPrintLog() throws RemotingException { 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/ProtocolUtils.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/ProtocolUtils.java index c2a088f6ce7..7b6cd2b27d2 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/ProtocolUtils.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/ProtocolUtils.java @@ -35,7 +35,8 @@ public static T refer(Class type, String url) { 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 static Exporter export(T instance, Class type, String url) { 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-qos/src/test/java/org/apache/dubbo/qos/legacy/TraceTelnetHandlerTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/TraceTelnetHandlerTest.java index 8c0adeb65a4..567d171fbe4 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/TraceTelnetHandlerTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/TraceTelnetHandlerTest.java @@ -27,15 +27,15 @@ 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 @@ void testTraceTelnetAddTracer() throws Exception { 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 @@ void testTraceTelnetAddTracer() throws Exception { Assertions.assertTrue(channels.contains(mockChannel)); } -} \ No newline at end of file +} diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/channel/MockChannel.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/channel/MockChannel.java index 4eb09a30edc..6410aa475f3 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/channel/MockChannel.java +++ b/dubbo-plugin/dubbo-qos/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-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 cb1114d7cc6..3c54f5daa78 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 @@ 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 39503802561..dea474c2443 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 @@ 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 466e193acd9..1b862ae88f3 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 String getThreadName() { } 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 Set keys(Map map) { 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 09154632c20..838fe0a953b 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 ff61e579704..c0548771662 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 @@ /** * 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 9588c9a8c03..c41aa89a437 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 c719be8d50d..04c3d82648c 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 DemoException(String message) { 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 67d9988e43e..ae057f30c76 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 @@ 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 37d8f4ea23f..f6d85e3c9cb 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 String sayName(String name) { return "say:" + name; } - public void throwDemoException() throws DemoException { throw new DemoException("DemoServiceImpl"); } @@ -39,5 +38,4 @@ public List getUsers(List users) { 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 5de484b373b..e2fd02664fa 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.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.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 @@ void testGenericServiceException() { 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 @@ void testGenericReferenceException() { 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 @@ void testGenericSerializationJava() throws Exception { 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 @@ void testGenericSerializationJava() throws Exception { 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 @@ void testGenericSerializationJava() throws Exception { // 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 @@ void testGenericInvokeWithBeanSerialization() { 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 @@ void testGenericImplementationWithBeanSerialization() { 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 @@ protected static class GenericParameter { 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 8cb7a59eb3e..f0c7ffd2ad8 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 boolean equals(Object obj) { } 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 eef2013fde9..9524b1fa40c 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.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 f3b0def49c4..f6a19e4b5cc 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 @@ void testRefer() throws Exception { @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 @@ void testMultiProtocol() throws Exception { 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 574d1171d16..f8a193535e4 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 @@ void shouldShowIpNotPermittedMsg_GivenAcceptForeignIpFalseAndEmptyWhiteList() th 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 @@ void shouldShowIpNotPermittedMsg_GivenAcceptForeignIpFalseAndNotMatchWhiteList() 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 @@ void shouldNotShowIpNotPermittedMsg_GivenAcceptForeignIpFalseAndMatchWhiteList() 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 @@ void shouldNotShowIpNotPermittedMsg_GivenAcceptForeignIpFalseAndMatchWhiteListRa 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 7afb2becabc..9919557e818 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 @@ void test1() throws Exception { 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 @@ void test2() throws Exception { 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 @@ void test3() throws Exception { 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 487496e0198..9a27ea8472c 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.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 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 @@ void testDecodeHttp() throws Exception { 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 @@ void testDecodeTelnet() throws Exception { 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 @@ void testDecodeTelnet() throws Exception { 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 045bcd39427..e3bd8b8b28c 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 @@ void testPrompt() throws Exception { @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 @@ void testBye() throws Exception { @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 @@ void testUnknownCommand() throws Exception { @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 dc9d5d60bab..d90bbf2e58c 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 @@ 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 @@ void test2() throws Exception { 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 319f84379b9..e181924d95b 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 @@ void testRendering() throws Exception { 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 7a83be62f4d..e40b086ff70 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 @@ void test1() throws Exception { 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 d990d244eec..081740876e5 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 @@ void test() throws Exception { 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 9ac35a68a8f..f32cbe921ed 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 0328c59d8fe..70d7028a006 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 96fa64866cd..86db8575829 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 1233dd8a54a..2ae90228043 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 @@ */ 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 7d59244d3d1..cc4f0de86f0 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 8f5382e1692..c5b93367416 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 1e8ef5e37f2..ce4206b2b68 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 c23e9874b97..dfe55003f39 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.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 @@ */ public final class ReactorClientCalls { - private ReactorClientCalls() { - } + private ReactorClientCalls() {} /** * Implements a unary -> unary call as Mono -> Mono @@ -43,29 +42,28 @@ private 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 void onCompleted() { * @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 static Flux oneToMany(Invoker< * @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 static Mono manyToOne(Invoker< * @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 33c54d1496d..33e529336e5 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,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; @@ -22,19 +21,19 @@ import org.apache.dubbo.reactive.ServerTripleReactorSubscriber; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; import org.apache.dubbo.rpc.protocol.tri.observer.ServerCallToObserverAdapter; -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 @@ -43,19 +42,16 @@ private 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(); + } + }); }); } @@ -66,9 +62,8 @@ public static void oneToOne(T request, * @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<>()); @@ -85,25 +80,26 @@ public static void oneToMany(T request, * @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); @@ -118,13 +114,15 @@ public static StreamObserver manyToOne(StreamObserver responseObser * @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 72f9b50905f..6c14436249b 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 d74a9ab1187..f82a6a614bd 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 a672c5b8524..b5b0534fff6 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 f20a3ece5e6..7cf32a2dbaa 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 1f979efc78e..99f44c7cc58 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 42276cdd8be..ddad0dd86f8 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 e1c8fd3122b..693d4cce623 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,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.common.stream.StreamObserver; import org.apache.dubbo.reactive.handler.ManyToOneMethodHandler; -import org.apache.dubbo.rpc.protocol.tri.observer.ServerCallToObserverAdapter; - -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; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * 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 2fbba77633f..e81e0a77c7c 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 @@ void init() { @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 @@ void testInvoke() { @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 22e1d42ec56..8e3753aa623 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 a31a27bf896..984a6fc3624 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 - 3.22.2 - 1.55.1 - + dubbo-security + jar - dubbo-security - jar + + false + 3.22.2 + 1.55.1 + - - - - 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 - 0.6.1 - - com.google.protobuf:protoc:${protobuf-java.version}:exe:${os.detected.classifier} - grpc-java - io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier} - - - - - compile - compile-custom - - - - - - + + + + org.xolstice.maven.plugins + protobuf-maven-plugin + 0.6.1 + + com.google.protobuf:protoc:${protobuf-java.version}:exe:${os.detected.classifier} + grpc-java + io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier} + + + + + compile + compile-custom + + + + + + + + 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 8759823e6c0..1e572676a7c 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 CertConfig(String remoteAddress, String envType, String caCertPath, Strin 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 boolean equals(Object o) { 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 2ed9be0e76a..13ba78e41e9 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 @@ 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 void onStopping(ApplicationModel scopeModel) { } @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 719f2ef84d7..e78ca918983 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 boolean equals(Object o) { 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 42ffa1d703f..ccf9be4bd8e 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 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-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 3fcb7fb80a1..bddef4a0942 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.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.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 synchronized void connect(CertConfig certConfig) { // 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 synchronized void connect(CertConfig certConfig) { * 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 @@ protected void scheduleRefresh() { 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 @@ protected CertPair generateCert() { 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 @@ protected CertPair refreshCert() throws IOException { } 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()); - - return new CertPair(privateKeyPem, - certificateResponse.getCertPem(), - String.join("\n", certificateResponse.getTrustCertsList()), - 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()); } - 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 @@ protected static KeyPair signWithRsa() { 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 @@ protected static KeyPair signWithEcdsa() { 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 @@ private String generatePemKey(String type, byte[] content) throws IOException { */ 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 df2dfded25a..808e50e1cec 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 @@ public class DubboCertProvider implements CertProvider { private final DubboCertManager dubboCertManager; - public DubboCertProvider(FrameworkModel frameworkModel) { dubboCertManager = frameworkModel.getBeanFactory().getBean(DubboCertManager.class); } @@ -46,9 +45,11 @@ public ProviderCert getProviderConnectionConfig(URL localAddress) { 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 Cert getConsumerConnectionConfig(URL remoteAddress) { 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 ce6a5fa665b..2fcfb191456 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.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 @@ void testEmpty1() { 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 @@ void testEmpty2() { 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 @@ void testCreate() { 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 @@ void testCreate() { 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 @@ void testFailure() { 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 @@ public Class loadClass(String name) throws ClassNotFoundException { }; 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 @@ public Class loadClass(String name) throws ClassNotFoundException { }; 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 @@ public Class loadClass(String name) throws ClassNotFoundException { 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 @@ void testParams1() { 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 @@ void testParams1() { 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 @@ void testParams2() { 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 a25c9d330cd..bb07578af1c 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.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 @@ protected CertPair generateCert() { } @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 @@ void testConnect1() { 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 @@ void testConnect2() { 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 @@ void testDisconnect() { 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 @@ void testSignWithEcdsa() { 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 @@ void testRefreshCert() throws IOException { 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 e022473ee44..5be5f3a242e 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.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 @@ public Class loadClass(String name) throws ClassNotFoundException { }; 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 @@ public Class loadClass(String name) throws ClassNotFoundException { }; 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 @@ public Class loadClass(String name) throws ClassNotFoundException { 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 @@ void getProviderConnectionConfigTest() { 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 a9d05888365..5bb4688fbea 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 e3a246d2bc4..6999931d08e 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.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 void onResponse(Result result, Invoker invoker, Invocation invocation) } @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 c71ef982f50..ec1bdb90995 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.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 ff8a4fbea78..0183938b54a 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.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 @@ private void getSecurityContext(Invocation invocation) { 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 7d81ca4c86f..853398f0098 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 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 Result invoke(Invoker invoker, Invocation invocation) { } 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 97d1048bbad..e70aeaeb9e9 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 T deserialize(byte[] bytes, Class clazz) { 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 String serialize(Object object) { 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 @@ private void registerDefaultModule() { 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 @@ private void registerDefaultModule() { 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 2674172fe5d..15335e44b40 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 @@ 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 d87a90cd83d..1a9531d5631 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.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 void initializeFrameworkModel(FrameworkModel frameworkModel) { 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 void initializeFrameworkModel(FrameworkModel frameworkModel) { 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 f40adf4822e..b9d62c2eef4 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 67d1368a11e..ea2d613ec6b 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.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 afc7e65b76f..04e6f806fcb 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 - - - false - + dubbo-plugin + The registry module of dubbo project + + dubbo-qos + dubbo-auth + dubbo-reactive + dubbo-security + dubbo-spring-security + dubbo-qos-api + + + 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-registry/dubbo-registry-api/pom.xml b/dubbo-registry/dubbo-registry-api/pom.xml index 4c3a15f3536..2468037ca8f 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 + + 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 18eba314c83..f72b23e1672 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 55418c99aea..936cc6433a1 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 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 void subscribe(URL url, NotifyListener listener) { } } - @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 08f1a1aa2a8..30fbd0cf184 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 @@ default ServiceInstancesChangedListener getServiceListener() { 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 8ed918aae59..5c3669170ec 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 6fe365d9705..90713759174 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 RegistryFactoryWrapper(RegistryFactory 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 ae60b913fab..d399e6c5048 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 RegistryNotifier(URL registryUrl, long delayTime, ScheduledExecutorServic 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 synchronized void notify(Object rawAddresses) { // 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 void run() { } } } - } 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 40c788985c9..618795c627f 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 @@ -38,7 +38,5 @@ public void initializeApplicationModel(ApplicationModel applicationModel) { } @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 66d0c91267a..5093c6e7190 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 283d7ee7e6c..4c514926672 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 @@ @SPI public interface RegistryServiceListener { - default void onRegister(URL url, Registry registry) { - - } - - - default void onUnregister(URL url, Registry registry) { - - } - - default void onSubscribe(URL url, Registry registry) { + default void onRegister(URL url, Registry registry) {} - } + default void onUnregister(URL url, Registry registry) {} - default void onUnsubscribe(URL url, Registry registry) { + default void onSubscribe(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/client/AbstractServiceDiscovery.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java index b3b771c20e4..341d8926f84 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 @@ private AbstractServiceDiscovery(ApplicationModel applicationModel, String servi 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 synchronized void update() throws RuntimeException { 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 synchronized void unregister() throws RuntimeException { 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 MetadataInfo getRemoteMetadata(String revision, List ins 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 MetadataInfo getRemoteMetadata(String revision, List ins } 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 void unsubscribe(URL url, NotifyListener listener) { @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 @@ protected void reportMetadata(MetadataInfo metadataInfo) { 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 @@ protected void reportMetadata(MetadataInfo metadataInfo) { 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 @@ private String getCacheNameSuffix() { 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 469a507510c..ae90f36d755 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 @@ protected String createRegistryCacheKey(URL url) { } 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 266615de54f..191636e19ad 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 void setRawAddress(String rawAddress) { this.rawAddress = rawAddress; } - public void setServiceName(String serviceName) { this.serviceName = serviceName; } @@ -292,8 +291,8 @@ public void setServiceMetadata(MetadataInfo serviceMetadata) { @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 boolean equals(Object o) { 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 int hashCode() { 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 String toString() { } 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 d1d46e1e559..00000000000 --- 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 d418030d6be..8cb2ff99350 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 @@ protected InstanceAddressURL() { 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 String getServiceKey() { @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 boolean hasMethodParameter(String method) { @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 Map getOriginalServiceParameters(String protocolServiceKe return params; } - /** * Avoid calling this method in RPC call. * @@ -452,7 +449,8 @@ public Map getOriginalServiceParameters(String protocolServiceKe @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 ApplicationModel getApplicationModel() { @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 2df58f9b193..c5f23b6ca52 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 NopServiceDiscovery(ApplicationModel applicationModel, URL registryURL) { } @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 4791dceab4e..5a15892c033 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 String getServiceParameter(String service, String key) { @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 @@ private Object readResolve() { // 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 d6f37d6f0fe..dfb5e18ea44 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.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(); - - 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."); + 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."); + } + 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 @@ private void updateInstanceMetadata(ServiceInstance serviceInstance) { 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 @@ private void updateInstanceMetadata(ServiceInstance serviceInstance) { // 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 final void fillServiceInstance(DefaultServiceInstance serviceInstance) { // 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 List getInstances(String serviceName) throws NullPointer } 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 f6132eac059..7cffb2dd97c 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 9f9cc984d5d..a891121ea75 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.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 @@ default void addServiceInstancesChangedListener(ServiceInstancesChangedListener * @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 @@ default boolean isAvailable() { * * @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 21680951e84..d02c902d024 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 7740ec87ddb..a0abbf5383f 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 ServiceDiscovery getServiceDiscovery() { * @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)); } /** @@ -141,7 +144,8 @@ protected boolean shouldRegister(URL providerURL) { } 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; } @@ -200,7 +204,6 @@ public void doSubscribe(URL url, NotifyListener listener) { String key = ServiceNameMapping.buildMappingKey(url); - if (mappingByUrl == null) { Lock mappingLock = serviceNameMapping.getMappingLock(key); try { @@ -210,18 +213,27 @@ public void doSubscribe(URL url, NotifyListener listener) { 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 { @@ -259,10 +271,9 @@ public void doUnsubscribe(URL url, NotifyListener listener) { 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); @@ -299,7 +310,7 @@ public List lookup(URL url) { @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(); } @@ -326,7 +337,8 @@ protected void subscribeURLs(URL url, NotifyListener listener, Set servi 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); @@ -338,7 +350,8 @@ protected void subscribeURLs(URL url, NotifyListener listener, Set servi 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); @@ -349,14 +362,16 @@ protected void subscribeURLs(URL url, NotifyListener listener, Set servi 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); @@ -398,7 +413,11 @@ public synchronized void onEvent(MappingChangedEvent event) { 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(); @@ -408,7 +427,8 @@ public synchronized void onEvent(MappingChangedEvent event) { 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 { @@ -424,7 +444,8 @@ public synchronized void onEvent(MappingChangedEvent event) { 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 456b581fded..224b2240227 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 @@ -85,13 +85,15 @@ 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; @@ -105,12 +107,15 @@ public ServiceDiscoveryRegistryDirectory(Class serviceType, URL url) { 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) { @@ -124,13 +129,19 @@ public ServiceDiscoveryRegistryDirectory(Class serviceType, URL url) { } 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); @@ -141,15 +152,20 @@ public void subscribe(URL 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); 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(); } @@ -158,7 +174,10 @@ public void unSubscribe(URL url) { @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(); } @@ -166,7 +185,8 @@ public void destroy() { @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 @@ -178,8 +198,10 @@ public synchronized void notify(List instanceUrls) { 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); @@ -197,10 +219,10 @@ protected synchronized void refreshOverrideAndInvoker(List instanceUrls) { 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) { @@ -219,18 +241,19 @@ private URL overrideWithConfigurators(List configurators, URL url) 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); @@ -242,7 +265,8 @@ private URL overrideWithConfigurators(List configurators, URL url) 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) { @@ -258,10 +282,12 @@ private InstanceAddressURL overrideWithConfigurators(List configur 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; } @@ -280,8 +306,10 @@ public boolean isServiceDiscovery() { */ @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) { @@ -289,36 +317,58 @@ private void refreshInvoker(List invokerUrls) { 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; @@ -335,13 +385,13 @@ private void refreshInvoker(List invokerUrls) { // 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()); } /** @@ -352,8 +402,10 @@ private void refreshInvoker(List invokerUrls) { * @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; } @@ -363,15 +415,24 @@ private Map> toInvokers(Map> toInvokers(Map matchedProtocolServiceKeys = instanceAddressURL.getMetadataInfo() - .getMatchedServiceInfos(consumerProtocolServiceKey) - .stream() - .filter(serviceInfo -> serviceInfo.getPort() <= 0 || serviceInfo.getPort() == port) - .map(MetadataInfo.ServiceInfo::getProtocolServiceKey) - .collect(Collectors.toList()); + List matchedProtocolServiceKeys = + instanceAddressURL.getMetadataInfo().getMatchedServiceInfos(consumerProtocolServiceKey).stream() + .filter(serviceInfo -> serviceInfo.getPort() <= 0 || serviceInfo.getPort() == port) + .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)) { @@ -409,18 +476,28 @@ private Map> toInvokers(Map 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); @@ -446,13 +523,16 @@ private boolean urlChanged(Invoker invoker, InstanceAddressURL newURL, Protoc // 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; } @@ -494,7 +574,12 @@ protected void destroyAllInvokers() { 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(); @@ -507,9 +592,11 @@ protected void destroyAllInvokers() { @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); @@ -523,7 +610,9 @@ protected Map getDirectoryMeta() { * @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; @@ -542,7 +631,12 @@ private void destroyUnusedInvokers(Map 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); } } } @@ -553,7 +647,8 @@ private class ReferenceConfigurationListener extends AbstractConfiguratorListene 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; @@ -614,7 +709,11 @@ public static final class ProtocolServiceKeyWithAddress extends ProtocolServiceK 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; } @@ -648,7 +747,8 @@ public static final class InstanceWrappedInvoker implements Invoker { 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; @@ -664,11 +764,18 @@ public Result invoke(Invocation invocation) throws RpcException { // 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); @@ -695,10 +802,12 @@ public void destroy() { @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 def02318b00..477df606ad0 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 @@ protected Registry createRegistry(URL url) { } 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 9f9aaaa8600..6ccd7b281f4 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 @@ default String getMetadata(String name, String defaultValue) { 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 9172fafb4b7..62754331784 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 2b6b2e375af..897093089f0 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 String getServiceName() { 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 61d04072f3b..ba5e7ac8035 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 @@ */ 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 ServiceInstancesChangedListener(Set serviceNames, ServiceDiscover 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 @@ private synchronized void doOnEvent(ServiceInstancesChangedEvent event) { } continue; } - List subInstances = revisionToInstances.computeIfAbsent(revision, r -> new LinkedList<>()); + List subInstances = + revisionToInstances.computeIfAbsent(revision, r -> new LinkedList<>()); subInstances.add(instance); } } @@ -155,11 +165,11 @@ private synchronized void doOnEvent(ServiceInstancesChangedEvent event) { 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 @@ private synchronized void doOnEvent(ServiceInstancesChangedEvent event) { } 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 @@ private synchronized void doOnEvent(ServiceInstancesChangedEvent event) { 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 @@ private synchronized void doOnEvent(ServiceInstancesChangedEvent event) { 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())); - - List list = newServiceUrls.computeIfAbsent(serviceInfo.getPath(), k -> new LinkedList<>()); + 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.add(new ProtocolServiceKeyWithUrls(serviceInfo.getProtocolServiceKey(), (List) urls)); } @@ -221,10 +248,14 @@ public synchronized void addListenerAndNotify(URL url, NotifyListener listener) 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 synchronized void addListenerAndNotify(URL url, NotifyListener listener) 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 @@ private boolean accept(ServiceInstancesChangedEvent event) { 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 @@ private void refreshInstance(ServiceInstancesChangedEvent event) { 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 @@ protected int hasEmptyMetadata(Map> revisionToInst 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 @@ protected int hasEmptyMetadata(Map> revisionToInst } 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 @@ protected int hasEmptyMetadata(Map> revisionToInst 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 @@ protected Map> parseMetadata(String revision, MetadataI 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 @@ protected Object getServiceUrlsCache(Map> revision 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 @@ protected Object getServiceUrlsCache(Map> revision } 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 @@ protected List getAddresses(ProtocolServiceKey protocolServiceKey, URL cons */ 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 @@ protected List toUrlsWithEmpty(List urls) { 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 boolean equals(Object o) { 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 b9440f02c56..7069d7a04af 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.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 String getAndListenInstanceMetadata(String consumerId, InstanceMetadataCh 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 @@ private SortedSet getServiceURLs(Map> exportedSer 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 3da0d20df13..62322d820b6 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 boolean hasValidMetadataCenter() { */ @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 boolean map(URL url) { } 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 boolean map(URL url) { } 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 boolean map(URL url) { } } 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 Set get(URL url) { @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 Set getAndListen(URL url, MappingListener mappingListener) { @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 6434b24ae43..9e4ed1de64a 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 @@ -56,9 +56,11 @@ 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; } @@ -71,49 +73,51 @@ public static void publishServiceDefinition(URL url, ServiceDescriptor serviceDe 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. @@ -126,8 +130,8 @@ public static ProxyHolder referProxy(ServiceInstance instance) { 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); @@ -135,7 +139,8 @@ public static ProxyHolder referProxy(ServiceInstance instance) { // 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); @@ -143,7 +148,8 @@ public static ProxyHolder referProxy(ServiceInstance instance) { 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); @@ -155,7 +161,8 @@ public static ProxyHolder referProxy(ServiceInstance instance) { 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; @@ -170,13 +177,21 @@ public static MetadataInfo getRemoteMetadata(String revision, List 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) { @@ -249,5 +267,4 @@ public ModuleModel getInternalModel() { 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 3a4e0ec76f3..3e66da4e03d 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 @@ * @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 void customize(ServiceInstance serviceInstance, ApplicationModel applicat 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 e7c20e3bff0..e8542ceab17 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 @@ * 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 void customize(ServiceInstance serviceInstance, ApplicationModel applicat 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 void customize(ServiceInstance serviceInstance, ApplicationModel applicat 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 b4eeb944da2..853ea6cf397 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 void customize(ServiceInstance serviceInstance, ApplicationModel applicat // 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 fbb858aac04..336af3c532a 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 @@ -63,7 +63,8 @@ * @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." @@ -126,9 +127,9 @@ private static Map getParams(URL providerURL) { */ 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)); } /** @@ -208,20 +209,23 @@ public static void registerMetadataAndInstance(ApplicationModel applicationModel // register service instance 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) { @@ -243,7 +247,7 @@ public static void unregisterMetadataAndInstance(ApplicationModel applicationMod 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 @@ -269,5 +273,4 @@ private static void setDefaultParams(Map params, URL providerURL } } } - } 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 750eb6e6e9c..e0509b0a37a 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 void customize(List serviceInstance) { 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 2aae71f30e1..b77bb1020e0 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 @@ private URL generateWithMetadata(String serviceName, String host, Map 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 boolean shouldMigrate(ClusterInvoker newInvoker, ClusterInvoker 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 boolean shouldMigrate(ClusterInvoker newInvoker, ClusterInvoker 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 c4662966e81..a0a6b614f7d 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 MigrationInvoker(ClusterInvoker invoker, 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 boolean migrateToForceInterfaceInvoker(MigrationRule newRule) { 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 boolean migrateToForceApplicationInvoker(MigrationRule newRule) { 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 @@ private ClusterInvoker decideInvoker() { @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 void destroy() { 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 Directory getDirectory() { @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 @@ protected void destroyServiceDiscoveryInvoker() { } 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 @@ protected void refreshServiceDiscoveryInvoker(CountDownLatch latch) { 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 @@ protected void refreshInterfaceInvoker(CountDownLatch latch) { 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 @@ private synchronized void calcPreferredInvoker(MigrationRule migrationRule) { 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 @@ protected void destroyInterfaceInvoker() { } 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 URL getConsumerUrl() { @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 920e1d65c28..ccf2dd8cd6a 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.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 synchronized void doMigrate(MigrationRule rule) { 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 @@ private boolean refreshInvoker(MigrationStep step, Float threshold, MigrationRul 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 @@ private boolean refreshInvoker(MigrationStep step, Float threshold, MigrationRul 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 de6abfd39bf..cd4cf2816c4 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 @@ */ @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 MigrationRuleListener(ModuleModel moduleModel) { 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 @@ private void init() { 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 synchronized void process(ConfigChangedEvent event) { 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 synchronized void process(ConfigChangedEvent event) { 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 synchronized void process(ConfigChangedEvent event) { 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 synchronized void process(ConfigChangedEvent event) { 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 @@ private MigrationRule parseRule(String rawRule) { } @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 b48c79cd22e..bc35f401df9 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 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 void migrateToApplicationFirstInvoker(MigrationRule newRule) { 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 846cfba368e..c8a7e68f984 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.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.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 @@ private static MigrationRule parseFromMap(Map map) { 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 MigrationStep getStep(URL consumerURL) { */ 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 boolean equals(Object o) { 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 cbc2b62c02c..6650bc29887 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 static SubMigrationRule parseFromMap(Map map) { 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 5d01197275a..8c6b0ca7994 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 @@ * 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 @@ protected final void stopListen(String key) { @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 @@ private boolean genConfiguratorsFromRawRule(String rawConfig) { } 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 1f57e972d76..87a1871067c 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.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 DynamicDirectory(Class serviceType, URL url) { 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 void unSubscribe(URL url) { } @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 List> doList(SingleRouterChain singleRouterChain, 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 void setSubscribeUrl(URL subscribeUrl) { 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 void destroy() { } } 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 void destroy() { } } 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 void destroy() { 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 void discordAddresses() { 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 boolean isNotificationReceived() { 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 5eebc1bcaac..f9d89ebf1a5 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 674747474f0..ba3e936d161 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 ClusterInvoker getInvoker(Cluster cluster, Registry registry, Clas } @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 bcdce7172f3..a86167a5070 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 void unexport() { } @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 cf33c533f1d..1eaf26c2c94 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 @@ -92,7 +92,6 @@ import static org.apache.dubbo.rpc.cluster.Constants.ROUTER_KEY; import static org.apache.dubbo.rpc.model.ScopeModelUtil.getModuleModel; - /** * RegistryDirectory */ @@ -112,6 +111,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) { @@ -128,35 +128,48 @@ public void subscribe(URL url) { 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(); @@ -167,7 +180,10 @@ public void unSubscribe(URL url) { @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(); @@ -182,12 +198,15 @@ public synchronized void notify(List urls) { } Map> categoryUrls = urls.stream() - .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)) { + .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)) { List configuratorURLs = categoryUrls.getOrDefault(CONFIGURATORS_CATEGORY, Collections.emptyList()); this.configurators = Configurator.toConfigurators(configuratorURLs).orElse(this.configurators); @@ -199,8 +218,10 @@ public synchronized void notify(List urls) { 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); @@ -249,11 +270,11 @@ private void refreshInvoker(List invokerUrls) { 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 @@ -266,30 +287,38 @@ private void refreshInvoker(List invokerUrls) { 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. @@ -304,17 +333,19 @@ private void refreshInvoker(List invokerUrls) { // 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; @@ -329,13 +360,13 @@ private void refreshInvoker(List invokerUrls) { 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) { @@ -402,7 +433,8 @@ private Optional> toRouters(List urls) { * @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; } @@ -434,13 +466,23 @@ private Map> toInvokers(Map> oldUrlInvokerMap, L // 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 @@ -475,15 +517,23 @@ private boolean checkProtocolValid(String queryProtocols, URL providerUrl) { 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; } @@ -501,9 +551,16 @@ private URL mergeUrl(URL providerUrl) { 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 @@ -511,9 +568,9 @@ private URL mergeUrl(URL providerUrl) { 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('/'); @@ -554,18 +611,19 @@ private URL overrideWithConfigurators(List configurators, URL url) 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); @@ -587,8 +645,12 @@ protected void destroyAllInvokers() { 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(); @@ -618,12 +680,18 @@ private void destroyUnusedInvokers(Map> oldUrlInvokerMap, Map> getUrlInvokerMap() { 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; } @@ -653,9 +725,9 @@ private boolean isValidCategory(URL url) { @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); @@ -712,8 +784,6 @@ protected void notifyOverrides() { @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 43dbeaf5aca..6fb5f43f322 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 @@ */ 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 Map> getOverrideListeners() { 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 @@ private static void register(Registry registry, URL registeredProviderUrl) { 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 Exporter export(final Invoker originInvoker) throws RpcExceptio // 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 Exporter export(final Invoker originInvoker) throws RpcExceptio // 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 Exporter export(final Invoker originInvoker) throws RpcExceptio } 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 @@ private URL overrideUrlWithConfig(URL providerUrl, OverrideListener listener) { 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 @@ private ExporterChangeableWrapper doLocalExport(final Invoker originIn 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 void reExport(final Invoker originInvoker, URL newInvokerUrl) { 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 void reExport(final Invoker originInvoker, URL newInvokerUrl) { 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 @@ private void doReExport(final Invoker originInvoker, ExporterChangeableWr } 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 @@ private ProviderModel.RegisterStatedURL getStatedUrl(URL registryUrl, URL provid * @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 @@ protected URL getRegistryUrl(URL url) { * @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 @@ private URL getUrlToRegistry(final URL providerUrl, final URL registryUrl) { } 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 @@ private URL getSubscribedOverrideUrl(URL registeredProviderUrl) { 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; } @@ -546,19 +603,20 @@ public Invoker refer(Class type, URL url) throws RpcException { 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 +626,13 @@ private String getPath(Map parameters, Class type) { 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 +660,8 @@ protected Invoker interceptInvoker(ClusterInvoker invoker, URL url, UR 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 +672,19 @@ public ClusterInvoker getInvoker(Cluster cluster, Registry registry, Clas 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 +699,12 @@ protected ClusterInvoker doCreateInvoker(DynamicDirectory directory, C 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 +718,7 @@ public static URL toSubscribeUrl(URL url) { 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 +735,9 @@ public void destroy() { // 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 +747,10 @@ public void destroy() { } 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 +758,19 @@ public void destroy() { 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 +782,7 @@ public List getServers() { 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 +878,10 @@ public synchronized void notify(List urls) { } 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 +898,45 @@ public synchronized void doOverrideIfNecessary() { } 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 +963,10 @@ private ProviderConfigurationListener getProviderConfigurationListener(URL url) } 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 +980,10 @@ public ServiceConfigurationListener(ModuleModel moduleModel, URL providerUrl, Ov 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 +994,8 @@ private URL overrideUrl(URL providerUrl) { @Override protected void notifyOverrides() { - ApplicationDeployer deployer = this.moduleModel.getApplicationModel().getDeployer(); + ApplicationDeployer deployer = + this.moduleModel.getApplicationModel().getDeployer(); try { deployer.increaseServiceRefreshCount(); notifyListener.doOverrideIfNecessary(); @@ -917,7 +1014,10 @@ private class ProviderConfigurationListener extends AbstractConfiguratorListener public ProviderConfigurationListener(ModuleModel moduleModel) { super(moduleModel); 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(moduleModel.getApplicationModel().getApplicationName() + CONFIGURATORS_SUFFIX); } } @@ -935,7 +1035,8 @@ private URL overrideUrl(URL providerUrl) { @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 +1076,11 @@ public ExporterChangeableWrapper(ReferenceCountExporter exporter, Invoker 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 +1104,19 @@ public void register() { 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 +1126,18 @@ public synchronized void unregister() { 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 +1147,37 @@ public synchronized void unregister() { 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 +1238,4 @@ public URL getRegisterUrl() { 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 c6226db1327..cdbffdedfe0 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 void run(Timeout timeout) throws Exception { // 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 void run(Timeout timeout) throws Exception { // 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 c4d9cc6f08c..66b369b1630 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 06d1ec3151b..a845e6e44ed 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 4cf3aa4ebf2..bc75aed5756 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 4b873f71b80..fa17ffe31f6 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 f8e6080d222..b40958a84d3 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 Status check() { } 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 1ba9b330b80..431632a731a 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 @@ protected AbstractRegistry(URL url) { 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 void doSaveProperties(long version) { } 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 void doSaveProperties(long version) { 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 void doSaveProperties(long version) { 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 @@ private void loadProperties() { } } 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 @@ protected void notify(List urls) { 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 @@ protected void notify(URL url, NotifyListener listener, List urls) { 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 @@ private void saveProperties(URL url) { 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 void destroy() { } } 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 void destroy() { } } 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 @@ protected boolean acceptable(URL urlToRegistry) { 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 3400ac1ff1c..c24d4c6b3f4 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 @@ */ 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 void setApplicationModel(ApplicationModel applicationModel) { @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 Registry getRegistry(URL url) { } 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 Registry getRegistry(URL url) { 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 @@ protected String createRegistryCacheKey(URL url) { } 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 0fce283a38c..94b38c6224e 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.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 @@ * @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 @@ protected CacheableFailbackRegistry(URL url) { 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 @@ protected static int getIntConfig(ScopeModel scopeModel, String key, int def) { } 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 @@ protected void evictURLCache(URL url) { } 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 @@ protected void evictURLCache(URL url) { // 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 @@ protected List toUrlsWithEmpty(URL consumer, String path, Collection 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 @@ protected ServiceAddressURL createURL(String rawProvider, URL consumerURL, Map 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 void run() { 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 void run() { } 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 void run() { 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 cae73df67f2..0a18f2572a8 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.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 84613f74fe8..5d311ca17d8 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 @@ -36,8 +36,8 @@ import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; -import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_NOTIFY_EVENT; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_NOTIFY_EVENT; import static org.apache.dubbo.registry.Constants.DEFAULT_REGISTRY_RETRY_PERIOD; import static org.apache.dubbo.registry.Constants.REGISTRY_RETRY_PERIOD_KEY; @@ -70,7 +70,8 @@ public FailbackRegistry(URL url) { 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) { @@ -192,11 +193,11 @@ ConcurrentMap getFailedUnsubscribed() { return failedUnsubscribed; } - @Override public void register(URL url) { if (!acceptable(url)) { - logger.info("URL " + url + " will not be registered to Registry. Registry " + this.getUrl() + " does not accept service of this protocol type."); + logger.info("URL " + url + " will not be registered to Registry. Registry " + this.getUrl() + + " does not accept service of this protocol type."); return; } super.register(url); @@ -210,16 +211,24 @@ public void register(URL url) { // 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 @@ -230,7 +239,8 @@ public void register(URL url) { @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); @@ -241,7 +251,10 @@ public void reExportRegister(URL url) { 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); } } } @@ -259,16 +272,24 @@ public void unregister(URL url) { // 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 @@ -286,7 +307,10 @@ public void reExportUnregister(URL url) { 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); } } } @@ -304,11 +328,17 @@ public void subscribe(URL url, NotifyListener listener) { 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) { @@ -316,7 +346,12 @@ public void subscribe(URL url, NotifyListener listener) { } 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); } } @@ -336,16 +371,24 @@ public void unsubscribe(URL url, NotifyListener listener) { 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 @@ -365,7 +408,12 @@ protected void notify(URL url, NotifyListener listener, List urls) { 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 e01f3118ff6..d6ba90cf7e9 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.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 void putRegistry(String key, Registry registry) { } 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 void reset() { 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 boolean isAvailable() { } @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 d881344a911..b1ff33fddcb 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.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 @@ public void setUp() throws Exception { 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 @@ void testEmptyProtection() { emptyRegistry.clearChildren(); assertEquals(0, currentUrls.get().size()); assertEquals(EMPTY_LIST, currentUrls.get()); - } @Test @@ -284,6 +286,5 @@ void testNoEmptyProtection() { 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 363adec7fa3..ecdcb694349 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 @@ void testSubscribe() { 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 @@ void testSubscribe() { 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 @@ void testSubscribe() { 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 50fa724a978..cfcf7aa0802 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 @@ protected boolean isMatch(URL subscribeUrl, URL providerUrl) { } @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 162f72de0b4..13b3cc333cc 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,59 +34,37 @@ public boolean checkLogHappened(String msgPrefix) { } @Override - public void trace(String msg) { - - } + public void trace(String msg) {} @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(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(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(Throwable e) { - - } + public void warn(Throwable e) {} @Override public void warn(String msg, Throwable e) { @@ -94,19 +72,13 @@ public void warn(String msg, Throwable e) { } @Override - public void error(String msg) { - - } + public void error(String msg) {} @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 fdf5d25ccbb..1c024d9b5a3 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 @@ */ 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 @@ void testRegistry() { 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 @@ public void run() { } } } - } 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 a5c43cf7936..51238d8a400 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 static boolean getBooleanProperty(String key, boolean defaultValue) { 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 static NetworkInterface getNetworkInterface() { } 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 c87b31c750d..4684e324526 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.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 @@ void test() throws Exception { 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 @@ void test() throws Exception { 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 391e0e13841..9ea7ab713bc 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 3cf932e0ac0..78383335705 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 37466c8a405..c81ca906450 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 @@ 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 fcd3dcd76c3..aedbed07274 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 @@ 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.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); - -// testMigrationRule(); + 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(); 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 static void testMigrationRule() { } 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 static void testAppMigrationRule() { } 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 static void testStartupConfig() { } 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" + - "..."; - -// System.out.println(str); + 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); try { String path = "/dubbo/config/dd-test*org.apache.dubbo.demo.DemoService:1.0.4/configurators"; @@ -166,35 +167,33 @@ public static void testProviderConfig() { } 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 static void testConsumerConfig() { } 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 static void setData(String path, String data) throws Exception { } 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 void childEvent(CuratorFramework client, TreeCacheEvent event) { 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 @@ private static String pathToKey(String path) { } 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 65b39fc83a7..99f72eeb2c2 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.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 11c618d651d..742ba2e8a94 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 @@ 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 @@ void testInstanceOperations() { 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 6e8b8b4026a..00000000000 --- 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 1667dba8e0d..28c00b73eff 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.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.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.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 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 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 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 @@ private MetadataInfo createMetaDataInfo() { } 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 @@ public void setUp() { @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 @@ void test1() { 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 @@ void test1() { 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 @@ void test2() { 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 9b759b8ef4d..a12f414cba1 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 @@ void test() throws InterruptedException { 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 @@ void test() throws InterruptedException { 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 @@ void test() throws InterruptedException { 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 72bb09cbd5a..f1711eb3b34 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.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.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 @@ public static void setUp() { instanceList2.add(new DefaultServiceInstance()); instanceList2.add(new DefaultServiceInstance()); - } @AfterEach @@ -136,20 +137,20 @@ void testDoSubscribe() { 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 @@ void testDoSubscribe() { serviceDiscoveryRegistry.unsubscribe(checkURL, testServiceListener); } - //test provider case + // test provider case checkURL = url.addParameter(PROVIDED_BY, APP_NAME1); try { @@ -196,7 +197,8 @@ void testSubscribeURLs() { 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 @@ void testSubscribeURLs() { 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 @@ void testSubscribeURLs() { 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 @@ void testUnsubscribe() { 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 e5a93351457..00000000000 --- 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 02b01cf5af6..66a0376841b 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.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.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 @@ public static void setUp() { 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 @@ public static void setUp() { 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 @@ public static void setUp() { 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 @@ public void testMultipleAppEmptyNotification() { 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 @@ public void testMultipleAppEmptyNotification() { 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 @@ public void testSubscribeMultipleProtocols() { 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 @@ public void testRevisionFailureOnStartup() { 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 @@ public MetadataInfo answer(InvocationOnMock invocationOnMock) throws Throwable { 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 @@ public MetadataInfo answer(InvocationOnMock invocationOnMock) throws Throwable { 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 @@ static List buildInstances(List rawURls) { 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 37e863121c4..942eaca3cc8 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.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.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 static void setUp() { 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 static void setUp() { 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 static void setUp() { 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 void testMultipleAppEmptyNotification() { 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 void testMultipleAppEmptyNotification() { 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 void testSubscribeMultipleProtocols() { 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 void testRevisionFailureOnStartup() { 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 MetadataInfo answer(InvocationOnMock invocationOnMock) throws Throwable { 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 MetadataInfo answer(InvocationOnMock invocationOnMock) throws Throwable { 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 @@ static List buildInstances(List rawURls) { 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 57b8086324c..00000000000 --- 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 0f9a347f486..c7ce2cba61b 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.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 @@ void testMap() { // 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; - - @Override - public Boolean answer(InvocationOnMock invocationOnMock) { - if (++counter == 10) { - return true; - } - return false; - } - }); + 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; + } + }); 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 4a590662882..65d2e7e578d 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 @@ */ 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 3c6919d6447..b29f42ae775 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.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.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 @@ public static void clearUp() { 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 @@ void test() { 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 095708537da..93f032e3ff4 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.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 @@ */ class ServiceInstanceHostPortCustomizerTest { private static ServiceInstanceHostPortCustomizer serviceInstanceHostPortCustomizer; - + @BeforeAll public static void setUp() { serviceInstanceHostPortCustomizer = new ServiceInstanceHostPortCustomizer(); @@ -51,7 +51,7 @@ public static void setUp() { public static void clearUp() { ApplicationModel.reset(); } - + @Test void customizePreferredProtocol() throws ExecutionException, InterruptedException { ScopeBeanFactory beanFactory = mock(ScopeBeanFactory.class); @@ -64,7 +64,8 @@ void customizePreferredProtocol() throws ExecutionException, InterruptedExceptio 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 81362c384fa..9a199e78788 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 @@ public static void clearUp() { ApplicationModel.reset(); } - /** * Only 'include' policy spicified in Customized Filter will take effect */ @@ -54,15 +53,18 @@ void testCustomizeWithIncludeFilters() { 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 @@ void testCustomizeWithExcludeFilters() { 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 b736f31530c..00000000000 --- 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 91aba6b4cf0..0ce4e31aef5 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.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 @@ void testBuild() { 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 d6bd958d1f5..df091959f3e 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.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 @@ public static void clearUp() { @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 @@ void testBuild() { 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 @@ void testBuild() { 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 86743ce816d..6af958263d4 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 String[] serviceParamsExcluded() { */ @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 b686a7dd532..7d13b00b96c 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 String[] instanceParamsIncluded() { @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 ec9c1c0fa63..34b6386c751 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 String[] instanceParamsIncluded() { @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 2fb85ccda35..00000000000 --- 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 b4e38d5b9a0..cd1d5312cf1 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 @@ 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 @@ public void clear() throws URISyntaxException { @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 @@ void testCache() { 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 @@ void testCache() { } } - @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 @@ void testCacheDump() { } } - 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 f97f0b0c1a3..8cf2992a804 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.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 fd5cf5d1159..a1ef5cbb12a 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.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.mockito.ArgumentCaptor; import org.mockito.Mockito; -import java.util.LinkedList; -import java.util.List; - class MigrationInvokerTest { @BeforeEach public void before() { @@ -83,8 +83,11 @@ void test() { 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 @@ void test() { 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 @@ void testDecide() { 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 @@ void testDecide() { 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 318da69cbe3..d203a09ee26 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 @@ void test() { 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 @@ void test() { 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 @@ private void testMigrationFailed(MigrationRule rule, URL url, MigrationRuleHandl 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 6b06bf0f9bc..3fc111646ee 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.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 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 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 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 @@ void test() { 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 @@ void test() { 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 @@ public synchronized void process(ConfigChangedEvent event) { 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 @@ void testWithInitAndNoLocalRule() { 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 @@ void testWithConfigurationListenerAndLocalRule() { 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 @@ void testWithConfigurationListenerAndLocalRule() { 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 @@ void testWithConfigurationListenerAndLocalRule() { 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 @@ void testWithConfigurationListenerAndLocalRule() { 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 e801688f7db..673daf44362 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.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 @@ void test_parse() { 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 46e7e04264d..07dc6045811 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 MockServiceDiscovery(String serviceName, URL registryURL) { } @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 1de1e3994aa..0c2f109147c 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 void onRefer(RegistryProtocol registryProtocol, ClusterInvoker invoker } @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 a48a5c9c925..36e4cb25aea 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 8253614c6ce..310611a4c1d 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 @@ void testSimplifiedUrl() { 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 @@ void testSubscribe() { 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 @@ void testSubscribe() { 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 @@ void testSubscribe() { Assertions.assertEquals(subscribeUrl, demoDynamicDirectory.getSubscribeUrl()); } - static class DemoDynamicDirectory extends DynamicDirectory { public DemoDynamicDirectory(Class serviceType, URL url) { @@ -157,14 +131,10 @@ public DemoDynamicDirectory(Class serviceType, URL url) { } @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 @@ public boolean isAvailable() { } @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 69742155097..6e70f9c9f04 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; @@ -36,17 +35,17 @@ 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 +85,7 @@ void testConsumerUrlWithoutProtocol() { 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 +94,8 @@ void testConsumerUrlWithoutProtocol() { 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 +111,15 @@ void testConsumerUrlWithoutProtocol() { 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 +153,7 @@ void testConsumerUrlWithProtocol() { 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 +162,8 @@ void testConsumerUrlWithProtocol() { 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 +179,15 @@ void testConsumerUrlWithProtocol() { 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 +206,6 @@ void testConsumerUrlWithProtocol() { Assertions.assertEquals(parameters.get(REGISTER_IP_KEY), consumerUrl.getHost()); Assertions.assertFalse(consumerUrl.getAttributes().containsKey(REFER_KEY)); Assertions.assertEquals("value1", consumerUrl.getAttribute("key1")); - } /** @@ -219,13 +219,12 @@ void testReferWithoutGroup() { 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 +232,8 @@ void testReferWithoutGroup() { 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 +247,15 @@ void testReferWithoutGroup() { 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 +266,13 @@ void testReferWithoutGroup() { 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); + ((ScopeClusterWrapper) ((MigrationInvoker) invoker).getCluster()).getCluster() + instanceof MockClusterWrapper); + Assertions.assertTrue( + ((MockClusterWrapper) ((ScopeClusterWrapper) ((MigrationInvoker) invoker).getCluster()).getCluster()) + .getCluster() + instanceof FailoverCluster); } /** @@ -286,7 +290,7 @@ void testReferWithGroup() { 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 +299,7 @@ void testReferWithGroup() { 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 +314,15 @@ void testReferWithGroup() { 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,11 +334,14 @@ void testReferWithGroup() { 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 MergeableCluster); + ((ScopeClusterWrapper) ((MigrationInvoker) invoker).getCluster()).getCluster() + instanceof MockClusterWrapper); + Assertions.assertTrue( + ((MockClusterWrapper) ((ScopeClusterWrapper) ((MigrationInvoker) invoker).getCluster()).getCluster()) + .getCluster() + instanceof MergeableCluster); } /** @@ -352,7 +359,7 @@ void testInterceptInvokerForMigrationRuleListener() { 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()); @@ -361,11 +368,7 @@ void testInterceptInvokerForMigrationRuleListener() { 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); @@ -375,13 +378,15 @@ void testInterceptInvokerForMigrationRuleListener() { 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<>(); @@ -389,18 +394,21 @@ void testInterceptInvokerForMigrationRuleListener() { 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 @@ -417,7 +425,7 @@ void testInterceptInvokerForCustomRegistryProtocolListener() { 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()); @@ -427,11 +435,7 @@ void testInterceptInvokerForCustomRegistryProtocolListener() { 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); @@ -442,29 +446,36 @@ void testInterceptInvokerForCustomRegistryProtocolListener() { 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()); } /** @@ -480,7 +491,7 @@ void testRegisterConsumerUrl() { 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()); @@ -489,11 +500,8 @@ void testRegisterConsumerUrl() { 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"); @@ -503,7 +511,10 @@ void testRegisterConsumerUrl() { 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); @@ -524,13 +535,16 @@ void testRegisterConsumerUrl() { 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 436924531e1..9ac6c8892e0 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.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 @@ public boolean isAvailable() { } @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 @@ void testRegistryFactoryCache() { */ // @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 637df6ba5b6..3eb4eb3dc7c 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.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.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 @@ public void after() { */ @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 @@ void testRegisterIfURLNULL() { */ @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 @@ void testUnregister() { 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 @@ void testUnregisterIfUrlNull() { */ @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 @@ void testRecover() throws Exception { 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 @@ void testNotifyIfNotifyNull() { }); } - /** * Test method for * {@link org.apache.dubbo.registry.support.AbstractRegistry#notify(URL, NotifyListener, List)}. @@ -471,10 +473,8 @@ void filterEmptyTest() { // 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 @@ void lookupTest() { abstractRegistry.notify(urls); List urlList2 = abstractRegistry.lookup(testUrl); Assertions.assertTrue(urlList2.contains(testUrl)); - } @Test @@ -546,7 +545,7 @@ void getCacheUrlsTest() { 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 b63ae3f1e6c..b3141fa9ecd 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.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 @@ void testDoRetry() throws Exception { 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 @@ void testDoRetry() throws Exception { 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 @@ void testDoRetry() throws Exception { 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 @@ void testDoRetryRegister() throws Exception { 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 @@ void testDoRetryRegister() throws Exception { 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 @@ void testDoRetrySubscribe() throws Exception { 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 @@ public void doRegister(URL url) { throw new RuntimeException("can not invoke!"); } latch.countDown(); - } @Override @@ -198,7 +201,6 @@ public void doUnregister(URL url) { throw new RuntimeException("can not invoke!"); } latch.countDown(); - } @Override @@ -206,7 +208,7 @@ public void doSubscribe(URL url, NotifyListener listener) { 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 @@ public void removeFailedSubscribedTask(URL url, NotifyListener listener) { 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 8e03ce51d43..6269d50fc28 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 0bbdf57679c..c5e386bb993 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 MulticastRegistry(URL url) { 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 MulticastRegistry(URL url) { } 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 @@ private void checkMulticastAddress(InetAddress multicastAddress) { 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 @@ private void clean() { } 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 @@ private void receive(String msg, InetSocketAddress remoteAddress) { 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 @@ private void receive(String msg, InetSocketAddress remoteAddress) { } } } - }/* else if (msg.startsWith(UNSUBSCRIBE)) { - }*/ + } /* else if (msg.startsWith(UNSUBSCRIBE)) { + }*/ } private void multicast(String msg) { @@ -429,5 +450,4 @@ public MulticastSocket getMulticastSocket() { 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 de3d64e27cd..2ce2920d560 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 012caf8e8bd..40c9376f677 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 MulticastServiceDiscovery(String serviceName, URL registryURL) { } @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 List getInstances(String serviceName) throws NullPointer 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 fde87af6056..582a3b2ee97 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.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.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 @@ void testMulticastAddress() { multicastSocket.close(); } } - } - } diff --git a/dubbo-registry/dubbo-registry-multiple/pom.xml b/dubbo-registry/dubbo-registry-multiple/pom.xml index 6719cdf2b8c..012288a5a5d 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 7a24a407794..82f9bbef5f9 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 MultipleRegistry(URL url, boolean initServiceRegistry, boolean initRefere 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 @@ protected void initServiceRegistry(URL url, Map registryMap) { 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 @@ protected void initReferenceRegistry(URL url, Map registryMap) 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 void subscribe(URL url, NotifyListener listener) { 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 List lookup(URL url) { return urls.stream().distinct().collect(Collectors.toList()); } - protected void init() { - } + protected void init() {} protected List filterServiceRegistry(List serviceRegistryURLs) { return serviceRegistryURLs; @@ -229,9 +235,7 @@ protected List filterReferenceRegistry(List referenceRegistryURL return referenceRegistryURLs; } - - protected void checkApplicationName(String applicationName) { - } + protected void checkApplicationName(String applicationName) {} protected String getApplicationName() { return applicationName; @@ -294,8 +298,8 @@ public synchronized void notifySourceListener() { } // 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 synchronized void notifySourceListener() { 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 List getUrlList() { 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 69d695b235f..3f92856c343 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 d675b74cce1..1c44f41e3e5 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 MultipleServiceDiscovery(URL registryURL) { 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 void unregister() throws RuntimeException { @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 ServiceInstance getLocalInstance() { @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 MetadataInfo getLocalMetadata(String revision) { @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 void putSingleListener(String registryKey, SingleServiceInstancesChangedL 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 @@ protected static class SingleServiceInstancesChangedListener extends ServiceInst 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 a91df2ad425..cb83155ff7d 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.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 @@ public static void beforeAll() { 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 @@ void testParamConfig() { 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(MultipleRegistryTestUtil.getZookeeperRegistry(multipleRegistry.getServiceRegistries().values()), - MultipleRegistryTestUtil.getZookeeperRegistry(multipleRegistry.getReferenceRegistries().values())); - - Assertions.assertEquals(MultipleRegistryTestUtil.getZookeeperRegistry(multipleRegistry.getServiceRegistries().values()), - 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(multipleRegistry.getApplicationName(), "vic"); @@ -108,8 +121,10 @@ void testParamConfig() { @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 @@ public void notify(List urls) { @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 @@ public void notify(List urls) { 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 @@ public void notify(List urls) { 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 @@ void testAggregation() { 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 5f5adfadd6f..c69d39b0a58 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 static List getProviderURLsFromNotifyURLS(List urls) { // 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 9d0786a77b5..359d8a5d0c9 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.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.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 void testOnEvent() { 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 c0918d5dad6..6c7e7760435 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 b8dcaad92f4..e3e3a90c109 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.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.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 List saveAndAggregateAllInstances(String serviceName, List 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 NacosNamingServiceWrapper(NacosConnectionManager nacosConnectionManager, * @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 String getServerStatus() { 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 void unsubscribe(String serviceName, String group, EventListener eventLis } 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 void registerInstance(String serviceName, String group, Instance instance 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 void registerInstance(String serviceName, String group, Instance instance } // 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 void registerInstance(String serviceName, String group, Instance instance } } - 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 void updateInstance(String serviceName, String group, Instance oldInstanc 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 void updateInstance(String serviceName, String group, Instance oldInstanc 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 void updateInstance(String serviceName, String group, Instance oldInstanc 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 void deregisterInstance(String serviceName, String group, String ip, int } } - 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 void deregisterInstance(String serviceName, String group, Instance instan 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 ListView getServicesOfServer(int pageNo, int pageSize, String gro } 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 boolean equals(Object o) { 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 @@ protected Map getRegisterStatus() { return registerStatus; } - private R apply(NacosFunction command) throws NacosException { NacosException le = null; R result = null; @@ -433,15 +450,27 @@ private R apply(NacosFunction command) throws NacosException { 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 @@ private R apply(NacosFunction command) throws NacosException { 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 @@ private void accept(NacosConsumer command) throws NacosException { 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 @@ private void accept(NacosConsumer command) throws NacosException { 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 893d77a061b..de2d990ac43 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.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.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 List lookup(final URL url) { 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 void doRegister(URL url) { * * 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 void doUnregister(final URL url) { 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 @@ private void doSubscribe(final URL url, final NacosAggregateListener listener, f * 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 @@ private void doSubscribe(final URL url, final NacosAggregateListener listener, f } 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 void doUnsubscribe(URL url, NotifyListener listener) { } 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 void doUnsubscribe(URL url, NotifyListener listener) { 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 void doUnsubscribe(URL url, NotifyListener listener) { } } - 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 @@ private Set getServiceNames0(URL url) { // 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 @@ private Set getServiceNames0(URL url) { 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 @@ private boolean isConformRules(String serviceName) { 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 @@ private void appendIfPresent(StringBuilder target, URL url, String parameterName } } - private boolean isAdminProtocol(URL url) { return ADMIN_PROTOCOL.equals(url.getProtocol()); } @@ -413,21 +431,25 @@ private boolean isAdminProtocol(URL url) { 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 @@ private Set getAllServiceNames() { 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 @@ private Set getAllServiceNames() { } // 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 @@ private void filterServiceNames(Set serviceNames, URL url) { 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 @@ private List toUrlWithEmpty(URL consumerURL, Collection instances 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 @@ private List buildURLs(URL consumerURL, Collection instances) { } 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 @@ private void unsubscribeEventListener(String serviceName, final URL url, final N 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 @@ private void unsubscribeEventListener(String serviceName, final URL url, final N * @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 @@ private void notifySubscriber(URL url, String serviceName, NacosAggregateListene * @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 @@ private interface NacosDataFilter { * should be accepted */ boolean accept(T data); - } private class RegistryChildListenerImpl implements EventListener { @@ -743,7 +764,9 @@ public boolean equals(Object o) { 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 int hashCode() { 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 3fbe2853c4f..c967fd56aca 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.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 NacosServiceDiscovery(ApplicationModel applicationModel, URL registryURL) 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 void doUnregister(ServiceInstance serviceInstance) throws RuntimeExceptio } @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 Set getServices() { @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 void addServiceInstancesChangedListener(ServiceInstancesChangedListener l 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 void removeServiceInstancesChangedListener(ServiceInstancesChangedListene 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 URL getUrl() { 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 c6a350a3c06..4d0bf68cb77 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 @@ protected String createRegistryCacheKey(URL url) { 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 03a74dfa313..e74c74e3bfa 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 boolean isCompatible(NacosServiceName concreteServiceName) { 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 String getValue() { 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/util/NacosNamingServiceUtils.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtils.java index f594e473d06..8a87e23d25d 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 @@ */ 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 static Instance toInstance(ServiceInstance serviceInstance) { * @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 static NacosNamingServiceWrapper createNamingService(URL connectionURL) { 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 e611bae3577..81bfe0b631f 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.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 List getAllInstances(String serviceName, List clusters, } @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 List selectInstances(String serviceName, List clusters, } @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 Instance selectOneHealthyInstance(String serviceName, List cluste } @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 String getServerStatus() { } @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 bc2dea58d04..ca17d3c2dbe 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 @@ 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.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 String getServerStatus() { 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 String getServerStatus() { } } } + @Test void testNoCheck() { try (MockedStatic nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) { @@ -123,7 +126,9 @@ public String getServerStatus() { 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 String getServerStatus() { 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 String getServerStatus() { 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 6e3c730d83b..f55f9f13859 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 @@ 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.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 @@ protected NamingService createNamingService() { 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 @@ protected NamingService createNamingService() { 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 @@ void testRegisterNacos2_1_xClient2_0_xServer() throws NacosException { 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 @@ protected NamingService createNamingService() { 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 @@ protected NamingService createNamingService() { 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 @@ protected NamingService createNamingService() { 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 @@ protected NamingService createNamingService() { 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 @@ protected NamingService createNamingService() { 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 @@ protected NamingService createNamingService() { 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 @@ protected NamingService createNamingService() { 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 @@ protected NamingService createNamingService() { 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; - - @Override - public void lock() { - delegate.lock(); - } - - @Override - public void unlock() { - delegate.unlock(); - } - - @Override - public List getInstances() { - try { - if (startLatch.getCount() > 0) { - Thread.sleep(1000); - startLatch.countDown(); - Thread.sleep(1000); + 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 unlock() { + delegate.unlock(); + } + + @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(); - } - - @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(); + }) + .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 @@ public List getAllInstances(String serviceName, String groupName) { } }; - 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 @@ public List getAllInstances(String serviceName, String groupName) { 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 @@ public List getAllInstances(String serviceName, String groupName) thro } }; - 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 @@ void testFailRetry() { 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 @@ public List getAllInstances(String serviceName, String groupName) thro } }; - 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 @@ public List getAllInstances(String serviceName, String groupName) thro } 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 2af57626a49..a8665b03f2e 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 @@ 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 @@ public void setup() { } @AfterEach - public void teardown() { - } + public void teardown() {} @Test void testCreateRegistryCacheKey() { @@ -49,10 +49,10 @@ void testCreateRegistryCacheKey() { @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 c5355d6e367..110cff95e19 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 @@ public void setUp() throws Exception { this.nacosRegistry = (NacosRegistry) nacosRegistryFactory.createRegistry(registryUrl); } - @AfterEach - public void tearDown() throws Exception { - - } + public void tearDown() throws Exception {} @Test void testRegister() { @@ -103,7 +101,8 @@ void testRegister() { // 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 @@ void testUnRegister() { 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 @@ void testSubscribe() { 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 @@ void testUnSubscribe() { 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 @@ void testUnSubscribe() { 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 @@ void testIsConformRules() { 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 @@ void testIsConformRules() { 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 @@ void testIsConformRules() { 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 6f9003490c5..271d8291134 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.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 d994a08f599..97b8a3e540b 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.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.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 @@ public static class NacosServiceDiscoveryGroupTest2 extends NacosServiceDiscover 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 @@ public void init() throws Exception { 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 @@ public void destroy() throws Exception { @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 @@ void testDoRegister() throws NacosException { @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 @@ void testDoUnRegister() throws NacosException { @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 @@ void testGetServices() throws NacosException { 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 @@ void testAddServiceInstancesChangedListener() { 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 b2e0b4e5159..5f0a0fbbcba 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 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 java.util.HashMap; +import java.util.List; +import java.util.Map; +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; 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 @@ void testCreateNamingService() { Assertions.assertNotNull(namingService); } - @Test void testRetryCreate() throws NacosException { try (MockedStatic nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) { @@ -94,13 +93,15 @@ public String getServerStatus() { 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 @@ public String getServerStatus() { 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 @@ public String getServerStatus() { 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 9571e7e3d39..f1e9cfa3d23 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 5bf38d02846..f021e32aac0 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 void setMetadata(Map metadata) { @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 b35ca177970..4052df8d262 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 ZookeeperRegistry(URL url, ZookeeperTransporter zookeeperTransporter) { 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 ZookeeperRegistry(URL url, ZookeeperTransporter zookeeperTransporter) { 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 void doRegister(URL url) { 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 void doUnregister(URL url) { 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 void doSubscribe(final URL url, final NotifyListener listener) { 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<>()); - - 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); - } - } - }); + 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); + } + } + }); zkClient.create(root, false, true); @@ -201,8 +223,11 @@ public void doSubscribe(final URL url, final NotifyListener listener) { 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 void doSubscribe(final URL url, final NotifyListener listener) { /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 void doSubscribe(final URL url, final NotifyListener listener) { } } } 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 List lookup(URL url) { } 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 @@ private String toServicePath(URL url) { 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 void childChanged(String path, List children) { 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 void notify(String path, Object rawAddresses) { } 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 b4f20df09da..ec4ce4ac342 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 void setZookeeperTransporter(ZookeeperTransporter zookeeperTransporter) { 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 34ee84363a8..06c2305055f 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.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 void doUnregister(ServiceInstance serviceInstance) throws RuntimeExceptio } @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 void addServiceInstancesChangedListener(ServiceInstancesChangedListener l } @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 void removeServiceInstancesChangedListener(ServiceInstancesChangedListene 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 void removeServiceInstancesChangedListener(ServiceInstancesChangedListene @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 @@ protected void registerServiceWatcher(String serviceName, ServiceInstancesChange 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 f4e51684318..73830b44455 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.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.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/util/CuratorFrameworkParams.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkParams.java index fd095a2ff61..d3dce60aaa0 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 @@ 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 T getParameterValue(URL url) { 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 178757b5b98..83b47fc1c1f 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.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.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 @@ */ 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 List getAclForPath(String path) { 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 static RetryPolicy buildRetryPolicy(URL connectionURL) { 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 static org.apache.curator.x.discovery.ServiceInstance 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 3f36ad395b4..6ca59621852 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.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 @@ void testLookupIllegalUrl() { 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 @@ void testLookupWithException() { @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 @@ void testDestroy() { assertThat(zookeeperRegistry.isAvailable(), is(false)); } - @Test void testDoRegisterWithException() { Assertions.assertThrows(RpcException.class, () -> { @@ -194,7 +192,6 @@ void testDoUnregisterWithException() { @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 f3420bb596b..a9405e93924 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.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.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 @@ void testRegistration() throws InterruptedException { // 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 @@ public void onEvent(ServiceInstancesChangedEvent event) { 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 @@ public void onEvent(ServiceInstancesChangedEvent event) { 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 01ed19db286..40b233c9be1 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.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.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 @@ void testBuildCuratorFramework() throws Exception { @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 @@ void testBuildServiceDiscovery() throws Exception { @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 @@ void testBuild() { 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 b72880197a0..28008cdf8ed 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 a9eace27b84..a9ab59c31a1 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 - - + 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 + + 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 14fa5d043e6..d09da2fe6dc 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 @@ 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 1e3f87a91f9..a3a02c144a3 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 ee0dcad8850..89bdd695570 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 a862cae6154..bcae4766f28 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 4ffe4b0b17d..019a113a017 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; - public interface Constants { String BUFFER_KEY = "buffer"; @@ -74,6 +72,7 @@ public interface Constants { * ticks per wheel. */ int TICKS_PER_WHEEL = 128; + String PAYLOAD_KEY = "payload"; /** * 8M @@ -180,5 +179,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 a913ef87407..e46ba5ef14b 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 6f6f88f2e5a..99ff0238c23 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 2a20f7c379a..c8e8aaf47c6 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 97783c158b6..d36767b17cd 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 ExecutionException(Object request, Channel channel, Throwable cause) { 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 32abe4eaf13..146ce3888c4 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 RemotingException(InetSocketAddress localAddress, InetSocketAddress remot } 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 RemotingException(InetSocketAddress localAddress, InetSocketAddress remot } 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/RemotingScopeModelInitializer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/RemotingScopeModelInitializer.java index 30f6cdf309c..820f45e2b85 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/RemotingScopeModelInitializer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/RemotingScopeModelInitializer.java @@ -33,30 +33,34 @@ */ 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-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 2c60d396d0d..29fe60ace2f 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 9ecb8e4e4ea..861073e6644 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 TimeoutException(boolean serverSide, Channel channel, String message) { 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 boolean isServerSide() { 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 3b4ba462a84..eee680fd122 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 d8dbb4ee45a..05783637ccc 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 @@ */ 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 static Client connect(URL url, ChannelHandler... handlers) throws Remotin } 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/AbstractWireProtocol.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/AbstractWireProtocol.java index 4bc8702cbbc..d91d5e01edc 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 ProtocolDetector detector() { } @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 856d0f1631f..5e04f30e1c2 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,10 +16,8 @@ */ package org.apache.dubbo.remoting.api; - import org.apache.dubbo.remoting.buffer.ChannelBuffer; - /** * Determine incoming bytes belong to the specific protocol. * @@ -29,6 +27,8 @@ public interface ProtocolDetector { Result detect(ChannelBuffer in); enum Result { - RECOGNIZED, UNRECOGNIZED, NEED_MORE_DATA + RECOGNIZED, + UNRECOGNIZED, + NEED_MORE_DATA } } 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 66e9b3a410c..052b50d0ec4 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 @@ 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 final boolean release() { 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 4ed563a5c3b..4bafd19266f 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 61a984b7574..129d2399ab3 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 25ef6fa0099..28cfbebc774 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 MultiplexProtocolConnectionManager(FrameworkModel frameworkModel) { @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 void forEachConnection(Consumer connectionConsu } 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 d8333efbbc9..3f840696710 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 AbstractConnectionClient connect(URL url, ChannelHandler handler) { 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/AbstractPortUnificationServer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/AbstractPortUnificationServer.java index 9a6ac624c69..8704881b70b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/AbstractPortUnificationServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/AbstractPortUnificationServer.java @@ -44,7 +44,9 @@ public abstract class AbstractPortUnificationServer extends AbstractServer { public AbstractPortUnificationServer(URL url, ChannelHandler handler) throws RemotingException { super(url, handler); - this.protocols = url.getOrDefaultFrameworkModel().getExtensionLoader(WireProtocol.class).getActivateExtension(url, new String[0]); + this.protocols = url.getOrDefaultFrameworkModel() + .getExtensionLoader(WireProtocol.class) + .getActivateExtension(url, new String[0]); } public List getProtocols() { 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 b17dd7c7bec..583095472d0 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 ChannelHandlerPretender(Object realHandler) { 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 4756dd38ef0..c4f18ab9531 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 @@ 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 0e021f934d0..8ca7dc6c855 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 @@ 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 0562085c328..e9f3c789a9b 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 37f10b44a93..06972640770 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 ByteBuffer toByteBuffer() { @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 int compareTo(ChannelBuffer that) { @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 6bcfa16acfc..2a1880e3d3d 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 ChannelBufferFactory factory() { } } - @Override public int capacity() { return capacity; } - @Override public ChannelBuffer copy(int index, int length) { ByteBuffer src; @@ -69,21 +66,17 @@ public ChannelBuffer copy(int index, int length) { 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 void getBytes(int index, byte[] dst, int dstIndex, int length) { data.get(dst, dstIndex, length); } - @Override public void getBytes(int index, ByteBuffer dst) { ByteBuffer data = buffer.duplicate(); @@ -108,7 +100,6 @@ public void getBytes(int index, ByteBuffer dst) { dst.put(data); } - @Override public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { if (dst instanceof ByteBufferBackedChannelBuffer) { @@ -124,7 +115,6 @@ public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { } } - @Override public void getBytes(int index, OutputStream out, int length) throws IOException { if (length == 0) { @@ -140,19 +130,16 @@ public void getBytes(int index, OutputStream out, int length) throws IOException } } - @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 void setBytes(int index, byte[] src, int srcIndex, int length) { data.put(src, srcIndex, length); } - @Override public void setBytes(int index, ByteBuffer src) { ByteBuffer data = buffer.duplicate(); @@ -168,7 +154,6 @@ public void setBytes(int index, ByteBuffer src) { data.put(src); } - @Override public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) { if (src instanceof ByteBufferBackedChannelBuffer) { @@ -184,7 +169,6 @@ public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) { } } - @Override public ByteBuffer toByteBuffer(int index, int length) { if (index == 0 && length == capacity()) { @@ -194,7 +178,6 @@ public ByteBuffer toByteBuffer(int index, int length) { } } - @Override public int setBytes(int index, InputStream in, int length) throws IOException { int readBytes = 0; @@ -235,19 +218,16 @@ public int setBytes(int index, InputStream in, int length) throws IOException { 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 e77cf46ab2c..fd384f0f165 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 5042260c24d..30290d96793 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 8e64eaa01d4..6b461ad7819 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 @@ private int skipBytes(int n) throws IOException { 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 afc71874138..95e1664dcbd 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 cc62925da1d..08dde5e42ae 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 static ChannelBuffer dynamicBuffer(int capacity) { 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 static ChannelBuffer directBuffer(int capacity) { 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 static int compare(ChannelBuffer bufferA, ChannelBuffer bufferB) { 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 0b99a6cb314..4fd29224357 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 ChannelBuffer getBuffer(ByteBuffer nioBuffer) { 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 cfd7965ffec..6733d83a508 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 void ensureWritableBytes(int minWritableBytes) { 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 ChannelBuffer copy(int index, int length) { 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 int writeBytes(InputStream in, int length) throws IOException { 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 2d1e32ec02d..623c9faed66 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 void getBytes(int index, ByteBuffer dst) { } @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 11e1b0afe7b..5b2b5374c7a 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 ChannelBuffer getBuffer(ByteBuffer nioBuffer) { 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 8ce3fac479d..67988f97365 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 @@ * * */ -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 118c9328056..57d61a8208f 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 f8565c41251..3e519c2ac1d 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 9b94db8bd70..fd3d19819fa 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 c8f9b9da149..080ca5e3526 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 @@ * 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 static ExchangeClient connect(URL url, Replier replier) throws Remotin 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 static ExchangeClient connect(URL url, ExchangeHandler handler) throws Re 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 35d4477c491..e85a2e8a7bd 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 26252adc989..58da07715ff 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 @@ 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 static ConcurrentMap getServers() { } 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 20d80453d67..bab83e2023f 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 Request copyWithoutData() { @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 1a4c15eb132..32dbb38275a 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 717f894cc76..4eeccebca75 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 Object decode(Channel channel, ChannelBuffer buffer) throws IOException { @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 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro // 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 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro 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 @@ protected Object getRequestData(Channel channel, Response response, long id) { } } - 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 @@ protected void encodeResponse(Channel channel, ChannelBuffer buffer, Response re 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 @@ protected Object decodeEventData(Channel channel, ObjectInput in, byte[] eventBy 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 @@ protected void encodeResponseData(Channel channel, ObjectOutput out, Object data 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 @@ private Object finishRespWhenOverPayload(Channel channel, long size, byte[] head 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 75544e99270..9f2e9c2d215 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 static void closeChannel(Channel channel, long timeout) { 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 static void closeChannel(Channel channel, long timeout) { 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 static void received(Channel channel, Response response, boolean timeout) 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 @@ private void doReceived(Response res) { 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 @@ private void doSent() { 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 6b923cfb5ea..cabb3683a25 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 ExchangeHandlerAdapter(FrameworkModel frameworkModel) { 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 066c700187e..44680de02f3 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 void caught(Channel channel, Throwable exception) { 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 8fdc4289b53..e6dff6291bd 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 void close(int timeout) { 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 dbe3bff714c..2821a0b823d 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 Collection removeMessages() { 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 1be0c1cb1c9..194067637ce 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 afb6052a314..549593a888a 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 @@ private Replier getReplier(Class type) { 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 ce5c5e60149..e9c1dfeada7 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 aa4df8d0537..ac75bb64325 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 @@ protected void doTask(Channel channel) { 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 b4c7bb65a33..6145e985f9a 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 @@ */ 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 @@ public void send(Object message) throws RemotingException { @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 @@ public CompletableFuture request(Object request, ExecutorService executo } @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 @@ public void close(int timeout) { } 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 @@ public boolean equals(Object obj) { 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 6b9dd53e95a..e654b327c09 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 CompletableFuture request(Object request, ExecutorService executo } @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 @@ private void startHeartBeatTask(URL url) { 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 d1fc4cdd1af..cefa8bb20e2 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.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 @@ static void handleResponse(Channel channel, Response response) throws RemotingEx 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 @@ void handleRequest(final ExchangeChannel channel, Request req) throws RemotingEx } 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 @@ void handleRequest(final ExchangeChannel channel, Request req) throws RemotingEx 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 void sent(Channel channel, Object message) throws RemotingException { } 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 void received(Channel channel, Object message) throws RemotingException { 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 3dca5a9746e..340c50c724d 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 void close(final int timeout) { 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 void reset(org.apache.dubbo.common.Parameters parameters) { @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 void send(Object message) throws RemotingException { @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 @@ private long calculateLeastDuration(int time) { 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 67f2440d83a..7c6b4d51be3 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 f1bb03cbefb..56470f0203a 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 void received(Channel channel, Object message) throws RemotingException { 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 e418a1de99a..6c3c3eaad13 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 @@ protected void doTask(Channel channel) { 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 @@ protected void doTask(Channel channel) { 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 506ec003c15..354df1b6895 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 @@ protected void doTask(Channel channel) { } // 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 @@ protected void doTask(Channel channel) { } } } 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 fe3acb776c9..3d8ea36d547 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 9cfd979e178..c106572e3f3 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 @@ private static String toString(byte[] message, Charset charset) throws Unsupport } 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 @@ protected Object decode(Channel channel, ChannelBuffer buffer, int readable, byt 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 @@ protected Object decode(Channel channel, ChannelBuffer buffer, int readable, byt 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 @@ protected Object decode(Channel channel, ChannelBuffer buffer, int readable, byt } 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 cc8f2ba98ad..23df4bf891d 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 @@ 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 cb18ed7cb1e..2e3d0308c1e 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 String telnet(Channel channel, String message) throws RemotingException { } 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 @@ private boolean commandEnabled(URL url, String command) { } 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 009f6ba4c31..8a78d599ff9 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 static String toTable(List header, List> table) { } 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 static String toTable(List header, List> table) { 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 static String toTable(List header, List> table) { 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 static String toTable(List header, List> table) { buf.append('+'); } buf.append("\r\n"); - //content + // content for (List row : table) { StringBuilder rowbuf = new StringBuilder(); rowbuf.append('|'); @@ -126,9 +126,10 @@ public static String toTable(List header, List> table) { 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 static String toTable(List header, List> table) { } 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 static String toTable(List header, List> table) { 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 f7de70eaebf..5af5551de08 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 String telnet(Channel channel, String message) { 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 String telnet(Channel channel, String message) { } 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 becf205bb60..829abfda642 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 String telnet(Channel channel, String message) { 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 04c81427663..da5b7273985 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 HelpTelnetHandler(FrameworkModel frameworkModel) { @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 @@ private String generateForAllCommand(Channel channel) { 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 144fabb8a8c..4cd8010cfa1 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 String telnet(Channel channel, String message) { 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 String telnet(Channel channel, String message) { .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 946362e85e4..f65966321cd 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 28353269fce..d96513965a9 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 AbstractChannel(URL url, ChannelHandler handler) { @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 71392adf822..7b465c66498 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.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 AbstractClient(URL url, ChannelHandler handler) throws RemotingException 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 AbstractClient(URL url, ChannelHandler handler) throws RemotingException 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 @@ private void initExecutor(URL url) { * 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 void send(Object message, boolean sent) throws RemotingException { 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 @@ protected void connect() throws RemotingException { } 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 @@ protected void connect() throws RemotingException { 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 void reconnect() throws RemotingException { @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 144e352bb27..d5320053f67 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 @@ protected static void checkPayload(Channel channel, long size) throws IOExceptio 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 @@ protected static void checkPayload(Channel channel, int payload, long size) thro 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 @@ protected boolean isClientSide(Channel channel) { 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 @@ protected boolean isClientSide(Channel channel) { 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 16b57f12047..f8ab69fdcdc 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 @@ protected static Codec2 getChannelCodec(URL url) { 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 @@ protected static Codec2 getChannelCodec(URL url) { @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 @@ protected Codec2 getCodec() { 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 65978841fbd..bb50ddc304d 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 AbstractServer(URL url, ChannelHandler handler) throws RemotingException 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 void reset(URL url) { 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 void send(Object message, boolean sent) throws RemotingException { @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 int getAccepts() { 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 void connected(Channel ch) throws RemotingException { @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 eb4ce77a03a..1a89b9fc78a 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 void startClose() { 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 188b7de4bad..8e09d2b920e 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 @@ 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 13174c5c75b..f8c47276c02 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 @@ */ 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 ChannelHandlerDispatcher(ChannelHandler... handlers) { 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 void caught(Channel channel, Throwable exception) { } } } - } 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 d2a7673d0e0..9b1204bb3c7 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 void startClose() { 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 d109e97cb1a..8023274ac4d 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 static Byte getIDByName(String name) { } 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 static ObjectInput deserialize(URL url, InputStream is, byte proto) throw */ 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 static byte[] getNullBytesOf(Serialization s) { 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 static void checkSerialization(String requestSerializeName, URL url) thro 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 11b93b8494f..71d4e535b2a 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 0e78bb06b07..9cb55fb5143 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 @@ */ 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 void received(Channel channel, Object message) throws RemotingException { 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 0aa39495ceb..76477df1455 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 d49313ffe3b..dad824eca87 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 CodecAdapter(Codec codec) { } @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 4bb558c4cdc..0cc0d0a9eb2 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 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 ChannelEventRunnable(Channel channel, ChannelHandler handler, ChannelStat 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 void run() { 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 void run() { 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 enum ChannelState { */ 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 f11163515a7..9ffe65d08af 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 @@ static void setTestingChannelHandlers(ChannelHandlers instance) { } 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 325f53625b8..36c3b4499f2 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.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 @@ protected void sendFeedback(Channel channel, Request request, Throwable t) throw 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 ExecutorService getPreferredExecutorService(Object msg) { 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 ExecutorService getSharedExecutorService() { 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 d5fa975cf61..6305514fb80 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 void connected(Channel channel) throws RemotingException { 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 void disconnected(Channel channel) throws RemotingException { 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 void received(Channel channel, Object message) throws RemotingException { 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 31ee4c8b455..836568d1b90 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 77fb6bb9ba5..4652bc1dd4d 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 void connected(Channel channel) throws RemotingException { 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 void disconnected(Channel channel) throws RemotingException { 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 void caught(Channel channel, Throwable exception) throws RemotingExceptio 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 fed92b1768b..a6b5b0d367d 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 9bb8d1f40f9..60e01d4b9bc 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 void received(Channel channel, Object message) throws RemotingException { 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 aaed4e79227..4cd138ff175 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 d5bc91d90fd..a2e61f51517 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 c3c25852bec..77eb620d628 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 void received(Channel channel, Object message) throws RemotingException { 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 fa427d16d4a..3fbad4bd44f 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 e3f510c7cc8..2ba32fc4eba 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 static String serializationOrDefault(URL url) { 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/main/java/org/apache/dubbo/remoting/zookeeper/AbstractZookeeperClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/AbstractZookeeperClient.java index 9f5d3c7bf59..e830246617a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/AbstractZookeeperClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/AbstractZookeeperClient.java @@ -34,7 +34,8 @@ 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 URL getUrl() { @Override public void delete(String path) { - //never mind if ephemeral + // never mind if ephemeral persistentExistNodePath.remove(path); deletePath(path); } @@ -107,8 +110,10 @@ public Set getSessionListeners() { @Override public List 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 void addDataListener(String path, DataListener listener) { @Override public void addDataListener(String path, DataListener listener, Executor executor) { - ConcurrentMap 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 @@ protected void doClose() { * @param path the node path */ protected abstract void deletePath(String path); - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/AbstractZookeeperTransporter.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/AbstractZookeeperTransporter.java index c447ec1dfc9..802ec8820c2 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/AbstractZookeeperTransporter.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/AbstractZookeeperTransporter.java @@ -55,13 +55,15 @@ public ZookeeperClient connect(URL url) { // address format: {[username:password@]address} List 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 @@ URL toClientURL(URL url) { 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-api/src/main/java/org/apache/dubbo/remoting/zookeeper/ChildListener.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/ChildListener.java index 0e876aff3e2..5ada2815a87 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/ChildListener.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/ChildListener.java @@ -21,5 +21,4 @@ public interface ChildListener { void childChanged(String path, List children); - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/EventType.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/EventType.java index 791e7e3044d..9e288036472 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/EventType.java +++ b/dubbo-remoting/dubbo-remoting-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-api/src/main/java/org/apache/dubbo/remoting/zookeeper/StateListener.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/StateListener.java index ca4dbe09ae4..202b6cc63bf 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/StateListener.java +++ b/dubbo-remoting/dubbo-remoting-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-api/src/main/java/org/apache/dubbo/remoting/zookeeper/ZookeeperClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/ZookeeperClient.java index bb6f78dba4a..b2877cd2598 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/ZookeeperClient.java +++ b/dubbo-remoting/dubbo-remoting-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-api/src/main/java/org/apache/dubbo/remoting/zookeeper/ZookeeperTransporter.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/ZookeeperTransporter.java index 36bb5cd3e22..f73bc6b1a7e 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/ZookeeperTransporter.java +++ b/dubbo-remoting/dubbo-remoting-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-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 f17bced5ca3..8c3bde9838a 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 @@ public static ExchangeClient initClient(String url) { 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 @@ void testClient() throws Throwable { 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 @@ public void disconnected(Channel channel) throws RemotingException { */ @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 6b8006ac850..2ec49a987d6 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.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 @@ */ 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 @@ void testClient() throws Throwable { 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 @@ public void run() { } } } - } 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 a684d9c2d70..2248f0c0c4d 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.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 @@ 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 @@ void testClient() throws Exception { 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; - - //int idx = server.indexOf(':'); + // 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(':'); Random rd = new Random(connectionCount); ArrayList arrays = new ArrayList(); String oneKBlock = null; @@ -92,7 +96,8 @@ void testClient() throws Exception { 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 @@ void testClient() throws Exception { 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 0628f7fb245..9ae015061e2 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 a81b835ec89..49b6bb763dc 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.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.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 @@ */ 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 @@ public void testClient() throws Throwable { 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 @@ public void testClient() throws Throwable { 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 @@ public void testClient() throws Throwable { 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)); - - bfirst = false; - lastCount = count.get(); - Thread.sleep(sleepTime); + 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); + } + } catch (Exception e) { + e.printStackTrace(); + } } - } catch (Exception e) { - e.printStackTrace(); - } - } - }).start(); + }) + .start(); latch.await(); @@ -209,12 +219,14 @@ public void run() { 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 878221b75d1..03b64206361 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 90af441c7ae..a5ccc5c7ecb 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.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 @@ */ 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 @@ private static void restartServer(int times, int alive, int sleep) throws Except 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(); + 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 "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 telnetserver; } @@ -170,5 +178,4 @@ void testServer() throws Exception { } } } - } 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 6ae0073a717..56e9bd9906d 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 static boolean getBooleanProperty(String key, boolean defaultValue) { 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 static NetworkInterface getNetworkInterface() { } 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 8a6aef4a331..892fe351053 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 void received(Channel channel, Object message) throws RemotingException { } } } - } 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 774638491e5..cd719809921 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 @@ 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 ProtocolDetector detector() { } @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 e3232bd7c9a..99d7fb1300c 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.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 @@ protected boolean discardReadBytesDoesNotMoveWritableBytes() { return true; } - @BeforeEach public void init() { buffer = newBuffer(CAPACITY); @@ -240,7 +238,8 @@ void getByteBufferState() { @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 @@ void testSkipBytes1() { // 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 2d3b1f8a1b2..f846ff8dcf5 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 @@ protected ChannelBuffer newBuffer(int capacity) { @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 e8c21fca8a8..e88052f3771 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 @@ void test() { 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 8e549b1155c..c1689585629 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.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 @@ void testChannelBufferInputStreamWithOutOfBounds() { 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 @@ public void testChannelBufferOutputStream(final ChannelBuffer buf) { // 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 50e656c23c5..17effade2a3 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 @@ void testDynamicBuffer() { } @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 @@ void testWrappedBuffer() { 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 @@ void testDirectBuffer() { @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 f3d2636c74a..879f1b7c5e0 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 @@ protected ChannelBuffer newBuffer(int capacity) { @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 9e1e8f4ee5d..6c968568d03 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 @@ protected ChannelBuffer newBuffer(int length) { @Override protected ChannelBuffer[] components() { - return new ChannelBuffer[]{buffer}; + return new ChannelBuffer[] {buffer}; } @Test @@ -71,7 +71,5 @@ void ensureWritableBytes() { 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 ed62db0a96e..c1b51b3ee91 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 @@ protected ChannelBuffer newBuffer(int capacity) { @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 b2d8bc9624b..994bd9acfd0 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 60214b2c6f2..d7621863666 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 c747ea6eff9..f14f3552824 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 @@ public Object decode(Channel channel, InputStream is) throws IOException { 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 @@ protected Object decode(Channel channel, InputStream is, int readable, byte[] he } // 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 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro 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 @@ protected void encodeResponse(Channel channel, OutputStream os, Response res) th 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 @@ protected void encodeResponse(Channel channel, OutputStream os, Response res) th 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 @@ protected void encodeRequestData(Channel channel, ObjectOutput out, Object data) 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 3f7ded39310..2f9180277ce 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 @@ 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 @@ static void checkPayload(Channel channel, long size) throws IOException { 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 @@ private static String toString(byte[] message, Charset charset) throws Unsupport } 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 @@ protected boolean isClientSide(Channel channel) { 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 void encode(Channel channel, OutputStream output, Object message) throws 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 @@ protected Object decode(Channel channel, InputStream is, int readable, byte[] me 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 @@ protected Object decode(Channel channel, InputStream is, int readable, byte[] me 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 ee5ea1134e7..14a6fbf7335 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.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 @@ private byte[] getReadonlyEventRequestBytes(Object obj, byte[] header) throws IO 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 @@ private byte[] assemblyDataProtocol(byte[] header) { byte[] newbuf = join(header, objectToByte(request)); return newbuf; } - //=================================================================================== + // =================================================================================== @BeforeEach public void setUp() throws Exception { @@ -132,11 +134,11 @@ public void setUp() throws Exception { @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 @@ void test_Decode_Error_MagicNum() throws IOException { 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 @@ void test_Decode_Error_Length() throws IOException { @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 @@ void test_Decode_Error_Response_Object() throws IOException { @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 @@ void testInvalidSerializaitonId() throws Exception { @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 @@ void test_Decode_Check_Payload() throws IOException { 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 @@ void test_Decode_MigicCodec_Contain_ExchangeHeader() throws IOException { 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 @@ void test_Decode_Return_Response_Person() throws IOException { 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 @@ public void test_Decode_Return_Response_Error() throws IOException { @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 @@ void test_Decode_Return_Request_Event_Object() throws IOException { @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 @@ void test_Decode_Return_Request_Event_String() throws IOException { @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 @@ void test_Decode_Return_Request_Heartbeat_Object() throws IOException { @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 @@ void test_Decode_Return_Request_Object() throws IOException { @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 @@ void test_Decode_Error_Request_Object() throws IOException { 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 @@ void test_Header_Response_NoSerializationFlag() throws IOException { 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 @@ void test_Encode_Request() throws IOException { 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 @@ void test_Encode_Response() throws IOException { 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 @@ void test_Encode_Response() throws IOException { 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 @@ void test_Encode_Error_Response() throws IOException { 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 @@ void test_Encode_Error_Response() throws IOException { 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 @@ void testMessageLengthExceedPayloadLimitWhenEncode() throws Exception { 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 cd0a9c5d489..bdcbc4a9c92 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.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.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 @@ protected byte[] objectToByte(Object obj) { 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 @@ protected void testDecode_assertEquals(byte[] request, Object ret) throws IOExce } 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 @@ private void testDecode_assertEquals(Object request, Object ret, Object channelR 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 @@ private void testDecode_assertEquals(AbstractMockChannel channel, Object request 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 @@ private void testDecode_PersonWithEnterByte(byte[] enterBytes, boolean isNeedMor } 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 @@ void testDecode_String_ClientSide() throws IOException { @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 @@ void testDecode_Person_ObjectOnly() throws IOException { @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 @@ void testDecode_WithExitByte() throws IOException { @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 @@ void testDecode_Backspace_WithError() throws IOException { @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 @@ void testDecode_UPorDOWN_WithError() throws IOException { 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 @@ void testDecode_UPorDOWN_WithError() throws IOException { }); } - //============================================================================================================================= + // ============================================================================================================================= @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 @@ public void testDecode_History_UP_DOWN_MULTI() throws IOException{ 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 @@ public int hashCode() { @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 f6a991d1644..134aaa90e33 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 @@ void testBind() throws RemotingException { 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 @@ void testConnect() throws RemotingException { 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 9c820c08cf7..1a6b662c7d1 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.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 ae1323e865a..9bfa7def771 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 @@ void test() { 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 54d135bd9b2..95a8da81ced 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 @@ void test() { 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 171d040cd90..c2d5f4ac8fe 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.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 @@ void isDone() { 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 @@ void isDone() { @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 @@ public void timeoutNotSend() throws Exception { @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 @@ public void clientTimeoutSend() throws Exception { // 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 @@ public void clientTimeoutSend() throws Exception { @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 @@ public void timeoutSend() throws Exception { @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 @@ void interruptSend() throws Exception { } 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 @@ void testClose1() { 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 @@ public InterruptThread(Thread parent) { 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 f06ae441e57..8a351658555 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.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 5cfb6fdacf6..f24a927092d 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 @@ void test() { 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 882a481c244..0e385a6f4c4 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.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 @@ void testClose() throws Exception { 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 150752639cc..5def632fd7e 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.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 @@ public URL getUrl() { public boolean isConnected() { return true; } - }; Assertions.assertNull(channel.getAttribute(CHANNEL_KEY)); HeaderExchangeChannel ret = HeaderExchangeChannel.getOrAddChannel(channel); @@ -88,7 +87,6 @@ void getOrAddChannelTest02() { Assertions.assertNull(ret); } - @Test void removeChannelIfDisconnectedTest() { Assertions.assertNull(channel.getAttribute(CHANNEL_KEY)); @@ -186,18 +184,16 @@ void closeTest() { 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 @@ void isConnectedTest() { Assertions.assertFalse(header.isConnected()); } - @Test void getChannelHandlerTest() { Assertions.assertNull(header.getChannelHandler()); @@ -242,7 +237,6 @@ void getExchangeHandlerTest() { Assertions.assertNull(header.getExchangeHandler()); } - @Test void getAttributeAndSetAttributeTest() { header.setAttribute("test", "test"); @@ -258,7 +252,6 @@ void removeAttributeTest() { Assertions.assertFalse(header.hasAttribute("test")); } - @Test void hasAttributeTest() { Assertions.assertFalse(header.hasAttribute("test")); @@ -284,10 +277,8 @@ void equalsTest() { }); } - @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 5fedc828dfc..37b1dc9b69c 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.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 @@ void test() throws InterruptedException, RemotingException { 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 @@ void test() throws InterruptedException, RemotingException { 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 07a0f63a0aa..f5ccd397939 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 @@ public URL getUrl() { } }; - 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 @@ void testHeartBeat() throws Exception { 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 0512dffe042..335247f48da 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 boolean isClosing() { } @Override - public void reset(URL url) { - - } + public void reset(URL url) {} @Override public void reconnect() throws RemotingException { @@ -134,9 +131,7 @@ public void reconnect() throws RemotingException { } @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 e68b26355e2..6c758b372a9 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 @@ 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 @@ public boolean isConnected() { } }; - 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 7cd1437d590..ed0bde4f9a4 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.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 @@ void testReceivedResponse() throws Exception { 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 902445e3c76..7224aab9818 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 MockedChannel() { super(); } - @Override public URL getUrl() { return url; @@ -55,8 +54,7 @@ public InetSocketAddress getLocalAddress() { } @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 d9ffe9bebce..a38fe8d6a51 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 void sent(Channel channel, Object message) throws RemotingException { @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 452a3df5c05..23dd1faa8fe 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 @@ 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 @@ void testToList() { @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 c9163fb98e7..8cf9f990b0e 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 @@ void test() { 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 a5b77dd8ef0..34e55e6d6a8 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 @@ void test() { 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 9fc9da58249..471a6355d59 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 @@ void test() { 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 40afb734be2..65b8d6fda17 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.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 @@ void testTelnet() throws RemotingException { 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 @@ void testTelnet() throws RemotingException { 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 973af20a581..7b559f22620 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.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 @@ void testCheckPayloadDefault8M() throws Exception { 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 @@ void testCheckProviderPayload() throws Exception { 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 @@ void testIsClientSide() { 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 960551f2a66..2e7fdf28389 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 @@ 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 @@ void test() { channelHandlerDispatcher = channelHandlerDispatcher.removeChannelHandler(channelHandler1); Assertions.assertFalse(channelHandlerDispatcher.getChannelHandlers().contains(channelHandler1)); - } @Test @@ -63,18 +63,23 @@ void constructorNullObjectTest() { 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 5411a608a68..d05c7c6f2ae 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.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 5c0e3849f62..f598b40853f 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 @@ void test() throws Exception { // 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 @@ void test() throws Exception { 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 @@ void test() throws Exception { 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 59641bf20ec..3bea230978e 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 @@ 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 @@ void test() throws Exception { 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 @@ void test() throws Exception { 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 e184f53eedd..056ad679b96 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 - + + 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 + - - 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 d644daf7dd1..23c78419ad6 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 BaseRestClient(HttpClientConfig clientConfig) { 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 338283b4828..26db36d92cf 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 e6e9203c890..27085f67bc7 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 57d5399e106..d85582eb76a 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 6d19f1636bf..d02d63be29d 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.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 String getQueryString() { } return queryBuilder.toString().replace("?&", "?"); - } - public RequestTemplate path(String path) { this.path = path; return this; @@ -132,7 +127,7 @@ public boolean isBodyEmpty() { 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 void addHeaders(String key, Collection values) { header.addAll(values); } - public void addParam(String key, String value) { addValueByKey(key, value, this.queries); } @@ -231,7 +225,6 @@ public void addParams(String key, Collection values) { params.addAll(values); } - public void addValueByKey(String key, String value, Map> maps) { if (value == null) { @@ -245,12 +238,9 @@ public void addValueByKey(String key, String value, Map 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 void setProtocol(String protocol) { this.protocol = protocol; } - public Invocation getInvocation() { return invocation; } @@ -296,7 +283,6 @@ public String getContextPath() { } 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 f8827dd2d47..e5b8cecf7df 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 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 6e7e49e660f..09e0ab92a13 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 44936b0d37f..ad9e7f7821f 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 RestClient createRestClient(URL url) throws RpcException { //////////////////////////////////////// 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 ca82b052e50..c64453dbda9 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 @@ @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 08fef6f4ea4..89d9c36f6fb 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 @@ @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 87e154c76a4..523df3caf89 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 @@ @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 94676a091d2..40c2a82a66a 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 @@ @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 9a41285684e..05e5dc5a354 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 cba4f9fa002..0139a5d79ff 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 JettyHttpServer(URL url, final HttpHandler handler) { // 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 void close() { } } } - } 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 f8f85411af5..f09b288c5f8 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.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.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 CompletableFuture send(RequestTemplate requestTemplate) { 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 byte[] getBody() throws IOException { @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 int getResponseCode() { @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 void close() { } @Override - public void close(int timeout) { - - } + public void close(int timeout) {} @Override public boolean isClosed() { @@ -186,7 +184,5 @@ protected HttpRequestBase createHttpUriRequest(String httpMethod, RequestTemplat 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 461d2bcd628..36ba2e6d187 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.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.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 void close() { } @Override - public void close(int timeout) { - - } + public void close(int timeout) {} @Override public boolean isClosed() { @@ -142,11 +140,11 @@ public boolean isClosed() { } 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 960912c0eac..65f20a19f28 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.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.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 CompletableFuture send(RequestTemplate requestTemplate) { } } - // writeBody boolean gzipEncodedRequest = requestTemplate.isGzipEncodedRequest(); @@ -103,21 +101,16 @@ public CompletableFuture send(RequestTemplate requestTemplate) { } @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 int getResponseCode() throws IOException { @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 @@ private void prepareConnection(HttpURLConnection connection, String httpMethod) 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 @@ private void prepareConnection(HttpURLConnection connection, String httpMethod) 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 94554ba56ff..0a902f292f9 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 3500f05e0fa..ced2170b3b0 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.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 static DispatcherServlet getInstance() { 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 447ea4e6ed4..33aecc5aff5 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 29e02d2208a..bf0b01457e1 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 ServletHttpServer(URL url, HttpHandler handler) { 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 e81fae23c67..a261b6e54c4 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 437ac0d36d4..cc01b1e0645 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 URL getUrl() { } @Override - public void reset(URL url) { - } + public void reset(URL url) {} @Override public boolean isBound() { @@ -91,7 +90,6 @@ public boolean isClosed() { /** * Following methods are extended from RemotingServer, useless for http servers */ - @Override public boolean canHandleIdle() { return false; @@ -108,9 +106,7 @@ public Channel getChannel(InetSocketAddress remoteAddress) { } @Override - public void reset(Parameters parameters) { - - } + public void reset(Parameters parameters) {} @Override public ChannelHandler getChannelHandler() { @@ -118,17 +114,11 @@ public ChannelHandler getChannelHandler() { } @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 4e4a74bb7ec..92b4bf1c70b 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 dfbba2948e7..3d73fcadb1c 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.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 a00fbcd9c27..04fc431863c 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.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 f2de8ccdefd..e4cbbfd5397 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.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 @@ 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 @@ public void handle(HttpServletRequest request, HttpServletResponse response) thr 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 @@ void testSuccessLogger() throws Exception{ 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 04b4489b5bd..3f1491e94b4 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.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.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 void handle(HttpServletRequest request, HttpServletResponse response) thr 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 void handle(HttpServletRequest request, HttpServletResponse response) thr 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 void handle(HttpServletRequest request, HttpServletResponse response) thr 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 void handle(HttpServletRequest request, HttpServletResponse response) thr 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 void handle(HttpServletRequest request, HttpServletResponse response) thr Assertions.assertEquals(contentType, restResult.getContentType()); restClient.close(); - httpServer.close(); } @@ -171,29 +166,28 @@ public void testMethod() { 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); - - - Assertions.assertArrayEquals(strings.toArray(new String[0]),requestTemplate.getHeaders("header").toArray(new String[0])); - - strings = Arrays.asList("p1", "p2"); - - requestTemplate.addParams("param",strings); + requestTemplate.addHeaders("header", strings); - Assertions.assertArrayEquals(strings.toArray(new String[0]),requestTemplate.getParam("param").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])); } } 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 ac100eef3fe..75efc28b412 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.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)}); - - 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(); + 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"); + } + }); + + String response = + Request.Get(url.toJavaURL().toURI()).execute().returnContent().asString(); assertThat(response, is("Tomcat")); diff --git a/dubbo-remoting/dubbo-remoting-netty/pom.xml b/dubbo-remoting/dubbo-remoting-netty/pom.xml index 5d7cefac959..bc0bd6fa9fe 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.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.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 54b8f28af9e..ab193b31f78 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 int capacity() { 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 void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { 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 void setBytes(int index, ChannelBuffer src, int srcIndex, int length) { 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 void getBytes(int index, ChannelBuffer dst, int length) { 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 void readBytes(ChannelBuffer dst, int length) { dst.writerIndex(dst.writerIndex() + length); } - @Override public void readBytes(ChannelBuffer dst, int dstIndex, int length) { // careful @@ -284,56 +248,47 @@ public void readBytes(ChannelBuffer dst, int dstIndex, int length) { 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 void setBytes(int index, ChannelBuffer src, int length) { 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 void writeBytes(ChannelBuffer src, int length) { src.readerIndex(src.readerIndex() + length); } - @Override public void writeBytes(ChannelBuffer src, int srcIndex, int length) { // careful @@ -425,25 +368,21 @@ public void writeBytes(ChannelBuffer src, int srcIndex, int length) { 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 de3e8091c49..218b6e26808 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 @@ 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 static ChannelBufferFactory getInstance() { 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 ChannelBuffer getBuffer(byte[] array, int offset, int length) { 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 ee51ee6050f..695983a22f1 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.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 @@ public void send(Object message, boolean sent) throws RemotingException { 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 @@ public boolean equals(Object obj) { 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 3f907959be5..6ed419f3a35 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.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.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 @@ protected void doConnect() throws Throwable { 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 @@ protected void doConnect() throws Throwable { } 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 @@ protected org.apache.dubbo.remoting.Channel getChannel() { 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 984ec89a40a..4034392695a 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.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.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 @@ public void messageReceived(ChannelHandlerContext ctx, MessageEvent event) throw 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 db6e2dded6e..f1d4bfd23c8 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.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.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 void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) thr 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 void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) thr } 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 void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) thr 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 void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws 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 f7f70bfecd7..b25d5be1401 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 @@ public String toString() { 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 a4d63b608d8..204009b9c15 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.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.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 @@ */ 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 void close() { } } - public void bind(){ - if(channel == null) { + public void bind() { + if (channel == null) { doOpen(); } } @@ -93,8 +93,10 @@ public void bind(){ 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 @@ protected void doOpen() { 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 ChannelPipeline getPipeline() { } InetSocketAddress bindAddress = new InetSocketAddress(bindIp, bindPort); channel = bootstrap.bind(bindAddress); - - } @Override @@ -201,5 +202,4 @@ public InetSocketAddress getLocalAddress() { 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 d5aec38b920..42a23464819 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.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.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 NettyServer(URL url, ChannelHandler handler) throws RemotingException { 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 Channel getChannel(InetSocketAddress remoteAddress) { 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 4dde31eb26f..c9dd8f53d22 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 RemotingServer bind(URL url, ChannelHandler handler) throws RemotingExcep 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 608a5307310..ca34345c953 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.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 @@ public void after() throws Exception { 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 @@ void testServerHeartbeat() throws Exception { @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 @@ void testHeartbeat() throws Exception { 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 @@ 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 { @@ -197,5 +195,4 @@ public String telnet(Channel channel, String message) throws RemotingException { 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 0e17dab774b..8c3c96411f2 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 static void resetChannelHandlers() { @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 37183b94cb5..a5a82dca66f 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 @@ void testReconnect() throws RemotingException, InterruptedException { } } - 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 @@ public HandlerAdapter() { } @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 a21ed9e1145..3a8ff64488d 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.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 @@ protected void setUp() throws Exception { @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 @@ void testFuture() throws Exception { 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 dfcd94a4475..eb0112e5881 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 @@ void testGetTransportNull() { @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 52ce36b2a83..3b669f8c4a4 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 String getName() { 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 99005d91409..aacca988231 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 4b14d0f4b1b..46337903d62 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.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 @@ public static void setUp() throws Exception { @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 @@ void testClientClose() throws Exception { @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 57131fcbc62..c7c1a86478b 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 @@ protected ExchangeChannel newClient(int port) throws RemotingException { 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 8b1fde4034f..64a2bb85e8d 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.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 @@ public static void setUp() throws Exception { @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 54b951b5de2..c83db19c843 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 Object reply(ExchangeChannel channel, String msg) throws RemotingExceptio } 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 203cc35353a..ffc7100b93d 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.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 @@ private void checkThreadName() { 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 @@ public void sent(Channel channel, Object message) throws RemotingException { @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 @@ public void caught(Channel channel, Throwable exception) throws RemotingExceptio 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 7185da312a2..372857aee05 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 String getName() { 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 689f978ccf5..80ac7118dbb 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 interest() { 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 dd8b9d4eaf2..dcf8857c175 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-remoting-api + ${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 - - - io.netty - netty-transport-classes-epoll - compile - - - io.netty - netty-transport-native-epoll - linux-aarch_64 - runtime - - + + 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 + + + io.netty + netty-transport-classes-epoll + compile + + + io.netty + netty-transport-native-epoll + linux-aarch_64 + runtime + + 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 b07eae7d3f4..75089d31c25 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 @@ protected void flush(MessageTuple item) { public void operationComplete(ChannelFuture future) throws Exception { ChannelPromise cp; while ((cp = promises.poll()) != null) { - if (future.isSuccess()){ + if (future.isSuccess()) { cp.setSuccess(); } else { cp.setFailure(future.cause()); @@ -98,6 +99,5 @@ public MessageTuple(Object originMessage, ChannelPromise channelPromise) { this.originMessage = originMessage; this.channelPromise = channelPromise; } - } } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyBackedChannelBuffer.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyBackedChannelBuffer.java index dc4ef5937f5..d0fb5f27533 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyBackedChannelBuffer.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyBackedChannelBuffer.java @@ -21,14 +21,14 @@ import org.apache.dubbo.remoting.buffer.ChannelBufferFactory; import org.apache.dubbo.remoting.buffer.ChannelBuffers; -import io.netty.buffer.ByteBuf; -import io.netty.util.ReferenceCountUtil; - import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; +import io.netty.buffer.ByteBuf; +import io.netty.util.ReferenceCountUtil; + public class NettyBackedChannelBuffer implements ChannelBuffer { private final ByteBuf buffer; @@ -38,43 +38,37 @@ public NettyBackedChannelBuffer(ByteBuf buffer) { this.buffer = buffer; } - @Override public int capacity() { return buffer.capacity(); } - @Override public ChannelBuffer copy(int index, int length) { return new NettyBackedChannelBuffer(buffer.copy(index, length)); } - //has nothing use + // has nothing use @Override public ChannelBufferFactory factory() { return null; } - @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 void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { 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 void setBytes(int index, ChannelBuffer src, int srcIndex, int length) { 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 void getBytes(int index, ChannelBuffer dst, int length) { 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 void readBytes(ChannelBuffer dst, int length) { dst.writerIndex(dst.writerIndex() + length); } - @Override public void readBytes(ChannelBuffer dst, int dstIndex, int length) { // careful @@ -284,56 +248,47 @@ public void readBytes(ChannelBuffer dst, int dstIndex, int length) { 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 void setBytes(int index, ChannelBuffer src, int length) { 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 void writeBytes(ChannelBuffer src, int length) { src.readerIndex(src.readerIndex() + length); } - @Override public void writeBytes(ChannelBuffer src, int srcIndex, int length) { // careful @@ -425,26 +368,22 @@ public void writeBytes(ChannelBuffer src, int srcIndex, int length) { 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 2ca031cdf42..41b7bb5f4cd 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.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 @@ public void operationComplete(ChannelFuture future) throws Exception { } } 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 @@ public void removeAttribute(String key) { attributes.remove(key); } - @Override public int hashCode() { final int prime = 31; @@ -344,9 +351,9 @@ public Channel getNioChannel() { */ 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 @@ private static Codec2 getChannelCodec(URL url) { 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 cfedb14371c..6082db24a03 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.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 void channelActive(ChannelHandlerContext ctx) throws Exception { 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 void channelInactive(ChannelHandlerContext ctx) throws Exception { 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 d175a84c0ab..d01a4810492 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.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.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 @@ protected NettyClientHandler createNettyClientHandler() { } 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 @@ protected void initChannel(SocketChannel ch) throws Exception { } 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); - - String socksProxyHost = ConfigurationUtils.getProperty(getUrl().getOrDefaultApplicationModel(), SOCKS_PROXY_HOST); + 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); 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 @@ protected void doConnect() throws Throwable { 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 @@ protected void doConnect() throws Throwable { } finally { // just add new valid channel to NettyChannel's cache if (!isConnected()) { - //future.cancel(true); + // future.cancel(true); } } } @@ -194,7 +200,8 @@ private void doConnect(InetSocketAddress serverAddress) throws RemotingException 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 @@ private void doConnect(InetSocketAddress serverAddress) throws RemotingException // 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 @@ private void doConnect(InetSocketAddress serverAddress) throws RemotingException // 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()); - - logger.error(TRANSPORT_CLIENT_CONNECT_TIMEOUT, "provider crash", "", - "Client-side timeout.", remotingException); + 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); throw remotingException; } } finally { // just add new valid channel to NettyChannel's cache if (!isConnected()) { - //future.cancel(true); + // future.cancel(true); } } } @@ -263,7 +284,8 @@ protected void doDisConnect() throws Throwable { @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 0ab1c129fd8..71c9f5ec0bf 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 void channelActive(ChannelHandlerContext ctx) throws Exception { 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 void channelInactive(ChannelHandlerContext ctx) throws Exception { } 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 void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc } @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 void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) 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 bf029272ab9..6001213c784 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 @@ 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.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 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf input, List out 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 c708b12810a..ef950b66354 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 @@ -51,48 +51,51 @@ public void configChannelHandler(List handlerList) { 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)); - }else { - codec2 = url.getOrDefaultFrameworkModel().getExtensionLoader(Codec2.class).getExtension("default"); + 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"); } - if (!(codec2 instanceof DefaultCodec)){ + 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) { + for (ChannelHandler handler : handlerList) { if (handler instanceof ChannelHandlerPretender) { Object realHandler = ((ChannelHandlerPretender) handler).getRealHandler(); - if(realHandler instanceof io.netty.channel.ChannelHandler) { - ((NettyChannel) channel).getNioChannel().pipeline().addLast( - (io.netty.channel.ChannelHandler) realHandler - ); + if (realHandler instanceof io.netty.channel.ChannelHandler) { + ((NettyChannel) channel).getNioChannel().pipeline().addLast((io.netty.channel.ChannelHandler) + realHandler); } } } // todo distinguish between client and server channel - if( isClientSide(channel)){ - //todo config client channel handler - }else { + if (isClientSide(channel)) { + // 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); } } 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 a86e9634c5b..66e8c084169 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.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.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 @@ 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 @@ protected void doOpen() throws Throwable { 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 @@ protected void initChannel(SocketChannel ch) { 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 @@ protected void doClose() { 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 @@ protected void doConnect() throws RemotingException { 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); - - LOGGER.error(TRANSPORT_FAILED_CONNECT_PROVIDER, "network disconnected", "", - "Failed to connect to provider server by other reason.", 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); 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 boolean isAvailable() { nettyChannel = getNettyChannel(); return nettyChannel != null && nettyChannel.isActive(); - } @Override @@ -303,9 +315,10 @@ public static AbstractConnectionClient getConnectionClientFromChannel(io.netty.c 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 void destroy() { @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 void operationComplete(ChannelFuture future) { 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 3ab6fbc8fc6..c583cd3c89a 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.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 void reconnect(Object channel) { 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 void channelActive(ChannelHandlerContext ctx) { 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 void channelInactive(ChannelHandlerContext ctx) throws Exception { 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 2db6f9697e8..ad3c807cf61 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 @@ 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.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 a7cab7b985f..eaaab27f71f 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.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.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 @@ */ 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 void doOpen() throws Throwable { 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); - - 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); - } - }); + 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); + } + }); // bind String bindIp = getUrl().getParameter(Constants.BIND_IP_KEY, getUrl().getHost()); @@ -153,10 +160,9 @@ private void closeBootstrap() { 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 InetSocketAddress getLocalAddress() { 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 cb7e672c67b..93ca1a824c6 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.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.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 NettyPortUnificationServerHandler(URL url, boolean detectSsl, @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 void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc 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 void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc } @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 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) 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); @@ -111,8 +127,9 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) 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); @@ -128,12 +145,15 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) 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(); @@ -145,9 +165,9 @@ private void enableSsl(ChannelHandlerContext ctx, ProviderCert providerConnectio 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); } @@ -158,6 +178,4 @@ private boolean isSsl(ByteBuf buf) { } 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 f75375b5332..03ff97fc299 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 AbstractPortUnificationServer bind(URL url, ChannelHandler handler) throw @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 1c0c7da3a9e..0c8c6a3da9c 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 @@ -31,6 +31,11 @@ import org.apache.dubbo.remoting.transport.netty4.ssl.SslServerTlsHandler; import org.apache.dubbo.remoting.utils.UrlUtils; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Map; + import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.ChannelFuture; @@ -41,11 +46,6 @@ 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.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; @@ -53,7 +53,6 @@ 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. */ @@ -79,7 +78,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)); @@ -121,8 +121,8 @@ protected EventLoopGroup createBossGroup() { 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() { @@ -131,25 +131,26 @@ protected NettyServerHandler createNettyServerHandler() { 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 @@ -192,7 +193,8 @@ private void closeBootstrap() { 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 7ea3733120b..1eff7fc84b1 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.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 Map getChannels() { 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 void channelActive(ChannelHandlerContext ctx) throws Exception { 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 void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception 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 void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc } @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 void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) 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 e1f7f523964..38873bb4069 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 78e334b7614..0743e4d3743 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 RemotingServer bind(URL url, ChannelHandler handler) throws RemotingExcep 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/logging/FormattingTuple.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/logging/FormattingTuple.java index eac0a474946..a66efb40e07 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 5c98405ddf7..a8f3c302c50 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 @@ static FormattingTuple format(String messagePattern, Object arg) { * 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 @@ static Throwable getThrowableCandidate(Object[] argArray) { * 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 @@ static FormattingTuple arrayFormat(final String messagePattern, 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 @@ static FormattingTuple arrayFormat(final String messagePattern, } } - static boolean isEscapedDelimeter(String messagePattern, - int delimeterStartIndex) { + static boolean isEscapedDelimeter(String messagePattern, int delimeterStartIndex) { if (delimeterStartIndex == 0) { return false; @@ -239,14 +234,12 @@ static boolean isEscapedDelimeter(String messagePattern, 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 @@ private static void safeObjectAppend(StringBuffer sbuf, Object o) { 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 @@ private static void doubleArrayAppend(StringBuffer sbuf, double[] a) { 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 4c0ea5dd633..9918d171ee3 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.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 void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc 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 ec07ad4e030..beb7e611420 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.CertManager; import org.apache.dubbo.common.ssl.ProviderCert; -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 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 static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE_STREAM; public class SslContexts { @@ -53,11 +54,11 @@ public static SslContext buildServerSslContext(ProviderCert providerConnectionCo 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 static SslContext buildServerSslContext(ProviderCert providerConnectionCo } 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 @@ private static SslProvider findSslProvider() { 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 @@ private static void safeCloseStream(InputStream stream) { 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 5aaca5e00af..408b8915a6b 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.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.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 SslServerTlsHandler(URL url, boolean sslDetected) { @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 void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc 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 void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc } @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 @@ protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteB 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 @@ private void enableSsl(ChannelHandlerContext ctx, SslContext sslContext) { 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 ff15bda5160..47fce295e79 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 @@ void testReconnect() throws RemotingException, InterruptedException { } } - 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 @@ public HandlerAdapter() { } @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 f97f31f1aa1..2fdbe070358 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.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 @@ protected void setUp() throws Exception { @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 4eb68351b75..cec40e77d06 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 @@ void testGetTransportNull() { @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 ba9fd3eb0d7..37b4439bba6 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.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 static void init() throws Throwable { 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 @@ void testRefCnt2() throws InterruptedException { 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 @@ void connectSyncTest() throws Throwable { 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 9f33bfaa007..d74e8e53984 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 @@ 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 cd622b9f074..30603e752b4 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 @@ /** * 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 22cb86cf4d9..a428b03b7d7 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 @@ /** * 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 f99bb4ab958..e7eb7f39dcb 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 String getName() { 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 fbd05f796a5..182626a5925 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 @@ /** * 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 f50bf214605..c2224e19940 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 @@ void testBufferTransfer() { 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 2d6c99deb74..3d51c148b8f 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 @@ void test() throws Exception { nettyChannel = NettyChannel.getOrAddChannel(channel, url, channelHandler); nettyChannel.markActive(true); Assertions.assertTrue(nettyChannel.isActive()); - } @Test @@ -94,15 +93,21 @@ void testSend() throws Exception { 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 @@ void testSend() throws Exception { 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 508153fd830..8db75f0be5a 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 @@ void test() throws Exception { 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 4b66d3faea2..2fb11c51a64 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 @@ protected ExchangeServer newServer(int port, Replier receiver) throws Remotin 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 @@ protected ExchangeChannel newClient(int port) throws RemotingException { 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 98f647a8468..43fbdbe5a6a 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 @@ void eventLoopGroup() { 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 @@ void eventLoopGroup() { 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 @@ private boolean isEpoll() { 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 772f3d604a8..3267f908344 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.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 @@ void shouldConnectToNetty4Server() throws Exception { 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 faa9de88698..87c1fa9bc59 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.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 @@ void testConnection() { 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/ReplierDispatcherTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ReplierDispatcherTest.java index 3ba8098f2d1..0fa2d0a9e38 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.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.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 @@ public void startServer() throws RemotingException { 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 @@ public void startServer() throws RemotingException { 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 @@ void testDataPackage() throws Exception { clients.put(Thread.currentThread().getName(), client); } - @Test void testMultiThread() throws Exception { int tc = 10; @@ -120,12 +118,18 @@ void testMultiThread() throws Exception { } 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 @@ void clientExchangeInfo(int port) throws Exception { } } - @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 @@ public void tearDown() { } } - 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 44630924a62..0773242d6d9 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 @@ /** * RpcMessage. */ - public class RpcMessage implements Serializable { private static final long serialVersionUID = -5148079121106659095L; @@ -55,5 +54,4 @@ public Class[] getParameterTypes() { 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 6912a5b7a62..89099f8d6bf 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 @@ /** * 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 Object reply(ExchangeChannel channel, RpcMessage msg) throws RemotingExce } 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 9ee2814cd35..9775bbe617d 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 String getName() { 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 7b83598154a..511a2071234 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 interest() { 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 5f90d7975b7..2943b64a9f6 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.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 ProtocolDetector detector() { } @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 76a45adadd6..9ed0cafe7f9 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.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 static void init() throws Throwable { 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 void testForEachConnection() throws Throwable { // 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 5369ea0f226..61dd658e4ba 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.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 static void init() throws Throwable { 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 static void close() { @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 void testConnect() throws Exception { // 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 void testForEachConnection() throws RemotingException { 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-curator5/pom.xml b/dubbo-remoting/dubbo-remoting-zookeeper-curator5/pom.xml index c66185db78f..8d0b1c61213 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-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-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} + + 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 028ebb6fe48..65b6bd67975 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.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.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 Curator5ZookeeperClient(URL url) { int timeout = url.getParameter(TIMEOUT_KEY, DEFAULT_CONNECTION_TIMEOUT_MS); int sessionExpireMs = url.getParameter(SESSION_KEY, DEFAULT_SESSION_TIMEOUT_MS); CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder() - .connectString(url.getBackupAddress()) - .retryPolicy(new RetryNTimes(1, 1000)) - .connectionTimeoutMs(timeout) - .sessionTimeoutMs(sessionExpireMs); + .connectString(url.getBackupAddress()) + .retryPolicy(new RetryNTimes(1, 1000)) + .connectionTimeoutMs(timeout) + .sessionTimeoutMs(sessionExpireMs); String userInformation = url.getUserInformation(); if (userInformation != null && userInformation.length() > 0) { builder = builder.authorization("digest", userInformation.getBytes()); @@ -98,11 +100,16 @@ public List getAclForPath(String path) { boolean connected = client.blockUntilConnected(timeout, TimeUnit.MILLISECONDS); if (!connected) { - IllegalStateException illegalStateException = new IllegalStateException("zookeeper not connected, the address is: " + url); + IllegalStateException illegalStateException = + new IllegalStateException("zookeeper not connected, the address is: " + url); // 5-1 Failed to connect to configuration center. - logger.error(CONFIG_FAILED_CONNECT_REGISTRY, "Zookeeper server offline", "", - "Failed to connect with zookeeper", illegalStateException); + logger.error( + CONFIG_FAILED_CONNECT_REGISTRY, + "Zookeeper server offline", + "", + "Failed to connect with zookeeper", + illegalStateException); throw illegalStateException; } @@ -132,10 +139,11 @@ public void createEphemeral(String path, boolean faultTolerant) { client.create().withMode(CreateMode.EPHEMERAL).forPath(path); } catch (NodeExistsException e) { if (faultTolerant) { - logger.info("ZNode " + path + " already exists, since we will only try to recreate a node on a session expiration" + - ", this duplication might be caused by a delete delay from the zk server, which means the old expired session" + - " may still holds this ZNode and the server just hasn't got time to do the deletion. In this case, " + - "we can just try to delete and create again."); + logger.info("ZNode " + path + + " already exists, since we will only try to recreate a node on a session expiration" + + ", this duplication might be caused by a delete delay from the zk server, which means the old expired session" + + " may still holds this ZNode and the server just hasn't got time to do the deletion. In this case, " + + "we can just try to delete and create again."); deletePath(path); createEphemeral(path, true); } else { @@ -176,10 +184,11 @@ protected void createEphemeral(String path, String data, boolean faultTolerant) client.create().withMode(CreateMode.EPHEMERAL).forPath(path, dataBytes); } catch (NodeExistsException e) { if (faultTolerant) { - logger.info("ZNode " + path + " already exists, since we will only try to recreate a node on a session expiration" + - ", this duplication might be caused by a delete delay from the zk server, which means the old expired session" + - " may still holds this ZNode and the server just hasn't got time to do the deletion. In this case, " + - "we can just try to delete and create again."); + logger.info("ZNode " + path + + " already exists, since we will only try to recreate a node on a session expiration" + + ", this duplication might be caused by a delete delay from the zk server, which means the old expired session" + + " may still holds this ZNode and the server just hasn't got time to do the deletion. In this case, " + + "we can just try to delete and create again."); deletePath(path); createEphemeral(path, data, true); } else { @@ -222,7 +231,6 @@ protected void createOrUpdatePersistent(String path, String data) { } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } - } @Override @@ -236,7 +244,6 @@ protected void createOrUpdateEphemeral(String path, String data) { } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } - } @Override @@ -354,7 +361,8 @@ public List addTargetChildListener(String path, CuratorWatcherImpl liste } @Override - protected Curator5ZookeeperClient.NodeCacheListenerImpl createTargetDataListener(String path, DataListener listener) { + protected Curator5ZookeeperClient.NodeCacheListenerImpl createTargetDataListener( + String path, DataListener listener) { return new NodeCacheListenerImpl(client, listener, path); } @@ -364,7 +372,8 @@ protected void addTargetDataListener(String path, Curator5ZookeeperClient.NodeCa } @Override - protected void addTargetDataListener(String path, Curator5ZookeeperClient.NodeCacheListenerImpl nodeCacheListener, Executor executor) { + protected void addTargetDataListener( + String path, Curator5ZookeeperClient.NodeCacheListenerImpl nodeCacheListener, Executor executor) { try { NodeCache nodeCache = new NodeCache(client, path); if (nodeCacheMap.putIfAbsent(path, nodeCache) != null) { @@ -383,7 +392,8 @@ protected void addTargetDataListener(String path, Curator5ZookeeperClient.NodeCa } @Override - protected void removeTargetDataListener(String path, Curator5ZookeeperClient.NodeCacheListenerImpl nodeCacheListener) { + protected void removeTargetDataListener( + String path, Curator5ZookeeperClient.NodeCacheListenerImpl nodeCacheListener) { NodeCache nodeCache = nodeCacheMap.get(path); if (nodeCache != null) { nodeCache.getListenable().removeListener(nodeCacheListener); @@ -404,8 +414,7 @@ static class NodeCacheListenerImpl implements NodeCacheListener { private String path; - protected NodeCacheListenerImpl() { - } + protected NodeCacheListenerImpl() {} public NodeCacheListenerImpl(CuratorFramework client, DataListener dataListener, String path) { this.client = client; @@ -443,8 +452,7 @@ public CuratorWatcherImpl(CuratorFramework client, ChildListener listener, Strin this.path = path; } - protected CuratorWatcherImpl() { - } + protected CuratorWatcherImpl() {} public void unwatch() { this.childListener = null; @@ -459,7 +467,8 @@ public void process(WatchedEvent event) throws Exception { } if (childListener != null) { - childListener.childChanged(path, client.getChildren().usingWatcher(this).forPath(path)); + childListener.childChanged( + path, client.getChildren().usingWatcher(this).forPath(path)); } } } @@ -482,34 +491,55 @@ public void stateChanged(CuratorFramework client, ConnectionState state) { try { sessionId = client.getZookeeperClient().getZooKeeper().getSessionId(); } catch (Exception e) { - logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Curator client state changed, but failed to get the related zk session instance."); + logger.warn( + REGISTRY_ZOOKEEPER_EXCEPTION, + "", + "", + "Curator client state changed, but failed to get the related zk session instance."); } if (state == ConnectionState.LOST) { - logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Curator zookeeper session " + Long.toHexString(lastSessionId) + " expired."); + logger.warn( + REGISTRY_ZOOKEEPER_EXCEPTION, + "", + "", + "Curator zookeeper session " + Long.toHexString(lastSessionId) + " expired."); Curator5ZookeeperClient.this.stateChanged(StateListener.SESSION_LOST); } else if (state == ConnectionState.SUSPENDED) { - logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Curator zookeeper connection of session " + Long.toHexString(sessionId) + " timed out. " + - "connection timeout value is " + timeout + ", session expire timeout value is " + sessionExpireMs); + logger.warn( + REGISTRY_ZOOKEEPER_EXCEPTION, + "", + "", + "Curator zookeeper connection of session " + Long.toHexString(sessionId) + " timed out. " + + "connection timeout value is " + timeout + ", session expire timeout value is " + + sessionExpireMs); Curator5ZookeeperClient.this.stateChanged(StateListener.SUSPENDED); } else if (state == ConnectionState.CONNECTED) { lastSessionId = sessionId; - logger.info("Curator zookeeper client instance initiated successfully, session id is " + Long.toHexString(sessionId)); + logger.info("Curator zookeeper client instance initiated successfully, session id is " + + Long.toHexString(sessionId)); Curator5ZookeeperClient.this.stateChanged(StateListener.CONNECTED); } else if (state == ConnectionState.RECONNECTED) { if (lastSessionId == sessionId && sessionId != UNKNOWN_SESSION_ID) { - logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Curator zookeeper connection recovered from connection lose, " + - "reuse the old session " + Long.toHexString(sessionId)); + logger.warn( + REGISTRY_ZOOKEEPER_EXCEPTION, + "", + "", + "Curator zookeeper connection recovered from connection lose, " + "reuse the old session " + + Long.toHexString(sessionId)); Curator5ZookeeperClient.this.stateChanged(StateListener.RECONNECTED); } else { - logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "New session created after old session lost, " + - "old session " + Long.toHexString(lastSessionId) + ", new session " + Long.toHexString(sessionId)); + logger.warn( + REGISTRY_ZOOKEEPER_EXCEPTION, + "", + "", + "New session created after old session lost, " + "old session " + + Long.toHexString(lastSessionId) + ", new session " + Long.toHexString(sessionId)); lastSessionId = sessionId; Curator5ZookeeperClient.this.stateChanged(StateListener.NEW_SESSION_CREATED); } } } - } /** diff --git a/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperTransporter.java b/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperTransporter.java index 95dcd0480eb..223981a2558 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperTransporter.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperTransporter.java @@ -26,5 +26,4 @@ public class Curator5ZookeeperTransporter extends AbstractZookeeperTransporter { public ZookeeperClient createZookeeperClient(URL url) { return new Curator5ZookeeperClient(url); } - } 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 dc1de17c45f..50e96f93543 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.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.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 @@ public void process(WatchedEvent watchedEvent) { countDownLatch.await(); } - @Test void testWithInvalidServer() { Assertions.assertThrows(IllegalStateException.class, () -> { @@ -227,23 +229,25 @@ void testPersistentCas1() throws Exception { // 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); - } - - @Override - protected void update(String path, String data, int version) { - if (runnable.get() != null) { - runnable.get().run(); - } - super.update(path, data, version); - } - }; + 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); + } + }; curatorClient.delete(path); runnable.set(() -> { @@ -253,7 +257,8 @@ protected void update(String path, String data, int version) { 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 @@ protected void update(String path, String data, int version) { } }); 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 @@ protected void update(String path, String data, int version) { 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 @@ void testPersistentCas2() { 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); - } - - @Override - protected void update(String path, String data, int version) { - if (runnable.get() != null) { - runnable.get().run(); - } - super.update(path, data, version); - } - }; + 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); + } + }; curatorClient.delete(path); curatorClient.createOrUpdate(path, "version 0", false); @@ -352,23 +362,25 @@ void testEphemeralCas1() throws Exception { // 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); - } - - @Override - protected void update(String path, String data, int version) { - if (runnable.get() != null) { - runnable.get().run(); - } - super.update(path, data, version); - } - }; + 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); + } + }; curatorClient.delete(path); runnable.set(() -> { @@ -378,7 +390,8 @@ protected void update(String path, String data, int version) { 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 @@ protected void update(String path, String data, int version) { } }); 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 @@ protected void update(String path, String data, int version) { 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 @@ void testEphemeralCas2() { 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); - } - - @Override - protected void update(String path, String data, int version) { - if (runnable.get() != null) { - runnable.get().run(); - } - super.update(path, data, version); - } - }; + 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); + } + }; 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 1418d2fc3d9..f94f4e0053e 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 @@ public static void beforeAll() { @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 a90d735e4e5..5b3eac89683 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.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 @@ void testZookeeperClient() { @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 @@ void testGetURLBackupAddress() { @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 @@ void testGetURLBackupAddressNoBack() { @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); - - 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"); + 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"); 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 @@ private void checkFetchAndUpdateCacheNotNull(URL url) { @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 9e40b3dbc37..2f0b7a0116b 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-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.zookeeper - zookeeper - ${zookeeper_version} - - - org.slf4j - slf4j-log4j12 - - - + 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-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.zookeeper + zookeeper + ${zookeeper_version} + + + org.slf4j + slf4j-log4j12 + + + - - 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 dc4a5d3fab3..e9a99f38b44 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.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.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 CuratorZookeeperClient(URL url) { int timeout = url.getParameter(TIMEOUT_KEY, DEFAULT_CONNECTION_TIMEOUT_MS); int sessionExpireMs = url.getParameter(SESSION_KEY, DEFAULT_SESSION_TIMEOUT_MS); CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder() - .connectString(url.getBackupAddress()) - .retryPolicy(new RetryNTimes(1, 1000)) - .connectionTimeoutMs(timeout) - .sessionTimeoutMs(sessionExpireMs); + .connectString(url.getBackupAddress()) + .retryPolicy(new RetryNTimes(1, 1000)) + .connectionTimeoutMs(timeout) + .sessionTimeoutMs(sessionExpireMs); String userInformation = url.getUserInformation(); if (StringUtils.isNotEmpty(userInformation)) { builder = builder.authorization("digest", userInformation.getBytes()); @@ -103,11 +105,16 @@ public List getAclForPath(String path) { boolean connected = client.blockUntilConnected(timeout, TimeUnit.MILLISECONDS); if (!connected) { - IllegalStateException illegalStateException = new IllegalStateException("zookeeper not connected, the address is: " + url); + IllegalStateException illegalStateException = + new IllegalStateException("zookeeper not connected, the address is: " + url); // 5-1 Failed to connect to configuration center. - logger.error(CONFIG_FAILED_CONNECT_REGISTRY, "Zookeeper server offline", "", - "Failed to connect with zookeeper", illegalStateException); + logger.error( + CONFIG_FAILED_CONNECT_REGISTRY, + "Zookeeper server offline", + "", + "Failed to connect with zookeeper", + illegalStateException); throw illegalStateException; } @@ -139,10 +146,11 @@ public void createEphemeral(String path, boolean faultTolerant) { client.create().withMode(CreateMode.EPHEMERAL).forPath(path); } catch (NodeExistsException e) { if (faultTolerant) { - logger.info("ZNode " + path + " already exists, since we will only try to recreate a node on a session expiration" + - ", this duplication might be caused by a delete delay from the zk server, which means the old expired session" + - " may still holds this ZNode and the server just hasn't got time to do the deletion. In this case, " + - "we can just try to delete and create again."); + logger.info("ZNode " + path + + " already exists, since we will only try to recreate a node on a session expiration" + + ", this duplication might be caused by a delete delay from the zk server, which means the old expired session" + + " may still holds this ZNode and the server just hasn't got time to do the deletion. In this case, " + + "we can just try to delete and create again."); deletePath(path); createEphemeral(path, true); } else { @@ -183,10 +191,11 @@ protected void createEphemeral(String path, String data, boolean faultTolerant) client.create().withMode(CreateMode.EPHEMERAL).forPath(path, dataBytes); } catch (NodeExistsException e) { if (faultTolerant) { - logger.info("ZNode " + path + " already exists, since we will only try to recreate a node on a session expiration" + - ", this duplication might be caused by a delete delay from the zk server, which means the old expired session" + - " may still holds this ZNode and the server just hasn't got time to do the deletion. In this case, " + - "we can just try to delete and create again."); + logger.info("ZNode " + path + + " already exists, since we will only try to recreate a node on a session expiration" + + ", this duplication might be caused by a delete delay from the zk server, which means the old expired session" + + " may still holds this ZNode and the server just hasn't got time to do the deletion. In this case, " + + "we can just try to delete and create again."); deletePath(path); createEphemeral(path, data, true); } else { @@ -366,7 +375,8 @@ public List addTargetChildListener(String path, CuratorWatcherImpl liste } @Override - protected CuratorZookeeperClient.NodeCacheListenerImpl createTargetDataListener(String path, DataListener listener) { + protected CuratorZookeeperClient.NodeCacheListenerImpl createTargetDataListener( + String path, DataListener listener) { return new NodeCacheListenerImpl(listener, path); } @@ -376,7 +386,8 @@ protected void addTargetDataListener(String path, CuratorZookeeperClient.NodeCac } @Override - protected void addTargetDataListener(String path, CuratorZookeeperClient.NodeCacheListenerImpl nodeCacheListener, Executor executor) { + protected void addTargetDataListener( + String path, CuratorZookeeperClient.NodeCacheListenerImpl nodeCacheListener, Executor executor) { try { NodeCache nodeCache = new NodeCache(client, path); if (nodeCacheMap.putIfAbsent(path, nodeCache) != null) { @@ -395,7 +406,8 @@ protected void addTargetDataListener(String path, CuratorZookeeperClient.NodeCac } @Override - protected void removeTargetDataListener(String path, CuratorZookeeperClient.NodeCacheListenerImpl nodeCacheListener) { + protected void removeTargetDataListener( + String path, CuratorZookeeperClient.NodeCacheListenerImpl nodeCacheListener) { NodeCache nodeCache = nodeCacheMap.get(path); if (nodeCache != null) { nodeCache.getListenable().removeListener(nodeCacheListener); @@ -414,8 +426,7 @@ static class NodeCacheListenerImpl implements NodeCacheListener { private String path; - protected NodeCacheListenerImpl() { - } + protected NodeCacheListenerImpl() {} public NodeCacheListenerImpl(DataListener dataListener, String path) { this.dataListener = dataListener; @@ -454,7 +465,8 @@ private static void initExecutorIfNecessary() { if (!closed && CURATOR_WATCHER_EXECUTOR_SERVICE == null) { synchronized (CuratorWatcherImpl.class) { if (!closed && CURATOR_WATCHER_EXECUTOR_SERVICE == null) { - CURATOR_WATCHER_EXECUTOR_SERVICE = Executors.newSingleThreadExecutor(new NamedThreadFactory("Dubbo-CuratorWatcher")); + CURATOR_WATCHER_EXECUTOR_SERVICE = + Executors.newSingleThreadExecutor(new NamedThreadFactory("Dubbo-CuratorWatcher")); } } } @@ -466,8 +478,7 @@ public CuratorWatcherImpl(CuratorFramework client, ChildListener listener, Strin this.path = path; } - protected CuratorWatcherImpl() { - } + protected CuratorWatcherImpl() {} public void unwatch() { this.childListener = null; @@ -482,14 +493,17 @@ public void process(WatchedEvent event) throws Exception { } if (childListener != null) { - 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); - } - }); + 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 void stateChanged(CuratorFramework client, ConnectionState state) { try { sessionId = client.getZookeeperClient().getZooKeeper().getSessionId(); } catch (Exception e) { - logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Curator client state changed, but failed to get the related zk session instance."); + logger.warn( + REGISTRY_ZOOKEEPER_EXCEPTION, + "", + "", + "Curator client state changed, but failed to get the related zk session instance."); } if (state == ConnectionState.LOST) { - logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Curator zookeeper session " + Long.toHexString(lastSessionId) + " expired."); + logger.warn( + REGISTRY_ZOOKEEPER_EXCEPTION, + "", + "", + "Curator zookeeper session " + Long.toHexString(lastSessionId) + " expired."); CuratorZookeeperClient.this.stateChanged(StateListener.SESSION_LOST); } else if (state == ConnectionState.SUSPENDED) { - logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Curator zookeeper connection of session " + Long.toHexString(sessionId) + " timed out. " + - "connection timeout value is " + timeout + ", session expire timeout value is " + sessionExpireMs); + logger.warn( + REGISTRY_ZOOKEEPER_EXCEPTION, + "", + "", + "Curator zookeeper connection of session " + Long.toHexString(sessionId) + " timed out. " + + "connection timeout value is " + timeout + ", session expire timeout value is " + + sessionExpireMs); CuratorZookeeperClient.this.stateChanged(StateListener.SUSPENDED); } else if (state == ConnectionState.CONNECTED) { lastSessionId = sessionId; - logger.info("Curator zookeeper client instance initiated successfully, session id is " + Long.toHexString(sessionId)); + logger.info("Curator zookeeper client instance initiated successfully, session id is " + + Long.toHexString(sessionId)); CuratorZookeeperClient.this.stateChanged(StateListener.CONNECTED); } else if (state == ConnectionState.RECONNECTED) { if (lastSessionId == sessionId && sessionId != UNKNOWN_SESSION_ID) { - logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Curator zookeeper connection recovered from connection lose, " + - "reuse the old session " + Long.toHexString(sessionId)); + logger.warn( + REGISTRY_ZOOKEEPER_EXCEPTION, + "", + "", + "Curator zookeeper connection recovered from connection lose, " + "reuse the old session " + + Long.toHexString(sessionId)); CuratorZookeeperClient.this.stateChanged(StateListener.RECONNECTED); } else { - logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "New session created after old session lost, " + - "old session " + Long.toHexString(lastSessionId) + ", new session " + Long.toHexString(sessionId)); + logger.warn( + REGISTRY_ZOOKEEPER_EXCEPTION, + "", + "", + "New session created after old session lost, " + "old session " + + Long.toHexString(lastSessionId) + ", new session " + Long.toHexString(sessionId)); lastSessionId = sessionId; CuratorZookeeperClient.this.stateChanged(StateListener.NEW_SESSION_CREATED); } diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperTransporter.java b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperTransporter.java index eb2d5a0430a..c69ab90368e 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperTransporter.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperTransporter.java @@ -25,6 +25,4 @@ public class CuratorZookeeperTransporter extends AbstractZookeeperTransporter { public ZookeeperClient createZookeeperClient(URL url) { return new CuratorZookeeperClient(url); } - - } 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 7ece96bc828..818b3f95550 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.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.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 @@ public void process(WatchedEvent watchedEvent) { countDownLatch.await(); } - @Test void testWithInvalidServer() { Assertions.assertThrows(IllegalStateException.class, () -> { @@ -246,29 +247,30 @@ public void nodeChanged() { 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); - } - - @Override - protected void update(String path, String data, int version) { - if (runnable.get() != null) { - runnable.get().run(); - } - super.update(path, data, version); - } - }; + 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); + } + }; curatorClient.delete(path); runnable.set(() -> { @@ -278,7 +280,8 @@ protected void update(String path, String data, int version) { 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 @@ protected void update(String path, String data, int version) { } }); 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 @@ protected void update(String path, String data, int version) { 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 @@ void testPersistentCas2() { 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); - } - - @Override - protected void update(String path, String data, int version) { - if (runnable.get() != null) { - runnable.get().run(); - } - super.update(path, data, version); - } - }; + 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); + } + }; curatorClient.delete(path); curatorClient.createOrUpdate(path, "version 0", false); @@ -377,23 +385,25 @@ void testEphemeralCas1() 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 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); - } - }; + 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); + } + }; curatorClient.delete(path); runnable.set(() -> { @@ -403,7 +413,8 @@ protected void update(String path, String data, int version) { 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 @@ protected void update(String path, String data, int version) { } }); 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 @@ protected void update(String path, String data, int version) { 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 @@ void testEphemeralCas2() { 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); - } - - @Override - protected void update(String path, String data, int version) { - if (runnable.get() != null) { - runnable.get().run(); - } - super.update(path, data, version); - } - }; + 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); + } + }; curatorClient.delete(path); curatorClient.createOrUpdate(path, "version 0", true); @@ -496,5 +512,4 @@ protected void update(String path, String data, int version) { 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 8831ab65279..328107ae13a 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 @@ public static void beforeAll() { @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 @@ void testZookeeperClient() { 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 506a4f41af8..37cc93c0f28 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.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.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 @@ void testZookeeperClient() { @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 @@ void testGetURLBackupAddress() { @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 @@ void testGetURLBackupAddressNoBack() { @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); - - 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"); + 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"); 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 @@ private void checkFetchAndUpdateCacheNotNull(URL url) { @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 f1c154729e1..63b2b3b3331 100644 --- a/dubbo-remoting/pom.xml +++ b/dubbo-remoting/pom.xml @@ -16,35 +16,35 @@ 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 - dubbo-remoting-zookeeper-curator5 - dubbo-remoting-netty4 - + 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 + dubbo-remoting-zookeeper-curator5 + dubbo-remoting-netty4 + + + 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 c2fa7517433..8bf711c08a8 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} - - - net.bytebuddy - byte-buddy - - - com.alibaba - hessian-lite - 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} + + + net.bytebuddy + byte-buddy + + + com.alibaba + hessian-lite + test + - + diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AdaptiveMetrics.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AdaptiveMetrics.java index e48c591b05a..dfd077f947a 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AdaptiveMetrics.java +++ b/dubbo-rpc/dubbo-rpc-api/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 double getLoad(String idKey, int weight, int timeout) { 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 double getLoad(String idKey, int weight, int timeout) { } 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 void setPickTime(String idKey, long time) { 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-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 a41bc386cd4..5e3906b732d 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 Object recreate() throws Throwable { } 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 void setAttribute(String key, Object value) { @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 4ff3368aa0d..26ecb91008c 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 void write(Object value) { 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 39e5cceb74a..4f9551ff6eb 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 void setValue(Object value) { } } 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 void setException(Throwable t) { } } 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 Result getAppResponse() { } } 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 Result get(long timeout, TimeUnit unit) throws InterruptedException, Exec 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 @@ private static Result createDefaultValue(Invocation invocation) { 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 49ebc93b0a2..8142066231d 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 5f325100947..5e3573ca605 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 1cdb86d3475..e660ae1634b 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 edfc05a49d4..d3935df028e 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 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 ExecutableListener(Executor executor, CancellationListener listener) { 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 fd3d58bc8e7..15d3022f1a9 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 68197469b48..8d16129d870 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 79fea6e8664..ae2c2026cb7 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 @@ * @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 d17a244b15b..c125fb3c9c3 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 static FutureContext getContext() { /** * 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 void setCompatibleFuture(CompletableFuture compatibleFuture) { 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 b40fa05e8a8..7f4e3f534a5 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 @@ default Object getObjectAttachmentWithoutConvert(String key) { 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 a97a0be61f4..fec363900df 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 6bf3a3a3cec..0151b89959a 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 b81de6ab4c8..94f0bc69370 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 83c5979cb82..ba8d17cdcc4 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 13bad8aa2e7..906e867ae09 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 0bbc24f34c7..910d030e404 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 08141111e5f..eb3e1700e58 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 @@ default RemotingServer getRemotingServer() { return null; } - default void setRemotingServers(RemotingServer server) { - } + default void setRemotingServers(RemotingServer server) {} String getAddress(); @@ -42,8 +41,7 @@ default URL getUrl() { 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 dcd51ac0923..c681c0ddea4 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 b0dd6f6286a..cd3b4a7bfd5 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.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 18e6ed3c15e..f771aea066e 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 @@ * @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 33a302e03ac..12d00716cf2 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.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 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 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 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 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 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 static void restoreCancellationContext(CancellationContext oldContext) { private boolean remove = true; - protected RpcContext() { - } + protected RpcContext() {} /** * get server side context. ( A <-- B , in B side) @@ -180,7 +182,7 @@ public static RpcContextAttachment getServerAttachment() { 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 Map getAttachments() { */ @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 850a8dd6413..e0c70c38acd 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 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 4d6876fd41e..5d076adedac 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 boolean isSerialization() { 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 e46a6b274fc..4c69c499338 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.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 RpcInvocation(Invocation invocation) { * @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 RpcInvocation(Invocation invocation, Invoker invoker) { /** * 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 RpcInvocation(ServiceModel serviceModel, Method method, String interfaceN */ @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 @@ private void initParameterDesc() { 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 @@ private void initParameterDesc() { } } - 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 ServiceModel getServiceModel() { @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 d2464315652..cfde6bc9cc1 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 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-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 c1bcdd79e6d..4a35342ea51 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 ObjectAttachmentMap(RpcServerContextAttachment adapter) { } 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 int size() { @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 c0f11894fd0..5a8a640bd66 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 @@ public class RpcServiceContext extends RpcContext { - protected RpcServiceContext() { - } + protected RpcServiceContext() {} // RPC service context updated before each service call. private URL consumerUrl; @@ -62,8 +61,10 @@ protected RpcServiceContext() { @Deprecated private List> invokers; + @Deprecated private Invoker invoker; + @Deprecated private Invocation invocation; @@ -381,8 +382,10 @@ public String getRemoteHostName() { */ @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 int getLocalPort() { */ @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 CompletableFuture asyncCall(Callable callable) { 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 RpcServiceContext copyOf(boolean needCopy) { 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 6ea826a1161..30de38825d6 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 @@ */ 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 static void removeStatus(URL url) { */ 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 long getAverageTps() { } 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 b00c6ef6167..7228ca52021 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 0e4910f947b..c1ad880a2a0 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 long timeRemaining(TimeUnit unit) { 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 9f842f4b92a..93a12d26ce4 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/filter/AccessLogFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java index 184aaf20018..14696307819 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/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 Result invoke(Invoker invoker, Invocation inv) throws RpcException { 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 Result invoke(Invoker invoker, Invocation inv) throws RpcException { } 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 Result invoke(Invoker invoker, Invocation inv) throws RpcException { } 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 @@ private void writeLogSetToFile(String accessLog, Queue logSet, bo 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-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java index 6123b5ba102..2912b5e6274 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java @@ -67,11 +67,14 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept 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-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AdaptiveLoadBalanceFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AdaptiveLoadBalanceFilter.java index b41e72e391a..b6cd7411b24 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AdaptiveLoadBalanceFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AdaptiveLoadBalanceFilter.java @@ -45,7 +45,10 @@ * @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 AdaptiveLoadBalanceFilter(ApplicationModel scopeModel) { 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 Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept 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 void onResponse(Result appResponse, Invoker invoker, Invocation invoca 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 void onResponse(Result appResponse, Invoker invoker, Invocation invoca 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-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 87031617d94..279dd0192f7 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 @@ -60,7 +60,8 @@ public void onResponse(Result appResponse, Invoker invoker, Invocation invoca 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()); @@ -69,8 +70,10 @@ public void onResponse(Result appResponse, Invoker invoker, Invocation invoca 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; @@ -86,7 +89,5 @@ public void onResponse(Result appResponse, Invoker invoker, Invocation invoca } @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/ContextFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java index 5320b1894ea..5a955a958d2 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/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.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 Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept 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 Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept 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 void onResponse(Result appResponse, Invoker invoker, Invocation invoca // 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-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 228cc44a82d..1cbabd45d01 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 Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept 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 @@ private String getMethodSignature(Invocation invocation) { 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 f3dbe01c6f1..760aab3c6ba 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 Result invoke(Invoker invoker, Invocation inv) throws RpcException { } 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 9265bad5958..0fc159967a8 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 static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FILTER_VALIDATION_EXCEPTION; - /** * ExceptionInvokerFilter *

    @@ -67,7 +66,8 @@ public void onResponse(Result appResponse, Invoker invoker, Invocation invoca } // 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 void onResponse(Result appResponse, Invoker invoker, Invocation invoca } // 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 void onResponse(Result appResponse, Invoker invoker, Invocation invoca } // 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 void onResponse(Result appResponse, Invoker invoker, Invocation invoca // 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 void setLogger(ErrorTypeAwareLogger logger) { this.logger = logger; } } - diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java index e77e512f3e2..28df4ed9cf1 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java @@ -32,7 +32,6 @@ 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 Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept 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 void onError(Throwable t, Invoker invoker, Invocation invocation) { } 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-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java index fa61d9b4f74..b4fbcce3bbd 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java @@ -86,9 +86,9 @@ public void setApplicationModel(ApplicationModel applicationModel) { @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 Result invoke(Invoker invoker, Invocation inv) throws RpcException { } 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 Result invoke(Invoker invoker, Invocation inv) throws RpcException { } 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 Result invoke(Invoker invoker, Invocation inv) throws RpcException { 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 Result invoke(Invoker invoker, Invocation inv) throws RpcException { 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 Result invoke(Invoker invoker, Invocation inv) throws RpcException { // 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 Result invoke(Invoker invoker, Invocation inv) throws RpcException { } 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 @@ private String getGenericValueFromRpcContext() { 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 Method findMethodByMethodSignature(Class clazz, String methodName, Str 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 Method findMethodByMethodSignature(Class clazz, String methodName, Str } } 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 Method findMethodByMethodSignature(Class clazz, String methodName, Str @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; @@ -316,28 +338,33 @@ public void onResponse(Result appResponse, Invoker invoker, Invocation inv) { 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.isGenericReturnRawResult(generic)) { return; @@ -348,7 +375,5 @@ public void onResponse(Result appResponse, Invoker invoker, Invocation inv) { } @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/GenericImplFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java index 65c8bd16e82..e4be336a690 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/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 Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept } 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 @@ else if (isMakingGenericCall(generic, invocation)) { } 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 void onResponse(Result appResponse, Invoker invoker, Invocation invoca 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 void onResponse(Result appResponse, Invoker invoker, Invocation invoca } 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 void onResponse(Result appResponse, Invoker invoker, Invocation invoca } 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 void onResponse(Result appResponse, Invoker invoker, Invocation invoca 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-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 36aa5c8ca02..5899f7c0d11 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 @@ @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 Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept 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 @@ private void afterInvoke(Invoker invoker, Invocation invocation) { } } } + private void addAdaptiveResponse(Result appResponse, Invocation invocation) { String adaptiveLoadAttachment = invocation.getAttachment(Constants.ADAPTIVE_LOADBALANCE_ATTACHMENT_KEY); if (StringUtils.isNotEmpty(adaptiveLoadAttachment)) { @@ -93,9 +96,13 @@ private void addAdaptiveResponse(Result appResponse, Invocation invocation) { 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 @@ private void dumpIfNeed(Invoker invoker, Invocation invocation, ProfilerEntry 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 3531dab50ea..859edff0f8c 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.Result; import org.apache.dubbo.rpc.RpcException; - /** * RpcExceptionFilter *

    @@ -53,8 +52,5 @@ public void onResponse(Result appResponse, Invoker invoker, Invocation invoca } @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 dac40680de7..28a061e5b1e 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 void onResponse(Result appResponse, Invoker invoker, Invocation invoca 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/filter/TokenFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TokenFilter.java index f00dae649d3..219080941fb 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TokenFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TokenFilter.java @@ -39,19 +39,19 @@ 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-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TokenHeaderFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TokenHeaderFilter.java index 583e91d4ccd..c8d8c6e1da9 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TokenHeaderFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TokenHeaderFilter.java @@ -37,9 +37,13 @@ public RpcInvocation invoke(Invoker invoker, RpcInvocation invocation) throws 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-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TpsLimitFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TpsLimitFilter.java index b3eaae5d57f..8ec1a8482d4 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TpsLimitFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/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-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiter.java index 9d638c02788..0410d70c505 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiter.java +++ b/dubbo-rpc/dubbo-rpc-api/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 boolean isAllowable(URL url, Invocation invocation) { 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 boolean isAllowable(URL url, Invocation invocation) { return true; } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/StatItem.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/StatItem.java index 144ce497c07..768a0bac49f 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/StatItem.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/StatItem.java @@ -57,12 +57,10 @@ public long getInterval() { return interval; } - public int getRate() { return rate; } - long getLastResetTime() { return lastResetTime.get(); } @@ -73,10 +71,6 @@ int getToken() { @Override public String toString() { - return "StatItem " + - "[name=" + name + ", " + - "rate = " + rate + ", " + - "interval = " + interval + ']'; + return "StatItem " + "[name=" + name + ", " + "rate = " + rate + ", " + "interval = " + interval + ']'; } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/TPSLimiter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/TPSLimiter.java index f104eb12c3a..5a4f706cf0c 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/TPSLimiter.java +++ b/dubbo-rpc/dubbo-rpc-api/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-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 4ec9a15f5ce..a18345cc30f 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 @@ @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 001bc9c5c5e..825cbb7c50e 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 @@ 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 f4dbd0b5577..c36e79f3010 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.Set; import java.util.concurrent.ConcurrentHashMap; - /** * The InjvmExporterListener class is an implementation of the ExporterListenerAdapter abstract class, *

    @@ -74,7 +73,6 @@ public void exported(Exporter exporter) throws RpcException { super.exported(exporter); } - /** * Overrides the unexported method to remove the given exporter from the exporters ConcurrentHashMap, *

    @@ -130,6 +128,4 @@ public synchronized void removeExporterChangeListener(ExporterChangeListener lis 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 ebe5a9ea4c3..d5c95788dd3 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 @@ 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 b5eb3c52cb4..d60171c7f2c 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 @@ */ 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 2dd6d9c7e89..7a69a0dcf5e 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 @@ */ 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 ListenerInvokerWrapper(Invoker invoker, List listener listenerEvent(listener -> listener.referred(invoker)); } - @Override public Class getInterface() { return invoker.getInterface(); @@ -101,7 +101,12 @@ private void listenerEvent(Consumer consumer) { 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 a9fd653bfab..1d11fbe53ed 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 Invoker getInvoker() { } @Override - final public void unexport() { + public final void unexport() { if (unexported) { return; } @@ -61,24 +61,18 @@ final public void unexport() { } @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 555ac3ac18a..556c0e9e5f7 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.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 AbstractInvoker(Class type, URL url, Map attachment) { 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 String toString() { 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 @@ private void addInvocationAttachments(RpcInvocation invocation) { } // client context attachment - Map clientContextAttachments = RpcContext.getClientAttachment().getObjectAttachments(); + Map clientContextAttachments = + RpcContext.getClientAttachment().getObjectAttachments(); if (CollectionUtils.isNotEmptyMap(clientContextAttachments)) { invocation.addObjectAttachmentsIfAbsent(clientContextAttachments); } @@ -287,21 +292,43 @@ private void waitForResultIfSync(AsyncRpcResult asyncResult, RpcInvocation invoc 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 @@ protected ExecutorService getCallbackExecutor(URL url, Invocation inv) { 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 25a3068693a..2fe17714f34 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 List getServers() { 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 Collection> getExporters() { 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 @@ protected void optimizeSerialization(URL url) throws RpcException { 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 @@ protected void optimizeSerialization(URL url) throws RpcException { } catch (InstantiationException | IllegalAccessException e) { throw new RpcException("Cannot instantiate the serialization optimizer class: " + className, e); - } } @@ -189,7 +188,7 @@ protected String getAddr(URL url) { 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 e1727c38caf..843754a1dd8 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 Exporter export(final Invoker invoker) throws RpcException { 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 @@ protected void destroyInternal(URL url) { } 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 Channel getChannel(InetSocketAddress remoteAddress) { } @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 InetSocketAddress getLocalAddress() { } @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 a2e0dae3b5d..fe4bf6b462f 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 Result invoke(Invocation invocation) throws RpcException { 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 7bc8d120177..55d2c09aa77 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 0071fa66ce1..421e1148e7b 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 Exporter export(Invoker invoker) throws RpcException { 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 Invoker refer(Class type, URL url) throws RpcException { 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 e02dc7920da..4f83bcf42e3 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 @@ 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 Exporter export(Invoker invoker) throws RpcException { 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 Invoker refer(Class type, URL url) throws RpcException { 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 dfaaffc827c..7edb260f8ae 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 int getDefaultPort() { @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 4558113b72d..a3a3291681c 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.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 boolean isAvailable() { @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 void destroy() { } 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 Result invoke(Invocation invocation) throws RpcException { 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 33332406da3..efdf85f7b03 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 FutureAdapter(CompletableFuture future) { // 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 V get(long timeout, TimeUnit unit) throws InterruptedException, Execution throw new RpcException(e); } } - } 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 e48d12ea78f..112306ad022 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 Invoker getInvoker(T proxy, Class type, URL url) throws RpcExce 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 T getProxy(Invoker invoker, Class[] interfaces) { 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 8219bb74db6..87215d2919b 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 @@ * 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 T getProxy(Invoker invoker, boolean generic) throws RpcException { } catch (Throwable e) { // ignore } - } } @@ -83,8 +81,9 @@ public T getProxy(Invoker invoker, boolean generic) throws RpcException { // 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 T getProxy(Invoker invoker, boolean generic) throws RpcException { } 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 static Class[] getInternalInterfaces() { } 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 871fe9672cf..58f573cd500 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 boolean isAvailable() { } @Override - public void destroy() { - } + public void destroy() {} @Override public Result invoke(Invocation invocation) throws RpcException { @@ -91,13 +90,15 @@ public Result invoke(Invocation invocation) throws RpcException { 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 Result invoke(Invocation invocation) throws RpcException { }); 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 Result invoke(Invocation invocation) throws RpcException { Profiler.setToBizProfiler(originEntry); } } - } private CompletableFuture wrapWithFuture(Object value, Invocation invocation) { @@ -148,12 +157,11 @@ private CompletableFuture wrapWithFuture(Object value, Invocation invoca 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 cc4c258f6aa..1e8cd988f44 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.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 static Object invoke(Invoker invoker, RpcInvocation rpcInvocation) thr 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 255a5ad0896..a95022524f2 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 Object invoke(Object proxy, Method method, Object[] args) throws Throwabl } 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 8f7df1f86a9..ed4a199f54d 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 @@ class SingleMethodInvoker implements 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 @@ class OverloadMethodInvoker implements 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 @@ Map getInvokers() { } @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/bytebuddy/ByteBuddyInterceptor.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyInterceptor.java index 6670af89b85..25d5311d2e6 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyInterceptor.java +++ b/dubbo-rpc/dubbo-rpc-api/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-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxy.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxy.java index ccc25b9df73..d414e542a19 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxy.java +++ b/dubbo-rpc/dubbo-rpc-api/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.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 @@ private Object newInstance() { 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-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyInvoker.java index 2f5761c39ec..9fd17783849 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/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-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 4d341b2ec9e..93695bde04f 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 @@ * 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 T getProxy(Invoker invoker, Class[] interfaces) { // 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 T getProxy(Invoker invoker, Class[] interfaces) { 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 @@ protected Object doInvoke(T proxy, String methodName, // 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 9cf31df9f2b..2e74a0de791 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 9721df43ec0..7a41c52bb7c 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 @@ */ 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 T getProxy(Invoker invoker, boolean generic) throws RpcException { 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 T getProxy(Invoker invoker, boolean generic) throws RpcException { } } } 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 Invoker getInvoker(T proxy, Class type, URL url) throws RpcExce 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 eca018dfa38..b67670552e5 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 16a69a6457b..771c1555039 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 f90b0b77428..c9342b4c7c4 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 994becda561..3f5350b0bd3 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 1a7b8d2b22a..465390d89f9 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 c8d0efacda1..f626031a834 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 a56e52f643f..0da4da185a3 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 @@ private static String stubClassName(String interfaceName) { } 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 81e069fa63e..9a1ddca338c 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/AccessLogData.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/AccessLogData.java index a3acfb2efd4..ac452956d74 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/AccessLogData.java +++ b/dubbo-rpc/dubbo-rpc-api/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 static AccessLogData newLogData() { return new AccessLogData(); } - /** * Add version information. * @@ -197,25 +195,26 @@ public String getServiceName() { 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 String getLogMessage() { } 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 @@ private Date getInvocationTime() { } private Date getOutTime() { - return (Date)get(OUT_TIME); + return (Date) get(OUT_TIME); } /** @@ -291,5 +289,4 @@ public void buildAccessLogData(Invoker invoker, Invocation inv) { setTypes(inv.getParameterTypes()); setArguments(inv.getArguments()); } - } 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 548e6807bcb..076aa95cc88 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 @@ private static Class loadClass() { } } - 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/MockInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java index eab455ce46d..9e798e51df8 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java @@ -45,10 +45,10 @@ 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 @@ public static Object parseMockValue(String mock) throws Exception { 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 @@ public Result invoke(Invocation invocation) throws RpcException { 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 @@ public Result invoke(Invocation invocation) throws RpcException { 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 @@ public static Throwable getThrowable(String throwstr) { 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 @@ public static Object getMockObject(ExtensionDirector extensionDirector, String m 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 @@ public static Object getMockObject(ExtensionDirector extensionDirector, String m } } - /** * Normalize mock string: * @@ -269,7 +276,7 @@ public boolean isAvailable() { @Override public void destroy() { - //do nothing + // do nothing } @Override diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockProtocol.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockProtocol.java index f2d46d80b48..f0ea53fd3c8 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockProtocol.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockProtocol.java @@ -25,7 +25,7 @@ /** * 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-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 6605d93d2d4..94d48c72fb6 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 static Class getReturnType(Invocation invocation) { 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 @@ private static boolean isAttachInvocationId(URL url, Invocation invocation) { 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 static String getMethodName(Invocation invocation) { 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 static Object[] getArguments(Invocation invocation) { 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 static boolean isGenericAsync(Invocation inv) { // 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 static boolean isOneway(URL url, Invocation inv) { 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 static long getTimeout(Invocation invocation, long defaultTimeout) { 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 static int calculateTimeout(URL url, Invocation invocation, String method 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 df26ab24023..2990c61ef1e 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 @@ void testAppResponseWithEmptyStackTraceException() { StackTraceElement[] stackTrace = appResponse.getException().getStackTrace(); Assertions.assertNotNull(stackTrace); - Assertions.assertEquals(0,stackTrace.length); + Assertions.assertEquals(0, stackTrace.length); } @Test @@ -71,7 +71,7 @@ void testSetExceptionWithEmptyStackTraceException() { 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 @@ void testObjectAttachment() { 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 f6fd20b09d6..02eb431ffd1 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 @@ void testAddListenerAfterCancel() throws Exception { }); 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 ae4c3a3ab39..5cae1c2071a 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 d30bc237338..8efd2205d4b 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 @@ /** * 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 df2d19b394a..a152ddda367 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 @@ void testFutureContext() throws Exception { 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 21ff35c2b41..b90e8bb2aa2 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.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 @@ void test() { @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 e6d26ff8fe4..b6ce8339e08 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 @@ 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.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 @@ void testGetContext() { 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 @@ void testGetContext() { RpcContext.removeServerContext(); Assertions.assertNotEquals(serverRpcContext, RpcContext.getServerContext()); - } @Test @@ -74,8 +73,8 @@ void testCheckSide() { 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 @@ void testAsync() { 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 @@ void testObjectAttachment() { rpcContext.setObjectAttachments(map); Assertions.assertEquals(map, rpcContext.getObjectAttachments()); } + @Test public void say() { final String key = "user-attachment"; @@ -215,15 +216,13 @@ public void say() { } @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 @@ public void testRpcServerContextAttachment() { 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 @@ public void testAsyncContext() { @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 @@ public void testObjectAttachmentMap() { 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 @@ public void testObjectAttachmentMap() { @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 461867efefa..0933bc42fb5 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 @@ void testInvokers() { 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 0ed74bf5316..efa938e803e 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.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 @@ void testBeginCountEndCount() { Assertions.assertTrue(flag); flag = RpcStatus.beginCount(url, methodName, max); Assertions.assertFalse(flag); - } @Test @@ -93,7 +92,6 @@ void testBeginCountEndCountInMultiThread() throws Exception { 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 5a37f30743b..3ef36b44935 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/AccessLogFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/AccessLogFilterTest.java index 570522af782..6b96546cb3c 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/AccessLogFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/AccessLogFilterTest.java @@ -27,6 +27,10 @@ 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.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 @@ void testCustom() { 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 @@ private void sleep() { e.printStackTrace(); } } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ActiveLimitFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ActiveLimitFilterTest.java index a2c4ddf5a7f..ca17f8fce08 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ActiveLimitFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ActiveLimitFilterTest.java @@ -27,12 +27,12 @@ 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 @@ void testInvokeTimeOut() { 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 @@ void testInvokeNotTimeOut() { 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 @@ void testInvokeRuntimeException() { 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 @@ void testInvokeRuntimeExceptionWithActiveCountMatch() { } 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-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ClassLoaderFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ClassLoaderFilterTest.java index a133ea327b2..041b6e58801 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ClassLoaderFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/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.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 @@ void testInvoke() throws Exception { 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-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 d07d58452da..d5931e7f3d4 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 @@ public void tearDown() { 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 @@ void testInvokerGeneric() { 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 @@ void testResultHasException() { 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 @@ void testInvokerJsonPojoSerialization() throws Exception { 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 @@ void testInvokerNonJsonEnumSerialization() throws Exception { 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/ContextFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ContextFilterTest.java index 6bab37aab6a..bdb39c64470 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ContextFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/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-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 8809dc8ba8c..750d54d7953 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 @@ void testDeprecatedFilter() { 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 3408b2ebc5a..bf89c7032d9 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 @@ void testNonEcho() { 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 b2cae229e9a..76c964d8cfb 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 @@ void testRpcException() { 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 @@ void testRpcException() { 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 @@ void testRpcException() { 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 @@ void testJavaException() { Result newResult = exceptionFilter.invoke(invoker, invocation); Assertions.assertEquals(appResponse.getException(), newResult.getException()); - } @SuppressWarnings("unchecked") @@ -97,7 +103,8 @@ void testJavaException() { 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 @@ void testRuntimeException() { Result newResult = exceptionFilter.invoke(invoker, invocation); Assertions.assertEquals(appResponse.getException(), newResult.getException()); - } @SuppressWarnings("unchecked") @@ -117,13 +123,13 @@ void testRuntimeException() { 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 @@ void testConvertToRunTimeException() throws Exception { Assertions.assertEquals(appResponse.getException().getClass(), RuntimeException.class); } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilterTest.java index 2f0f3b5fafd..97c72298976 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilterTest.java @@ -26,13 +26,13 @@ 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 @@ void testNoExecuteLimitInvoke() { 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 @@ void testExecuteLimitInvoke() { @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 @@ void testExecuteLimitInvokeWithException() { 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-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.java index 17f26e10058..5ef6f985bbc 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.java @@ -28,14 +28,14 @@ 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 @@ void testInvokeWithDefault() throws Exception { 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 @@ void testInvokeWithDefault() throws Exception { 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 @@ void testInvokeWithJavaException() throws Exception { 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 @@ void testInvokeWithJavaException() throws Exception { 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 @@ void testInvokeWithMethodArgumentSizeIsNot3() { 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 @@ void testInvokeWithMethodArgumentSizeIsNot3() { Assertions.assertEquals(Person.class, result.getValue().getClass()); Assertions.assertEquals(10, ((Person) (result.getValue())).getAge()); } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java index ecf08b6e361..222a2585645 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java @@ -29,15 +29,15 @@ 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 @@ 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 @@ void testInvoke() throws Exception { 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 @@ void testInvoke() throws Exception { @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 @@ void testInvokeWithException1() throws Exception { 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 @@ void testInvokeWithException2() throws Exception { Result result = asyncResult.get(); genericImplFilter.onResponse(result, invoker, invocation); Assertions.assertEquals(GenericException.class, result.getException().getClass()); - } @Test @@ -129,17 +142,20 @@ void testInvokeWithException2() throws Exception { 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-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 3613f540074..878d2b78c4c 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 @@ void testInvokeWithoutTimeout() { 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 @@ void testInvokeWithTimeout() { 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/filter/TokenFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TokenFilterTest.java index e9007ea821f..a53f4ef01ea 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TokenFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TokenFilterTest.java @@ -23,13 +23,13 @@ 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 @@ void testInvokeWithoutToken() throws Exception { }); } } - diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiterTest.java index bcfdf265de3..188631f8dc4 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiterTest.java @@ -20,13 +20,13 @@ 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 @@ void testMultiThread() throws InterruptedException { 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 @@ static class Task implements Runnable { 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-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/StatItemTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/StatItemTest.java index c820c3a2ae2..79a65bf6616 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/StatItemTest.java +++ b/dubbo-rpc/dubbo-rpc-api/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 @@ void testConcurrency() throws Exception { 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-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/TpsLimitFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/TpsLimitFilterTest.java index a91aa25eaef..5b7a59c606a 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/TpsLimitFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/TpsLimitFilterTest.java @@ -24,6 +24,7 @@ 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 @@ void testFail() throws Exception { assertTrue(re.hasException()); throw re.getException(); } - } }); - } } 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 420bbf7a54f..c1c78ca04e0 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 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 void referred(Invoker invoker) throws RpcException { } @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 d902559af92..56491e09d42 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 @@ protected Result doInvoke(Invocation invocation) throws Throwable { 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 @@ protected Result doInvoke(Invocation invocation) throws Throwable { 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/proxy/AbstractProxyTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/AbstractProxyTest.java index 52091590a4c..09158b38dfc 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.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 @@ void testGetProxy() { 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")); - - Destroyable destroyable = (Destroyable)proxy; + 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.$destroy(); Assertions.assertTrue(invoker.isDestroyed()); - } @Test @@ -70,9 +74,14 @@ void testGetInvoker() { 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 28c100ae7ab..34347e01538 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 @@ /** * 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 c61176b2d75..95536a95a9e 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 @@ /** * DemoServiceImpl */ - public class DemoServiceImpl implements DemoService { public DemoServiceImpl() { super(); @@ -44,25 +43,23 @@ public String getThreadName() { } 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 e4b1266de7d..6b2b8b33e2b 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 @@ 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 @@ void testInvokeToString() throws Throwable { 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 e2be1938d22..4969cf8efc5 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 @@ void testNewInstance() throws Throwable { 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 @@ void testNewInstance() throws Throwable { 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 54b3420ba24..87c0ab083f2 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 @@ 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 bf59a4baa57..96f4bd18961 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/bytebuddy/ByteBuddyInterceptorTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyInterceptorTest.java index 1ac609d3c9e..3ea668a5324 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyInterceptorTest.java +++ b/dubbo-rpc/dubbo-rpc-api/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 @@ void testIntercept() throws Throwable { 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-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyFactoryTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyFactoryTest.java index 312c09c9c9a..482abd22986 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyFactoryTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyFactoryTest.java @@ -23,5 +23,4 @@ class ByteBuddyProxyFactoryTest extends AbstractProxyTest { static { factory = new ByteBuddyProxyFactory(); } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyInvokerTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyInvokerTest.java index 2a11557295e..6dd9c004a38 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyInvokerTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyInvokerTest.java @@ -18,6 +18,7 @@ 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-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyTest.java index 1e2295a0b8e..9cf18e41d6b 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyTest.java @@ -18,11 +18,12 @@ 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-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 b2b0f8f203a..0c81e72db5c 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 57b401e114f..a11f43558ff 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 57b50e95e07..7af61e41fea 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 @@ void test() { 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 7f2138edb83..4f2a09032c1 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 1cfe2784b31..14701b0a79f 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 c27a495c7c4..c9f758b5ef0 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 @@ void invoke() { 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 0a115eb445e..c98428aaf70 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.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 @@ void getInterface() { 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 899d939348c..de8abf39e8d 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 @@ public ServiceDescriptor getServiceDescriptor() { @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 76347e9f6be..c6718e9ab71 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 571b8a55c32..6fe533b28d7 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/DemoServiceAMock.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/DemoServiceAMock.java index 23c623ac1f5..928bb463822 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/DemoServiceAMock.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/DemoServiceAMock.java @@ -19,8 +19,9 @@ /** * 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-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 d1ed931da0c..9ed2780d397 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 @@ /** * DemoServiceImpl */ - public class DemoServiceImpl implements DemoService { public DemoServiceImpl() { super(); @@ -49,25 +48,23 @@ public String getThreadName() { } 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 CompletableFuture> testReturnType5(String str) { } @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 2b13b36cb2e..c03abd55f77 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 89086b332d8..bd43df71c86 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 ae8a69cc5d0..ffcabd8d479 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 String getServiceName() { } 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 Invoker getInvoker() { } @Override - public void setServiceModel(ServiceModel serviceModel) { - - } + public void setServiceModel(ServiceModel serviceModel) {} @Override public ServiceModel getServiceModel() { @@ -164,5 +162,4 @@ public Object getObjectAttachment(String key, Object defaultValue) { } return result; } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvokerTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvokerTest.java index 019b39c3f43..97698186219 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvokerTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvokerTest.java @@ -21,14 +21,14 @@ 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 @@ void testParseMockValue() throws Exception { 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 @@ void testInvoke() { 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 @@ void testGetDefaultObject() { 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 @@ void testGetDefaultObject() { 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 @@ void testInvokeThrowsRpcException2() { 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 @@ void testInvokeThrowsRpcException3() { 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.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.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)); } @Test @@ -156,11 +157,8 @@ void testNormalizeMock() { 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-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 f2dbe070814..670a3f78855 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 boolean isDestroyed() { 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 9f74ef1cf15..57f55b14d31 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 @@ 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 1c2f5df7be6..c3b1fb143fa 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.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 @@ void testAttachInvocationIdIfAsync_forceAttache() { 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 @@ void testGetReturnTypesUseCache() throws Exception { 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 @@ void testGetReturnTypesUseCache() throws Exception { 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 @@ void testGetReturnTypesUseCache() throws Exception { 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 @@ void testGetReturnTypesUseCache() throws Exception { 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 @@ void testGetReturnTypesWithoutCache() throws Exception { 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 @@ void testGetReturnTypesWithoutCache() throws Exception { 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 @@ void testGetReturnTypesWithoutCache() throws Exception { 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 @@ void testGetParameterTypes() { } @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 @@ public void testGetMethodName(String methodName) { 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 @@ void testIsAsync() { 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 @@ void testIsAsync() { @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 @@ void testIsEcho() { 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 63d497f9aa1..46006ac1b7e 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 22ded467770..b5368d2b38b 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 0570e6209ca..d9c14fd0845 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.apache.maven.plugins - maven-surefire-plugin - - alphabetical - - - - + + javax.validation + validation-api + test + + + org.hibernate + hibernate-validator + test + + + org.glassfish + javax.el + 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 405edadaa02..1457243047a 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 7c15e8a26e6..6750751e6a3 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 @@ * 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 CallbackServiceCodec(FrameworkModel frameworkModel) { 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 @@ private static byte isCallBack(URL url, String protocolServiceKey, String method * @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 @@ private String exportOrUnexportCallbackService(Channel channel, RpcInvocation in } 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 @@ private String exportOrUnexportCallbackService(Channel channel, RpcInvocation in 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 @@ private String exportOrUnexportCallbackService(Channel channel, RpcInvocation in * @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 @@ private Object referOrDestroyCallbackService(Channel channel, URL url, Class 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 @@ private Object referOrDestroyCallbackService(Channel channel, URL url, Class } 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 @@ private static String getClientSideCallbackServiceCacheKey(int instid) { } 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 @@ private static String getServerSideCountKey(Channel channel, String interfaceCla 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 @@ private static boolean isInstancesOverLimit(Channel channel, URL url, String int 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 Object encodeInvocationArgument(Channel channel, RpcInvocation inv, int p 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 Object decodeInvocationArgument(Channel channel, RpcInvocation inv, Class 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 71645f8dc67..7fda985f274 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 @@ protected Result doInvoke(Invocation invocation) throws Throwable { 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 @@ protected Result doInvoke(Invocation invocation) throws Throwable { @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 @@ public void removeAttribute(String key) { } @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 fa0eca02816..d54b646add3 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 49cdac2313f..7c197597ee6 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 @@ 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 DecodeableRpcInvocation(FrameworkModel frameworkModel, Channel channel, R 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 Object decode(Channel channel, InputStream input) throws IOException { 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 Object decode(Channel channel, InputStream input) throws IOException { 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 Object decode(Channel channel, InputStream input) throws IOException { 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 Object decode(Channel channel, InputStream input) throws IOException { 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 @@ protected void decodeArgument(Channel channel, Class[] pts, Object[] args) th } 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 @@ protected Class[] drawPts(String path, String version, String desc, Class[ // 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 @@ protected Object[] drawArgs(ObjectInput in, Class[] pts) throws IOException, 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 ea6f94ed890..0469f9567ad 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 Object decode(Channel channel, InputStream input) throws IOException { // 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 void decode() throws Exception { 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 c775ae50a04..bb446fcb15a 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 DubboCodec(FrameworkModel frameworkModel) { 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 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro // 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 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro 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 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro 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 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro 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 @@ private boolean isDecodeDataInIoThread(Channel channel) { 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 @@ private byte[] readMessageData(InputStream is) throws IOException { is.read(result); return result; } - return new byte[]{}; + return new byte[] {}; } @Override @@ -266,7 +275,8 @@ protected void encodeResponseData(Channel channel, ObjectOutput out, Object data } @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 @@ protected void encodeRequestData(Channel channel, ObjectOutput out, Object data, } @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 @@ protected Serialization getSerialization(Channel channel, Response res) { } 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 97dccf5232a..ed97a0d0349 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 static Serialization getRequestSerialization(URL url, Invocation invocati 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 static Serialization getResponseSerialization(URL url, AppResponse appRes 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 b37ab75df05..8fa74a209f9 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 @@ private void logMessageLength(Object result, int bytes) { } } } - } 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 28099ea355e..266cf3ef4e5 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 DubboExporter(Invoker invoker, String key, Map> ex 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 f1a324e01af..707f71e1fe2 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.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 @@ private void sendEvent(String event) { 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 25657a26cb9..2b2463defed 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 @@ protected Result doInvoke(final Invocation invocation) throws Throwable { 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 @@ protected Result doInvoke(final Invocation invocation) throws Throwable { 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 @@ protected Result doInvoke(final Invocation invocation) throws Throwable { 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 boolean isAvailable() { } 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 231aa546ca2..fd8aef43f7f 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.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 958db3aad8d..a8bd3c0c02e 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_DISCONNECT_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.SHARE_CONNECTIONS_KEY; - /** * dubbo protocol support. */ @@ -118,16 +117,23 @@ public DubboProtocol(FrameworkModel frameworkModel) { 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 CompletableFuture reply(ExchangeChannel channel, Object message) } } 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 @@ private void invoke(Channel channel, String methodKey) { } 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 @@ private void tryToGetStubService(Channel channel, Invocation invocation) throws 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 @@ private Invocation createInvocation(Channel channel, URL url, String methodKey) 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 @@ private Invocation createInvocation(Channel channel, URL url, String methodKey) */ @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 static DubboProtocol getDubboProtocol(ScopeModel scopeModel) { 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 @@ Invoker getInvoker(Channel channel, Invocation inv) throws RemotingException 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 @@ Invoker getInvoker(Channel channel, Invocation inv) throws RemotingException 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 Exporter export(Invoker invoker) throws RpcException { 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 @@ private void checkDestroyed() { 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 @@ private ProtocolServer createServer(URL url) { } 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 @@ private ProtocolServer createServer(URL url) { return protocolServer; } - @Override public Invoker refer(Class type, URL url) throws RpcException { checkDestroyed(); @@ -424,16 +458,16 @@ private ClientsProvider getClients(URL url) { * 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 @@ private SharedClientsProvider getSharedClient(URL url, int connectNum) { 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 @@ private ExchangeClient initClient(URL url) { 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 @@ private ExchangeClient initClient(URL url) { // 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 void destroy() { 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 b5704213788..c00d271b15f 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 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 7454df2b8ff..e4cb6f639ef 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 @@ @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 @@ public CompletableFuture request(Object request, ExecutorService executo } @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 @@ public CompletableFuture request(Object request, int timeout, ExecutorSe 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 @@ private void checkClient() { } 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 22cc722cf08..f5acca0f21f 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 @@ @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 @@ public CompletableFuture request(Object request, ExecutorService executo } @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 @@ public void startClose() { 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 @@ public void setShutdownWaitTime(int shutdownWaitTime) { 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 83ca0cfce2f..9f97a919ad1 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 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 @@ private boolean checkClientCanUse(List referenceCo // 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 @@ private void batchClientRefIncr(List referenceCoun return; } referenceCountExchangeClients.stream() - .filter(Objects::nonNull) - .forEach(ReferenceCountExchangeClient::incrementAndGetCount); + .filter(Objects::nonNull) + .forEach(ReferenceCountExchangeClient::incrementAndGetCount); } /** @@ -129,5 +132,4 @@ private void closeReferenceCountExchangeClient(ReferenceCountExchangeClient clie 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/filter/FutureFilter.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java index ce6d89555d0..9586afe0d4d 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java @@ -78,7 +78,9 @@ private void fireInvokeCallback(final Invoker invoker, final Invocation invoc 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); @@ -103,13 +105,15 @@ private void fireReturnCallback(final Invoker invoker, final Invocation invoc 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); @@ -129,7 +133,7 @@ private void fireReturnCallback(final Invoker invoker, final Invocation invoc System.arraycopy(args, 0, params, 1, args.length); } } else { - params = new Object[]{result}; + params = new Object[] {result}; } try { onReturnMethod.invoke(onReturnInst, params); @@ -149,12 +153,14 @@ private void fireThrowCallback(final Invoker invoker, final Invocation invoca 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); @@ -176,14 +182,26 @@ private void fireThrowCallback(final Invoker invoker, final Invocation invoca 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); } } @@ -202,5 +220,4 @@ private AsyncMethodInfo getAsyncMethodInfo(Invoker invoker, Invocation invoca return ((ConsumerModel) serviceModel).getAsyncInfo(methodName); } - } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java index f26692e7222..b856e8d57b6 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java @@ -103,13 +103,16 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept } 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 Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept } return result; } - } 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 88d146c9333..a295b327010 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 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 ba833940021..96200b5f11a 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 DubboWireProtocol() { 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 451b682362e..e096d7b1dc1 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 Status check() { } 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 cccf18f7332..878e3ef9877 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 ThreadPoolStatusChecker(ApplicationModel applicationModel) { @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 Status check() { 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 7d5123f4c73..c26d136ae13 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.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 @@ public void exportService() { // 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 @@ public void exportService() { } 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 @@ void TestCallbackNormalWithBindPort() throws Exception { 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 @@ void TestCallbackNormal() throws Exception { 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 @@ void TestCallbackConsumerLimit() { // 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 @@ void TestCallbackProviderLimit() { 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 HelloServiceImpl implements IHelloService { public String sayHello() { return "hello"; } - } class DemoServiceImpl implements IDemoService { @@ -360,7 +390,8 @@ public void run() { 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 f4a39cf5d03..3433c42134f 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.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 @@ void test() throws Exception { 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 89fa8c44dbc..3c289238efd 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.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 @@ public void tearDown() { @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 @@ void test() throws Exception { 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 @@ void test() throws Exception { 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 @@ private ChannelBuffer writeBuffer(URL url, Response response, Byte proto, boolea 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 59e1f4c5a2c..0d4933339cd 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.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 @@ void test() throws Exception { 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 @@ void test() throws Exception { 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 9766e3bba74..def9df1b6ee 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.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.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 @@ */ 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 @@ void test_Normal_ChannelReadOnly() throws Exception { @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 @@ void test_normal_channel_close_wait_gracefully() { @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 @@ void test_NoInvokers() throws Exception { 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 @@ void test_Lazy_ChannelReadOnly() throws Exception { 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 @@ void test_Lazy_ChannelReadOnly() throws Exception { @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 6a0fed5d124..6cb0e99dcac 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 @@ 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 @@ void testSticky1() { @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 @@ void testSticky2() { 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 @@ void testSticky3() { @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 0da2ea933e2..66ac18bf662 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.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.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 @@ void testDubboProtocol() throws Exception { 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 @@ void testDubboProtocolMultiService() throws Exception { 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 @@ void testPerm() { 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,14 +260,22 @@ public void testNonSerializedParameter() { 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")); } } @@ -235,13 +283,15 @@ public void testReturnNonSerialized() { 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 +309,21 @@ void testRemoteApplicationName() throws Exception { 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/FutureFilterTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/FutureFilterTest.java index fc970cdc7d3..3485957971e 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/FutureFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/FutureFilterTest.java @@ -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-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 89f90fc4720..00000000000 --- 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 a28f9c1d016..bcfdaafaad6 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.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 1c18774e561..eeb7d426876 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.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.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 @@ public static Exporter export(T instance, Class type, String url) { } 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 @@ void test_counter_error() { 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 @@ private ExchangeClient getInvokerClient(Invoker invoker) { } 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 13beb738bda..0e3ac37f844 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.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 @@ public void after() { 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 @@ void testRpcFilter() throws Exception { 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 9f05c81fe28..ee6a9ab7167 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.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.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 @@ void testDubboDecode() throws InterruptedException, IOException { 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 @@ void testTelnetDecode() throws InterruptedException { 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 @@ void testTelnetDubboDecoded() throws InterruptedException, IOException { 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(); - } - - return getDefaultFuture(); - } - })))); + 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(); + } + })))); 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 @@ void testTelnetTelnetDecoded() throws InterruptedException { 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 @@ void testDubboDubboDecoded() throws InterruptedException, IOException { 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 @@ void testDubboTelnetDecoded() throws InterruptedException, IOException { 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 @@ private ByteBuf createDubboByteBuf() throws IOException { 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 @@ private ByteBuf createDubboByteBuf() throws IOException { // 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 adc590d7516..df11f5c342a 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 @@ 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 46670000696..46ae895c1c2 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 @@ public class MockChannel implements Channel { private Consumer consumer; - public MockChannel() { - - } + public MockChannel() {} public MockChannel(Consumer consumer) { this.consumer = consumer; @@ -58,14 +56,10 @@ public Object getAttribute(String key) { } @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 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() { 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 492929706dd..f15a32a77c4 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 void sent(Channel channel, Object message) throws RemotingException { @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 f4f432a733e..8c58663646e 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 @@ 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/filter/MockChannel.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/filter/MockChannel.java index f8df7e4749d..4f21521f510 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/filter/MockChannel.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/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 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/filter/TraceFilterTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilterTest.java index d58bf5ebaf0..11ead27a510 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilterTest.java @@ -24,17 +24,17 @@ import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoService; -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 @@ void testAddAndRemoveTracer() throws Exception { 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 @@ void testInvoke() throws Exception { 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-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 4876dd7b853..f2e4ab7acd5 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.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 352a8c2738b..2781a361d67 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.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 @@ void testConnectBlocked() throws RemotingException { 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 @@ void testConnectBlocked() throws RemotingException { 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 @@ void testDisconnectExecuteError() throws RemotingException { }); } - //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 @@ void testReceivedEventInvokeDirect() throws RemotingException { 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 baa35eac690..c5bec9d7af9 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 MockedChannel() { super(); } - @Override public URL getUrl() { return url; @@ -55,8 +54,7 @@ public InetSocketAddress getLocalAddress() { } @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 f2dc66abbab..0f95be38af3 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 void sent(Channel channel, Object message) throws RemotingException { @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 e0e567d9b81..a95d9ba2290 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.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 @@ public void setUp() throws Exception { } @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 @@ void testGetExecutor() { 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 6061be5c79d..40c4921530a 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.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 @@ void test() { 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 6b26f368d3c..eb3321dd630 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.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 @@ void test() { 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 952c8b27c50..96bac4f56af 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 @@ 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 5a9e7451b40..e44a171f417 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 @@ /** * 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 ed1d5842804..55a7dc6ee51 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 @@ 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 f31081dca06..ad1255ecac4 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 String getThreadName() { } 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 Set keys(Map map) { 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 c2b08dc280b..13bf7e5e6fc 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.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 void testNormal() { 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 void testNormal() { @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 void testExportService() throws InterruptedException { 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 void testNormalEnum() { @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 void testEnumCompat() { @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 void testGenricEnumCompat() { 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 void testGenricCustomArg() { 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,20 @@ public void testGenricCustomArg() { @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); } @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 +194,8 @@ public void testGenericEnum() throws InterruptedException { 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 0d584d0213b..158acb353e1 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 1ec80e5c0cd..8c7ab677b9e 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 @@ /** * 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 e614b2652ea..625dc6b1989 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 @@ */ 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 static Exporter export(T instance, Class type, String url) { 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 0c0cd09f6eb..88f6520830d 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 @@ 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 984c6c64365..51715e99cc2 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 a74078d832a..66d86080a38 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 c02bdd34f98..0b6ede8afe9 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 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 T copy(URL url, Object src, Class targetClass) { 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 bc38844265f..f0fdbb1df18 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 0ebdca71e86..8712d202300 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 Result doInvoke(Invocation invocation) throws Throwable { } 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 Result doInvoke(Invocation invocation) throws Throwable { 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 Result doInvoke(Invocation invocation) throws Throwable { future.complete(rpcResult); } return new AsyncRpcResult(future, invocation); - } } @@ -225,15 +233,23 @@ private Invocation recreateInvocation(Invocation invocation, Invoker invoker, 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 @@ private Invocation recreateInvocation(Invocation invocation, Invoker invoker, 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 9f361054f3c..c4955e7ce7f 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 Invoker protocolBindingRefer(Class serviceType, URL url) throws 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 6a9678c25cf..cd89dd14ba5 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 b315aa2e4ee..b546238ef38 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 9dd67ca5a57..0d07661d134 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 @@ 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 c4ed2aa702b..f4d2b96a452 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 @@ 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 3925531c884..d9f580037e9 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 @@ /** * 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 9a09ed96171..0009ff5b002 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 @@ /** * 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 b4d2314a6d7..7d364b2bcc9 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 @@ /** * DemoServiceImpl */ - public class DemoServiceImpl implements DemoService { public DemoServiceImpl() { super(); @@ -44,25 +43,23 @@ public String getThreadName() { } 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 a12c1893a56..45534ff5ba6 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.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.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 @@ void testDifferentClassLoaderRequest() throws Exception { 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 @@ void testDifferentClassLoaderRequest() throws Exception { 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 @@ void testDifferentClassLoaderRequest() throws Exception { 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 @@ private Class compileCustomRequest(ClassLoader classLoader) throws NotFoundEx 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 @@ private Class compileCustomResult(ClassLoader classLoader) throws NotFoundExc 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 @@ public Class loadClass(String name, boolean resolve) throws ClassNotFoundExce 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 @@ public Class loadClass(String name, boolean resolve) throws ClassNotFoundExce } } - public byte[] loadClassData(String className) throws IOException { className = className.replaceAll("\\.", "/"); String path = basePath + File.separator + className + ".class"; @@ -250,7 +272,6 @@ public Class loadClass(String name, boolean resolve) throws ClassNotFoundExce } } - 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 80c7fba2736..7ba33480309 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.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 @@ void testDeepCopy() { 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 @@ public Data call(Data obj) { } } - 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 3ef342e8ea2..983784da0bb 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.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 @@ /** * 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 @@ public void after() throws Exception { @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 @@ void testIsInjvmRefer() { 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 @@ void testLocalProtocolAsync() throws ExecutionException, InterruptedException { 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 @@ void testApplication() { 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 @@ void testRemoteAddress() { 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 a2d578fac1b..0a683d09682 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 @@ public String echo(String e) { 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 @@ void test_destroyWontCloseAllProtocol() throws Exception { 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 05f251ede33..fce2ec79cb2 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 7fc848b823c..09017694484 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 JAX-RS 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-cluster - ${project.parent.version} - - - - org.jboss.resteasy - resteasy-jaxrs - provided - - - - org.jboss.resteasy - resteasy-client - - - - javax.validation - validation-api - - - - - - org.jboss.resteasy - resteasy-netty4 - provided - - - - org.jboss.resteasy - resteasy-jdk-http - provided - - - - org.jboss.resteasy - resteasy-jackson-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 - - - - - - org.apache.dubbo - dubbo-serialization-jdk - ${project.parent.version} - test - - - - - org.apache.dubbo - dubbo-metadata-api - ${project.parent.version} - - - - javax.servlet - javax.servlet-api - provided - - - - io.netty - netty-codec-http - provided - - - - io.netty - netty-transport - compile - - - - - org.springframework - spring-web - test - - - - org.springframework - spring-context - test - - + 4.0.0 + + org.apache.dubbo + dubbo-rpc + ${revision} + ../pom.xml + + dubbo-rpc-rest + jar + ${project.artifactId} + The JAX-RS 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-cluster + ${project.parent.version} + + + + org.jboss.resteasy + resteasy-jaxrs + provided + + + + org.jboss.resteasy + resteasy-client + + + + javax.validation + validation-api + + + + + + org.jboss.resteasy + resteasy-netty4 + provided + + + + org.jboss.resteasy + resteasy-jdk-http + provided + + + + org.jboss.resteasy + resteasy-jackson-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 + + + + + + org.apache.dubbo + dubbo-serialization-jdk + ${project.parent.version} + test + + + + org.apache.dubbo + dubbo-metadata-api + ${project.parent.version} + + + + javax.servlet + javax.servlet-api + provided + + + + io.netty + netty-codec-http + provided + + + + io.netty + netty-transport + compile + + + + + org.springframework + spring-web + test + + + + org.springframework + spring-context + 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 c7d49dd3166..5aa43155c46 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/NettyHttpRestServer.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/NettyHttpRestServer.java index 092633651a2..f2bcfa65ae9 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/NettyHttpRestServer.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/NettyHttpRestServer.java @@ -16,12 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest; -import io.netty.buffer.PooledByteBufAllocator; -import io.netty.channel.ChannelHandler; -import io.netty.channel.ChannelOption; -import io.netty.handler.codec.http.HttpObjectAggregator; -import io.netty.handler.codec.http.HttpRequestDecoder; -import io.netty.handler.codec.http.HttpResponseEncoder; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.metadata.rest.ServiceRestMetadata; @@ -40,6 +34,13 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import io.netty.buffer.PooledByteBufAllocator; +import io.netty.channel.ChannelHandler; +import io.netty.channel.ChannelOption; +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.BACKLOG_KEY; import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY; import static org.apache.dubbo.remoting.Constants.BIND_IP_KEY; @@ -67,7 +68,6 @@ protected NettyServer getNettyServer() { private final Map attributes = new ConcurrentHashMap<>(); - @Override public String getAddress() { return address; @@ -82,7 +82,6 @@ public void setAddress(String address) { @Override public void close() { server.stop(); - } @Override @@ -119,15 +118,18 @@ private UnSharedHandlerCreator getUnSharedHttpChannelHandlers() { @Override public List getUnSharedHandlers(URL url) { return Arrays.asList( - // add SslServerTlsHandler - new SslServerTlsHandler(url), - 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)) - ; + // add SslServerTlsHandler + new SslServerTlsHandler(url), + 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)); } }; } @@ -140,7 +142,8 @@ public List getUnSharedHandlers(URL url) { */ protected Map getChildChannelOptionMap(URL url) { Map channelOption = new HashMap<>(); - channelOption.put(ChannelOption.SO_KEEPALIVE, url.getParameter(Constants.KEEP_ALIVE_KEY, Constants.DEFAULT_KEEP_ALIVE)); + channelOption.put( + ChannelOption.SO_KEEPALIVE, url.getParameter(Constants.KEEP_ALIVE_KEY, Constants.DEFAULT_KEEP_ALIVE)); return channelOption; } @@ -155,7 +158,9 @@ protected Map getChannelOptionMap(URL url) { options.put(ChannelOption.SO_REUSEADDR, Boolean.TRUE); options.put(ChannelOption.TCP_NODELAY, Boolean.TRUE); - options.put(ChannelOption.SO_BACKLOG, url.getPositiveParameter(BACKLOG_KEY, org.apache.dubbo.remoting.Constants.DEFAULT_BACKLOG)); + options.put( + ChannelOption.SO_BACKLOG, + url.getPositiveParameter(BACKLOG_KEY, org.apache.dubbo.remoting.Constants.DEFAULT_BACKLOG)); options.put(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); return options; } @@ -185,6 +190,4 @@ public void undeploy(ServiceRestMetadata serviceRestMetadata) { private void registerExtension(URL url) { serviceDeployer.registerExtension(url); } - - } 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 c9fea955ec5..bf4bcb225ba 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 @@ * 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 void addPathAndInvoker(Map metadataMap, 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 InvokerAndRestMethodMetadataPair getRestMethodMetadata(PathMatcher pathMa } return null; - } /** @@ -90,32 +97,39 @@ public InvokerAndRestMethodMetadataPair getRestMethodMetadata(PathMatcher pathMa */ 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 void addPathMatcherToPathMap(PathMatcher pathMatcher, 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 @@ private void addPathMatcherToHttpMethodsMap(PathMatcher pathMatcher) { 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 boolean isHttpMethodAllowed(PathMatcher pathMatcher) { return false; } - Set httpMethods = pathMatcherToHttpMethodMap.get(newPathMatcher); return httpMethods.contains(newPathMatcher.getHttpMethod()); - } public String pathHttpMethods(PathMatcher pathMatcher) { @@ -167,11 +177,8 @@ public String pathHttpMethods(PathMatcher pathMatcher) { 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 ada7d5c1c30..b7dbaa0263c 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 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 T getClient() { 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 f229773b538..6447bff8956 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 @@ 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 RestConstraintViolation(String path, String message, String value) { 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 96743943590..7eab6db4d6b 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 fe3a8e9f090..5afb5fecd17 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 RestInvoker(Class type, URL url, 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 @@ protected Result doInvoke(Invocation invocation) { } // 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 @@ protected Result doInvoke(Invocation invocation) { 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 @@ protected Result doInvoke(Invocation invocation) { * @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 64d0e666111..2311928019d 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 @@ -31,7 +31,6 @@ import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionPreBuildIntercept; import org.apache.dubbo.rpc.protocol.rest.annotation.metadata.MetadataResolver; - import java.util.LinkedHashSet; import java.util.Map; import java.util.Objects; @@ -52,24 +51,26 @@ public class RestProtocol extends AbstractProtocol { private final RestServerFactory serverFactory = new RestServerFactory(); - 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 { @@ -83,24 +84,19 @@ public Exporter export(final Invoker invoker) throws RpcException { } } - // resolve metadata - ServiceRestMetadata serviceRestMetadata = - MetadataResolver.resolveProviderServiceMetadata(url.getServiceModel().getProxyObject().getClass(), - url, getContextPath(url)); - + ServiceRestMetadata serviceRestMetadata = MetadataResolver.resolveProviderServiceMetadata( + url.getServiceModel().getProxyObject().getClass(), url, getContextPath(url)); // TODO add Extension filter // create rest server RestProtocolServer server = (RestProtocolServer) ConcurrentHashMapUtils.computeIfAbsent( - (ConcurrentMap) serverMap, - getAddr(url), restServer -> { - RestProtocolServer s = serverFactory.createServer(url.getParameter(SERVER_KEY, DEFAULT_SERVER)); - s.setAddress(url.getAddress()); - s.start(url); - return s; - }); - + (ConcurrentMap) serverMap, getAddr(url), restServer -> { + RestProtocolServer s = serverFactory.createServer(url.getParameter(SERVER_KEY, DEFAULT_SERVER)); + s.setAddress(url.getAddress()); + s.start(url); + return s; + }); server.deploy(serviceRestMetadata, invoker); @@ -116,7 +112,6 @@ public void afterUnExport() { return exporter; } - @Override protected Invoker protocolBindingRefer(final Class type, final URL url) throws RpcException { @@ -125,27 +120,26 @@ protected Invoker protocolBindingRefer(final Class type, final URL url 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 * @@ -161,7 +155,6 @@ private ReferenceCountedClient createReferenceCountedClien return new ReferenceCountedClient<>(restClient, clients, clientFactory, url); } - @Override public void destroy() { if (logger.isInfoEnabled()) { @@ -211,13 +204,14 @@ private String getContextPath(URL url) { 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()); @@ -225,7 +219,13 @@ private void destroyInternal(URL url) { 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/RestProtocolServer.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocolServer.java index 4de74c937d3..35d6f08ea51 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocolServer.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocolServer.java @@ -21,14 +21,11 @@ import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.ProtocolServer; - public interface RestProtocolServer extends ProtocolServer { void start(URL url); - void deploy(ServiceRestMetadata serviceRestMetadata, Invoker invoker); void undeploy(ServiceRestMetadata serviceRestMetadata); - } 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 d125ff3052c..79f8ae8d924 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 @@ -32,14 +32,14 @@ import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; import org.apache.dubbo.rpc.protocol.rest.util.HttpHeaderUtil; - 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 @@ -50,12 +50,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(); @@ -64,8 +68,8 @@ public static void parseMethodArgs(RpcInvocation rpcInvocation, RequestFacade re // 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()); } } @@ -85,7 +89,8 @@ public static void parseMethodArgs(RpcInvocation rpcInvocation, RequestFacade re * @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); @@ -94,7 +99,6 @@ private static ProviderParseContext createParseContext(RequestFacade request, Ob parseContext.setArgs(Arrays.asList(objects)); parseContext.setArgInfos(restMethodMetadata.getArgInfos()); - return parseContext; } @@ -113,26 +117,27 @@ public static RpcInvocation createBaseRpcInvocation(RequestFacade request, RestM 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); } @@ -143,23 +148,19 @@ public static InvokerAndRestMethodMetadataPair getRestMethodMetadataAndInvokerPa * @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); @@ -167,7 +168,6 @@ public static Invoker getInvokerByRequest(RequestFacade request) { return getInvoker(pathMatcher, request.getServiceDeployer()); } - /** * get invoker by service method *

    @@ -176,7 +176,6 @@ public static Invoker getInvokerByRequest(RequestFacade request) { * @param serviceMethod * @return */ - public static Invoker getInvokerByServiceInvokeMethod(Method serviceMethod, ServiceDeployer serviceDeployer) { if (serviceMethod == null) { @@ -224,6 +223,4 @@ public static PathMatcher createPathMatcher(RequestFacade request) { 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/RestServerFactory.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestServerFactory.java index 367c3a01950..97e0d554845 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestServerFactory.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestServerFactory.java @@ -16,14 +16,12 @@ */ package org.apache.dubbo.rpc.protocol.rest; - /** * Only the server that implements servlet container * could support something like @Context injection of servlet objects. */ public class RestServerFactory { - public RestProtocolServer createServer(String name) { return new NettyHttpRestServer(); } 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 fe07516ba47..6336f1cf548 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.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 Object result(RpcException e) { } 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 1d5346044fe..0a87d6d8f34 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 @@ 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 e2fdc252efd..1dffe88535b 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,19 +16,16 @@ */ 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; - 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 e8af563d3ef..a093b0edf95 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 @@ 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 5c0dbaa2360..8c89c8fac16 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; @@ -29,12 +28,13 @@ public class ParamParserManager { + private static final Set consumerParamParsers = FrameworkModel.defaultModel() + .getExtensionLoader(BaseConsumerParamParser.class) + .getSupportedExtensionInstances(); - private static final Set consumerParamParsers = - FrameworkModel.defaultModel().getExtensionLoader(BaseConsumerParamParser.class).getSupportedExtensionInstances(); - - private static final Set providerParamParsers = - FrameworkModel.defaultModel().getExtensionLoader(BaseProviderParamParser.class).getSupportedExtensionInstances(); + private static final Set providerParamParsers = FrameworkModel.defaultModel() + .getExtensionLoader(BaseProviderParamParser.class) + .getSupportedExtensionInstances(); /** * provider Design Description: @@ -60,7 +60,6 @@ public static Object[] providerParamParse(ProviderParseContext parseContext) { return parseContext.getArgs().toArray(new Object[0]); } - /** * consumer Design Description: *

    @@ -89,6 +88,5 @@ public static void consumerParamParse(ConsumerParseContext parseContext) { // 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 584b831835b..f2b3e473c24 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 c5e6248d5b3..49a50116250 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 @@ /** * 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 void intercept(HttpConnectionCreateContext connectionCreateContext) { 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 d1e1126f5d4..c6a4a26548e 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 void intercept(HttpConnectionCreateContext connectionCreateContext) { 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 951d19476bd..7de10660a8f 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 @@ -27,15 +27,18 @@ /** * resolve method args by args info */ -@Activate(value = "paramparse",order = 5) +@Activate(value = "paramparse", order = 5) public class ParamParseIntercept implements HttpConnectionPreBuildIntercept { @Override public void intercept(HttpConnectionCreateContext connectionCreateContext) { - ConsumerParseContext consumerParseContext = new ConsumerParseContext(connectionCreateContext.getRequestTemplate()); - consumerParseContext.setArgInfos(connectionCreateContext.getRestMethodMetadata().getArgInfos()); - consumerParseContext.setArgs(Arrays.asList(connectionCreateContext.getInvocation().getArguments())); + ConsumerParseContext consumerParseContext = + new ConsumerParseContext(connectionCreateContext.getRequestTemplate()); + consumerParseContext.setArgInfos( + connectionCreateContext.getRestMethodMetadata().getArgInfos()); + consumerParseContext.setArgs( + Arrays.asList(connectionCreateContext.getInvocation().getArguments())); 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 9837d352b8b..a8ef83d8674 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 @@ /** * 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 void intercept(HttpConnectionCreateContext connectionCreateContext) { 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 8bfbfbfbfe9..d6fb6f8bf8c 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 void intercept(HttpConnectionCreateContext connectionCreateContext) { 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 void intercept(HttpConnectionCreateContext connectionCreateContext) { 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 22d6ab32b82..6e898cea561 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 @@ @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 void intercept(HttpConnectionCreateContext connectionCreateContext) { 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 f1521476a1b..7957bd4dbce 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.ServiceRestMetadataResolver; import org.apache.dubbo.rpc.protocol.rest.exception.CodeStyleNotSupportException; - public class MetadataResolver { - private MetadataResolver() { - } + private MetadataResolver() {} /** * for consumer @@ -35,12 +33,16 @@ private 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.getSupportedExtensionInstances()) { + for (ServiceRestMetadataResolver serviceRestMetadataResolver : + extensionLoader.getSupportedExtensionInstances()) { 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 +50,27 @@ public static ServiceRestMetadata resolveConsumerServiceMetadata(Class target } // 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.getSupportedExtensionInstances()) { + for (ServiceRestMetadataResolver serviceRestMetadataResolver : + extensionLoader.getSupportedExtensionInstances()) { 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 74c2ca15212..6393daca5fd 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 0632ca3474a..3c300861e9d 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 672b30e4de4..c6833f40568 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 ConsumerParseContext(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/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 2b2e04f1ba7..e4fdbb0c0bc 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 void parse(ConsumerParseContext parseContext, ArgInfo argInfo) { return; } - Map> tmp = new HashMap<>(); if (DataParseUtils.isTextType(value.getClass())) { tmp.put(argInfo.getAnnotationNameAttribute(), Arrays.asList(String.valueOf(value))); @@ -59,11 +57,9 @@ public void parse(ConsumerParseContext parseContext, ArgInfo argInfo) { 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 void parse(ConsumerParseContext parseContext, ArgInfo argInfo) { 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 d99a01164db..c62f1750a06 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 void parse(ConsumerParseContext parseContext, ArgInfo argInfo) { return; } - // Map if (Map.class.isAssignableFrom(argInfo.getParamType())) { Map headerValues = (Map) headerValue; @@ -48,9 +47,7 @@ public void parse(ConsumerParseContext parseContext, ArgInfo argInfo) { } 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 11509a79653..65f8fe30e8e 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 void parse(ConsumerParseContext parseContext, ArgInfo argInfo) { return; } - if (Map.class.isAssignableFrom(argInfo.getParamType())) { Map paramValues = (Map) paramValue; for (Object name : paramValues.keySet()) { @@ -46,10 +45,7 @@ public void parse(ConsumerParseContext parseContext, ArgInfo argInfo) { } } 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 343efbbf624..3b31d703b81 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,12 +16,9 @@ */ 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.rpc.protocol.rest.annotation.ParamParser; @SPI(scope = ExtensionScope.FRAMEWORK) -public interface BaseProviderParamParser extends ParamParser { - -} +public interface BaseProviderParamParser extends ParamParser {} 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 da4897e1ab5..022a1c7d602 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.request.RequestFacade; import org.apache.dubbo.rpc.protocol.rest.util.MediaTypeUtil; - /** * body param parse */ @@ -42,7 +41,8 @@ protected void doParse(ProviderParseContext parseContext, ArgInfo argInfo) { 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 9b87792bd9d..06227ab82de 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; @@ -33,7 +34,7 @@ public class HeaderProviderParamParser 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())) { @@ -46,16 +47,12 @@ protected void doParse(ProviderParseContext parseContext, ArgInfo argInfo) { } 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/ParamProviderParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/ParamProviderParamParser.java index 5505ba4b801..be489d33cf9 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 @@ protected void doParse(ProviderParseContext parseContext, ArgInfo argInfo) { } 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 4addb20a53f..f33a677429a 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 @@ protected void doParse(ProviderParseContext parseContext, ArgInfo argInfo) { 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 12606b0cf5d..9f0d74464ba 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.metadata.rest.ParamType; import org.apache.dubbo.rpc.protocol.rest.util.DataParseUtils; @@ -44,10 +43,6 @@ public boolean matchParseType(Class paramAnno) { 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 0e2be572a62..be247cd361f 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,19 +16,15 @@ */ 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; - public ProviderParseContext(RequestFacade request) { this.requestFacade = request; } @@ -63,8 +59,5 @@ public String getPathVariable(int urlSplitIndex) { String[] split = getRequestFacade().getRequestURI().split("/"); return split[urlSplitIndex]; - } - - } 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 09835f8cd6b..e50f7805258 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 @@ -47,7 +47,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"; @@ -67,6 +66,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 1830dc2e868..df724b03b88 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 @@ 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 void registerExtension(URL url) { 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 List getExtensions(Class extensionClass) { return exts; } - for (Object extension : extensions) { if (extensionClass.isAssignableFrom(extension.getClass())) { exts.add((T) extension); @@ -137,13 +130,13 @@ public List getExtensions(Class extensionClass) { } 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/exception/CodeStyleNotSupportException.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/CodeStyleNotSupportException.java index d2c6c5849d8..979994750eb 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 @@ /** * 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 7c3d922e44f..29af0d7f1f1 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 a8b2751fb3a..e3ced44086a 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 @@ /** * 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 a552562deee..fce0964b672 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 @@ 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 d4ad67b3b28..6ab784e8541 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 3a1c7fa99ad..0c6f9fd5fc4 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 c0b890da7b3..7c5109cacef 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 Object getEntity() { @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 0ed07c7bc9a..c2204992967 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 @@ 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 ExceptionHandlerResult exceptionToResult(Object throwable) { return ExceptionHandlerResult.build().setEntity(result).setStatus(exceptionHandler.status()); } - public Object getExceptionHandler(Class causeClass) { return getExceptionHandler(allExceptionHandlers, causeClass); @@ -72,10 +69,8 @@ public boolean hasExceptionMapper(Object throwable) { return allExceptionHandlers.containsKey(throwable.getClass()); } - public void registerMapper(Class exceptionHandler) { - try { List methods = getExceptionHandlerMethods(exceptionHandler); @@ -107,19 +102,22 @@ public void registerMapper(Class exceptionHandler) { 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 void registerMapper(String 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 221bbb4e6e4..6731dd04ed7 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 @@ 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 ExceptionHandlerResult exceptionToResult(Object throwable) { 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 21343818422..d1e6ec0fa4b 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,28 +27,33 @@ 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 org.jboss.resteasy.core.interception.ResponseContainerRequestContext; -import org.jboss.resteasy.plugins.server.netty.NettyHttpRequest; -import org.jboss.resteasy.plugins.server.netty.NettyUtil; -import org.jboss.resteasy.specimpl.BuiltResponse; -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; +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; +import org.jboss.resteasy.specimpl.BuiltResponse; +import org.jboss.resteasy.specimpl.ResteasyHttpHeaders; +import org.jboss.resteasy.spi.HttpResponse; +import org.jboss.resteasy.spi.ResteasyUriInfo; + 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 @@ default DubboPreMatchContainerRequestContext convertHttpRequestToContainerReques 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 @@ default DubboPreMatchContainerRequestContext convertHttpRequestToContainerReques } return new DubboPreMatchContainerRequestContext(nettyRequest, requestFilters, null); - } default ResteasyUriInfo extractUriInfo(HttpRequest request) { @@ -112,31 +112,47 @@ default ResteasyUriInfo extractUriInfo(HttpRequest request) { 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 @@ default void addResponseHeaders(NettyHttpResponse response, MultivaluedMap entityClass) { 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 65246fcd57f..4812038a0c1 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,17 +18,6 @@ import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; -import org.jboss.resteasy.core.Dispatcher; -import org.jboss.resteasy.core.ServerResponseWriter; -import org.jboss.resteasy.core.SynchronousDispatcher; -import org.jboss.resteasy.core.interception.ResponseContainerRequestContext; -import org.jboss.resteasy.core.interception.jaxrs.SuspendableContainerResponseContext; -import org.jboss.resteasy.specimpl.BuiltResponse; -import org.jboss.resteasy.spi.ApplicationException; -import org.jboss.resteasy.spi.HttpRequest; -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; @@ -39,6 +28,7 @@ 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; @@ -50,8 +40,21 @@ 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; +import org.jboss.resteasy.core.interception.ResponseContainerRequestContext; +import org.jboss.resteasy.core.interception.jaxrs.SuspendableContainerResponseContext; +import org.jboss.resteasy.specimpl.BuiltResponse; +import org.jboss.resteasy.spi.ApplicationException; +import org.jboss.resteasy.spi.HttpRequest; +import org.jboss.resteasy.spi.HttpResponse; +import org.jboss.resteasy.spi.ResteasyAsynchronousResponse; +import org.jboss.resteasy.spi.ResteasyProviderFactory; + 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 Type getEntityType() { 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 void setEntity(Object entity) { 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 String getHeaderString(String name) { 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 synchronized void resume() { } // 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 synchronized void resume() { @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 synchronized void filter() throws IOException { } 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 synchronized void filter() throws IOException { // 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 synchronized void filter() throws IOException { 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 3369659e600..4964f1792d8 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.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.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 String getHeaderString(String 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 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 synchronized void abortWith(Response response) { @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 synchronized void resume() { } // 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 synchronized void resume() { @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 synchronized BuiltResponse filter() throws Throwable { // 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 1b05c722206..826f84df704 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 ResteasyNettyHttpResponse(NettyHttpResponse response) { } } - @Override public int getStatus() { return response.getStatus(); @@ -72,9 +73,7 @@ public void setOutputStream(OutputStream os) { } @Override - public void addNewCookie(NewCookie cookie) { - - } + public void addNewCookie(NewCookie cookie) {} @Override public void sendError(int status) throws IOException { @@ -99,7 +98,5 @@ public void reset() { } @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 851da89a2f8..6cb0aa07d9b 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.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 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 void filter(RestFilterContext restFilterContext) throws Exception { 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 void filter(RestFilterContext restFilterContext) throws Exception { } 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 89ea8a6e21e..35e008e7f0e 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.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 void filter(RestFilterContext restFilterContext) throws Exception { // 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 void filter(RestFilterContext restFilterContext) throws Exception { 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 1a793b6b337..f1697edd804 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 @@ 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 void proceed() throws IOException, WebApplicationException { 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 60d7b63eff0..5116fce40e7 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.context.RestInterceptContext; import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; -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"}) +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; + +@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 void intercept(RestInterceptContext restResponseInterceptor) throws Excep Class type = rpcInvocation.getReturnType(); - List extension = serviceDeployer.getExtensions(WriterInterceptor.class); if (extension.isEmpty()) { @@ -78,7 +84,8 @@ public void intercept(RestInterceptContext restResponseInterceptor) throws Excep 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 void intercept(RestInterceptContext restResponseInterceptor) throws Excep } 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 3bdb40457be..dc7608de8a4 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 @@ 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 7ed94195049..da5a2c9a758 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 @@ * 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 200202dced7..97fdf00c946 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 @@ * 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 33a32ec108c..8e824301ad2 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 @@ 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 72508ce868e..8c0d04a467d 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 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 void filter(RestFilterContext restFilterContext) throws Exception { 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 @@ private void doHandler(HttpRequest nettyHttpRequest, 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 @@ private void doHandler(HttpRequest nettyHttpRequest, 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 @@ private void doHandler(HttpRequest nettyHttpRequest, 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 @@ private void doHandler(HttpRequest nettyHttpRequest, * @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 @@ private void acceptSupportJudge(RequestFacade requestFacade, Class returnType throw e; } - if (!accept.contains(mediaType.value)) { throw e; } - } } - public static String stackTraceToString(Throwable throwable) { StackTraceElement[] stackTrace = throwable.getStackTrace(); @@ -232,7 +244,6 @@ public static String stackTraceToString(Throwable throwable) { */ public void executeResponseIntercepts(RestInterceptContext restFilterContext) throws Exception { - for (RestResponseInterceptor restResponseInterceptor : restResponseInterceptors) { restResponseInterceptor.intercept(restFilterContext); @@ -240,8 +251,6 @@ public void executeResponseIntercepts(RestInterceptContext restFilterContext) th 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 c3832efbcab..db3c3d8f253 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 d40c41e27ed..c9544f47d8a 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 @@ 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 bf2be29d45f..dd3e2c51024 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 ee4ba10bd6c..9ba91ae87d5 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 @@ 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 d1c3939c93a..55b24de256d 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.util.ArrayList; import java.util.List; - /** * netty http request handler */ @@ -48,15 +47,17 @@ 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 public void handle(NettyRequestFacade requestFacade, NettyHttpResponse nettyHttpResponse) throws IOException { @@ -74,7 +75,8 @@ public void handle(NettyRequestFacade requestFacade, NettyHttpResponse nettyHttp Object nettyHttpRequest = requestFacade.getRequest(); - RestFilterContext restFilterContext = new RestFilterContext(url, requestFacade, nettyHttpResponse, serviceDeployer); + RestFilterContext restFilterContext = + new RestFilterContext(url, requestFacade, nettyHttpResponse, serviceDeployer); try { @@ -82,32 +84,61 @@ public void handle(NettyRequestFacade requestFacade, NettyHttpResponse nettyHttp executeFilters(restFilterContext, restRequestFilters); } catch (PathNoFoundException pathNoFoundException) { - logger.error("", pathNoFoundException.getMessage(), "", "dubbo rest protocol provider path no found ,raw request is :" + nettyHttpRequest, pathNoFoundException); + logger.error( + "", + pathNoFoundException.getMessage(), + "", + "dubbo rest protocol provider path no found ,raw request is :" + nettyHttpRequest, + pathNoFoundException); nettyHttpResponse.sendError(404, pathNoFoundException.getMessage()); } catch (ParamParseException paramParseException) { - logger.error("", paramParseException.getMessage(), "", "dubbo rest protocol provider param parse error ,and raw request is :" + nettyHttpRequest, paramParseException); + logger.error( + "", + paramParseException.getMessage(), + "", + "dubbo rest protocol provider param parse error ,and raw request is :" + nettyHttpRequest, + paramParseException); nettyHttpResponse.sendError(400, paramParseException.getMessage()); } catch (MediaTypeUnSupportException contentTypeException) { - logger.error("", contentTypeException.getMessage(), "", "dubbo rest protocol provider content-type un support" + nettyHttpRequest, contentTypeException); + logger.error( + "", + contentTypeException.getMessage(), + "", + "dubbo rest protocol provider content-type un support" + nettyHttpRequest, + contentTypeException); nettyHttpResponse.sendError(415, contentTypeException.getMessage()); } catch (Throwable throwable) { - logger.error("", throwable.getMessage(), "", "dubbo rest protocol provider error ,and raw request is " + nettyHttpRequest, throwable); - nettyHttpResponse.sendError(500, "dubbo rest invoke Internal error, message is " + throwable.getMessage() + " ,and exception type is : " + throwable.getClass() - + " , stacktrace is: " + ServiceInvokeRestFilter.stackTraceToString(throwable)); + logger.error( + "", + throwable.getMessage(), + "", + "dubbo rest protocol provider error ,and raw request is " + nettyHttpRequest, + throwable); + nettyHttpResponse.sendError( + 500, + "dubbo rest invoke Internal error, message is " + throwable.getMessage() + + " ,and exception type is : " + throwable.getClass() + " , stacktrace is: " + + ServiceInvokeRestFilter.stackTraceToString(throwable)); } // second response filter try { executeFilters(restFilterContext, restResponseFilters); } catch (Throwable throwable) { - logger.error("", throwable.getMessage(), "", "dubbo rest protocol provider error ,and raw request is " + nettyHttpRequest, throwable); - nettyHttpResponse.sendError(500, "dubbo rest invoke Internal error, message is " + throwable.getMessage() + " ,and exception type is : " + throwable.getClass() - + " , stacktrace is: " + ServiceInvokeRestFilter.stackTraceToString(throwable)); + logger.error( + "", + throwable.getMessage(), + "", + "dubbo rest protocol provider error ,and raw request is " + nettyHttpRequest, + throwable); + nettyHttpResponse.sendError( + 500, + "dubbo rest invoke Internal error, message is " + throwable.getMessage() + + " ,and exception type is : " + throwable.getClass() + " , stacktrace is: " + + ServiceInvokeRestFilter.stackTraceToString(throwable)); } - } - /** * execute rest filters * @@ -124,5 +155,4 @@ public void executeFilters(RestFilterContext restFilterContext, List } } } - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerApiListingResource.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerApiListingResource.java index 57ff74c74b5..bf0652d2cbf 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerApiListingResource.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerApiListingResource.java @@ -18,9 +18,6 @@ import org.apache.dubbo.config.annotation.Service; -import com.fasterxml.jackson.core.JsonProcessingException; -import io.swagger.jaxrs.listing.BaseApiListingResource; - import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.ws.rs.core.Application; @@ -29,6 +26,9 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; +import com.fasterxml.jackson.core.JsonProcessingException; +import io.swagger.jaxrs.listing.BaseApiListingResource; + @Service public class DubboSwaggerApiListingResource extends BaseApiListingResource implements DubboSwaggerService { @@ -36,13 +36,13 @@ public class DubboSwaggerApiListingResource extends BaseApiListingResource imple ServletContext context; @Override - public Response getListingJson(Application app, ServletConfig sc, - HttpHeaders headers, UriInfo uriInfo) throws JsonProcessingException { - Response response = getListingJsonResponse(app, context, sc, headers, uriInfo); + public Response getListingJson(Application app, ServletConfig sc, HttpHeaders headers, UriInfo uriInfo) + throws JsonProcessingException { + Response response = getListingJsonResponse(app, context, sc, headers, uriInfo); response.getHeaders().add("Access-Control-Allow-Origin", "*"); response.getHeaders().add("Access-Control-Allow-Headers", "x-requested-with, ssi-token"); response.getHeaders().add("Access-Control-Max-Age", "3600"); - response.getHeaders().add("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS"); + response.getHeaders().add("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS"); return response; } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerService.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerService.java index e0e5a7d3616..eacdfbd283e 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerService.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerService.java @@ -16,8 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest.integration.swagger; -import com.fasterxml.jackson.core.JsonProcessingException; - import javax.servlet.ServletConfig; import javax.ws.rs.Consumes; import javax.ws.rs.GET; @@ -30,6 +28,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; +import com.fasterxml.jackson.core.JsonProcessingException; @Path("dubbo") @Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) @@ -38,6 +37,7 @@ public interface DubboSwaggerService { @GET @Path("swagger") - Response getListingJson(@Context Application app, @Context ServletConfig sc, - @Context HttpHeaders headers, @Context UriInfo uriInfo) throws JsonProcessingException; + Response getListingJson( + @Context Application app, @Context ServletConfig sc, @Context HttpHeaders headers, @Context UriInfo uriInfo) + throws JsonProcessingException; } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageCodec.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageCodec.java index f38ee24a579..08530451038 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageCodec.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageCodec.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest.message; - import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.metadata.rest.media.MediaType; @@ -27,8 +26,8 @@ * @param */ @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 eb34605eda9..212ebb4ffb5 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.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 static MessageCodecResultPair httpMessageEncode(OutputStream outputStream */ 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 static MediaType typeSupport(Class type) { 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 b072a8a9c20..8b322816009 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 6d35d9c43e4..8ae427ec5e7 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 6db52df8613..71152a81faa 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.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 @@ private static List getDefaultList() { 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 ff15fc56630..2dc0a85ad7a 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 @@ @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 MediaType contentType() { 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 2c295e2ce3b..c03ed001d43 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 @@ -66,7 +66,6 @@ public MediaType contentType() { 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)); 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 ee11bb5954b..a78f793c7b9 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 @@ @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 Object decode(byte[] body, Class targetType, Type type) throws Excepti } 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 Object decode(byte[] body, Class targetType, Type type) throws Excepti 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 Object decode(byte[] body, Class targetType, Type type) throws Excepti 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 9717df88d77..0cb0efc7b11 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 726c007f677..4f939ea7fb1 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 @@ @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 Object decode(byte[] body, Class targetType, Type type) throws Excepti } @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 MediaType contentType() { 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 69c4eaa35ac..16f13bd4137 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 Object decode(byte[] body, Class targetType, Type type) throws Excepti 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 d24d27a85f5..f696c91e8e8 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.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 MediaType contentType() { 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 0e9d9bb9043..dcc602ba01c 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 void write(int b) throws IOException { } 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 void close() throws IOException { super.close(); } - @Override public void write(byte[] b, int off, int len) throws IOException { int dataLengthLeftToWrite = len; @@ -86,6 +84,4 @@ public void flush() throws IOException { 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 890fe039b95..888547bf5bd 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 4ed2c5525b5..72256f53e9d 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,23 +16,11 @@ */ package org.apache.dubbo.rpc.protocol.rest.netty; - -import io.netty.channel.ChannelFuture; -import io.netty.channel.ChannelFutureListener; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.http.DefaultFullHttpResponse; -import io.netty.handler.codec.http.DefaultHttpResponse; -import io.netty.handler.codec.http.HttpHeaders; -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; @@ -41,8 +29,18 @@ import java.util.List; import java.util.Map; -import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelFutureListener; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.http.DefaultFullHttpResponse; +import io.netty.handler.codec.http.DefaultHttpResponse; +import io.netty.handler.codec.http.HttpHeaders; +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 static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; /** * netty http response @@ -65,7 +63,7 @@ public NettyHttpResponse(final ChannelHandlerContext ctx, final boolean keepAliv 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 NettyHttpResponse(final ChannelHandlerContext ctx, final boolean keepAliv this.keepAlive = keepAlive; } - public void setOutputStream(OutputStream os) { this.os = os; } @@ -101,7 +98,6 @@ public OutputStream getOutputStream() throws IOException { return os; } - @Override public void sendError(int status) throws IOException { sendError(status, null); @@ -114,7 +110,6 @@ public void sendError(int status, String message) throws IOException { if (message != null) { getOutputStream().write(message.getBytes(StandardCharsets.UTF_8)); } - } @Override @@ -155,7 +150,6 @@ private void transformResponseHeaders(io.netty.handler.codec.http.HttpResponse r transformHeaders(this, res); } - public void prepareChunkStream() { committed = true; DefaultHttpResponse response = getDefaultHttpResponse(); @@ -164,8 +158,7 @@ public void prepareChunkStream() { } 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 void finish() throws IOException { @Override public void flushBuffer() throws IOException { - if (os != null) - os.flush(); + if (os != null) os.flush(); ctx.flush(); } @@ -202,20 +194,21 @@ public void addOutputHeaders(String name, String value) { } @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); -// } - - for (Map.Entry> entry : nettyResponse.getOutputHeaders().entrySet()) { + 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()) { 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/NettyServer.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/NettyServer.java index 782072f6cc2..0feb90f2805 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/NettyServer.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/NettyServer.java @@ -14,9 +14,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.rest.netty; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.utils.NamedThreadFactory; +import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; + +import java.net.InetSocketAddress; +import java.util.Collections; +import java.util.List; +import java.util.Map; + import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; @@ -28,19 +36,10 @@ import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.timeout.IdleStateHandler; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.NamedThreadFactory; -import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; - -import java.net.InetSocketAddress; -import java.util.Collections; -import java.util.List; -import java.util.Map; import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_BOSS_POOL_NAME; import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_WORKER_POOL_NAME; - public class NettyServer { protected ServerBootstrap bootstrap = new ServerBootstrap(); @@ -57,9 +56,7 @@ public class NettyServer { private Map childChannelOptions = Collections.emptyMap(); private UnSharedHandlerCreator unSharedHandlerCallBack; - public NettyServer() { - } - + public NettyServer() {} /** * Specify the worker count to use. For more information about this please see the javadocs of {@link EventLoopGroup} @@ -86,7 +83,6 @@ public void setPort(int port) { this.configuredPort = port; } - /** * Add additional {@link io.netty.channel.ChannelHandler}s to the {@link io.netty.bootstrap.ServerBootstrap}. *

    The additional channel handlers are being added before the HTTP handling.

    @@ -114,7 +110,8 @@ public void setChannelOptions(final Map channelOptions) { * @see io.netty.bootstrap.ServerBootstrap#childOption(io.netty.channel.ChannelOption, Object) */ public void setChildChannelOptions(final Map channelOptions) { - this.childChannelOptions = channelOptions == null ? Collections.emptyMap() : channelOptions; + this.childChannelOptions = + channelOptions == null ? Collections.emptyMap() : channelOptions; } public void setUnSharedHandlerCallBack(UnSharedHandlerCreator unSharedHandlerCallBack) { @@ -126,10 +123,10 @@ public void start(URL url) { workerLoopGroup = new NioEventLoopGroup(ioWorkerCount, new NamedThreadFactory(EVENT_LOOP_WORKER_POOL_NAME)); // Configure the server. - bootstrap.group(eventLoopGroup, workerLoopGroup) - .channel(NioServerSocketChannel.class) - .childHandler(setupHandlers(url)); - + bootstrap + .group(eventLoopGroup, workerLoopGroup) + .channel(NioServerSocketChannel.class) + .childHandler(setupHandlers(url)); for (Map.Entry entry : channelOptions.entrySet()) { bootstrap.option(entry.getKey(), entry.getValue()); @@ -150,7 +147,6 @@ public void start(URL url) { runtimePort = ((InetSocketAddress) channel.localAddress()).getPort(); } - protected ChannelHandler setupHandlers(URL url) { return new ChannelInitializer() { @@ -170,13 +166,10 @@ public void initChannel(SocketChannel ch) throws Exception { for (ChannelHandler unSharedHandler : unSharedHandlers) { channelPipeline.addLast(unSharedHandler); } - } }; - } - public void stop() { runtimePort = -1; eventLoopGroup.shutdownGracefully(); 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 d5233c3e10f..f89d229d9a6 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.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 @@ protected void decode(ChannelHandlerContext ctx, io.netty.handler.codec.http.Ful nettyHttpHandler.handle(requestFacade, nettyHttpResponse); } catch (IOException e) { - logger.error("", e.getCause().getMessage(), "dubbo rest rest http request handler error", e.getMessage(), e); + logger.error( + "", e.getCause().getMessage(), "dubbo rest rest http request handler error", e.getMessage(), e); } finally { // write response try { nettyHttpResponse.addOutputHeaders(RestHeaderEnum.CONNECTION.getHeader(), "close"); nettyHttpResponse.finish(); } catch (IOException e) { - logger.error("", e.getCause().getMessage(), "dubbo rest rest http response flush error", e.getMessage(), e); + logger.error( + "", + e.getCause().getMessage(), + "dubbo rest rest http response flush error", + e.getMessage(), + e); } } - }); - - } } - diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/UnSharedHandlerCreator.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/UnSharedHandlerCreator.java index 24fce27ab63..98b127c5579 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/UnSharedHandlerCreator.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/UnSharedHandlerCreator.java @@ -16,11 +16,12 @@ */ package org.apache.dubbo.rpc.protocol.rest.netty; -import io.netty.channel.ChannelHandler; import org.apache.dubbo.common.URL; import java.util.List; +import io.netty.channel.ChannelHandler; + /** * FOR create netty un shared (no @Shared) handler */ diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/ssl/SslContexts.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/ssl/SslContexts.java index 12dd3d712b7..d1c2be29732 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/ssl/SslContexts.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/ssl/SslContexts.java @@ -16,11 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest.netty.ssl; -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 org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -30,11 +25,18 @@ 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 static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE_STREAM; public class SslContexts { @@ -52,11 +54,11 @@ public static SslContext buildServerSslContext(ProviderCert providerConnectionCo 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) { @@ -82,7 +84,8 @@ public static SslContext buildServerSslContext(ProviderCert providerConnectionCo } 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; @@ -135,8 +138,8 @@ private static SslProvider findSslProvider() { 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() { @@ -154,5 +157,4 @@ private static void safeCloseStream(InputStream stream) { logger.warn(TRANSPORT_FAILED_CLOSE_STREAM, "", "", "Failed to close a stream.", e); } } - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/ssl/SslServerTlsHandler.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/ssl/SslServerTlsHandler.java index 756c429c406..e0dde1aa007 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/ssl/SslServerTlsHandler.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/ssl/SslServerTlsHandler.java @@ -16,13 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest.netty.ssl; -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelPipeline; -import io.netty.handler.codec.ByteToMessageDecoder; -import io.netty.handler.ssl.SslContext; -import io.netty.handler.ssl.SslHandler; -import io.netty.handler.ssl.SslHandshakeCompletionEvent; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -31,8 +24,17 @@ 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; +import io.netty.handler.codec.ByteToMessageDecoder; +import io.netty.handler.ssl.SslContext; +import io.netty.handler.ssl.SslHandler; +import io.netty.handler.ssl.SslHandshakeCompletionEvent; + import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; public class SslServerTlsHandler extends ByteToMessageDecoder { @@ -54,7 +56,12 @@ public SslServerTlsHandler(URL url, boolean sslDetected) { @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 @@ -62,12 +69,18 @@ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc 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(); } } @@ -75,7 +88,8 @@ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc } @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; @@ -85,8 +99,10 @@ protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteB 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 @@ private void enableSsl(ChannelHandlerContext ctx, SslContext sslContext) { 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 70380c986b2..2b11f75a16b 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 RestMethodMetadata getRestMethodMetadata() { return restMethodMetadata; } - public static InvokerAndRestMethodMetadataPair pair(Invoker invoker, RestMethodMetadata restMethodMetadata) { return new InvokerAndRestMethodMetadataPair(invoker, restMethodMetadata); } @@ -63,21 +62,17 @@ public boolean compareServiceMethod(InvokerAndRestMethodMetadataPair beforeMetad 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 00b3154c0ad..9f1deeaac69 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/request/NettyRequestFacade.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/request/NettyRequestFacade.java index ef8b07f4aac..3fba2d33a42 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.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 String getHeader(String name) { 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 String getHeader(String name) { } else { return values.get(0); } - } @Override @@ -98,7 +93,6 @@ public Enumeration getHeaders(String name) { list = new ArrayList<>(); } - ListIterator stringListIterator = list.listIterator(); return new Enumeration() { @@ -114,7 +108,6 @@ public String nextElement() { }; } - @Override public Enumeration getHeaderNames() { @@ -149,13 +142,11 @@ public String getContextPath() { 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 String getParameter(String name) { String value = null; if (strings != null && !strings.isEmpty()) { value = strings.get(0); - } return value; } @@ -184,7 +174,6 @@ public String nextElement() { return iterator.next(); } }; - } @Override @@ -204,10 +193,8 @@ public Map getParameterMap() { map.put(entry.getKey(), entry.getValue().toArray(new String[0])); }); return map; - } - @Override public String getRemoteAddr() { return getChannel().remoteAddress().getHostString(); @@ -259,7 +246,6 @@ protected void parseBody() { } } - } 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 ab0dcbf4844..e908a552396 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 RequestFacade(T request, ServiceDeployer serviceDeployer) { this.serviceDeployer = serviceDeployer; } - protected void initHeaders() { - - } - + protected void initHeaders() {} protected void initParameters() { String requestURI = getRequestURI(); @@ -84,7 +80,6 @@ protected void initParameters() { parameters.put(name, values); } values.add(value); - } } } else { @@ -92,22 +87,18 @@ protected void initParameters() { } } - 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 14579668ba9..8e586b5e159 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 @@ 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 df0e34f0578..0663703e699 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 @@ 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 9737c152c40..ceeae1c7450 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 static Object stringTypeConvert(Class targetType, String value) { } return value; - } public static boolean isTextType(Class targetType) { @@ -66,12 +65,13 @@ public static boolean isTextType(Class targetType) { 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 static byte[] objectTextConvertToByteArray(Object object) { } 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 static Object multipartFormConvert(byte[] body, Class targetType) thro 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 194d7de464e..5388e7b27ed 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 @@ public class HttpHeaderUtil { - /** * convert attachment to Map> * @@ -66,7 +64,6 @@ public static Map> createAttachments(Map at return attachments; } - /** * add consumer attachment to request * @@ -79,24 +76,24 @@ public static void addRequestAttachments(RequestTemplate requestTemplate, Map { 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 static void parseRequestHeader(RpcInvocation rpcInvocation, RequestFacade // attachment rpcInvocation.setAttachment(subRestAttachRealHeaderPrefix(header.trim()), requestFacade.getHeader(header)); - } } - /** * for judge rest header or rest attachment * @@ -160,7 +155,6 @@ public static String appendPrefixToAttachRealHeader(String header) { return RestHeaderEnum.REST_HEADER_PREFIX.getHeader() + header; } - /** * parse request attribute * @param rpcInvocation @@ -178,7 +172,6 @@ public static void parseRequestAttribute(RpcInvocation rpcInvocation, RequestFac rpcInvocation.put(RestConstant.LOCAL_PORT, localPort); } - /** * parse request * @param rpcInvocation @@ -211,7 +204,5 @@ public static void parseResponseHeader(AppResponse appResponse, RestResult restR 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 55a9783b12f..57093dc2e55 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 static MediaType convertMediaType(Class targetType, String... contentT } 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 8a391b99552..31e9112ff2b 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 static Object providerCreateMultiValueMap(Class targetType) { 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 static void add(Object multiValueMap, String key, Object value) { 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/NumberUtils.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/NumberUtils.java index 77a87b7308a..d59680fdd03 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 static T parseNumber(String text, Class targetClass) { 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 static String trimAllWhitespace(String str) { return sb.toString(); } - public static Object numberToBytes(Number number) { if (number instanceof Byte) { @@ -122,8 +119,5 @@ public static Object numberToBytes(Number number) { } 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 b2734d081b8..627ad1c195e 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 static Class findClassAndTryCatch(String name, ClassLoader classLoader) { } return null; - } public static Class findClass(ClassLoader classLoader, String... name) throws ClassNotFoundException { @@ -66,7 +62,6 @@ public static Class findClass(ClassLoader classLoader, String... name) throws Cl throw new ClassNotFoundException(); } - public static Class findClassTryException(ClassLoader classLoader, String... name) { try { @@ -75,7 +70,6 @@ public static Class findClassTryException(ClassLoader classLoader, String... nam } return null; - } public static List getMethodByNameList(Class clazz, String name) { @@ -98,7 +92,6 @@ public static List getMethodByNameList(Class clazz, String name, boolean return new ArrayList<>(methods); } - try { filterMethod(name, methods, clazz.getMethods()); } catch (Exception e) { @@ -123,15 +116,12 @@ public static List> getConstructList(Class clazz) { } 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 static Class findClassTryException(String... name) { 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 static Object invokeAndTryCatch(Object object, Method method, Object[] pa 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 ae29327019b..5b3898eb26f 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,8 @@ void testJsonConvert() throws Exception { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); DataParseUtils.writeJsonContent(User.getInstance(), byteArrayOutputStream); - Assertions.assertEquals("{\"age\":18,\"id\":404,\"name\":\"dubbo\"}", - new String(byteArrayOutputStream.toByteArray())); - - + Assertions.assertEquals( + "{\"age\":18,\"id\":404,\"name\":\"dubbo\"}", new String(byteArrayOutputStream.toByteArray())); } @Test @@ -56,7 +55,5 @@ void testStr() { 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 803c1330208..53cbc758e96 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.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 0bdd95cc4c9..69c5cbc710b 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 Long testFormBody(Long number) { return number; } - public boolean isCalled() { return called; } @@ -77,9 +77,7 @@ public long primitiveShort(short a, Long b, int c) { } @Override - public void request(DefaultFullHttpRequest defaultFullHttpRequest) { - - } + public void request(DefaultFullHttpRequest defaultFullHttpRequest) {} @Override public String testMapParam(Map params) { @@ -111,7 +109,6 @@ public String noStringParam(String param) { return param; } - @Override public String noStringHeader(String header) { return header; @@ -146,7 +143,6 @@ public Integer hello(@QueryParam("a") Integer a, @QueryParam("b") Integer b) { return a + b; } - @GET @Path("/error") @Override @@ -158,7 +154,6 @@ public static Map getAttachments() { return context; } - @Override public List list(List users) { return users; @@ -189,5 +184,4 @@ public User formBody(User user) { 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 a432ef552b3..330439ab608 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 @@ 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 Object result(RuntimeException exception) { 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/HttpMessageCodecManagerTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/HttpMessageCodecManagerTest.java index b0f368e74bd..06c0ff5e181 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.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 @@ void testCodec() throws Exception { 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 @@ void testCodec() throws Exception { 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 265f45d2771..e68969817d5 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.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.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.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.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 @@ public void tearDown() { @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 @@ void testRestProtocol() { exporter.unexport(); } - @Test void testAnotherUserRestProtocolByDifferentRestClient() { testAnotherUserRestProtocol(org.apache.dubbo.remoting.Constants.OK_HTTP); @@ -122,20 +125,19 @@ void testAnotherUserRestProtocolByDifferentRestClient() { 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 @@ void testAnotherUserRestProtocol(String restClient) { Assertions.assertEquals("h1", client.headerMap(map)); Assertions.assertEquals(null, client.headerMap(null)); - invoker.destroy(); exporter.unexport(); } @@ -166,13 +167,15 @@ void testRestProtocolWithContextPath() { 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 @@ void testNettyServer() { 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 @@ void testInvoke() { 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 @@ void testFilter() { 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 @@ void testRpcContextFilter() { // 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 @@ void testFormConsumerParser() { 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 @@ void test404() { 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 @@ void test400() { 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 @@ void testPrimitive() { 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 @@ void testPrimitive() { 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 @@ void testMapParam() { 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 @@ void testMapParam() { 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 @@ void testMapParam() { exporter.unexport(); } - @Test void testNoArgParam() { DemoService server = new DemoServiceImpl(); @@ -516,12 +513,11 @@ void testNoArgParam() { 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 @@ void testToken() { 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 @@ void testHttpMethod(String restClient) { 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 @@ public String result(RuntimeException e) { 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 @@ void test405() { 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 @@ void test405() { @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 @@ void testContainerRequestFilter() { 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 @@ void testIntercept() { 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 @@ void testResponseFilter() { 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 @@ void testCollectionResult() { 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 @@ void testReExport() { 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 @@ void testRequestAndResponseFilter() { DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); - Assertions.assertEquals("header-result", demoService.sayHello("hello")); exporter.unexport(); } @@ -809,18 +791,13 @@ void testFormBody() { 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/MediaTypeUtilTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/MediaTypeUtilTest.java index bfb2e0005d1..84db93b5168 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 @@ 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 @@ void testException() { 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 de5f70776f7..87a30ad32cd 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.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 @@ void testMethod() { 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 @@ void testMethod() { 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 @@ void testMethod() { 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/NumberUtilsTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/NumberUtilsTest.java index a726e38cc5d..58cf56f916c 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 @@ 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 @@ void testParseNumber(String numberStr) { BigInteger f = NumberUtils.parseNumber(numberStr, BigInteger.class); Assertions.assertEquals(1, f.intValue()); - - } @Test @@ -77,32 +76,32 @@ void testNumberToBytes() { 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 @@ void testNumberToBytes() { except = User.getInstance().toString().getBytes(StandardCharsets.UTF_8); Assertions.assertArrayEquals(except, bytes); - - } @Test @@ -121,10 +118,8 @@ void testNumberStr() { testParseNumber("0X0001"); testParseNumber("0x0001"); testParseNumber("#1"); - } - @Test void testUnHexNumber() { String numberStr = "1"; @@ -160,18 +155,14 @@ void testException() { 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 8884ba780e3..fceab90fa11 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,27 +24,33 @@ 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(); @AfterEach public void tearDown() { protocol.destroy(); FrameworkModel.destroyAll(); } + @Test void testResponse() { RestDemoService server = new RestDemoServiceImpl(); @@ -63,16 +69,8 @@ void testResponse() { 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 2749282ea71..fdb3ffdf2f5 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 @@ void testNormalException() { RpcException rpcException = new RpcException(); Object response = exceptionMapper.result(rpcException); - assertThat(response, not(nullValue())); assertThat(response, instanceOf(String.class)); } @@ -80,12 +79,9 @@ void testBuildException() { 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 @@ public void testViolationReport() { 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 e37f646c08c..8fab22157fb 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.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 void tearDown() { 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 @@ void testControllerService() throws Exception { 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 0cbd1deed17..478b0b39be4 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.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.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,13 +57,16 @@ 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 final static int availablePort = NetUtils.getAvailablePort(); - private final static URL exportUrl = URL.valueOf("rest://127.0.0.1:" + availablePort + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.mvc.SpringRestDemoService"); + private Protocol protocol = + ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest"); + private ProxyFactory proxy = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + private static final int availablePort = NetUtils.getAvailablePort(); + private static final URL exportUrl = URL.valueOf("rest://127.0.0.1:" + availablePort + + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.mvc.SpringRestDemoService"); - - private final ModuleServiceRepository repository = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); + private final ModuleServiceRepository repository = + ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); private final ExceptionMapper exceptionMapper = new ExceptionMapper(); @@ -77,7 +80,6 @@ public SpringRestDemoService getServerImpl() { return new SpringDemoServiceImpl(); } - public Class getServerClass() { return SpringRestDemoService.class; } @@ -93,10 +95,10 @@ public Exporter getExceptionHandlerExport(URL url, Spring 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(); @@ -120,19 +122,19 @@ void testRestProtocol() { 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); @@ -157,13 +159,15 @@ void testRestProtocolWithContextPath() { 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"); @@ -196,7 +200,6 @@ void testNettyServer() { URL nettyUrl = this.registerProvider(exportUrl, server, SpringRestDemoService.class); - Exporter exporter = getExport(nettyUrl, server); SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl)); @@ -231,7 +234,8 @@ void testErrorHandler() { 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(); }); @@ -245,7 +249,12 @@ void testInvoke() { 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)); @@ -275,8 +284,8 @@ void testRpcContextFilter() { URL nettyUrl = this.registerProvider(exportUrl, 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)); @@ -319,7 +328,6 @@ void testDefaultPort() { assertThat(protocol.getDefaultPort(), is(80)); } - @Test void testExceptionMapper() { @@ -329,22 +337,20 @@ void testExceptionMapper() { 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(exportUrl, server, SpringRestDemoService.class); - Exporter exporter = getExport(nettyUrl, server); SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl)); @@ -370,7 +376,6 @@ void testPrimitive() { URL nettyUrl = this.registerProvider(exportUrl, server, SpringRestDemoService.class); - Exporter exporter = getExport(nettyUrl, server); SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl)); @@ -398,12 +403,7 @@ public String result(RuntimeException e) { 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/filter/TestContainerRequestFilter.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/filter/TestContainerRequestFilter.java index 5aede99fb5a..f7305bac58b 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.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 13ed1669f2b..cc2a0717b14 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.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 b6ca0f1e9f2..68373279416 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.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 5da404374ad..3bca8798061 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 @@ void test() throws Exception { 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 8c00af46fa1..6c35edc89c3 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 c2e58870515..66c62ecda93 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.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 38a26a6cafe..f5d92787c0c 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 Integer hello(Integer a, Integer b) { return a + b; } - @Override public String error() { throw new RuntimeException(); @@ -77,7 +74,6 @@ public static Map getAttachments() { return context; } - @Override public int primitiveInt(int a, int b) { return a + b; @@ -97,7 +93,4 @@ public long primitiveByte(byte a, Long b) { 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 adb461bf4ab..b2bcd08e0fd 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.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/rest/AnotherUserRestService.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/AnotherUserRestService.java index a2ecc368085..0eed7872e5c 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.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 7a81f071fe1..3e99f97bae9 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 java.util.Map; - public class AnotherUserRestServiceImpl implements AnotherUserRestService { - @Override public User getUser(Long id) { @@ -57,6 +55,4 @@ public Long number(Long number) { 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 914da271e9b..88696140a7f 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 f220d360f99..7dee6606c2c 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 ff48474d164..12b0e5627dd 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 c6c36593f4d..5ef5293a6dc 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 56b3fd1ee74..de00e901842 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.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 b0b32ed9a82..a71f4b20952 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 Long testFormBody(Long number) { return number; } - public boolean isCalled() { return called; } @@ -56,9 +57,9 @@ public Integer hello(Integer a, Integer b) { @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 39b42e740b1..994b7a285ad 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 ed66a1e3f8f..e04757afcfd 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 String getInvoker() { RequestFacade requestFacade = (RequestFacade) request; Invoker invokerByRequest = RestRPCInvocationUtil.getInvokerByRequest((RequestFacade) request); - Method hello = null; Method hashcode = null; try { @@ -45,10 +43,11 @@ public String getInvoker() { } - 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 a101d9fad90..bb9766c266c 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-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.apache.commons - commons-compress - - - io.reactivex.rxjava2 - rxjava - test - - - org.xerial.snappy - snappy-java - - - io.projectreactor - reactor-core - test - - - - - - 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-java_version}:exe:${os.detected.classifier} - - - - dubbo - org.apache.dubbo - dubbo-compiler - ${project.parent.version} - org.apache.dubbo.gen.tri.Dubbo3TripleGenerator - - - - - - - compile - - - - - - + + 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-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.apache.commons + commons-compress + + + io.reactivex.rxjava2 + rxjava + test + + + org.xerial.snappy + snappy-java + + + io.projectreactor + reactor-core + test + + + + + + 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-java_version}:exe:${os.detected.classifier} + + + dubbo + org.apache.dubbo + dubbo-compiler + ${project.parent.version} + org.apache.dubbo.gen.tri.Dubbo3TripleGenerator + + + + + + + compile + + + + + + 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 0c330f7a39b..dca88a772bf 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 TriRpcStatus getStatus() { 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 11a250bcaf3..abb5db671b5 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 @@ /** * 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 static Code httpStatusToGrpcCode(int httpStatusCode) { 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 static Code httpStatusToGrpcCode(int httpStatusCode) { } 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 String toMessage() { return msg; } - public enum Code { OK(0), CANCELLED(1), @@ -280,5 +276,4 @@ public static Code fromCode(int code) { 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 76ae697ed45..57ceae43fae 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 49312c67ec6..be2986c413b 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 d20d2f56b13..00f7cb0df27 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 08160dcd747..aea45b39b31 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 @@ private DeadlineFuture(String serviceName, String methodName, String address, in 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 static void destroy() { * @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 @@ private void doReceived(TriRpcStatus status, AppResponse appResponse) { // 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 void run(Timeout timeout) { } 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 36fb31f736b..39b93b4ef35 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 6f9de11f49c..a1fae862b3a 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 1b00e5ff091..ac86307e652 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 38519e4c42c..79b447b491e 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 9071ca4393d..eeaa50b204b 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 @@ 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 9a20d29f40f..b91d4b940f0 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 byte[] pack(Object obj) throws Exception { } 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 f2aaa69dd08..81d12d24205 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 66f34d48c3a..cb69e698c75 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.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.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 boolean needWrapper() { 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 ReflectionPackableMethod(MethodDescriptor method, URL url, String seriali 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 ReflectionPackableMethod(MethodDescriptor method, URL url, String seriali 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,10 @@ static boolean isStreamType(Class type) { * * @return true if the request and response object is not generated by protobuf */ - static boolean needWrap(MethodDescriptor methodDescriptor, Class[] parameterClasses, - Class returnClass) { + 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 +170,39 @@ static boolean needWrap(MethodDescriptor methodDescriptor, Class[] parameterC } // 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 +212,8 @@ static boolean needWrap(MethodDescriptor methodDescriptor, Class[] parameterC } 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 +226,14 @@ static boolean needWrap(MethodDescriptor methodDescriptor, Class[] parameterC 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 +319,11 @@ private static class WrapResponsePack implements Pack { // 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 +335,11 @@ public byte[] pack(Object obj) throws IOException { 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 +351,8 @@ private static class WrapResponseUnpack implements WrapperUnPack { 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 +364,9 @@ public Object unpack(byte[] data) throws IOException, ClassNotFoundException { 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 +388,18 @@ private static class WrapRequestPack implements Pack { 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 +407,12 @@ private WrapRequestPack(MultipleSerialization multipleSerialization, 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 +440,6 @@ private String convertHessianToWrapper(String serializeType) { } return serializeType; } - } private class WrapRequestUnpack implements WrapperUnPack { @@ -453,8 +451,11 @@ private class WrapRequestUnpack implements WrapperUnPack { 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 +463,8 @@ private WrapRequestUnpack(MultipleSerialization serialization, URL url, Collecti } 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 +472,9 @@ public Object unpack(byte[] data, boolean isReturnTriException) throws IOExcepti 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 e60af175ff3..90477e7336e 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.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 9d3a9b26410..f06ecd84080 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 5f79dad3b7c..ec51dacc7ae 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.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 static Parser getParser(Class clz) { 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 T parse(InputStream stream) throws InvalidProtocolBufferException { 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 77c4998d5ef..6ca934255fd 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 e9479375f3e..ace359c3de5 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 static int varIntComputeLength(int val) { return length; } - public static int readRawVarint32(ByteBuffer byteBuffer) { int val = 0; int currentPosition = byteBuffer.position(); @@ -140,39 +138,32 @@ public byte[] toByteArray() { 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 TripleResponseWrapper build() { } } - public static final class TripleRequestWrapper { private String serializeType; @@ -235,8 +225,7 @@ public List getArgTypes() { return argTypes; } - public TripleRequestWrapper() { - } + public TripleRequestWrapper() {} public static TripleRequestWrapper parseFrom(byte[] data) { TripleRequestWrapper tripleRequestWrapper = new TripleRequestWrapper(); @@ -280,8 +269,8 @@ public byte[] toByteArray() { 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 byte[] toByteArray() { 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 byte[] toByteArray() { 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 boolean equals(Object o) { } 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 7fd92f125cd..db1018e2d57 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 217b8c1496f..17676fccc45 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 70d018d78a8..56752eb8fee 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; @@ -40,6 +39,10 @@ import org.apache.dubbo.rpc.protocol.tri.transport.TripleTailHandler; import org.apache.dubbo.rpc.protocol.tri.transport.TripleWriteQueue; +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; @@ -51,10 +54,6 @@ 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,32 +106,34 @@ public void configServerProtocolHandler(URL url, ChannelOperator operator) { 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(); - ExecutorSupport executorSupport = ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()).getExecutorSupport(url); + .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(); + ExecutorSupport executorSupport = ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()) + .getExecutorSupport(url); codec.connection().local().flowController().frameWriter(codec.encoder().frameWriter()); TripleWriteQueue writeQueue = new TripleWriteQueue(); - final Http2MultiplexHandler handler = new Http2MultiplexHandler( - new ChannelInitializer() { - @Override - protected void initChannel(Http2StreamChannel ch) { - final ChannelPipeline p = ch.pipeline(); - p.addLast(new TripleCommandOutBoundHandler()); - p.addLast(new TripleHttp2FrameServerHandler(frameworkModel, executorSupport, - headFilters, ch, writeQueue)); - } - }); + final Http2MultiplexHandler handler = new Http2MultiplexHandler(new ChannelInitializer() { + @Override + protected void initChannel(Http2StreamChannel ch) { + final ChannelPipeline p = ch.pipeline(); + p.addLast(new TripleCommandOutBoundHandler()); + p.addLast(new TripleHttp2FrameServerHandler( + frameworkModel, executorSupport, headFilters, ch, writeQueue)); + } + }); List handlers = new ArrayList<>(); handlers.add(new ChannelHandlerPretender(codec)); handlers.add(new ChannelHandlerPretender(new FlushConsolidationHandler(64, true))); @@ -140,28 +141,28 @@ protected void initChannel(Http2StreamChannel ch) { handlers.add(new ChannelHandlerPretender(handler)); handlers.add(new ChannelHandlerPretender(new TripleTailHandler())); operator.configChannelHandler(handlers); - - } @Override public void configClientPipeline(URL url, ChannelOperator operator, ContextOperator contextOperator) { Configuration config = ConfigurationUtils.getGlobalConfiguration(url.getOrDefaultApplicationModel()); final Http2FrameCodec codec = TripleHttp2FrameCodecBuilder.forClient() - .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)) - .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(); + .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)) + .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)); 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 7903cf00db1..76b26247cb2 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.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.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 @@ private static AsciiString getSchemeFromUrl(URL url) { 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 @@ protected Result doInvoke(final Invocation invocation) { } 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 @@ private static boolean isSync(MethodDescriptor methodDescriptor, Invocation invo } 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 @@ StreamObserver streamCall(ClientCall call, 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 @@ AsyncRpcResult invokeUnary(MethodDescriptor methodDescriptor, Invocation invocat 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 @@ AsyncRpcResult invokeUnary(MethodDescriptor methodDescriptor, Invocation invocat 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 f3f9ebbc68f..be291bd8651 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 void remove(String path) { 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 cffb6ba10e9..b2134f330fe 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 void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception 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 void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc } 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 void run() { 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 f28d16287be..f5d0223467d 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.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 int getDefaultPort() { return 50051; } - @Override public Exporter export(Invoker invoker) throws RpcException { URL url = invoker.getUrl(); @@ -102,10 +100,12 @@ public void afterUnExport() { 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 void afterUnExport() { 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 Invoker refer(Class type, URL url) throws RpcException { 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/call/AbstractServerCall.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/AbstractServerCall.java index 7f687a34856..fb8f516367e 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.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 void setNeedReturnException(boolean needReturnException) { 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 void setNeedReturnException(boolean needReturnException) { 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 @@ private void doSendMessage(Object message) { 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 @@ private void doSendMessage(Object message) { } 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 @@ private void doSendMessage(Object message) { 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 final void onComplete() { // 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 final void onComplete() { @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 final void onCancelByRemote(TriRpcStatus status) { } // stream listener end - public final boolean isClosed() { return closed; } @@ -249,11 +253,13 @@ public final boolean isClosed() { */ 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 @@ protected RpcInvocation buildInvocation(MethodDescriptor methodDescriptor) { 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 @@ private void sendHeader() { 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 void cancelByLocal(Throwable throwable) { 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 void disableAutoRequestN() { autoRequestN = false; } - public boolean isAutoRequestN() { return autoRequestN; } - public void close(TriRpcStatus status, Map attachments) { doClose(status, attachments); } @@ -387,34 +393,34 @@ protected void responseErr(TriRpcStatus status) { } 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 @@ protected ServerCall.Listener startInternalCall( 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 f645a80468c..7fa838d8d75 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 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 AbstractServerCallListener(RpcInvocation invocation, Invoker invoker, 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 void invoke() { } 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 void invoke() { } } - 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 2d3346b5c6e..e37ac9d006c 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 void onCancel(TriRpcStatus status) { 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 d99c8c3bf03..8b0e1be1140 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 @@ interface Listener { * @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 @@ StreamObserver start(RequestMetadata metadata, */ void setAutoRequest(boolean autoRequest); - /** * No more data will be sent. */ @@ -110,5 +107,4 @@ StreamObserver start(RequestMetadata metadata, * @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 f52bf4e8d17..fce504e9582 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 80e7c3cbc9c..4be61a00df8 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.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 @@ private boolean isEcho(String methodName) { } 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 void startCall() { 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 @@ private void trySetListener() { if (isClosed()) { return; } - listener = ReflectionAbstractServerCall.this.startInternalCall(invocation, - methodDescriptor, invoker); + listener = ReflectionAbstractServerCall.this.startInternalCall(invocation, methodDescriptor, invoker); } @Override @@ -163,12 +167,10 @@ protected Object parseSingleMessage(byte[] data) throws Exception { 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 @@ private void trySetMethodDescriptor(byte[] data) { 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 @@ private void trySetMethodDescriptor(byte[] data) { } } 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 @@ private void trySetMethodDescriptor(byte[] data) { @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 45742b9a808..e5bdb365139 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 @@ interface Listener { * @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 c6b42e50e25..8e5ea19caf1 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 @@ 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 void onCancel(TriRpcStatus status) { 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 6f5027abfae..139c42c415a 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 @@ 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 @@ private static ServiceDescriptor getServiceDescriptor(URL url, String serviceNam 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 3673bd5e833..330deaa0bd9 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.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 void onCancelByRemote(TriRpcStatus status) { } @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 void onComplete(TriRpcStatus status, Map attachments, 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 void cancelByLocal(Throwable t) { 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 void request(int messageNumber) { 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 void sendMessage(Object message) { 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 void halfClose() { 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 void setCompression(String compression) { } @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 boolean isAutoRequest() { 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 b08ee0618fa..ca6e0d34bfc 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 void onClose(TriRpcStatus status, Map trailers, boolean i } else { result.setValue(appResponse); } - } else { + } else { result.setException(status.asException()); } result.setAttribute(Constants.CONTENT_LENGTH_KEY, actualContentLength); @@ -59,8 +58,7 @@ public void onClose(TriRpcStatus status, Map trailers, boolean i @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 e53b72079a3..9e6da9158f2 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 void onMessage(Object message, int actualContentLength) { 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 @@ protected void doOnResponseHasException(Throwable t) { } } - private void onReturnException(Exception value) { TriRpcStatus status = TriRpcStatus.getStatus(value); int exceptionCode = status.code.code; @@ -80,5 +81,4 @@ private void onReturnException(Exception value) { 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 eb8b249fd09..1b988f33881 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 static CancelQueueCommand createCommand(TripleStreamChannelFuture streamC 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 7044926bc1d..7c53c589981 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 cbd0a69ac2c..a9ef447abb4 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 void doSend(ChannelHandlerContext ctx, ChannelPromise promise) { } } - // for test public byte[] getData() { return data; @@ -66,5 +66,4 @@ public byte[] getData() { 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 863230b43e9..2164e02b63c 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 7ae2a1777c8..e221b4370b6 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 @@ private HeaderQueueCommand(TripleStreamChannelFuture streamChannelFuture, Http2H 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 fd140a92882..f3fe69a8eb2 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 Channel channel() { 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 2815bdabf74..548b25bc06b 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 ba35504973a..c7da28d42da 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 @@ private TextDataQueueCommand(TripleStreamChannelFuture streamChannelFuture, Stri 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 dbc54be92c6..03c5de55d0c 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,16 @@ * 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; +import java.io.ByteArrayInputStream; + import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream; import org.apache.commons.io.output.ByteArrayOutputStream; -import java.io.ByteArrayInputStream; - - /** * 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 35d7ab80fb6..73282b4b418 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; @@ -50,5 +49,4 @@ static Compressor getCompressor(FrameworkModel frameworkModel, String compressor * @return compressed payload byte array */ byte[] compress(byte[] payloadByteArr); - } 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 aa8c4940404..c6ba092fb08 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 @@ static DeCompressor getCompressor(FrameworkModel frameworkModel, String compress * @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 371b650baed..a6363397ee0 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; @@ -72,5 +71,4 @@ public byte[] decompress(byte[] payloadByteArr) throws RpcException { 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 3d3d32d7882..b9a835ed95e 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; /** 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 cdf2e0907cd..9889be67a4d 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 be5b11fe81f..208f740ec2c 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 66bb9e76e95..59083e9a241 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 5fcfda427d7..6970203cf8c 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 @@ private byte[] getUncompressedBody() { return data; } - private enum GrpcDecodeState { HEADER, PAYLOAD @@ -166,7 +165,5 @@ public interface Listener { void onRawMessage(byte[] data); void close(); - } - } 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 362ab9ed4b6..d7d74dfb882 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 @@ 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 37f17694c38..9f9b0540295 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 boolean isAutoRequestEnabled() { @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 f2ae04ac8cf..f0d84f1939c 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 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 void setNeedReturnException(boolean needReturnException) { 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 boolean isAutoRequestN() { return call.isAutoRequestN(); } - public boolean isTerminated() { return terminated; } @@ -79,8 +75,7 @@ private void setTerminated() { @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 be4fbc8301e..9b8e970803c 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 b1a2659eb62..9217d4ff2d9 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.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 @@ */ 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 void onNext(ServerReflectionRequest request) { 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 void onCompleted() { }; } - 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 @@ private void listServices(ServerReflectionRequest request, } 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 @@ private ServerReflectionResponse createServerReflectionResponse( } } 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 3d37505ae12..0eb6fc68256 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.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 @@ private static void addExtension(FieldDescriptor extension, FileDescriptor fd) { 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 8abfd9de406..b45a40ef069 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.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 void init() { 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 c21e78e1af4..72ebda45bd5 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.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 HealthCheckResponse check(HealthCheckRequest request) { 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 void watch(HealthCheckRequest request, } 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 @@ void enterTerminalState() { 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 e85620703cc..f2f69bb344d 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 42842c5fe3b..304d3c46539 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 @@ interface Listener extends Stream.Listener { * * @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 @@ default void onComplete(TriRpcStatus status, Map attachments) { * @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 @@ default void onComplete(TriRpcStatus status, Map attachments, * @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 0b815253d0e..88f45284d4e 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 @@ interface Listener extends Stream.Listener { * @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 @@ interface Listener extends Stream.Listener { * @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 72b7aec8448..05b55e5224c 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 @@ interface Listener { * @param status the cancel status */ void onCancelByRemote(TriRpcStatus status); - } /** @@ -83,5 +80,4 @@ interface Listener { * @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 07def88303e..593c97424fd 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,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.logger.ErrorTypeAwareLogger; @@ -25,8 +24,6 @@ import org.apache.dubbo.rpc.protocol.tri.TripleConstant; import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum; -import io.netty.handler.codec.http2.DefaultHttp2Headers; - import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Collections; @@ -34,6 +31,8 @@ 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 +42,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 +81,8 @@ public static Map toAttachments(Map origin) { * @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 +112,7 @@ public static void convertAttachment(DefaultHttp2Headers headers, } } - - public static void convertAttachment(DefaultHttp2Headers headers, - Map attachments) { + public static void convertAttachment(DefaultHttp2Headers headers, Map attachments) { convertAttachment(headers, attachments, false); } @@ -137,13 +132,20 @@ private static void convertSingleAttachment(DefaultHttp2Headers headers, String 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 da7ddc45439..8b060ae82df 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.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.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 @@ private TripleStreamChannelFuture initHttp2StreamChannel(Channel parent) { 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 ChannelFuture sendHeader(Http2Headers headers) { } 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 SocketAddress remoteAddress() { 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 @@ H2TransportListener createTransportListener() { 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 @@ void handleH2TransportError(TriRpcStatus status) { 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 @@ void finishProcess(TriRpcStatus status, Http2Headers trailers, boolean isReturnT } 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 @@ void onHeaderReceived(Http2Headers headers) { 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 @@ void onHeaderReceived(Http2Headers headers) { 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 @@ private TriRpcStatus statusFromTrailers(Http2Headers trailers) { 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 @@ private TriRpcStatus getStatusFromTrailers(Map metadata) { // 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 @@ private TriRpcStatus getStatusFromTrailers(Map metadata) { } finally { ClassLoadUtil.switchContextLoader(tccl); } - } - private Map, Object> tranFromStatusDetails(List detailList) { Map, Object> map = new HashMap<>(detailList.size()); try { @@ -433,7 +423,8 @@ public void onHeader(Http2Headers headers, boolean endStream) { 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 void onHeader(Http2Headers headers, boolean endStream) { onHeaderReceived(headers); } }); - } @Override @@ -460,8 +450,7 @@ public void onData(ByteBuf data, boolean endStream) { 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 @@ private void doOnData(ByteBuf data, boolean endStream) { 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 @@ private void doOnData(ByteBuf data, boolean endStream) { @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 88e5cd0b3d0..0aaca484910 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.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.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 ChannelFuture reset(Http2Error cause) { @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 ChannelFuture sendHeader(Http2Headers headers) { 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 Future cancelByLocal(TriRpcStatus status) { 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 @@ private ChannelFuture sendTrailers(Http2Headers trailers) { } 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 @@ private Http2Headers getTrailers(TriRpcStatus rpcStatus, Map att 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 @@ private String getGrpcMessage(TriRpcStatus status) { 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 @@ private void responsePlainTextError(int code, TriRpcStatus status) { 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 @@ private void responsePlainTextError(int code, TriRpcStatus status) { * @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 @@ private ChannelFuture preCheck() { 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 void onHeader(Http2Headers headers, boolean endStream) { 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 @@ private void processHeader(Http2Headers headers, boolean endStream) { 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 @@ private void processHeader(Http2Headers headers, boolean endStream) { 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 void cancelByRemote(long errorCode) { 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 void close() { 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 fc3e152aab0..6c47761cbec 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 5bcec31fdea..fe5c341b206 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.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 @@ protected Map headersToMap(Http2Headers trailers, Supplier 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 @@ protected Map headersToMap(Http2Headers trailers, Supplier filterReservedHeaders(Http2Headers trailers) { if (trailers == null) { return Collections.emptyMap(); @@ -104,5 +106,4 @@ protected Map filterReservedHeaders(Http2Headers trailers) { } 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 5e7090c6c82..29c0b6f44f5 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.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 GracefulShutdown(ChannelHandlerContext ctx, String goAwayMessage, Channel } 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 @@ void secondGoAwayAndClose(ChannelHandlerContext ctx) { 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 3f85317850f..2d6c62e0be4 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 741b3dbfe80..0cfb8bbfd26 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 14e652adf4b..3da48c1d6f0 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 c53e04d6c5d..b8e9230eb50 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 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 void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc 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 @@ protected void channelRead0(ChannelHandlerContext ctx, Http2StreamFrame msg) thr } 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 void channelInactive(ChannelHandlerContext ctx) { @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 4b17e82b291..daebefc3394 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.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 void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc } 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 void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws E 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 void onHeadersRead(ChannelHandlerContext ctx, Http2HeadersFrame msg) thro 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 a2f08ee9f5a..6a2935bd70a 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 @@ -26,7 +26,8 @@ import io.netty.handler.codec.http2.Http2Headers; 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); @@ -42,12 +43,12 @@ protected ServiceKey getServiceKey(Object data) { String path = headers.path().toString(); String[] parts = path.split("/"); // path like /{interfaceName}/{methodName} String interfaceName = parts[1]; - String version = headers.contains(TripleHeaderEnum.SERVICE_VERSION.getHeader()) ? - headers.get(TripleHeaderEnum.SERVICE_VERSION.getHeader()).toString() : null; - String group = headers.contains(TripleHeaderEnum.SERVICE_GROUP.getHeader()) ? - headers.get(TripleHeaderEnum.SERVICE_GROUP.getHeader()).toString() : null; + String version = headers.contains(TripleHeaderEnum.SERVICE_VERSION.getHeader()) + ? headers.get(TripleHeaderEnum.SERVICE_VERSION.getHeader()).toString() + : null; + String group = headers.contains(TripleHeaderEnum.SERVICE_GROUP.getHeader()) + ? headers.get(TripleHeaderEnum.SERVICE_GROUP.getHeader()).toString() + : 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 9703cb287b0..5b027bced35 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,31 +14,31 @@ * 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.DefaultHttp2ResetFrame; -import io.netty.handler.codec.http2.Http2Error; 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; import io.netty.handler.codec.http2.Http2ChannelDuplexHandler; +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 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<>(); @@ -57,7 +57,11 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception 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); } @@ -72,7 +76,7 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception @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 -> { DefaultHttp2ResetFrame resetFrame = new DefaultHttp2ResetFrame(Http2Error.NO_ERROR).stream(stream); ctx.fireChannelRead(resetFrame); 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 b7d1410d50b..7e0742648e7 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 c659e9e7083..7585e9a4849 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 b0125681b80..ff839473b78 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 @@ private void flush() { } } } - } 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 123cbbfd27a..39bc3d0aba5 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 @@ 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 static void unaryCall(Invoker invoker, MethodDescriptor method, 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 @@ private static Object call(Invoker invoker, MethodDescriptor methodDescriptor 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 67ad0b36c9e..712c60d3e85 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 92bad1446d0..0bbc325861a 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 @@ void fromCode() { TriRpcStatus.fromCode(1000); fail(); } catch (Throwable t) { - //pass + // pass } } @@ -51,21 +50,21 @@ void testFromCode() { @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 @@ void limitSizeTo1KB() { @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 @@ void decodeMessage() { @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 @@ void appendDescription() { @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 @@ void toEncodedMessage() { @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 @@ void toMessageWithoutCause() { @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 @@ void fromMessage() { @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 1de8acf0208..06c6fabfc7f 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 @@ public void onCompleted() { } @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 81875ccdc33..28d4f84fd0e 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 09d03513eb2..7de864f3498 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 @@ void test() throws InterruptedException, ExecutionException { 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 51f4d1000e4..7d93565c333 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 @@ 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 598da917f21..34545486708 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.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 @@ void getStackTrace() { @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 @@ void getStackFrameString() { @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 @@ void testSelfDefineException() throws Exception{ // 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 fa03322dc0c..73df537e85c 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 4edb95549f2..81b6e9614ff 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 @@ -52,6 +52,5 @@ void testDetect() { byteBuf.writeBytes(connectionPrefaceBuf, 0, 1); result = detector.detect(new ByteBufferBackedChannelBuffer(byteBuf.nioBuffer())); Assertions.assertEquals(result, ProtocolDetector.Result.NEED_MORE_DATA); - } } 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 919cfae3a14..4a3f6a8e064 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 1eadb5305e5..46c79a9ae8a 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.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 @@ class ReflectionPackableMethodTest { - @Test void testUnaryFuture() throws Exception { Method method = DescriptorService.class.getMethod("unaryFuture"); @@ -115,8 +114,8 @@ void testIsUnary() throws NoSuchMethodException { @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 @@ void testIgnoreMethod() throws NoSuchMethodException { 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 @@ void testDiffParametersAndReturn() throws Exception { @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 @@ public boolean needWrap(MethodDescriptor method) { 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 @@ public boolean needWrap(MethodDescriptor method) { 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 d8fcd939c16..2cbbfbe7249 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 @@ 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 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 @@ void test() throws IOException { 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 227a3cc84c4..f15b69368a6 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 @@ void testRangeViaInt() { @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 @@ void testTripleRequestWrapperBuild() { 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)); - - Assertions.assertArrayEquals(tripleRequestWrapper.toByteArray(), pbbuilder.build().toByteArray()); + .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()); } @Test @@ -90,39 +95,42 @@ void testTripleRequestWrapperParseFrom() { 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)); - - TripleCustomerProtocolWapper.TripleRequestWrapper parseFrom = TripleCustomerProtocolWapper.TripleRequestWrapper.parseFrom(pbbuilder.build().toByteArray()); + .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()); 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 @@ void testTripleResponseWrapperWithNullData() { 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 @@ void testTripleResponseWrapper() { 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 101941423af..a468d9d8155 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.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 @@ void testNewCall() throws NoSuchMethodException { 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 @@ void testNewCall() throws NoSuchMethodException { .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 fc223b11658..5e9d212bf04 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 @@ 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 @@ public boolean isAvailable() { } @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 483897d9713..0887afce9d1 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.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 @@ void testDemoProtocol() throws Exception { 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 @@ void testDemoProtocol() throws Exception { // 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 @@ void testDemoProtocol() throws Exception { 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 501b55f398b..9a5f9b48d53 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 7b379dbcddc..c598305ce62 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.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 @@ void doStartCall() throws NoSuchMethodException { 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 e9570921402..b500e91bbc5 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.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 @@ void doStartCall() throws Exception { 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 723c4b123cd..99490cae731 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 43bb0c701bb..9c10938a5e3 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 dc77255a0de..9c996f3a7ec 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 @@ void getMessageEncoding() { @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 7371f06c625..b611b12664a 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 355d407861b..c9ec2776d23 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 f0f2564b7b6..40e793fcb3f 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 @@ void decode() { 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 0665881ba12..4dfdc3e45b7 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 @@ void getHealthService() { 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 @@ void setStatus() { 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 @@ void clearStatus() { 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 6710fdc1420..d4d45a8e4a4 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 @@ void testDefaultNotEnable() { } @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 faa4b0ace34..11101168e92 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.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 @@ void testCheck() { 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 @@ void testCheck() { 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 @@ void testWatch() throws Exception { // 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 @@ public void onNext(HealthCheckResponse data) { } @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 ac135cf0cd8..4daeea81370 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 void onStart() { } @Override - public void onComplete(TriRpcStatus status, - Map attachments) { + public void onComplete(TriRpcStatus status, Map attachments) { this.status = status; } @@ -44,7 +42,5 @@ public void onMessage(byte[] message, boolean isNeedReturnException) { } @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 544332b22d6..07d08513e0e 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.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 @@ void testConvertAttachment() throws InterruptedException { 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 @@ void testConvertAttachment() throws InterruptedException { 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 0ab866e6ccf..4e6b6f25c92 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.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 @@ void progress() { 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 42a89af7436..85b0865bdfb 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 @@ default CompletableFuture echoAsync(String request) { 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 10f35d27b13..d180a422bbb 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 a76748fb0ac..3e781fe16bf 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 @@ 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 f0b54fa1c65..ad844c329e9 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 void onCompleted() { 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 f21686dbe0c..64aeb265d48 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 ba936e6084e..92d5b3c65cc 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 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 466066383cc..16f838466f2 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 @@ public void init() { @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 40e5c1d84de..22e8452463f 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.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.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 @@ public void init() { 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 @@ void test() throws Exception { 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 @@ void test() throws Exception { 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 @@ void testChunk() throws Exception { 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 9db612a3ef1..c3d92ff237d 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.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 @@ private Result createMockResult(String response) throws Throwable { 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 @@ void unaryCall() { } @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 @@ public void onNext(Object data) { } @Override - public void onError(Throwable throwable) { - } + public void onError(Throwable throwable) {} @Override public void onCompleted() { @@ -144,7 +144,8 @@ public void onCompleted() { 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 @@ public void onNext(Object data) { } @Override - public void onError(Throwable throwable) { - - } + public void onError(Throwable throwable) {} @Override public void onCompleted() { @@ -173,8 +172,7 @@ public void onNext(Object data) { } @Override - public void onError(Throwable throwable) { - } + public void onError(Throwable throwable) {} @Override public void onCompleted() { @@ -193,7 +191,8 @@ public void onCompleted() { 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 @@ public void onNext(Object data) { } @Override - public void onError(Throwable throwable) { - } + public void onError(Throwable throwable) {} @Override public void onCompleted() { @@ -219,5 +217,4 @@ public void onCompleted() { 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 752b6c560ca..14fe5010206 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 f76044ced27..dca58b1feb7 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 9dda745b0d6..00bb5f8486d 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 bff98424444..b0ccb0fd04b 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 6d7f4fabe86..6e290850680 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 byte readByte() throws IOException { return target.readByte(); } catch (Exception e) { throw handleToIOException(e); - } } @@ -91,7 +89,6 @@ public short readShort() throws IOException { return target.readShort(); } catch (Exception e) { throw handleToIOException(e); - } } @@ -101,7 +98,6 @@ public int readInt() throws IOException { return target.readInt(); } catch (Exception e) { throw handleToIOException(e); - } } @@ -111,7 +107,6 @@ public long readLong() throws IOException { return target.readLong(); } catch (Exception e) { throw handleToIOException(e); - } } @@ -359,5 +354,4 @@ private static IOException handleToIOException(Exception e) { } 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 55b67fcad6f..3bafedfbca8 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 853334f925a..34a54dc7845 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 20b189fd5d2..3681c811e5f 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 @@ default void writeEvent(String data) throws IOException { 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 d0314c576de..6ecca8d441c 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 ed0c445562a..9ad234f9674 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 SerializationException(String msg) { 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 86c08257eab..d7cb4a6e84d 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 591ba0e1b04..47cab4996b0 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 @@ */ 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 736bd1fc2ca..432de6f89d1 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 6b19a110ee6..a167ea3983c 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 @@ 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 byte[] readBytes() throws IOException { 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 T readObject(Class cls) throws IOException { 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 T readObject(Class cls, Type type) throws IOException, ClassNotFou 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 @@ private int readLength() throws IOException { 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 025e7a603f2..f596b8db4a6 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 void writeObject(Object obj) throws IOException { 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 @@ private void writeLength(int value) throws IOException { 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 47ce0e17083..39ee568f423 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 String getContentType() { @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 ObjectOutput serialize(URL url, OutputStream output) throws IOException { @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 8168aee13fa..4db5944ee29 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 @@ -19,13 +19,13 @@ import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ScopeClassLoaderListener; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + 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; - public class Fastjson2CreatorManager implements ScopeClassLoaderListener { /** 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 db256cce384..520d9465be1 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 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-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 1c1258af559..d155fabe1b2 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.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 @@ 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 static class Handler extends ContextAutoTypeBeforeHandler { 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 apply(String typeName, Class expectClass, long features) { // 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 apply(String typeName, Class expectClass, long features) { // 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 loadClassDirectly(String typeName) { 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 loadClassDirectly(String typeName) { 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 4a9dc6eb0a1..5c64491b955 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.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.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 @@ void testReadString() throws IOException { @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 @@ void testReadEvent() throws IOException, ClassNotFoundException { @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 @@ void testReadByte() throws IOException { @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 @@ void testReadObject() throws IOException, ClassNotFoundException { { 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 @@ void testReadObject() throws IOException, ClassNotFoundException { { 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 @@ void testReadObject() throws IOException, ClassNotFoundException { { 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 @@ void testReadObject() throws IOException, ClassNotFoundException { { 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 @@ void testReadObject() throws IOException, ClassNotFoundException { @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 @@ void testReadObjectNotMatched() throws IOException, ClassNotFoundException { { 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 @@ void testReadObjectNotMatched() throws IOException, ClassNotFoundException { { 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 @@ void testReadObjectNotMatched() throws IOException, ClassNotFoundException { { 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 @@ void testReadObjectNotMatched() throws IOException, ClassNotFoundException { { 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 @@ void testReadObjectNotMatched() throws IOException, ClassNotFoundException { { 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 @@ void testReadObjectNotMatched() throws IOException, ClassNotFoundException { { 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 @@ void testReadObjectNotMatched() throws IOException, ClassNotFoundException { { 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 @@ void testReadObjectNotMatched() throws IOException, ClassNotFoundException { @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 @@ void testLimit4() 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); 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 @@ void testLimit4() 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); 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 @@ void testLimit5() 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); - 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 @@ void testLimit5() 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); 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 974f685a2a9..21f4622f391 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.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.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 @@ public Stream provideArguments(ExtensionContext extensionCo 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 @@ public Stream provideArguments(ExtensionContext extensionCo 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 @@ public Stream provideArguments(ExtensionContext extensionCo @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 99a966ca6c9..49728e18f42 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 13b0b2462db..5387607d964 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 void onAddClassLoader(FrameworkModel scopeModel, ClassLoader classLoader) @Override public void onRemoveClassLoader(FrameworkModel scopeModel, ClassLoader classLoader) { - Hessian2FactoryManager hessian2FactoryManager = scopeModel.getBeanFactory().getBean(Hessian2FactoryManager.class); + Hessian2FactoryManager hessian2FactoryManager = + scopeModel.getBeanFactory().getBean(Hessian2FactoryManager.class); hessian2FactoryManager.onRemoveClassLoader(classLoader); } } diff --git a/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2FactoryManager.java b/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2FactoryManager.java index dbd595bcd59..ac342926600 100644 --- a/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2FactoryManager.java +++ b/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2FactoryManager.java @@ -23,10 +23,9 @@ import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.model.FrameworkModel; -import com.alibaba.com.caucho.hessian.io.SerializerFactory; - import java.util.concurrent.ConcurrentHashMap; +import com.alibaba.com.caucho.hessian.io.SerializerFactory; public class Hessian2FactoryManager { String WHITELIST = "dubbo.application.hessian2.whitelist"; @@ -41,7 +40,8 @@ public class Hessian2FactoryManager { public Hessian2FactoryManager(FrameworkModel frameworkModel) { serializeSecurityManager = frameworkModel.getBeanFactory().getOrRegisterBean(SerializeSecurityManager.class); - defaultSerializeClassChecker = frameworkModel.getBeanFactory().getOrRegisterBean(DefaultSerializeClassChecker.class); + defaultSerializeClassChecker = + frameworkModel.getBeanFactory().getOrRegisterBean(DefaultSerializeClassChecker.class); } public SerializerFactory getSerializerFactory(ClassLoader classLoader) { @@ -63,8 +63,8 @@ public SerializerFactory getSerializerFactory(ClassLoader classLoader) { return SYSTEM_SERIALIZER_FACTORY; } - SerializerFactory factory = ConcurrentHashMapUtils.computeIfAbsent(CL_2_SERIALIZER_FACTORY, - classLoader, this::createSerializerFactory); + SerializerFactory factory = ConcurrentHashMapUtils.computeIfAbsent( + CL_2_SERIALIZER_FACTORY, classLoader, this::createSerializerFactory); stickySerializerFactory = factory; return factory; } @@ -79,8 +79,10 @@ private SerializerFactory createSerializerFactory(ClassLoader classLoader) { } private SerializerFactory createDefaultSerializerFactory(ClassLoader classLoader) { - Hessian2SerializerFactory hessian2SerializerFactory = new Hessian2SerializerFactory(classLoader, defaultSerializeClassChecker); - hessian2SerializerFactory.setAllowNonSerializable(Boolean.parseBoolean(System.getProperty("dubbo.hessian.allowNonSerializable", "false"))); + Hessian2SerializerFactory hessian2SerializerFactory = + new Hessian2SerializerFactory(classLoader, defaultSerializeClassChecker); + hessian2SerializerFactory.setAllowNonSerializable( + Boolean.parseBoolean(System.getProperty("dubbo.hessian.allowNonSerializable", "false"))); hessian2SerializerFactory.getClassFactory().allow("org.apache.dubbo.*"); return hessian2SerializerFactory; } @@ -108,7 +110,8 @@ public SerializerFactory createWhiteListSerializerFactory(ClassLoader classLoade } } } - serializerFactory.setAllowNonSerializable(Boolean.parseBoolean(System.getProperty("dubbo.hessian.allowNonSerializable", "false"))); + serializerFactory.setAllowNonSerializable( + Boolean.parseBoolean(System.getProperty("dubbo.hessian.allowNonSerializable", "false"))); serializerFactory.getClassFactory().allow("org.apache.dubbo.*"); return serializerFactory; } diff --git a/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ObjectInput.java b/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ObjectInput.java index f345621cc02..302c78a7119 100644 --- a/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ObjectInput.java +++ b/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ObjectInput.java @@ -20,12 +20,12 @@ import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.rpc.model.FrameworkModel; -import com.alibaba.com.caucho.hessian.io.Hessian2Input; - import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Type; +import com.alibaba.com.caucho.hessian.io.Hessian2Input; + /** * Hessian2 object input implementation */ @@ -36,14 +36,17 @@ public class Hessian2ObjectInput implements ObjectInput, Cleanable { @Deprecated public Hessian2ObjectInput(InputStream is) { mH2i = new Hessian2Input(is); - this.hessian2FactoryManager = FrameworkModel.defaultModel().getBeanFactory().getOrRegisterBean(Hessian2FactoryManager.class); - mH2i.setSerializerFactory(hessian2FactoryManager.getSerializerFactory(Thread.currentThread().getContextClassLoader())); + this.hessian2FactoryManager = + FrameworkModel.defaultModel().getBeanFactory().getOrRegisterBean(Hessian2FactoryManager.class); + mH2i.setSerializerFactory(hessian2FactoryManager.getSerializerFactory( + Thread.currentThread().getContextClassLoader())); } public Hessian2ObjectInput(InputStream is, Hessian2FactoryManager hessian2FactoryManager) { mH2i = new Hessian2Input(is); this.hessian2FactoryManager = hessian2FactoryManager; - mH2i.setSerializerFactory(hessian2FactoryManager.getSerializerFactory(Thread.currentThread().getContextClassLoader())); + mH2i.setSerializerFactory(hessian2FactoryManager.getSerializerFactory( + Thread.currentThread().getContextClassLoader())); } @Override @@ -93,26 +96,34 @@ public String readUTF() throws IOException { @Override public Object readObject() throws IOException { - 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 mH2i.readObject(); } @Override @SuppressWarnings("unchecked") - public 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 InputStream readInputStream() throws IOException { @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 27c1ebd91d5..7468b095f7e 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.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 OutputStream getOutputStream() throws IOException { @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 a86b39bdb8f..41ee9b5fa99 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 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-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 1156c155130..4263d3de0e5 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 String getContentType() { @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 b6bf38fbe08..e8138942929 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 @@ 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 loadSerializedClass(String className) throws ClassNotFoundExcept @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 @@ private void checkSerializable(Class cl) { // 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 e94f41b3509..93dc9d1185e 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.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.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 @@ void testReadString() throws IOException { @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 @@ void testReadEvent() throws IOException, ClassNotFoundException { @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 @@ void testReadByte() throws IOException { @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 @@ void testReadObject() throws IOException, ClassNotFoundException { { 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 @@ void testReadObject() throws IOException, ClassNotFoundException { { 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 @@ void testReadObject() throws IOException, ClassNotFoundException { { 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 @@ void testReadObject() throws IOException, ClassNotFoundException { { 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 @@ void testReadObject() throws IOException, ClassNotFoundException { @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 @@ void testReadObjectNotMatched() throws IOException, ClassNotFoundException { { 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 @@ void testReadObjectNotMatched() throws IOException, ClassNotFoundException { { 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 @@ void testReadObjectNotMatched() throws IOException, ClassNotFoundException { { 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 @@ void testReadObjectNotMatched() throws IOException, ClassNotFoundException { { 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 @@ void testReadObjectNotMatched() throws IOException, ClassNotFoundException { { 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 @@ void testReadObjectNotMatched() throws IOException, ClassNotFoundException { { 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 @@ void testReadObjectNotMatched() throws IOException, ClassNotFoundException { { 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 @@ void testReadObjectNotMatched() throws IOException, ClassNotFoundException { @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 @@ void testLimit1() throws IOException, ClassNotFoundException { @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 @@ void testLimit2() throws IOException, ClassNotFoundException { @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 @@ void testLimit4() 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); 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 @@ void testLimit4() 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); 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 @@ void testLimit5() throws IOException, ClassNotFoundException { { 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 @@ void testLimit5() 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); 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 b155981be7f..6fcf10e6da1 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,20 +22,10 @@ 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 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; @@ -43,6 +33,13 @@ 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 @@ -71,24 +68,32 @@ public Stream provideArguments(ExtensionContext extensionCo 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 @@ public Stream provideArguments(ExtensionContext extensionCo 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 @@ public Stream provideArguments(ExtensionContext extensionCo @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 7058dbde4a6..3c9fe679dc5 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 2df9db1aa2a..b87e75c006a 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 ObjectOutput serialize(URL url, OutputStream out) throws IOException { 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 2eaf7af6abb..045fec3b146 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 b7a32942c7b..bbdd02ffaf8 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 Object readObject() throws IOException, ClassNotFoundException { @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 T readObject(Class cls) throws IOException, 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 4626ece767f..1962ab41233 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 String getContentType() { @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 ObjectOutput serialize(URL url, OutputStream out) throws IOException { @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 c791250f7af..74431832ff5 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 byte[] readBytes() throws IOException { 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 2ff82f76c36..a3274094db6 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 2e6e493b914..ea37e998a8a 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 String getContentType() { @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 ObjectOutput serialize(URL url, OutputStream output) throws IOException { @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 dbfa18c2882..0fed5f14fc0 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 88c25d4e3bd..b0009455083 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-actuator/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-actuator/pom.xml @@ -15,142 +15,140 @@ 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 - - dubbo-spring-boot-actuator - jar - Apache Dubbo Spring Boot Actuator - - - - - org.apache.dubbo - dubbo-spring-boot-actuator-compatible - ${project.version} - - - - - org.springframework.boot - spring-boot-starter-web - true - - - - org.apache.logging.log4j - log4j-api - - - - - org.apache.logging.log4j - log4j-api - ${log4j2_version} - true - - - - org.springframework.boot - spring-boot-starter-actuator - true - - - - org.springframework.boot - spring-boot-autoconfigure - true - - - - - org.apache.dubbo - dubbo-spring-boot-autoconfigure - ${project.version} - - - - - org.apache.dubbo - dubbo - ${project.version} - - - - org.apache.dubbo - dubbo-common - ${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-serialization-hessian2 - ${project.version} - true - - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${revision} - true - - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - true - - - - - org.springframework.boot - spring-boot-starter-test - test - - - - org.apache.logging.log4j - log4j-api - - - - - - org.junit.platform - junit-platform-runner - test - - - org.apache.dubbo - dubbo-metrics-default - ${project.version} - - - + + 4.0.0 + + org.apache.dubbo + dubbo-spring-boot + ${revision} + ../pom.xml + + + dubbo-spring-boot-actuator + jar + Apache Dubbo Spring Boot Actuator + + + + + org.apache.dubbo + dubbo-spring-boot-actuator-compatible + ${project.version} + + + + + org.springframework.boot + spring-boot-starter-web + true + + + + org.apache.logging.log4j + log4j-api + + + + + org.apache.logging.log4j + log4j-api + ${log4j2_version} + true + + + + org.springframework.boot + spring-boot-starter-actuator + true + + + + org.springframework.boot + spring-boot-autoconfigure + true + + + + + org.apache.dubbo + dubbo-spring-boot-autoconfigure + ${project.version} + + + + + org.apache.dubbo + dubbo + ${project.version} + + + + org.apache.dubbo + dubbo-common + ${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-serialization-hessian2 + ${project.version} + true + + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${revision} + true + + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.version} + true + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.apache.logging.log4j + log4j-api + + + + + + 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 c1e66cd6544..bad49280bad 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 DubboServicesMetadataEndpoint dubboServicesMetadataEndpoint() { 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 0543547cd68..88b05d4ef0b 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.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 77b1e2080cb..70fff635dc6 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 @@ 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 fb35b7f08f0..3eb816d17af 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 @@ 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 8105e330111..d14207c1747 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 @@ 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 f2497da3f36..77abd35f46f 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.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 845dbc1f3f0..5ee1b41d22f 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.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 9565e849794..4b1a8f5ed53 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 @@ 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 3c1bc1e1cb0..5d8078fa325 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 0c76ea76058..d5308c5680c 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 @@ */ 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 @@ public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) 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 dbb8ce349ca..85f5c27ce4e 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 e90122fbe86..1999808e7b9 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.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.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 @@ @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 @@ void testShutdown() throws Exception { Assert.assertEquals(1, shutdownCounts.get("protocols")); Assert.assertEquals(1, shutdownCounts.get("services")); Assert.assertEquals(0, shutdownCounts.get("references")); - } @Test @@ -141,7 +140,8 @@ void testConfigs() { 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 @@ void testConfigs() { beansMetadata = configsMap.get("ServiceConfig"); Assert.assertFalse(beansMetadata.isEmpty()); - } @Test @@ -179,10 +178,10 @@ void testServices() { 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 @@ void testReferences() { 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 @@ void testProperties() { 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 @@ private void testHttpEndpoint(String actuatorURI, Supplier resultsSupplier) Assert.assertEquals(objectMapper.writeValueAsString(resultsSupplier.get()), response); } - interface DemoService { String sayHello(String name); } @@ -242,14 +246,12 @@ interface DemoService { 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 @@ static class ConsumerConfiguration { @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 87dfb6333b9..0aea4fc7a80 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 @@ 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.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 @@ */ @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 @@ void testInvoke() { 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 392ecb89e4b..cc0687479e0 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/pom.xml @@ -15,85 +15,82 @@ 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.apache.logging.log4j + log4j-api + + + - - org.springframework.boot - spring-boot-starter-logging - true - - - - org.apache.logging.log4j - log4j-api - - - + + + 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.apache.logging.log4j + log4j-api + + + - - - org.springframework.boot - spring-boot-starter-test - test - - - - org.apache.logging.log4j - log4j-api - - - - - + 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 3da5f0b4100..361c5499358 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 @@ 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.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 @@ 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 @@ public void bind(Map configurationProperties, boolean ignoreUnkn // 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 @@ public void bind(Map configurationProperties, boolean ignoreUnkn 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 8e3454937f2..8883a94464a 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 @@ 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.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 PropertyResolver dubboScanBasePackagesPropertyResolver(ConfigurableEnviro 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 Set dubboBasePackages(ConfigurableEnvironment environment) { 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 807a0c49061..f9132ef6897 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.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.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; -import java.util.Map; - import static com.alibaba.spring.util.PropertySourcesUtils.getSubProperties; /** @@ -69,4 +69,4 @@ void testBinder() { 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 df418da7318..15995be3add 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.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.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 @@ * {@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 3adb6f17e33..cb9963777de 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.PropertySource; import org.springframework.mock.env.MockEnvironment; -import java.util.HashMap; - /** * {@link DubboDefaultPropertiesEnvironmentPostProcessor} Test */ @@ -94,4 +94,4 @@ void testPostProcessEnvironment() { 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 66f157f0b54..c0125dd087a 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/pom.xml @@ -15,100 +15,98 @@ 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 - - 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.apache.tomcat.embed - tomcat-embed-core - true - - - - org.springframework.boot - spring-boot-starter-actuator - true - - - - org.springframework.boot - spring-boot-autoconfigure - true - - - - - org.springframework.boot - spring-boot-configuration-processor - true - - - - - org.apache.dubbo - dubbo-spring-boot-autoconfigure-compatible - ${project.version} - - - - org.apache.dubbo - dubbo - ${project.version} - - - - org.apache.dubbo - dubbo-common - ${project.version} - true - - - - org.apache.dubbo - dubbo-config-spring - ${project.version} - true - - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - test - - - - - org.springframework.boot - spring-boot-starter-test - test - - - - org.apache.logging.log4j - log4j-api - - - - - + + 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 + + + + + org.springframework.boot + spring-boot-starter-web + true + + + + org.apache.tomcat.embed + tomcat-embed-core + true + + + + org.springframework.boot + spring-boot-starter-actuator + true + + + + org.springframework.boot + spring-boot-autoconfigure + true + + + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + + org.apache.dubbo + dubbo-spring-boot-autoconfigure-compatible + ${project.version} + + + + org.apache.dubbo + dubbo + ${project.version} + + + + org.apache.dubbo + dubbo-common + ${project.version} + true + + + + org.apache.dubbo + dubbo-config-spring + ${project.version} + true + + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.version} + test + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.apache.logging.log4j + log4j-api + + + + + 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 92a9ba0aa9a..0357b000bbd 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 @@ * @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 fa754d6a32a..32c0bd003dc 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 @@ /** * 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 c5bcd792c94..ed029875521 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 @@ * @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 b3cdabdc430..e879d09a3ca 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 @@ * @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 375902d5fff..5d9f0267bb9 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 5154d27c422..5a3f332dd61 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.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.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 @@ private static boolean isSimpleType(Class type) { || type == BigInteger.class || type == Date.class || type == URL.class - || type == Class.class - ; + || type == Class.class; } @Override @@ -97,7 +96,6 @@ protected Map resolveBeanMetadata(final Object bean) { beanMetadata.put(name, value); } } - } } catch (Exception e) { @@ -105,7 +103,6 @@ protected Map resolveBeanMetadata(final Object bean) { } return beanMetadata; - } protected Map getServiceBeansMap() { @@ -119,6 +116,4 @@ protected ReferenceAnnotationBeanPostProcessor getReferenceAnnotationBeanPostPro 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 5df03b403e9..5ddf3409785 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.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 Map>> configs() { 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 @@ private void addDubboConfigBeans(Class dubboConfigClas 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 77093478a78..f14e1e70335 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 @@ 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 5e3d4c43859..de9f146e3c5 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 7c51ccf2a75..d7130664d1e 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.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 Map> references() { referencesMetadata.putAll(buildReferencesMetadata(beanPostProcessor.getInjectedMethodReferenceBeanMap())); return referencesMetadata; - } private Map> buildReferencesMetadata( @@ -64,17 +63,15 @@ private Map> buildReferencesMetadata( 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 11ce4d567a7..44b63794d11 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 @@ 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 Map> services() { } servicesMetadata.put(serviceBeanName, serviceBeanMetadata); - } return servicesMetadata; - } private Object resolveServiceBean(String serviceBeanName, ServiceBean serviceBean) { @@ -74,11 +72,8 @@ private Object resolveServiceBean(String serviceBeanName, ServiceBean serviceBea 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 bdbd12590cb..8430108abd0 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.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 Map shutdown() throws Exception { 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 Map shutdown() throws Exception { 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 965de4d2559..6af90514182 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.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.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 DubboMvcEndpoint(DubboEndpoint dubboEndpoint) { 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 135ef96f8f1..14d5ba10967 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.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 @@ protected void doHealthCheck(Health.Builder builder) throws Exception { detail.put("status", status); builder.withDetail(statusCheckerName, detail); - } - - } /** @@ -122,33 +119,27 @@ protected Map resolveStatusCheckerNamesMap() { 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 @@ private Map resolveStatusCheckerNamesMapFromProtocolConfigs() { String source = buildSource(beanName, protocolConfig); statusCheckerNamesMap.put(statusCheckerName, source); - } - } return statusCheckerNamesMap; - } private Map resolveStatusCheckerNamesMapFromProviderConfig() { @@ -203,13 +191,10 @@ private Map resolveStatusCheckerNamesMapFromProviderConfig() { String source = buildSource(beanName, providerConfig); statusCheckerNamesMap.put(statusCheckerName, source); - } - } return statusCheckerNamesMap; - } private Set getStatusCheckerNames(ProtocolConfig protocolConfig) { @@ -225,5 +210,4 @@ private Set getStatusCheckerNames(ProviderConfig providerConfig) { 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 0bc1082ed7d..b0ba917dd3a 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 @@ 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 void setExtras(Set extras) { 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 e22741b872a..925b582c5a5 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.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.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 @@ */ @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 void testShutdown() throws Exception { Assert.assertEquals(1, shutdownCounts.get("protocols")); Assert.assertEquals(1, shutdownCounts.get("services")); Assert.assertEquals(0, shutdownCounts.get("references")); - } @Test @@ -128,7 +124,8 @@ public void testConfigs() { 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 void testConfigs() { beansMetadata = configsMap.get("ServiceConfig"); Assert.assertFalse(beansMetadata.isEmpty()); - } @Test @@ -166,10 +162,10 @@ public void testServices() { 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 void testReferences() { Map> references = dubboReferencesMetadata.references(); Assert.assertTrue(references.isEmpty()); - } @Test @@ -197,12 +192,13 @@ public void testProperties() { 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 @@ private void testHttpEndpoint(String actuatorURI, Supplier resultsSupplier) Assert.assertEquals(objectMapper.writeValueAsString(resultsSupplier.get()), response); } - interface DemoService { String sayHello(String name); } @@ -224,15 +219,11 @@ interface DemoService { 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 130e21e8d87..c785cf8ac45 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 @@ 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.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; -import java.util.Map; - /** * {@link DubboHealthIndicator} Test * @@ -38,24 +38,20 @@ * @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 void testResolveStatusCheckerNamesMap() { 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 void testHealth() { 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 da3174cc7d6..45fd459c6bc 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/pom.xml @@ -15,88 +15,86 @@ 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.apache.logging.log4j - log4j-api - - - + + org.springframework.boot + spring-boot-starter-logging + true + + + + org.apache.logging.log4j + log4j-api + + + - - - org.springframework.boot - spring-boot-configuration-processor - true - + + + org.springframework.boot + spring-boot-configuration-processor + 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.springframework.boot - spring-boot-starter-test - test - - - - org.apache.logging.log4j - log4j-api - - - + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.apache.logging.log4j + log4j-api + + + - + 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 05ed8ffdf63..0c2345cc7b3 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,8 @@ import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationPostProcessor; import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfig; +import java.util.Set; + import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; @@ -30,8 +32,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -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; @@ -62,9 +62,8 @@ 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) { return new ServiceAnnotationPostProcessor(packagesToScan); } - } 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 ff8fdda5a85..b3c18c681d2 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 @@ -31,14 +31,14 @@ import org.apache.dubbo.config.spring.ConfigCenterBean; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.context.properties.NestedConfigurationProperty; - import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.NestedConfigurationProperty; + import static org.apache.dubbo.spring.boot.util.DubboUtils.DEFAULT_MULTIPLE_CONFIG_PROPERTY_VALUE; import static org.apache.dubbo.spring.boot.util.DubboUtils.DEFAULT_OVERRIDE_CONFIG_PROPERTY_VALUE; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; 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 fdd3209362d..560ae96f47f 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.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 Set dubboBasePackages(Environment environment) { 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 40bc2270473..cecfc1dcde9 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 @@ 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 @@ 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 94592a9ee30..dee05c07cc1 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.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.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 @@ * @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 Object postProcessBeforeInitialization(Object bean, String beanName) thro // 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 56f78b99700..805b423a3c9 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 @@ private void overrideBeanDefinitions(ConfigurableApplicationContext applicationC 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 3f2fd415db6..bd3a7e5de62 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.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.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 @@ */ 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 @@ private void releaseOnExit(ConfigurableApplicationContext applicationContext) { 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 d9c7d4cf5c3..2e5c4fe9ffc 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 @@ 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.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 @@ * @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 @@ private BeanDefinitionRegistry getBeanDefinitionRegistry(ApplicationContext appl 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 @@ private void resolveUniqueApplicationConfigBean(BeanDefinitionRegistry registry, // 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 4ff84fc44b7..4d511307d42 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 @@ * @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 @@ String buildBannerText() { bannerTextBuilder .append(LINE_SEPARATOR) .append(LINE_SEPARATOR) - .append(" :: Dubbo (v").append(Version.getVersion()).append(") : ") + .append(" :: Dubbo (v") + .append(Version.getVersion()) + .append(") : ") .append(DUBBO_GITHUB_URL) .append(LINE_SEPARATOR) .append(" :: Discuss group : ") .append(DUBBO_MAILING_LIST) - .append(LINE_SEPARATOR) - ; + .append(LINE_SEPARATOR); return bannerTextBuilder.toString(); - } - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/env/DubboDefaultPropertiesEnvironmentPostProcessor.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/env/DubboDefaultPropertiesEnvironmentPostProcessor.java index adeb94b1f6a..d60c2b5da1c 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/env/DubboDefaultPropertiesEnvironmentPostProcessor.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/env/DubboDefaultPropertiesEnvironmentPostProcessor.java @@ -16,6 +16,10 @@ */ package org.apache.dubbo.spring.boot.env; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + import org.springframework.boot.SpringApplication; import org.springframework.boot.env.EnvironmentPostProcessor; import org.springframework.context.ConfigurableApplicationContext; @@ -28,10 +32,6 @@ import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_APPLICATION_NAME_PROPERTY; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_CONFIG_MULTIPLE_PROPERTY; import static org.apache.dubbo.spring.boot.util.DubboUtils.SPRING_APPLICATION_NAME_PROPERTY; @@ -52,7 +52,8 @@ public class DubboDefaultPropertiesEnvironmentPostProcessor implements Environme * The property name of "spring.main.allow-bean-definition-overriding". * Please refer to: https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.1-Release-Notes#bean-overriding */ - public static final String ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY = "spring.main.allow-bean-definition-overriding"; + public static final String ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY = + "spring.main.allow-bean-definition-overriding"; @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { @@ -87,8 +88,6 @@ private void setDubboConfigMultipleProperty(Map defaultPropertie defaultProperties.put(DUBBO_CONFIG_MULTIPLE_PROPERTY, Boolean.TRUE.toString()); } - - /** * Set {@link #ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY "spring.main.allow-bean-definition-overriding"} to be * true as default. @@ -107,14 +106,13 @@ private void setAllowBeanDefinitionOverriding(Map defaultPropert * @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 46d7291b9d8..dc7f6f9b916 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.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 e01131891f5..bde1d9c014f 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 @@ @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 ac7ab815824..ced20cf1172 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 @@ -36,11 +36,9 @@ * @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 { @@ -56,7 +54,8 @@ public void testBeans() { 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 c0d3e6282f4..746b759c7c6 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 @@ -38,9 +38,9 @@ * @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 { @@ -64,7 +64,8 @@ public void destroy() { 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 b0fc8accf28..147e2576ae0 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.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.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 @@ @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 void destroy() { @Test public void testMultipleDubboConfigBindingProperties() { - Assert.assertEquals(1, applications.size()); Assert.assertEquals(1, modules.size()); @@ -177,7 +171,6 @@ public void testMultipleDubboConfigBindingProperties() { Assert.assertEquals(1, providers.size()); Assert.assertEquals(1, consumers.size()); - } @Test @@ -186,7 +179,8 @@ public void testApplicationContext() { /** * 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 void testApplicationContext() { /** * 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 void testApplicationContext() { 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 void testProtocolConfig() { 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 db6d5a98c2b..2cfc203543f 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 @@ @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 void destroy() { 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 void testProtocolConfig() { 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 aebfb95debc..d79c3b27c5c 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.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.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 void testBinder() { 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 7975d4787be..6e4823ce1c4 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 void after() { 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 70f5e573d30..635b9f2b523 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.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.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 void testNormalCase() { @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 void testDuplicatedConfigsCase() { } @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 c006a7553e1..893ed17e0e5 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 @@ * @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 56642875d2a..b17c1af6346 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.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 bbcb245081a..b7598d03135 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 void testConstants() { Assert.assertTrue(DEFAULT_MULTIPLE_CONFIG_PROPERTY_VALUE); Assert.assertTrue(DEFAULT_OVERRIDE_CONFIG_PROPERTY_VALUE); - - } - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-compatible/pom.xml index baeaaa40fe0..67fce72cb26 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/pom.xml @@ -15,66 +15,63 @@ 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 + - - autoconfigure - actuator - + + 1.5.22.RELEASE + - + - - - spring-boot-1.4 - - 1.4.7.RELEASE - - - - jdk15ge-simple - - [15, - - - - - org.apache.maven.plugins - maven-surefire-plugin - - true - once - ${argline} ${jacocoArgLine} + + + spring-boot-1.4 + + 1.4.7.RELEASE + + + + jdk15ge-simple + + [15, + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + once + ${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-starter/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-starter/pom.xml index b510c64bc6b..74be57a12ea 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starter/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-starter/pom.xml @@ -15,48 +15,45 @@ 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.apache.logging.log4j + log4j-api + + + + + org.apache.logging.log4j + log4j-api + ${log4j2_version} + true + - - - - org.springframework.boot - spring-boot-starter - true - - - - org.apache.logging.log4j - log4j-api - - - - - org.apache.logging.log4j - log4j-api - ${log4j2_version} - 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 7f4df2957a4..49ea3b67beb 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 - - + + + com.alibaba.nacos + nacos-client + + - \ No newline at end of file + 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 e6e6c6ab918..54131944814 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,101 +15,99 @@ ~ 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} - - - io.netty - netty-handler - - - io.netty - netty-transport-native-epoll - - - + + org.apache.zookeeper + parent + ${zookeeper_version} + pom + import + + + - - com.github.spotbugs - spotbugs-annotations - true - + + + org.apache.curator + curator-x-discovery + ${curator5_version} + + + org.apache.zookeeper + zookeeper + ${zookeeper_version} + + + io.netty + netty-handler + + + io.netty + netty-transport-native-epoll + + + - - commons-cli - commons-cli - + + com.github.spotbugs + spotbugs-annotations + true + - - org.eclipse.jetty - jetty-server - + + commons-cli + commons-cli + - - org.eclipse.jetty - jetty-servlet - + + org.eclipse.jetty + jetty-server + - - org.eclipse.jetty - jetty-client - + + org.eclipse.jetty + jetty-servlet + - - jline - jline - + + org.eclipse.jetty + jetty-client + - - io.dropwizard.metrics - metrics-core - + + jline + jline + - - org.xerial.snappy - snappy-java - - + + io.dropwizard.metrics + metrics-core + + + + org.xerial.snappy + snappy-java + + - \ No newline at end of file + 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 189443c4404..ed854501a78 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,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-zookeeper-spring-boot-starter + + 4.0.0 + + org.apache.dubbo + dubbo-spring-boot-starters ${revision} - jar - Apache Dubbo Zookeeper Spring Boot Starter + ../pom.xml + + + dubbo-zookeeper-spring-boot-starter + ${revision} + jar + Apache Dubbo Zookeeper Spring Boot Starter - - + - - - org.apache.curator - curator-x-discovery - - - org.apache.zookeeper - zookeeper - - + + + org.apache.curator + curator-x-discovery + + + org.apache.zookeeper + zookeeper + + - \ No newline at end of file + 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 b9e13695564..784ffca1242 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,138 +15,136 @@ See the License for the specific language governing permissions and limitations under the License. --> - - - dubbo-spring-boot-observability-starters - org.apache.dubbo - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-spring-boot-observability-starters + ${revision} + ../pom.xml + - dubbo-spring-boot-observability-autoconfigure + dubbo-spring-boot-observability-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-common + ${project.version} + true + + + org.apache.dubbo + dubbo-spring-boot-starter + ${project.version} + + + org.apache.dubbo + dubbo-qos + ${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 4c8adef1e32..f864906d319 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 @@ * 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 io.micrometer.tracing.handler.DefaultTracingObservationHandler defaultTra @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 io.micrometer.tracing.handler.PropagatingSenderTracingObservationHandler< @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 37f552fadff..6710b41a563 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 @@ -22,6 +22,8 @@ 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; @@ -37,19 +39,18 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -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, SmartInitializingSingleton { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(QosProtocolWrapper.class); - public DubboObservationAutoConfiguration(ApplicationModel applicationModel) { this.applicationModel = applicationModel; } @@ -66,10 +67,12 @@ io.micrometer.observation.ObservationRegistry observationRegistry() { } @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); } @@ -81,7 +84,9 @@ public void setBeanFactory(BeanFactory beanFactory) throws BeansException { @Override public void afterSingletonsInstantiated() { try { - applicationModel.getBeanFactory().registerBean(beanFactory.getBean(io.micrometer.observation.ObservationRegistry.class)); + applicationModel + .getBeanFactory() + .registerBean(beanFactory.getBean(io.micrometer.observation.ObservationRegistry.class)); io.micrometer.tracing.Tracer bean = beanFactory.getBean(io.micrometer.tracing.Tracer.class); applicationModel.getBeanFactory().registerBean(bean); } catch (NoSuchBeanDefinitionException e) { @@ -92,21 +97,23 @@ public void afterSingletonsInstantiated() { @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 @@ -114,21 +121,25 @@ static class OnlyTracingConfiguration { 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) @@ -142,10 +153,10 @@ static class OnlyMetricsMeterObservationHandlerConfiguration { @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) @@ -153,14 +164,19 @@ io.micrometer.core.instrument.observation.DefaultMeterObservationHandler default 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 0c774d700ab..c4298d879df 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 1c3df968864..d2d18203528 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 @@ void apply(List> handlers, ObservationRegistry.Observation 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 @@ private Class findCategory(ObservationHandler h } 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 1d315c2b9a0..13308276013 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 Object postProcessAfterInitialization(Object bean, String beanName) throw 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 1404b62908a..b389de1abd3 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 @@ 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.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 @@ @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 24be95c4ec5..3af38c88009 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 @@ -23,6 +23,10 @@ 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; @@ -34,21 +38,25 @@ 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. @@ -64,23 +72,36 @@ public BraveAutoConfiguration(ModuleModel moduleModel) { @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) { - String applicationName = moduleModel.getApplicationModel().getApplicationConfigManager().getApplication() + public brave.Tracing braveTracing( + List spanHandlers, + List tracingCustomizers, + brave.propagation.CurrentTraceContext currentTraceContext, + brave.propagation.Propagation.Factory propagationFactory, + brave.sampler.Sampler sampler) { + String applicationName = moduleModel + .getApplicationModel() + .getApplicationConfigManager() + .getApplication() .map(ApplicationConfig::getName) .orElse(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 +118,14 @@ public brave.Tracer braveTracer(brave.Tracing tracing) { @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 +134,18 @@ public brave.propagation.CurrentTraceContext braveCurrentTraceContext(List 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 +237,19 @@ brave.baggage.BaggagePropagation.FactoryBuilder w3cPropagationFactoryBuilder( @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 +257,39 @@ brave.propagation.Propagation.Factory propagationFactory(brave.baggage.BaggagePr @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 f26a851f373..dd55dbe2f47 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.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 0bc815031f9..8b4fe1261fc 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.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 @@ private byte[] compress(byte[] input) { } 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 8e16503b4f4..7e37ade6b32 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 static org.apache.dubbo.spring.boot.observability.autoconfigure.ObservabilityUtils.DUBBO_TRACING_ZIPKIN_CONFIG_PREFIX; - /** * {@link EnableAutoConfiguration Auto-configuration} for Zipkin. *

    @@ -48,11 +46,16 @@ * * @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 3fc32ff2f45..cb5e3701a01 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.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.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 @@ static class UrlConnectionSenderConfiguration { @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 @@ static class RestTemplateSenderConfiguration { @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 @@ ZipkinRestTemplateSender restTemplateSender(DubboConfigurationProperties propert 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 @@ static class WebClientSenderConfiguration { @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 @@ static class ReporterConfiguration { AsyncReporter spanReporter(Sender sender, BytesEncoder encoder) { return AsyncReporter.builder(sender).build(encoder); } - } @Configuration(proxyBeanMethods = false) @@ -144,9 +146,9 @@ static class BraveConfiguration { @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 @@ static class OpenTelemetryConfiguration { @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 45eff7f6fbe..acd3b5b7337 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 @@ protected void doEnqueue(Callback callback) { 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 128f04431a8..637d1c50161 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 @@ protected void doEnqueue(Callback callback) { } private Mono> sendRequest() { - return this.webClient.post() + return this.webClient + .post() .uri(this.endpoint) .headers(this::addDefaultHeaders) .bodyValue(getBody()) @@ -79,6 +79,5 @@ private Mono> sendRequest() { 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 db7209e46ae..52db70e5514 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 d890280529c..243242d1283 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 85babb77f86..9b7e1fe8ada 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.config.ApplicationConfig; import org.apache.dubbo.rpc.model.ModuleModel; @@ -25,6 +24,10 @@ 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; @@ -34,18 +37,20 @@ 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 { @@ -65,45 +70,69 @@ 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) { - String applicationName = moduleModel.getApplicationModel().getApplicationConfigManager().getApplication() + io.opentelemetry.sdk.trace.SdkTracerProvider otelSdkTracerProvider( + ObjectProvider spanProcessors, + io.opentelemetry.sdk.trace.samplers.Sampler sampler) { + String applicationName = moduleModel + .getApplicationModel() + .getApplicationConfigManager() + .getApplication() .map(ApplicationConfig::getName) .orElse(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 @@ -114,29 +143,41 @@ io.opentelemetry.api.trace.Tracer otelTracer(io.opentelemetry.api.OpenTelemetry @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(); } @@ -164,33 +205,52 @@ static class BaggageConfiguration { @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) @@ -206,12 +266,14 @@ io.opentelemetry.extension.trace.propagation.B3Propagator b3TextMapPropagator() @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 { @@ -228,8 +290,5 @@ public void publishEvent(Object event) { 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 0e4734a9925..4b2f9e48686 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.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 @@ void shouldSupplyBeans() { @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 @@ void shouldBackOffOnCustomBeans() { @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 @@ void shouldNotSupplyBeansIfPropagatorIsMissing() { @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 @@ private static class TracerConfiguration { Tracer tracer() { return mock(Tracer.class); } - } @Configuration(proxyBeanMethods = false) @@ -141,7 +144,6 @@ private static class PropagatorConfiguration { Propagator propagator() { return mock(Propagator.class); } - } @Configuration(proxyBeanMethods = false) @@ -161,6 +163,5 @@ PropagatingReceiverTracingObservationHandler customPropagatingReceiverTracing PropagatingSenderTracingObservationHandler customPropagatingSenderTracingObservationHandler() { return mock(PropagatingSenderTracingObservationHandler.class); } - } } diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-spring-boot-observability-starter/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-spring-boot-observability-starter/pom.xml index 16c09acabd9..0aeb99ac5c7 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-spring-boot-observability-starter/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-spring-boot-observability-starter/pom.xml @@ -15,31 +15,29 @@ See the License for the specific language governing permissions and limitations under the License. --> - - - dubbo-spring-boot-observability-starters - org.apache.dubbo - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-spring-boot-observability-starters + ${revision} + ../pom.xml + - dubbo-spring-boot-observability-starter - jar - Apache Dubbo Spring Boot Observability Starter + dubbo-spring-boot-observability-starter + jar + Apache Dubbo Spring Boot Observability Starter - - - org.apache.dubbo - dubbo-spring-boot-observability-autoconfigure - ${project.version} - - - org.apache.dubbo - dubbo-spring-boot-actuator - ${project.version} - - + + + org.apache.dubbo + dubbo-spring-boot-observability-autoconfigure + ${project.version} + + + org.apache.dubbo + dubbo-spring-boot-actuator + ${project.version} + + diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-spring-boot-tracing-brave-zipkin-starter/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-spring-boot-tracing-brave-zipkin-starter/pom.xml index ac619e43027..6959ce15dce 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-spring-boot-tracing-brave-zipkin-starter/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-spring-boot-tracing-brave-zipkin-starter/pom.xml @@ -15,35 +15,33 @@ See the License for the specific language governing permissions and limitations under the License. --> - - - dubbo-spring-boot-observability-starters - org.apache.dubbo - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-spring-boot-observability-starters + ${revision} + ../pom.xml + - dubbo-spring-boot-tracing-brave-zipkin-starter - jar - Apache Dubbo Spring Boot Tracing Brave Zipkin Starter + dubbo-spring-boot-tracing-brave-zipkin-starter + jar + Apache Dubbo Spring Boot Tracing Brave Zipkin Starter - - - org.apache.dubbo - dubbo-spring-boot-observability-autoconfigure - ${project.version} - - - io.micrometer - micrometer-tracing-bridge-brave - - - io.zipkin.reporter2 - zipkin-reporter-brave - - + + + org.apache.dubbo + dubbo-spring-boot-observability-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-spring-boot-tracing-otel-otlp-starter/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-spring-boot-tracing-otel-otlp-starter/pom.xml index 57af321b3e8..89f84cfe19b 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-spring-boot-tracing-otel-otlp-starter/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-spring-boot-tracing-otel-otlp-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-spring-boot-observability-starters - org.apache.dubbo - ${revision} - ../pom.xml - + + 4.0.0 + + org.apache.dubbo + dubbo-spring-boot-observability-starters + ${revision} + ../pom.xml + - dubbo-spring-boot-tracing-otel-otlp-starter - jar - Apache Dubbo Spring Boot Tracing Otel OTLP Starter + dubbo-spring-boot-tracing-otel-otlp-starter + jar + Apache Dubbo Spring Boot Tracing Otel OTLP Starter - - - org.apache.dubbo - dubbo-spring-boot-observability-autoconfigure - ${project.version} - - - io.micrometer - micrometer-tracing-bridge-otel - - - io.opentelemetry - opentelemetry-exporter-otlp - - + + + org.apache.dubbo + dubbo-spring-boot-observability-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-spring-boot-tracing-otel-zipkin-starter/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-spring-boot-tracing-otel-zipkin-starter/pom.xml index 97279d2b730..5d8bd5bbe2a 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-spring-boot-tracing-otel-zipkin-starter/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-spring-boot-tracing-otel-zipkin-starter/pom.xml @@ -15,35 +15,33 @@ See the License for the specific language governing permissions and limitations under the License. --> - - - dubbo-spring-boot-observability-starters - org.apache.dubbo - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-spring-boot-observability-starters + ${revision} + ../pom.xml + - dubbo-spring-boot-tracing-otel-zipkin-starter - jar - Apache Dubbo Spring Boot Tracing Otel Zipkin Starter + dubbo-spring-boot-tracing-otel-zipkin-starter + jar + Apache Dubbo Spring Boot Tracing Otel Zipkin Starter - - - org.apache.dubbo - dubbo-spring-boot-observability-autoconfigure - ${project.version} - - - io.micrometer - micrometer-tracing-bridge-otel - - - io.opentelemetry - opentelemetry-exporter-zipkin - - + + + org.apache.dubbo + dubbo-spring-boot-observability-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 37cf3da9b61..e26ad13a49f 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-spring-boot-observability-starters + dubbo-spring-boot-observability-starters + pom - - autoconfigure - dubbo-spring-boot-tracing-otel-zipkin-starter - dubbo-spring-boot-tracing-brave-zipkin-starter - dubbo-spring-boot-observability-starter - dubbo-spring-boot-tracing-otel-otlp-starter - + + autoconfigure + dubbo-spring-boot-tracing-otel-zipkin-starter + dubbo-spring-boot-tracing-brave-zipkin-starter + dubbo-spring-boot-observability-starter + dubbo-spring-boot-tracing-otel-otlp-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 7414f9e7867..1d921ebd86b 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/pom.xml @@ -15,27 +15,25 @@ ~ 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 - + + observability + dubbo-nacos-spring-boot-starter + dubbo-zookeeper-spring-boot-starter + dubbo-zookeeper-curator5-spring-boot-starter + - \ No newline at end of file + diff --git a/dubbo-spring-boot/pom.xml b/dubbo-spring-boot/pom.xml index 1f20850f199..b8a058b7512 100644 --- a/dubbo-spring-boot/pom.xml +++ b/dubbo-spring-boot/pom.xml @@ -15,171 +15,169 @@ 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-actuator + dubbo-spring-boot-autoconfigure + dubbo-spring-boot-compatible + dubbo-spring-boot-starter + dubbo-spring-boot-starters + - - 2.7.17 - ${revision} - - 2.20.0 - - 1.14.9 - - - - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - + + 2.7.17 + ${revision} + + 2.20.0 + + 1.14.9 + + - - - org.junit.jupiter - junit-jupiter-engine - ${junit_jupiter_version} - test - - - org.junit.jupiter - junit-jupiter-params - ${junit_jupiter_version} - test - - - - org.junit.vintage - junit-vintage-engine - ${junit_jupiter_version} - 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.junit.jupiter + junit-jupiter-engine + ${junit_jupiter_version} + test + + + org.junit.jupiter + junit-jupiter-params + ${junit_jupiter_version} + test + + + + org.junit.vintage + junit-vintage-engine + ${junit_jupiter_version} + 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 + + - - - - spring-boot-2.0 - - 2.0.9.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.1 - - 2.1.15.RELEASE - - + + org.apache.maven.plugins + maven-compiler-plugin + ${maven_compiler_version} + + + -parameters + + true + ${java_source_version} + ${java_target_version} + ${file_encoding} + + + + - - - 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 + + - - org.apache.maven.plugins - maven-compiler-plugin - ${maven_compiler_version} - - - -parameters - - true - ${java_source_version} - ${java_target_version} - ${file_encoding} - - - - + + + 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 526743f3609..b39ac92a5cd 100644 --- a/dubbo-test/dubbo-dependencies-all/pom.xml +++ b/dubbo-test/dubbo-dependencies-all/pom.xml @@ -15,468 +15,467 @@ 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 - - dubbo-dependencies-all - Aggregate jacoco report - - - true - - - - - - org.apache.dubbo - dubbo-cluster - ${project.version} - - - - - org.apache.dubbo - dubbo-common - ${project.version} - - - - - org.apache.dubbo - dubbo-compatible - ${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-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 - ${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-metadata-api - ${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-default - ${project.version} - - - org.apache.dubbo - dubbo-metrics-registry - ${project.version} - - - - org.apache.dubbo - dubbo-metrics-metadata - ${project.version} - - - - org.apache.dubbo - dubbo-metrics-config-center - ${project.version} - - - org.apache.dubbo - dubbo-metrics-prometheus - ${project.version} - - - - - org.apache.dubbo - dubbo-monitor-api - ${project.version} - - - org.apache.dubbo - dubbo-monitor-default - ${project.version} - - - - - org.apache.dubbo - dubbo-native - ${project.version} - - - - - org.apache.dubbo - dubbo-native-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-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-netty - ${project.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${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-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-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-starter - ${project.version} - - - - org.apache.dubbo - dubbo-spring-boot-observability-autoconfigure - ${project.version} - - - org.apache.dubbo - dubbo-spring-boot-tracing-otel-zipkin-starter - ${project.version} - - - org.apache.dubbo - dubbo-spring-boot-tracing-otel-otlp-starter - ${project.version} - - - org.apache.dubbo - dubbo-spring-boot-tracing-brave-zipkin-starter - ${project.version} - - - org.apache.dubbo - dubbo-spring-boot-observability-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-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} - - + + 4.0.0 + + org.apache.dubbo + dubbo-test + ${revision} + ../pom.xml + + + dubbo-dependencies-all + Aggregate jacoco report + + + true + + + + + + org.apache.dubbo + dubbo-cluster + ${project.version} + + + + + org.apache.dubbo + dubbo-common + ${project.version} + + + + + org.apache.dubbo + dubbo-compatible + ${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-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 + ${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-metadata-api + ${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-default + ${project.version} + + + org.apache.dubbo + dubbo-metrics-registry + ${project.version} + + + + org.apache.dubbo + dubbo-metrics-metadata + ${project.version} + + + + org.apache.dubbo + dubbo-metrics-config-center + ${project.version} + + + org.apache.dubbo + dubbo-metrics-prometheus + ${project.version} + + + + + org.apache.dubbo + dubbo-monitor-api + ${project.version} + + + org.apache.dubbo + dubbo-monitor-default + ${project.version} + + + + + org.apache.dubbo + dubbo-native + ${project.version} + + + + + org.apache.dubbo + dubbo-native-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-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-netty + ${project.version} + + + org.apache.dubbo + dubbo-remoting-netty4 + ${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-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-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-starter + ${project.version} + + + + org.apache.dubbo + dubbo-spring-boot-observability-autoconfigure + ${project.version} + + + org.apache.dubbo + dubbo-spring-boot-tracing-otel-zipkin-starter + ${project.version} + + + org.apache.dubbo + dubbo-spring-boot-tracing-otel-otlp-starter + ${project.version} + + + org.apache.dubbo + dubbo-spring-boot-tracing-brave-zipkin-starter + ${project.version} + + + org.apache.dubbo + dubbo-spring-boot-observability-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-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} + + diff --git a/dubbo-test/dubbo-test-check/pom.xml b/dubbo-test/dubbo-test-check/pom.xml index 23a0d19685f..71db07ec91f 100644 --- a/dubbo-test/dubbo-test-check/pom.xml +++ b/dubbo-test/dubbo-test-check/pom.xml @@ -15,88 +15,86 @@ 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 - - 8 - 8 - true - 4.2.0 - 3.7.2 - 4.2.0 - 1.24.0 - 1.9.3 - 1.3 - 2.12.3 - + + 8 + 8 + 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 c5c607c88fc..6c29169eb0e 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 @@ private boolean supportEmbeddedZookeeper(TestIdentifier testIdentifier) { } 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 846d01a8ad9..6eb150aeab5 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.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.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 void init(Properties properties) throws IOException { 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 void init(Properties properties) throws IOException { } 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 void testPlanExecutionFinished(TestPlan testPlan) { 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 Map getUnclosedThreadMap() { 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 void executionFinished(TestIdentifier testIdentifier, TestExecutionResult } 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 void executionFinished(TestIdentifier testIdentifier, TestExecutionResult 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 Map checkUnclosedThreads(String testClassNam 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 @@ private void log(String msg) { } 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 static String getFullStacktrace(Thread thread, StackTraceElement[] stackT } 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 b3f56f3dd9f..35d151791ea 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 6c3f1062a6f..87ca7345fdc 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 0cda9b56848..814acf2ce33 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 76b15fcdbb5..b6fb61694d7 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 @@ /** * 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 cff1431affb..e9aa0459fae 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.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.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 @@ private static String getEmbeddedZookeeperDirectory() { 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 da12656acb8..487da08c1c5 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 2698d1a6069..7277ec1d339 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 @@ 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.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 Integer getPid(int clientPort) { * 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 f703f1e7807..67b4f98f79a 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 @@ private void updateConfig(ZookeeperContext context, int clientPort, int adminSer 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 @@ private void updateConfig(ZookeeperContext context, int clientPort, int adminSer 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 @@ private void updateConfig(ZookeeperContext context, int clientPort, int adminSer 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 @@ private void updateConfig(ZookeeperContext context, int clientPort, int adminSer 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 d961e42bfbd..fa53136f624 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.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.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 @@ */ 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 @@ protected void doInitialize(ZookeeperContext context) throws DubboTestException 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 @@ protected void doInitialize(ZookeeperContext context) throws DubboTestException 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 @@ protected void doInitialize(ZookeeperContext context) throws DubboTestException 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 @@ protected void doInitialize(ZookeeperContext context) throws DubboTestException * @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; - } - - @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 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); + } + }); // 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 d720c9494b6..209d0593bd3 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.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.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 @@ protected void doInitialize(ZookeeperContext context) throws DubboTestException 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 8be66db8807..e672bef4087 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.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.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 @@ private void findPid(ZookeeperWindowsContext context, int clientPort) { 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 @@ private void findPid(ZookeeperWindowsContext context, int clientPort) { // 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 @@ private void findPid(ZookeeperWindowsContext context, int clientPort) { } } } 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 @@ private void findPid(ZookeeperWindowsContext context, int clientPort) { */ 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 d83c67814d9..96e0e07b85e 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.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 @@ protected void doProcess(ZookeeperWindowsContext context) throws DubboTestExcept // 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 b9cb8685f2f..012954e18f4 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.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 3cb4587926e..ec65a96456a 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 7e40e657653..f384ede4ed4 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.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 @@ protected void doProcess(ZookeeperWindowsContext context) throws DubboTestExcept 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 452fbed2165..f7a2f0ae9a2 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 c5b25c8e336..100f00b54e1 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 @@ */ 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 void process(Context context) throws DubboTestException { 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 @@ private void logErrorStream(final InputStream errorStream) { 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 d364bd63ac3..340b3441d91 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.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 4a8cb97d446..a4acc9b7217 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 - - 8 - 8 - true - + + 8 + 8 + true + - - - org.apache.zookeeper - zookeeper - - - org.slf4j - slf4j-log4j12 - - - + + + org.apache.zookeeper + zookeeper + + + org.slf4j + slf4j-log4j12 + + + - - 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 b44ff13298a..ba8e9656913 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 dac5edd9f96..dcfafc37f8e 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 static void clear() { } 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 9a5dfc155a6..f90031bd1eb 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 809cd94d732..07b06674692 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.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 4b80d8b8b2c..0ab09bdc55c 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 String sayHello(String name) { @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 0ad249abf64..cd205bcc7bd 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 c8633145ffb..a2fd54edaf3 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 String sayHello(String name) { 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 bcd2a99a9a7..f2ade3d0779 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 a9182429f5a..209a25ff585 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.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")); @@ -75,33 +75,37 @@ void checkDubboBom() throws DocumentException { 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 @@ -114,28 +118,35 @@ void checkArtifacts() throws DocumentException, IOException { 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 @@ -148,33 +159,35 @@ void checkDubboDependenciesAll() throws DocumentException { 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()); - - String dubboDependenciesAllPath = "dubbo-test" + File.separator + "dubbo-dependencies-all" + File.separator + "pom.xml"; + .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"; 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 @@ -187,71 +200,83 @@ void checkDubboAllDependencies() throws DocumentException { 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 @@ -264,84 +289,97 @@ void checkDubboAllShade() throws DocumentException { 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 @@ -355,32 +393,37 @@ void checkDubboAllTransform() throws DocumentException { 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 @@ -393,12 +436,21 @@ void checkSpiFiles() { 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() { @@ -454,8 +506,9 @@ public void readSPI(File path, List spis) { } 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); @@ -476,10 +529,16 @@ public void readSPIResource(File path, Map spis) { 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); } @@ -498,35 +557,55 @@ public void readSPIUnexpectedResource(File path, List spis) { 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 9ac34620d59..6a4eb4744fc 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 - 1.7.33 - 3.2.18.RELEASE - - - - - - - - - org.springframework - spring-framework-bom - ${spring_version} - pom - import - - - + + true + 1.7.33 + 3.2.18.RELEASE + + + + + - - - org.apache.dubbo - dubbo-test-common - ${project.version} - + + org.springframework + spring-framework-bom + ${spring_version} + pom + import + + + - - - 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-api - - - org.slf4j - slf4j-log4j12 - ${slf4j-log4j12.version} - - - log4j - log4j - + + + + 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-api + + + org.slf4j + slf4j-log4j12 + ${slf4j-log4j12.version} + + + log4j + log4j + - - - org.junit.jupiter - junit-jupiter-engine - ${junit_jupiter_version} - - - - org.junit.jupiter - junit-jupiter-params - ${junit_jupiter_version} - - - - org.hamcrest - hamcrest - ${hamcrest_version} - - - - org.junit.jupiter - junit-jupiter-api - ${junit_jupiter_version} - - - - org.mockito - mockito-core - ${mockito_version} - - - - org.mockito - mockito-inline - ${mockito_version} - - - - cglib - cglib-nodep - ${cglib_version} - - + + + org.junit.jupiter + junit-jupiter-engine + ${junit_jupiter_version} + + + + org.junit.jupiter + junit-jupiter-params + ${junit_jupiter_version} + + + + org.hamcrest + hamcrest + ${hamcrest_version} + + + + org.junit.jupiter + junit-jupiter-api + ${junit_jupiter_version} + + + + org.mockito + mockito-core + ${mockito_version} + + + + org.mockito + mockito-inline + ${mockito_version} + + + + cglib + cglib-nodep + ${cglib_version} + + - - org.apache.curator - curator-framework - - - - org.apache.curator - curator-recipes - - - - org.apache.zookeeper - zookeeper - - - + + org.apache.curator + curator-framework + + + + org.apache.curator + curator-recipes + + + + org.apache.zookeeper + zookeeper + + + 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 f51f19a0547..b8e14461486 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 static void beforeAll() { } @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 472132ca527..8f4bb91efa2 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.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.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 static void beforeAll() { } @AfterAll - public static void afterAll(){ + public static void afterAll() { DubboBootstrap.reset(); } @@ -106,8 +106,10 @@ public void testBean() { 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 void testBean() { 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 void testBean() { } finally { consumerContext.close(); } - } - @EnableDubbo(scanBasePackages = "") @Configuration static class TestConfiguration { @@ -183,7 +183,6 @@ static class ConsumerConfiguration { 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 8df53b1cfdf..d3a75091e97 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 static void beforeAll() { } @AfterAll - public static void afterAll(){ + public static void afterAll() { DubboBootstrap.reset(); providerContext.close(); } @@ -83,6 +83,5 @@ public void test() { 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 e2ec79e8007..c794fcf985a 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.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.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 void customize(DubboSpringInitContext context) { 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 void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) 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 static void checkCustomizer(ConfigurableApplicationContext applicationCon 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 0156c22e75a..ca027c3d49e 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.maven.plugins - maven-surefire-plugin - - - org.apache.dubbo:dubbo-test-spring - - - - - + + + + org.apache.dubbo + dubbo-test-spring + ${project.version} + test + + + org.apache.curator + curator-framework + + + + org.apache.curator + curator-recipes + + + + org.apache.zookeeper + zookeeper + + - - - jdk15ge-simple - - [15, - - - - - org.apache.maven.plugins - maven-surefire-plugin - - true - once - ${argline} ${jacocoArgLine} + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + org.apache.dubbo:dubbo-test-spring + + + + + + + + + jdk15ge-simple + + [15, + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + once + ${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 bf3a2191869..f7a82c8ec30 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.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.curator - curator-recipes - - - - org.apache.zookeeper - zookeeper - - - + - - - - org.apache.maven.plugins - maven-surefire-plugin - - - org.apache.dubbo:dubbo-test-spring - - - - - + + + + org.apache.maven.plugins + maven-surefire-plugin + + + org.apache.dubbo:dubbo-test-spring + + + + + - - - jdk15ge-simple - - [15, - - - - - org.apache.maven.plugins - maven-surefire-plugin - - true - once - ${argline} ${jacocoArgLine} + + + jdk15ge-simple + + [15, + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + once + ${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 cc90e8aef9a..7c9aa640233 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.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.curator - curator-recipes - - - - org.apache.zookeeper - zookeeper - - - + - - - - org.apache.maven.plugins - maven-surefire-plugin - - - org.apache.dubbo:dubbo-test-spring - - - - - + + + + org.apache.maven.plugins + maven-surefire-plugin + + + org.apache.dubbo:dubbo-test-spring + + + + + - - - jdk15ge-simple - - [15, - - - - - org.apache.maven.plugins - maven-surefire-plugin - - true - once - ${argline} ${jacocoArgLine} + + + jdk15ge-simple + + [15, + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + once + ${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 d4c487812b6..f0028b9c195 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 + - - 8 - 8 - true - + + 8 + 8 + true + diff --git a/dubbo-xds/pom.xml b/dubbo-xds/pom.xml index b8d8a554092..9e9ef216d20 100644 --- a/dubbo-xds/pom.xml +++ b/dubbo-xds/pom.xml @@ -15,111 +15,109 @@ 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 - - - dubbo-xds - ${project.artifactId} - The xDS Integration - - false - - - - - - org.apache.dubbo - dubbo-registry-api - ${project.version} - - - - org.apache.dubbo - dubbo-common - ${project.version} - - - - io.grpc - grpc-protobuf - - - - io.grpc - grpc-stub - - - - io.grpc - grpc-netty-shaded - - - - io.envoyproxy.controlplane - api - - - - com.google.protobuf - protobuf-java - - - - com.google.protobuf - protobuf-java-util - - - - 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-java_version}:exe:${os.detected.classifier} - grpc-java - io.grpc:protoc-gen-grpc-java:${grpc_version}:exe:${os.detected.classifier} - - - - - compile - compile-custom - - - - - - + + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + + + dubbo-xds + ${project.artifactId} + The xDS Integration + + false + + + + + + org.apache.dubbo + dubbo-registry-api + ${project.version} + + + + org.apache.dubbo + dubbo-common + ${project.version} + + + + io.grpc + grpc-protobuf + + + + io.grpc + grpc-stub + + + + io.grpc + grpc-netty-shaded + + + + io.envoyproxy.controlplane + api + + + + 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.xolstice.maven.plugins + protobuf-maven-plugin + ${maven_protobuf_plugin_version} + + com.google.protobuf:protoc:${protobuf-java_version}:exe:${os.detected.classifier} + grpc-java + io.grpc:protoc-gen-grpc-java:${grpc_version}:exe:${os.detected.classifier} + + + + + compile + compile-custom + + + + + + + + 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 b79f55c7170..9a9b9a35cae 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 @@ 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 a4bd51e6b1d..30e005ffe76 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 boolean isAvailable() { } @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 b40b68650b5..3385ff97a08 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.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 List getInstances(String serviceName) throws NullPointer } @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 706e230c519..0f763c59c9a 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 @@ 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 @@ protected ServiceDiscovery createDiscovery(URL registryURL) { 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 99225b0316d..db54ea56287 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.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.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 CertPair createCert() throws IOException { 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 CertPair createCert() throws IOException { 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 CertPair createCert() throws IOException { 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 CertPair createCert() throws IOException { 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 CertPair createCert() throws IOException { } 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 void onNext(IstioCertificateResponse istioCertificateResponse) { @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 @@ private String generatePemKey(String type, byte[] content) throws IOException { } 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 9787643674e..018fa3a0faa 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 3ff1d1dfe50..e508e7cc294 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.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 String getServiceAccount() { 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 String getCaCert() { 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 9727dd67c16..5e1734806d9 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.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 void onNext(DiscoveryResponse discoveryResponse) { 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 void onCompleted() { } 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 @@ private void recover() { 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 e353bec85e8..eaa88f39047 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 @@ 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 static Node build() { // 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 d85965a7dfc..87fa81083a9 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.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 @@ protected PilotExchanger(URL url) { 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 @@ protected PilotExchanger(URL url) { 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 static boolean isEnabled() { return GLOBAL_PILOT_EXCHANGER != null; } - public void destroy() { xdsChannel.destroy(); } @@ -193,20 +203,20 @@ private void doObserveEndpoints(String domain) { // 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 void observeLds(Consumer> consumer) { 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 d4e069a3647..a6f7dffde11 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,30 +16,31 @@ */ 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 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 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 static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERROR_CREATE_CHANNEL_XDS; @@ -70,39 +71,52 @@ public XdsChannel(URL url) { 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 StreamObserver createDeltaDiscoveryRequest(StreamObserv 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 a4e44518918..3570b20e32e 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 String serverListenerResourceNameTemplate() { @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 static final class Builder extends Bootstrapper.BootstrapInfo.Builder { private Map certProviders; private String serverListenerResourceNameTemplate; - Builder() { - } + + Builder() {} + @Override Bootstrapper.BootstrapInfo.Builder servers(List servers) { this.servers = new LinkedList<>(servers); @@ -93,21 +99,22 @@ Bootstrapper.BootstrapInfo.Builder node(Node node) { } @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 @@ Bootstrapper.BootstrapInfo build() { 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 5e018c45a60..69a7ee89a51 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 static class ServerInfo { abstract boolean useProtocolV3(); abstract boolean ignoreResourceDeletion(); - } public abstract static class CertificateProviderInfo { @@ -66,8 +67,7 @@ abstract static class Builder { 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 d9e299763fc..66c7a623978 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.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 @@ BootstrapInfo bootstrap(Map rawData) throws XdsInitializationExceptio 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 @@ BootstrapInfo bootstrap(Map rawData) throws XdsInitializationExceptio 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 @@ private static List parseServerInfos(List rawServerConfigs) 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 @@ private static List parseServerInfos(List rawServerConfigs) 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 String readFile(String path) throws IOException { 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 2c3da740a2d..980b6e1fd30 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 @@ public String pluginName() { @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 001008a4554..c15f4f28b74 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 @@ boolean ignoreResourceDeletion() { @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 10545265945..a2e135f00db 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.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 T getCacheResource(String resourceName) { return resourcesMap.get(resourceName); } - @Override public Map getResource(Set resourceNames) { resourceNames = resourceNames == null ? Collections.emptySet() : resourceNames; @@ -120,8 +118,9 @@ public Map getResource(Set resourceNames) { } 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 Map getResourceFromRemote(Set resourceNames) { 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 Map getResourceFromRemote(Set resourceNames) { 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 Map getResourceFromRemote(Set resourceNames) { 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 void observeResource(Set resourceNames, Consumer> } 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 void unobserveResource(Set resourceNames, Consumer 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 @@ private void discoveryResponseListener(Map oldResult, Map 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 @@ private void discoveryResponseListener(Map oldResult, Map 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 9e192cf1c93..46988f38e5b 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 void removeResource(Collection resourceName) { @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 73b2c9a0056..bca3024ed96 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 void removeResource(Collection resourceName) { @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 820860435b5..91759cab9b6 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.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 String getTypeUrl() { 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 @@ private static Endpoint decodeLbEndpointToEndpoint(String clusterName, LbEndpoin 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 0de9a485e38..00abe22f37d 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.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 Map getListeners() { 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 @@ protected Map decodeDiscoveryResponse(DiscoveryResponse 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 68970f6f1f9..44bee78c1eb 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.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 String getTypeUrl() { 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 @@ protected Map decodeDiscoveryResponse(DiscoveryResponse res 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 @@ private static RouteConfiguration unpackRouteConfiguration(Any any) { 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 58f13bdee80..ceed1632787 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 void setWeight(int weight) { @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 boolean equals(Object o) { 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 4f890786b16..ead2c4de277 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 int hashCode() { @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 61d717e87d6..7c16703166a 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 int hashCode() { @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 a71e43cb6d1..cf0ed1d8465 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 VirtualHost searchVirtualHost(String domain) { 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 0416236166a..58aaa86234d 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 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 6291551889c..a54d74c7bf3 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.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 synchronized void subscribeEds(String cluster, EdsEndpointListener listen 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 @@ private void doUnsubscribeEds(String cluster) { ENDPOINT_DATA_CACHE.remove(cluster); } - public void notifyEndpointChange(String cluster, Set endpoints) { ENDPOINT_DATA_CACHE.put(cluster, endpoints); @@ -124,5 +124,4 @@ static ConcurrentHashMap> getEndpointDataCache() { 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 a76508a1384..b0371729eb3 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.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 @@ private void doUnsubscribeRds(String domain) { RDS_LISTENERS.remove(domain); } - public void notifyRuleChange(String domain, List xdsRouteRules) { ROUTE_DATA_CACHE.put(domain, xdsRouteRules); @@ -162,5 +159,4 @@ static ConcurrentHashMap> getRouteDataCache() { 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 85443cca86a..58771788eeb 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.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 void parseVirtualHost(VirtualHost virtualHost) { 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 @@ private HTTPRouteDestination parseAction(Route route) { 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 @@ private HTTPRouteDestination parseAction(Route route) { 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 bc2c5262cac..4e90fe2d41e 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 @@ 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 c994a219ad7..e043e2d3d74 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 XdsRouter(URL url) { /** * @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 @@ protected XdsRouter(URL url, RdsRouteRuleManager rdsRouteRuleManager, EdsEndpoin } @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 @@ protected BitList> doRoute(BitList> invokers, URL url, Inv } 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 @@ private String computeMatchCluster(Invocation invocation, XdsRouteRule rule) { } 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 void notify(BitList> invokers) { 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 void stop() { } } - @Deprecated Set getSubscribeApplications() { return subscribeApplications; @@ -367,7 +381,6 @@ ConcurrentHashMap> getXdsRouteRuleMap() { return xdsRouteRuleMap; } - /** * for ut only */ @@ -375,5 +388,4 @@ ConcurrentHashMap> getXdsRouteRuleMap() { 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 e94d4be4a9c..b34b86ffce2 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 @@ 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 void initializeApplicationModel(ApplicationModel applicationModel) { } @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 a48857cea41..fe1307c8f64 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 String getName() { 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 9644a687b0e..79fa2156f62 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 Set getEndpoints() { 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 471e2a215af..91d55d337f4 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 List getWeightedClusters() { 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 68bc38a9d56..04b0c45a04c 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 @@ public class HeaderMatcher { - public String name; public String exactValue; @@ -119,5 +118,4 @@ public boolean match(String input) { } 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 aff10ba8905..fef5aa18e48 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 PathMatcher getPathMatcher() { 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 d52123f03bf..df482575bd4 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 void setEnd(long end) { 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 00931fb0a55..cbf77e8711f 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 void setCaseSensitive(boolean caseSensitive) { 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 2ca613bdd16..5d2994d2d6b 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 XdsRouteRule(HttpRequestMatch match, HTTPRouteDestination route) { this.route = route; } - public HttpRequestMatch getMatch() { return match; } @@ -37,5 +34,4 @@ public HttpRequestMatch getMatch() { 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 71875022a6e..8efcdb02f08 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.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 @@ public String readFile(String path) { } }; } - } 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 354784d7de7..00000000000 --- 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 ed080fe768d..6a9d3e46198 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 void setResourcesMap(Map resourcesMap) { 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 3c37ec8d25d..bdeb636698d 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 void setResourcesMap(Map resourcesMap) { 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 Map, List>>> getConsumer 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 01581950d07..7d9aa78d3a6 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 void setResourcesMap(Map resourcesMap) { 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 7da4950c558..1a1f2f8ceb7 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 @@ 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 void subscribeEdsTest() { 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 void onEndPointChange(String cluster, Set endpoints) { assertNull(EdsEndpointManager.getEndpointListeners().get(domain)); } - @Test public void notifyRuleChangeTest() { @@ -112,5 +105,4 @@ public void onEndPointChange(String cluster, Set endpoints) { 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 44e2ad16e53..eaef9cb320a 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.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 void before() { RdsRouteRuleManager.getRdsListeners().clear(); } - @Test public void subscribeRdsTest() { RdsRouteRuleManager manager = new RdsRouteRuleManager(); @@ -50,35 +49,26 @@ public void subscribeRdsTest() { 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 void clearRule(String appName) { 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 void clearRule(String appName) { 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 2899e6f3b8f..d7985366a6e 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 @@ 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 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 void init() { 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 void parsePathPathMatcherTest() { 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 void parsePrefixPathMatcherTest() { 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 void parseRegexPathMatcherTest() { @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) - .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) + .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-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 void parseHeadMatcherTest() { 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 void parseRouteClusterTest() { @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 void parseRouteWeightClusterTest() { } } } - } 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 2e741931719..11c7e3b5841 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,10 +16,6 @@ */ 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; @@ -29,18 +25,21 @@ 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 com.google.protobuf.UInt32Value; +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; @@ -66,14 +65,16 @@ public void setup() { } 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 +116,51 @@ public void testRuleChange() { 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 +177,8 @@ public void testEndpointChange() { 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 +186,8 @@ public void testEndpointChange() { 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 +200,18 @@ public void testRoutePathMatch() { 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 +231,30 @@ public void testRoutePathMatch() { 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 +270,6 @@ public void testRouteHeadMatch() { assertEquals(invoker1, routes.get(0)); } - @Test public void testRouteWeightCluster() { XdsRouter xdsRouter = new XdsRouter<>(url, rdsRouteRuleManager, edsEndpointManager, true); @@ -273,28 +277,37 @@ public void testRouteWeightCluster() { 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 +341,18 @@ public void testRouteMultiApp() { 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 +373,4 @@ public void testRouteMultiApp() { 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 dc8e2404823..597c06e0de8 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 void exactValueMatcherTest() { assertTrue(headMatcher.match(value)); } - @Test public void regexMatcherTest() { HeaderMatcher headMatcher = new HeaderMatcher(); @@ -52,7 +51,6 @@ public void rangMatcherTest() { assertTrue(headMatcher.match("300")); } - @Test public void presentMatcherTest() { HeaderMatcher headMatcher = new HeaderMatcher(); @@ -71,7 +69,6 @@ public void prefixMatcherTest() { 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 51bb920a6c4..ce8e82b50b7 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 @@ public class PathMatcherTest { - @Test public void pathMatcherTest() { PathMatcher pathMatcher = new PathMatcher(); @@ -33,7 +32,6 @@ public void pathMatcherTest() { assertTrue(pathMatcher.isMatch(path.toUpperCase())); pathMatcher.setCaseSensitive(true); assertFalse(pathMatcher.isMatch(path.toUpperCase())); - } @Test @@ -56,5 +54,4 @@ public void regexMatcherTest() { pathMatcher.setRegex(regex); assertTrue(pathMatcher.isMatch(path)); } - } diff --git a/pom.xml b/pom.xml index 83871661683..4787a1ab812 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 - 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/ - - + ${project.artifactId} + The parent project of dubbo + https://github.com/apache/dubbo + 2011 - - The Apache Software Foundation - http://www.apache.org/ - + + 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 + + - - Github Issues - https://github.com/apache/dubbo/issues - + + dubbo-common + dubbo-container + dubbo-compiler + dubbo-remoting + dubbo-rpc + dubbo-cluster + dubbo-registry + dubbo-monitor + dubbo-config + dubbo-filter + dubbo-demo + dubbo-plugin + dubbo-serialization + dubbo-compatible + dubbo-dependencies-bom + dubbo-distribution + dubbo-configcenter + dubbo-dependencies + dubbo-metadata + dubbo-metrics + dubbo-build-tools + dubbo-spring-boot + dubbo-native + dubbo-test + dubbo-kubernetes + dubbo-xds + dubbo-native-plugin + dubbo-maven-plugin + - - - 5.9.3 - 4.2.0 - 3.12.13 - 2.2 - 5.2.4.Final - 2.2.5 - 2.2.7 - 2.2.2 - 4.11.0 - - -server -Xms256m -Xmx512m -Dfile.encoding=UTF-8 - -Djava.net.preferIPv4Stack=true -XX:MetaspaceSize=64m -XX:MaxMetaspaceSize=128m - - false - true - ${file_encoding} - 2020-04-01T08:04:00Z + + scm:git:https://github.com/apache/dubbo.git + scm:git:https://github.com/apache/dubbo.git + HEAD + https://github.com/apache/dubbo + - oss - - 1.8 - 1.8 - UTF-8 - - 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 - - true - true - true - true + + Github Issues + https://github.com/apache/dubbo/issues + - 1.2.2 - 3.22.3 - 1.54.0 - 2.40.0 - check - 1.0.0 - 3.2.8-SNAPSHOT - + + + 5.9.3 + 4.2.0 + 3.12.13 + 2.2 + 5.2.4.Final + 2.2.5 + 2.2.7 + 2.2.2 + 4.11.0 + + -server -Xms256m -Xmx512m -Dfile.encoding=UTF-8 + -Djava.net.preferIPv4Stack=true -XX:MetaspaceSize=64m -XX:MaxMetaspaceSize=128m + false + true + ${file_encoding} + 2020-04-01T08:04:00Z - - dubbo-common - dubbo-container - dubbo-compiler - dubbo-remoting - dubbo-rpc - dubbo-cluster - dubbo-registry - dubbo-monitor - dubbo-config - dubbo-filter - dubbo-demo - dubbo-plugin - dubbo-serialization - dubbo-compatible - dubbo-dependencies-bom - dubbo-distribution - dubbo-configcenter - dubbo-dependencies - dubbo-metadata - dubbo-metrics - dubbo-build-tools - dubbo-spring-boot - dubbo-native - dubbo-test - dubbo-kubernetes - dubbo-xds - dubbo-native-plugin - dubbo-maven-plugin - + oss + + 1.8 + 1.8 + UTF-8 + + 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 + + true + true + true + true - - - - org.apache.dubbo - dubbo-dependencies-bom - ${project.version} - pom - import - - - + 1.2.2 + 3.22.3 + 1.54.0 + 2.40.0 + check + 1.0.0 + 2.38.0 + 3.2.8-SNAPSHOT + + - - - 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.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 - + + org.apache.dubbo + dubbo-dependencies-bom + ${project.version} + pom + import + + + + + + + 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.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 + + + + + + + + false + src/main/resources + + + META-INF/ + false + ${maven.multiModuleProjectDirectory} + + NOTICE + LICENSE + + + + META-INF/versions + false + ${maven.multiModuleProjectDirectory} + + .artifacts + + + - - - 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.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 + once + ${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 + ${java_source_version} + ${java_target_version} + ${file_encoding} + + + + 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 - - - org.apache.dubbo - dubbo-build-tools - 1.0.0 - - - - - checkstyle-validation - validate - - codestyle/checkstyle.xml - codestyle/checkstyle-suppressions.xml - UTF-8 - true - true - ${checkstyle.skip} - - **/JSONWriter.java, + + + checkstyle + + false + false + + + + checkstyle_def + + [1.8,) + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + ${maven_checkstyle_version} + + + com.puppycrawl.tools + checkstyle + 8.45.1 + + + org.apache.dubbo + dubbo-build-tools + 1.0.0 + + + + + checkstyle-validation + + check + + validate + + codestyle/checkstyle.xml + codestyle/checkstyle-suppressions.xml + UTF-8 + 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, @@ -369,583 +621,320 @@ **/grpc/health/**/*, **/grpc/reflection/**/*, **/target/**/*, - **/*.json - - - - check - - - - checkstyle-unix-validation - validate - - codestyle/checkstyle_unix.xml - UTF-8 - 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 - - - - - maven-source-plugin - ${maven_source_version} - - - attach-sources - - jar - - - - - - 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} - - - - - - - public - UTF-8 - UTF-8 - UTF-8 - ${maven_source_version} - - http://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 - - - - - - - - - - - jdk15ge-add-open - - [15, - - - - - org.apache.maven.plugins - maven-surefire-plugin - - true - once - ${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 - once - ${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} - - + **/*.json - - - 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 + + + checkstyle-unix-validation + + check + + validate - true - once - ${argline} ${jacocoArgLine} - - - + codestyle/checkstyle_unix.xml + UTF-8 + true + true + ${checkstyle_unix.skip} + **/target/**/* + **/generated/**/* + **/generated-sources/**/* - - - 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 - ${java_source_version} - ${java_target_version} - ${file_encoding} - - - - org.apache.maven.plugins - maven-antrun-plugin - - - get-version-infos - compile - - true - - - - - - - - - - - - - - - run - - - - - - org.apache.maven.plugins - maven-release-plugin - 3.0.0 + + + + + + + + sources + + + + maven-source-plugin + ${maven_source_version} + + + attach-sources + + jar + + + + + + + + + release + + 2.17.2 + false + + + + + maven-source-plugin + ${maven_source_version} + + + attach-sources + + jar + + + + + + maven-javadoc-plugin + ${maven_javadoc_version} + + public + UTF-8 + UTF-8 + UTF-8 + ${maven_source_version} + + http://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 + - true - false - release - deploy - ${arguments} + + + org.apache.logging.log4j + log4j-api + ${log4j2_version} + + + org.apache.logging.log4j + log4j-core + ${log4j2_version} + + - - - org.codehaus.mojo - flatten-maven-plugin - ${maven_flatten_version} + + + + + 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 - true - oss + 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 + - - - flatten - process-resources - - flatten - - - - flatten.clean - clean - - clean - - - - + + + + + + + + jdk15ge-add-open + + [15, + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + once + ${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 + once + ${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 + + + ${palantirJavaFormat.version} + + + + dubbo-importorder.txt + + + checkstyle-header.txt + + + + + false + true + + + + true + + + + + com.alibaba + dubbo-shared-resources + ${dubbo-shared-resources.version} + + + + + + ${spotless.action} + + process-sources + + + + + + +