You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@dubbo.apache.org by je...@apache.org on 2019/03/26 06:28:39 UTC
[incubator-dubbo] branch 3.x-dev updated: Merge master branch to
3.x dev branch (#3718)
This is an automated email from the ASF dual-hosted git repository.
jefflv pushed a commit to branch 3.x-dev
in repository https://gitbox.apache.org/repos/asf/incubator-dubbo.git
The following commit(s) were added to refs/heads/3.x-dev by this push:
new 897b80d Merge master branch to 3.x dev branch (#3718)
897b80d is described below
commit 897b80de3840c0bc9d9928dc1fb3f28ca8d78cc7
Author: ken.lj <ke...@gmail.com>
AuthorDate: Tue Mar 26 14:28:33 2019 +0800
Merge master branch to 3.x dev branch (#3718)
* Release resource after use in ConfigParserTest (#3127)
Release resource after use in ConfigParserTest
* add javadoc for registry and some code (#3140)
add javadoc for registry and optimize code
* Correct spelling error (#3146)
* Code optimization (#3118)
* code optimization
* useless import
* optimization
* Code rule (#3016)
* code optimization (#3167)
code optimization
* Add javadoc for dubbo-serialization module(#3002). (#3004)
Add javadoc for dubbo-serialization module(#3002).
* optimize ReconnectTimerTask's log output (#3162)
* optimize log output
* Separate logs for reconnect and close
* remove reconnect exception log
* add some small optimize (#3171)
* modify some log describe
* use java8 lambda expression
* fix telnet trace times is always 1 (#3038)
* fix telnet trace times is always 1
* use StringUtils determine if the string is empty
* Fix 3105 , make invoke command with Json string parameter without "class" key
* Fix 3105 ,Keep the class key to support overloaded methods
* optimize InvokerTelnetHandlerTest
* Upgrade junt to junit5 (#3149)
* upgrade junit to junit5
* modify test
* 批量修改upgrade_junt_to_junit5
* 删除多余的文件
* fi test case
* Disabled soem test case temporarily
* upgrade junit to junit5 and batch modify test case
* copy some code from jupiter5.4.0.M1 for some issues
* 修改rat福泽
* update rat path
* revert case
* add junit-platform-surefire-provider to maven-surefire-plugin
* update dependency
* fix coverage issue (#1)
* use jupiter 5.4.0-M1 and remove junit5 source code
* Format change.
* fix wrong word spelling (#3217)
* Fix provicer --> provider (#3222)
* Optimize the code: use logger instead of printStackTrace(). (#3202)
* Optimize code: remove unnecessary judgment code. (#3196)
* Optimize the code: fix CallbackServiceCodec.java exportOrunexportCallbackService method issue. (#3199)
* Optimize the code: fix url to null, NullPointerException, change private variable to camel mode.
* Optimize the code: exportOrUnexportCallbackService method camel mode.
* Optimize the code: fix method:encodeInvocationArgument private callbackStatus is camel writing.
* Optimize the code: fix name issue
* Exporter is a noun, we should use a verb here, like Export.
* The generics that can be inferred automatically are also deleted.
* Refactor telnet invoke command (#3210)
* refactor telnet invoke command
* add select command for telnet
* fix test case
* Remove deprecated AnnotationBean, please refer #1485 for the new method to replace. (#3232)
* [Dubbo-3231]keep TagRouter consistent with 2.6.x (#3233)
* keep TagRouter consistent with 2.6.x
* refactor filterUsingStaticTag using lambda in tagRouter
* Modified to lower camel case (#3003)
* wrong event setting (#3043)
* wrong event setting
* modify event seeting
* modify
* call the util method (#3230)
* Code optimization, call the util method
* mofidy
* modify *
* import package
* Qos heart (#3170)
* qos heart question fix #3165
* modify
* judge if it's a IdleStateEvent
* add UT
* modify
* Merge pull request #3246 from cvictory:2.7.0-release remove gson from dubbo.jar in shading mode , and change to dependency way.
* just for modify comments and imports
* remove gson from dubbo.jar in shading mode, add dependency
* Extract compareTo impl to Router interface and concrete Router only responsible for provide priority. (#3240)
something is waiting for us to disscuss:
1. Every Route implement should set a priority?
2.https://github.com/apache/incubator-dubbo/issues/3249
* Protocol compatibility (#3254)
add default method into Protocol .
* remove getContext() (#3235)
* modify some typos (#3257)
* modify some typos
* fix some other addionalParameterKeys and paramter typos
* Merge 2.6.6 source code into 2.7 (#3241)
* Merge 2.6.6 source code into 2.7
* Fixed logging level for https://github.com/apache/incubator-dubbo/pull/3241#discussion_r248195964
* Change the implementation for apache/incubator-dubbo#3241
* Remove the implementation Ordered, because it does not work in Spring Framework : apache/incubator-dubbo#3241
* Remove the implementation Ordered, because it does not work in Spring Framework : apache/incubator-dubbo#3241
* Only Optimize Imports
* Add activation for the release profile
* Update the Java SE link to Java 8.
* Move the doclint configuration to correct position.
* Deactivate maven release profile.
* Fix final name.
* Optimize the Apollo extension of Config-Center SPI
* must shutdown thread pool when no in use (#3255)
* must shutdown thread pool when no in use
* Update 2.7.0 release notes
* Igonre .patch file.
* [maven-release-plugin] prepare release dubbo-2.7.0
* [maven-release-plugin] prepare for next development iteration
* [maven-release-plugin] prepare release dubbo-2.7.0
* [maven-release-plugin] prepare for next development iteration
* Bring back redis auth UT (#3278)
* Optimize code: Fix Constructor to determine illegal logic problems (#3197)
* fix return type (#3284)
* use standardcharset.utf-8 instead of literal (#3285)
* use standardcharset.utf-8 instead of literal
* remove unused import
* Move the iteration of methods of a service config to the if block of the class have method declared not by Object; remove some useless parameter type (#3282)
* Add shutdown command for telnet (#3280)
* telnet add shutdown command
* refactor rename shutDown to shutdown
* remove unregister in doDestroy
* unregister the ShutdownHook when the shutdown command invoked
* Ignore mvn wrapper binary files.
* [maven-release-plugin] prepare release dubbo-2.7.0
* [maven-release-plugin] prepare for next development iteration
* Fix typo (#3293)
* Improve/heartbeat (#3276)
* add the notice of code style
* modify the pic
* del teh faq.md, move to dubbo admin
* improve:remove the heartbeat on server side
* improve:change the scope of timer to static
* code optimization (#3297)
* further enhancement for pull request #3297, also fix an issue introduced in this pull request (#3303)
* further enhancement for pull request #3297, also fix an issue introduced
in this pull request
* rename the variable
* enhance the readability
* Fix UT conflicts of merging 2.7.0-release
* Remove usage of classes in Junit 4
* Remove usage of classes in Junit 4
* Remove usage of classes in Junit 4
* Remove usage of classes in Junit 4
* Remove usage of classes in Junit 4
* remove not used import (#3309)
* remove unused import (#3311)
* remove not used import
* remove unused import
* Degrade some UTs in dubbo-config-spring to use junit 4.
* use beforeEach and afterEach
* Merge pull request #3295, unregister consumer url when client destroyed (referenceconfig#destroy).
* fix client reconnect offline provider.
* refactor cancel future.
* fix client reconnect offline provider.
* refactor cancel future.
* fix client reconnect offline provider.
* refactor cancel future.
* fix unregister when client destroyed
* Optimize heartbeat (#3299)
* Optimize heartbeat.
We should cancel the timeout when the client or server is close.
* change the hashedWheelTimer's ticks
* Optimize tasks keeper.
* fix timeout cancel to task cancel.
keep task directly.
* simply telnet command enabled check logic (#3316)
* simply telnet command enabled check
* Add comments, manually merge #3181.
* Fix for loop reference test pass on protostuff (#3252)
* Fix maven compile warning (#3322)
* Merge pull request #3174, make timeout filter not work in async way.
* Merge pull request #3323, fix double-checked locking.
* Merge pull request #2959, fix a bug of service config.
* Fix random ut falling in DubboMonitorTest (#3327)
* Merge pull request #3017, fixes #2981, refresh invocation's attachments in each invoke.
Fixes #2981.
* Merge pull request #3141, optimize outbound event and some code formatting.
* Merge pull request #3333, add @Override for sub-class method.
* Fix thrift protocol, use path to locate exporter. (#3331)
* Fix thrift protocol, use path to locate exporter.
* Fix UT
* fix #2842. remove duplicate SPI definitions for 2.7.x (#3340)
remove duplicate SPI definitions for 2.7.x
* fix org.apache.dubbo replace com.alibaba.dubbo (#3338)
org.apache.dubbo replace com.alibaba.dubbo
* fix the typo of notification mail list address (#3335)
fix the typo of notification mail list address
* Review code of TypeDefinitionBuilder (#3064)
* Review code of TypeDefinitionBuilder
1. use init method to init builds' list
* use single list for all builders.
Seems like the builder is thread-safe, we can keep them static and final.
* clean code.
* [Dubbo-3339] Remove futility check code (#3346)
* Remove futility check code
* add no-argument constructor method to URL.java fix #3342 (#3350)
* Fix NullPointerException when Hessian instantiate URL with JavaDeserializer
* Enable ZookeeperMetadataReportTest (#3360)
* Package name error (#3354)
* some optimize on ExtensionLoader (#3307)
* some optimize on ExtensionLoader
* make ci rerun
* fix compile error
* fix ci failure
* Fix some unit test failure (#3337)
* Fix compilation error fix #3365 (#3366)
* [Dubbo-900] Fix 通过 override 修改 hessian协议的提供者的配置 不生效 #900 (#3363)
* reExport fail fix#900
* modify
* use Objects.equals
* compare URL for all proxy protocol
* delete useless judgment (#3326)
* Fix self assignment (#3301)
* Fix self assignment
* Replace set with list to insure item order
* Minor tweak of codestyle
* [Dubbo-2423] Multicast demo fails with message "Can't assign requested address". (#3317)
* Fix #2423, Multicast demo fails with message "Can't assign requested address"
* temporarily disable ipv6 test
* simplify map empty judgment (#3376)
* 应该是非空才循环,不然会导致在使用redis注册中心时消费者引用不到服务 (#3291)
* enhance unit test and logging (#3374)
* enhance unit test and logging
* enhance logging message
* fix unit test
* make code clean
* follow up for #3291 (#3378)
* correct typos,eg: occured -> occurred (#3380)
LGTM
* follow up for #3376 (#3377)
* [Dubbo-3347] Update package name in README file fix#3347 (#3362)
* [Enhancement] Replace explicit resource management with try-with-resource (#3281)
* first pull request (#3396)
* [Dubbo-3361] Make DubboAppender extends from FileAppender (#3383)
* Modify deprecated class to updated class in some comments (#3402)
* Merge pull request #3341, start to use IdleStateHandler in Netty4.
* Enhancement/logger factory (#3389)
* polishing LoggerFactory
* polishing code using map.computeIfAbsent
* fix ci failure
* remove unnecessary break in switch
* call overloaded method
* update as requested
* add unit test
* move construction of ConfigChangeEvent outside the lambda expression (#3398)
* make ConfigChangeEvent immutable (#3403)
* Fix license issues (#3382)
* Fix license issues
* revert change to Netty's copyright
* [Dubbo-936]fix The nc command is unstable in the dubbo startup script #936 (#3375)
* fix dubbo启动脚本中nc命令不稳定 #936
* modify
* refactor ScriptRouter: (#3404)
1, remove priority field, the same as super class
2, remove getUrl method, the same as super class
3, refactor constructor, extract method: getRule, getEngine
4, refactor route, extract method: createBindings, getRoutedInvokers
* Clean pom.xml file #3186 (#3211)
* update as requested
* add meta space size arguments
* [Enhancement] Use ThreadLocalRandom and try-with-resource (#3239)
* polish
* fix code reviews
* empty
* polish pom.xml (remove test profile and jvm permSize args) (#3407)
* update dubbo samples' link (#3413)
* Acesslog dateformat enhancemnet (#3274)
* #3026 Access log related changed
* Reviwe comment incorporated given by @satansk and removed unuded method
* Incorporated @beiwei30 review comment, incorporated common-lang3 time package modified version
* Added rat entry for common lang3 FastDateFormat related java files
* switch back to jdk's dateformatter
* refactor loadClass method (#3410)
* refactor: expression is always true, remove it
(names != null && names.length > 0)
* Update dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionLoader.java
Co-Authored-By: wanghbxxxx <wa...@gmail.com>
* Update ExtensionLoader.java
* Update ExtensionLoader.java
* Update ExtensionLoader.java
* Update ExtensionLoader.java
* implement pull request #3412 on master branch (#3418)
* event of response fix#3244 (#3247)
* [Dubbo-3069]Use regular expressions to judge fix #3069 (#3093)
* Use regular expressions to judge fix #3069
* moved into Constants class
* modify
* Unused import
* modify
* can not put it in front
* catch NumberFormatException and return 'null' if necessary
* remove recursive call
* support .1 and 1.
* modify
* Support multiple shared links (#2457)
* make dubbo support multiple shared links, upgrading RPC throughput
* Fix compilation error
* Fix compilation error
* opti import
* if add {}
* checkstyle fail
* fix getSharedClient referenceCount calculation error bug
* 优化 import
* Fix the problem that the getSharedClient thread is not safe
* Fix the problem that the getSharedClient thread is not safe
* Try fixing ci error, https://travis-ci.org/apache/incubator-dubbo/jobs/453185295
* 将DEFAULT_CONNECTIONS_KEY修改成SERVICE_CONNECTIONS_KEY
* dubbo.xsd add shareconnections attribute,
* Optimize code format
* Fix mult connect ghost connect problem
* format code
* Remove the concept of ghostClientMap and ghost connection. In fact, ghostClient is LazyConnectExchangeClient. At present, the LazyConnectExchangeClient object is added directly in ReferenceCountExchangeClient to realize the mapping relationship with ReferenceCountExchangeClient. The relationship between previous ghostClient and url mapping is not applicable to the current new share. Multiple connections.
* Optimize the ReferenceCountExchangeClient and remove the reference to the lazyConnectExchangeClient because it doesn't make much sense; add locks in the close operation of the AbstractClient, because connect, disconnect, and close should not be done at the same time.
* format code
* try remove close lock
* Restore close method
* Restore ReferenceCountExchangeClient reference to LazyConnectExchangeClient object
* Optimize the logic of using the LazyConnectExchangeClient inside the ReferenceCountExchangeClient; Supplemental shared multi-connected unit test
* remove useless catch exception (#3421)
* remove duplicated import (#3440)
* Update junit to 5.4.0 release version (#3441)
* update junit to 5.4.0 release version
* remove uesles config
* remove duplicated unused method and move unit test (#3446)
* Add checkstyle rule for redundant import (#3444)
* add checkstyle for redundant import and fix all issue in repo
* fix git diff issue
* Enhance the java doc of dubbo-container module (#3437)
Fixes #2994
* refactor adaptive extension class code creation: extract class AdaptiveClassCodeGenerator (#3419)
* refactor adaptive extension class code creation:
extract createAdaptiveExtensionClassCode to class
AdaptiveClassCodeGenerator
* add some comment
* add license and comment
* remove main method
* refactor javassist compiler: extract class CtClassBuilder (#3424)
* refactor JavassistCompiler
* rename variable names
* reformat code
* refactor: prepend modifier of constructor, field and method outside the
JavassistClassInfo
* add null for ClassUtils.getSimpleClassName
* rename JavassistClassInfo to CtClassBuilder
* fix #2619: is there a problem in NettyBackedChannelBuffer.setBytes(...)? (#3448)
* Bugfix/timeout queue full (#3451)
replace ArrayBlockingQueue with LinkedBlockingQueue and remove capacity.
* extract 2 methods: (#3453)
isSetter: test if a method is a setter
getSetterProperty: get property for setter, for instance setVersion
return "version"
* Add delay export test case (#3447)
* [Dubbo-3237]fix connectionMonitor in RestProtocol seems not work #3237 (#3455)
* extract method to cache default extension name (#3456)
* possibly bug fix (#3460)
* Merge pull request #3470, Apache parent pom version is updated to 21.
* A follow up of 6058846, update apache pom version to 21
* Class comment error (#3481)
* enhancement: extract duplicated method calls to variable (#3482)
extract duplicated method calls to variable
* [Enhancement]: language level migration (#3485)
* use java7 diamond operator
* replace Collections.sort with List.sort
* extract duplicated code blocks
* use StandardCharsets.UTF_8
* use try-with-resources
* use java7 diamond operator
* enhance log message
* fix unit tests failures
* Branch refactor version (#3471)
* fix typo (#3491)
* [Enhancement]: RestProtocol (#3480)
* Merge pull request #3466, Condition is not properly used.
fixes #1917
* fix issue#1293: A question for ReferenceConfigCache. (#3505)
* [Enhancement]: refactor categorizing with Collectors.groupingBy (#3490)
* Fix invocation of toString on an array (#3507)
Fix invocation of toString on an array
* Fix inefficient use of keySet iterator instead of entrySet iterator (#3508)
Fix inefficient use of keySet iterator instead of entrySet iterator
* Boolean class use method toString() instead of String.valueof() (#3495)
* Merge pull request #3515, add metadataFactory SPI config for all-in-one shade jar.
Fixes #3514, missing redis metadata SPI extension in dubbo.jar.
* Merge pull request #3513, bump up hessian-lite version
Fixes #3423.
* [Dubbo-3106]Make getRegistered return unmodifiable collection. #3106 (#3425)
* make getRegistered return unmodifiable collection. #3106
* fix ci failure
* Merge pull request #3527 Bricks-Man/incubator-dubbo, fix accidentally check exchanger in setDispatcher
fixes #3518
* Fix UT error following PR #3527
* Cache CompiledScript #390 (#3524)
* Merge pull request #3532 from beiwei30:use-concurrent-map, avoid using synchronized.
* Fix context filter's bug (#3526)
* Modify MetadataReportRetry ThreadName (#3550)
* fix: rename the thread name from DubboRegistryFailedRetryTimer to DubboMetadataReportRetryTimer in MetadataReportRetry
* fix issue #3533 (#3548)
* fix issue #195: @Reference check=false不生效 (#3530)
* Merge pull request #3528, fixes #208, setOnreturn does not work with generic invocation.
* fix issue #274: monitor的cluster一定是failsafe的,而且无法修改 (#3523)
* fix issue #274: monitor的cluster一定是failsafe的,而且无法修改
* remove unused import
* Merge pull request #3520, fix #538 polish the process of deciding the ip to bind.
* Fix npe when package is null. (#3557)
* a more elegant way (#3567)
* Correct security report link.
* Add go implementation link.
* fix DubboCodec re-implements Codec2 #2977 (#3547)
* Merge pull request #3566, optimize compareTo of Router to guarantee consistent behaviour.
* Merge pull request #3577, rmi support generic.
Fixes #2779
* Fixes #3367, fail to parse config text with white space (#3589)
* [DUBBO-3476]: NullPointerException happened when using SpringContainer.getContext() (#3600)
* #3476: NullPointerException happened when using SpringContainer.getContext()
* rollback change for DEFAULT_SPRING_CONFIG
* replace magic string "dubbo" with constants (#3602)
* dubbo-parent是头文件不包含依赖。替换成dubbo, 同时增加zk连接的依赖。因为curator-framework在dubbo-dependencies当中去除掉了zookeeper的包,所以外部使用的时候需要额外配置. (#3516)
* Merge pul request #3607, introduce dubbo-dependencies-zookeeper.
* Merge RestProtocolTest.java (#3597)
* [DUBBO-3494]: Refactor URL to URLBuilder (#3500)
* refactor URL to URLBuilder. #3494
* remove unrelated changes
* replace more with URLBuilder
* fix ci failure
* remove unnecessary comment
* Dubbo-3473 Fix Not Properly Closed Resources (#3474)
* Dump TagRouterRule (#3536)
Dump TagRouterRule since the TagRouterRule can be changed to `null` by ConfigCenter
* Merge pull request #3578, fixes #3289, enhance tagRoute: support ip expression match.
* Merge pull request #2614, follow up for issue #195.
* [Dubbo-3367] Fail to parse config text with white space (#3590)
* Merge pull request #3558, check if remoteGroup is empty or not.
Fixes #3555.
* Fluent style builder API support(#3431) (#3549)
* Update maven central badge.
* Merge pull request #3593, Consul support for Registry and Metadata.
* [Dubbo-808] Support etcd registry (#3605)
* Merge https://github.com/dubbo/dubbo-registry-etcd into incubator-dubbo
* Add UT to ConfigurationUtilsTest
* rename dubbo-ops to dubbo-admin (#3628)
* typo for AccessLogFilter (#3633)
* Fix some etcd3 registry bugs. (#3632)
* fix some bugs.
* fix typo
* cancel keep alive if recovery failed.
* remove duplicate license header.
* [Dubbo-3570] repackage compatible enhancement. (#3622)
* Fixes #3570, NoSuchMethodError are thrown when add custorm Filter using dubbo2.6.5 and JDK1.6 and upgrade to dubbo2.7.0
* Add compatible UT
* fix UT
* Replace RpcStatus to count (#2984) (#3636)
* Fix when qos is disable,log will print every time. (#3397)
* fix when qos is disable,log will print every time.
* change qos server boos thread number 1
* add openjdk to travis (#3300)
* add openjdk to travis
* add openjdk to travis
* Merge pull request #3647, workaround to fix #3646.
* add metrics integration #3598 (#3643)
* add metrics integration
* add license
* Merge pull request #3639, Add equivalent annotation support for MethodConfig.
Fixes #2045
* Fixes #3478, #3477 and #3445
* fix heartbeat internal (#3579)
* Merge pull request #3603, configcenter share zookeeper connection with registry.
Fixes #3288
* correct spelling error (#3645)
* make snakeyaml transitive, governance rule relies on this dependency to work. (#3659)
* check null for path before call rest server (#3665)
* [Dubbo-3653] etcd as config center (#3663)
* Minor refactor, no functinoal change.
* Separate ConnectionStateListener
* Simplify code
* Fix typo
* Support get external config from etcd config center
* Polish diamond operator
* Initial etcd support as config center
* Add a put interface for JEtcdClient
* Enhanced Etcd config center support with the ability to watch and cancel watch
* Polish code
* Distinguish modification event and delete event
* Add etcd registry and configcenter to dubbo-all
* Watch again when connection is re-established
* Polish code and fix some documentation errors (#3655)
* [Dubbo-3657] Fix junit test failed (#3658)
* Improve the checking of lease id. #3684 (#3692)
It looks good.
* Optimize DefaultTpsLimiter (#3654)
* Correct @Parameter config of field of ConfigCenterConfig (#3688)
* fix-3678 (#3681)
* Add unit test for unpack and stick pack of dubbo and telent (#3703)
* fix compile error after merged master branch
* remove useless imports
* add AddressListener into RegistryDirectory
---
.travis.yml | 5 +
CHANGES.md | 69 +-
CONTRIBUTING.md | 2 +-
LICENSE | 14 +-
README.md | 69 +-
codestyle/checkstyle.xml | 1 +
dubbo-all/pom.xml | 85 +-
dubbo-bom/pom.xml | 34 +-
dubbo-cluster/pom.xml | 2 +-
.../org/apache/dubbo/rpc/cluster/Configurator.java | 1 +
.../java/org/apache/dubbo/rpc/cluster/Router.java | 11 +
.../override/OverrideConfigurator.java | 2 +-
.../override/OverrideConfiguratorFactory.java | 2 +-
.../cluster/configurator/parser/ConfigParser.java | 2 +-
.../rpc/cluster/directory/StaticDirectory.java | 7 +-
.../cluster/loadbalance/AbstractLoadBalance.java | 3 +-
.../loadbalance/ConsistentHashLoadBalance.java | 10 +-
.../dubbo/rpc/cluster/router/AbstractRouter.java | 9 +-
.../cluster/router/condition/ConditionRouter.java | 12 +-
.../cluster/router/condition/config/AppRouter.java | 5 +
.../router/condition/config/ListenableRouter.java | 4 +-
.../router/condition/config/ServiceRouter.java | 5 +
.../rpc/cluster/router/file/FileRouterFactory.java | 8 +-
.../cluster/router/mock/MockInvokersSelector.java | 18 +-
.../rpc/cluster/router/script/ScriptRouter.java | 112 +-
.../dubbo/rpc/cluster/router/tag/TagRouter.java | 83 +-
.../cluster/support/AbstractClusterInvoker.java | 26 +-
.../dubbo/rpc/cluster/support/ClusterUtils.java | 4 +-
.../support/wrapper/MockClusterInvoker.java | 3 +-
.../org/apache/dubbo/rpc/cluster/StickyTest.java | 20 +-
.../absent/AbsentConfiguratorTest.java | 20 +-
.../override/OverrideConfiguratorTest.java | 20 +-
.../configurator/parser/ConfigParserTest.java | 193 +-
.../rpc/cluster/directory/StaticDirectoryTest.java | 10 +-
.../loadbalance/ConsistentHashLoadBalanceTest.java | 48 +-
.../loadbalance/LeastActiveBalanceTest.java | 17 +-
.../cluster/loadbalance/LoadBalanceBaseTest.java | 42 +-
.../cluster/loadbalance/RandomLoadBalanceTest.java | 19 +-
.../loadbalance/RoundRobinLoadBalanceTest.java | 39 +-
.../dubbo/rpc/cluster/merger/ResultMergerTest.java | 122 +-
.../cluster/router/ConfigConditionRouterTest.java | 10 +-
.../dubbo/rpc/cluster/router/TagRouterTest.java | 10 +-
.../router/condition/ConditionRouterTest.java | 84 +-
.../cluster/router/file/FileRouterEngineTest.java | 20 +-
.../cluster/router/script/ScriptRouterTest.java | 81 +-
.../support/AbstractClusterInvokerTest.java | 94 +-
.../rpc/cluster/support/ClusterUtilsTest.java | 50 +-
.../support/FailSafeClusterInvokerTest.java | 14 +-
.../support/FailbackClusterInvokerTest.java | 60 +-
.../support/FailfastClusterInvokerTest.java | 28 +-
.../support/FailoverClusterInvokerTest.java | 16 +-
.../cluster/support/ForkingClusterInvokerTest.java | 24 +-
.../support/MergeableClusterInvokerTest.java | 14 +-
.../support/wrapper/MockClusterInvokerTest.java | 120 +-
dubbo-cluster/src/test/resources/log4j.xml | 1 +
dubbo-common/pom.xml | 2 +-
.../java/org/apache/dubbo/common/Constants.java | 65 +-
.../java/org/apache/dubbo/common/Parameters.java | 38 +-
.../java/org/apache/dubbo/common/Resetable.java | 60 +-
.../src/main/java/org/apache/dubbo/common/URL.java | 189 +-
.../java/org/apache/dubbo/common/URLBuilder.java | 350 ++++
.../main/java/org/apache/dubbo/common/Version.java | 158 +-
.../dubbo/common/bytecode/ClassGenerator.java | 8 +-
.../org/apache/dubbo/common/bytecode/Proxy.java | 22 +-
.../org/apache/dubbo/common/bytecode/Wrapper.java | 78 +-
.../dubbo/common/compiler/support/ClassUtils.java | 27 +-
.../common/compiler/support/CtClassBuilder.java | 174 ++
.../common/compiler/support/JavassistCompiler.java | 97 +-
.../dubbo/common/concurrent/ExecutionList.java | 180 --
.../dubbo/common/config/ConfigurationUtils.java | 6 +-
.../extension/AdaptiveClassCodeGenerator.java | 381 ++++
.../dubbo/common/extension/ExtensionLoader.java | 481 ++---
.../extension/support/ActivateComparator.java | 129 +-
.../java/org/apache/dubbo/common/json/JSON.java | 2 +
.../org/apache/dubbo/common/json/JSONWriter.java | 1 +
.../java/org/apache/dubbo/common/json/Yylex.java | 1 +
.../org/apache/dubbo/common/logger/Logger.java | 40 +-
.../apache/dubbo/common/logger/LoggerFactory.java | 73 +-
.../threadpool/support/AbortPolicyWithReport.java | 63 +-
.../dubbo/common/timer/HashedWheelTimer.java | 18 +-
.../org/apache/dubbo/common/utils/CIDRUtils.java | 140 ++
.../org/apache/dubbo/common/utils/ClassHelper.java | 38 +-
.../apache/dubbo/common/utils/CollectionUtils.java | 14 +-
.../dubbo/common/utils/CompatibleTypeUtils.java | 13 +-
.../org/apache/dubbo/common/utils/ConfigUtils.java | 4 +-
.../apache/dubbo/common/utils/DubboAppender.java | 13 +-
.../apache/dubbo/common/utils/ExecutorUtil.java | 13 +-
.../org/apache/dubbo/common/utils/NetUtils.java | 279 ++-
.../org/apache/dubbo/common/utils/PojoUtils.java | 20 +-
.../org/apache/dubbo/common/utils/StringUtils.java | 76 +-
.../org/apache/dubbo/common/utils/UrlUtils.java | 47 +-
.../org/apache/dubbo/common/URLBuilderTest.java | 100 +
.../test/java/org/apache/dubbo/common/URLTest.java | 40 +-
.../common/beanutil/JavaBeanAccessorTest.java | 16 +-
.../common/beanutil/JavaBeanSerializeUtilTest.java | 319 +--
.../dubbo/common/bytecode/ClassGeneratorTest.java | 5 +-
.../apache/dubbo/common/bytecode/MixinTest.java | 7 +-
.../apache/dubbo/common/bytecode/ProxyTest.java | 48 +-
.../apache/dubbo/common/bytecode/WrapperTest.java | 60 +-
.../compiler/support/AdaptiveCompilerTest.java | 6 +-
.../common/compiler/support/ClassUtilsTest.java | 136 +-
.../compiler/support/JavassistCompilerTest.java | 26 +-
.../common/compiler/support/JdkCompilerTest.java | 36 +-
.../concurrent/CompletableFutureTaskTest.java | 4 +-
.../dubbo/common/concurrent/ExecutionListTest.java | 94 -
.../common/config/ConfigurationUtilsTest.java | 69 +
.../common/config/PropertiesConfigurationTest.java | 6 +-
.../common/extension/ExtensionLoaderTest.java | 77 +-
.../extension/ExtensionLoader_Adaptive_Test.java | 36 +-
...tensionLoader_Adaptive_UseJdkCompiler_Test.java | 8 +-
.../extension/ExtensionLoader_Compatible_Test.java | 4 +-
.../extension/ext6_inject/impl/Ext6Impl1.java | 6 +-
.../extension/support/ActivateComparatorTest.java | 14 +-
.../java/org/apache/dubbo/common/io/BytesTest.java | 29 +-
.../apache/dubbo/common/io/StreamUtilsTest.java | 87 +-
.../common/io/UnsafeByteArrayInputStreamTest.java | 29 +-
.../common/io/UnsafeByteArrayOutputStreamTest.java | 9 +-
.../dubbo/common/io/UnsafeStringReaderTest.java | 15 +-
.../dubbo/common/io/UnsafeStringWriterTest.java | 31 +-
.../apache/dubbo/common/json/JSONReaderTest.java | 4 +-
.../org/apache/dubbo/common/json/JSONTest.java | 26 +-
.../apache/dubbo/common/json/JSONWriterTest.java | 5 +-
.../dubbo/common/logger/LoggerAdapterTest.java | 56 +-
.../dubbo/common/logger/LoggerFactoryTest.java | 14 +-
.../org/apache/dubbo/common/logger/LoggerTest.java | 51 +-
.../dubbo/common/logger/slf4j/Slf4jLoggerTest.java | 2 +-
.../common/logger/support/FailsafeLoggerTest.java | 16 +-
.../org/apache/dubbo/common/status/StatusTest.java | 4 +-
.../status/support/LoadStatusCheckerTest.java | 4 +-
.../status/support/MemoryStatusCheckerTest.java | 4 +-
.../common/status/support/StatusUtilsTest.java | 4 +-
.../common/store/support/SimpleDataStoreTest.java | 10 +-
.../threadlocal/InternalThreadLocalTest.java | 36 +-
.../NamedInternalThreadFactoryTest.java | 6 +-
.../support/AbortPolicyWithReportTest.java | 2 +-
.../support/cached/CachedThreadPoolTest.java | 4 +-
.../support/eager/EagerThreadPoolExecutorTest.java | 10 +-
.../support/eager/EagerThreadPoolTest.java | 4 +-
.../threadpool/support/eager/TaskQueueTest.java | 27 +-
.../support/fixed/FixedThreadPoolTest.java | 4 +-
.../support/limited/LimitedThreadPoolTest.java | 4 +-
.../dubbo/common/timer/HashedWheelTimerTest.java | 2 +-
.../apache/dubbo/common/utils/ArrayUtilsTest.java | 6 +-
.../org/apache/dubbo/common/utils/AssertTest.java | 32 +-
.../common/utils/AtomicPositiveIntegerTest.java | 29 +-
.../apache/dubbo/common/utils/CIDRUtilsTest.java | 56 +
.../apache/dubbo/common/utils/ClassHelperTest.java | 44 +-
.../dubbo/common/utils/CollectionUtilsTest.java | 21 +-
.../common/utils/CompatibleTypeUtilsTest.java | 10 +-
.../apache/dubbo/common/utils/ConfigUtilsTest.java | 22 +-
.../dubbo/common/utils/DubboAppenderTest.java | 12 +-
.../dubbo/common/utils/ExecutorUtilTest.java | 4 +-
.../org/apache/dubbo/common/utils/HolderTest.java | 4 +-
.../org/apache/dubbo/common/utils/IOUtilsTest.java | 29 +-
.../apache/dubbo/common/utils/LRUCacheTest.java | 8 +-
.../apache/dubbo/common/utils/LogHelperTest.java | 2 +-
.../org/apache/dubbo/common/utils/LogTest.java | 4 +-
.../org/apache/dubbo/common/utils/LogUtilTest.java | 8 +-
.../dubbo/common/utils/NamedThreadFactoryTest.java | 10 +-
.../apache/dubbo/common/utils/NetUtilsTest.java | 123 +-
.../apache/dubbo/common/utils/ParametersTest.java | 6 +-
.../apache/dubbo/common/utils/PojoUtilsTest.java | 64 +-
.../dubbo/common/utils/ReflectUtilsTest.java | 34 +-
.../org/apache/dubbo/common/utils/StackTest.java | 45 +-
.../apache/dubbo/common/utils/StringUtilsTest.java | 39 +-
.../apache/dubbo/common/utils/UrlUtilsTest.java | 12 +-
.../apache/dubbo/common/version/VersionTest.java | 44 +-
dubbo-common/src/test/resources/log4j.xml | 28 +-
dubbo-compatible/pom.xml | 2 +-
.../main/java/com/alibaba/dubbo/common/URL.java | 7 +-
.../alibaba/dubbo/config/annotation/Reference.java | 2 +-
.../main/java/com/alibaba/dubbo/rpc/Invoker.java | 19 +-
.../main/java/com/alibaba/dubbo/rpc/Protocol.java | 16 +
.../java/com/alibaba/dubbo/rpc/cluster/Router.java | 12 +-
.../annotation/CompatibleReferenceBeanBuilder.java | 51 +-
.../CompatibleAnnotationBeanDefinitionParser.java | 4 +-
.../java/org/apache/dubbo/cache/CacheTest.java | 6 +-
.../dubbo/common/extension/ExtensionTest.java | 16 +-
.../dubbo/common/extension/MockDispatcher.java | 14 +-
.../apache/dubbo/config/ApplicationConfigTest.java | 13 +-
.../apache/dubbo/config/ArgumentConfigTest.java | 4 +-
.../java/org/apache/dubbo/config/ConfigTest.java | 14 +-
.../apache/dubbo/config/ConsumerConfigTest.java | 4 +-
.../org/apache/dubbo/config/MethodConfigTest.java | 6 +-
.../org/apache/dubbo/config/ModuleConfigTest.java | 15 +-
.../apache/dubbo/config/ProtocolConfigTest.java | 4 +-
.../apache/dubbo/config/ProviderConfigTest.java | 4 +-
.../apache/dubbo/config/ReferenceConfigTest.java | 10 +-
.../apache/dubbo/config/RegistryConfigTest.java | 4 +-
.../org/apache/dubbo/echo/EchoServiceTest.java | 8 +-
.../java/org/apache/dubbo/filter/FilterTest.java | 31 +-
.../org/apache/dubbo/filter/LegacyInvocation.java | 88 +
.../filter/{MyInvoker.java => LegacyInvoker.java} | 148 +-
.../apache/dubbo/generic/GenericServiceTest.java | 67 +-
.../apache/dubbo/rpc/cluster/CompatibleRouter.java | 1 +
...ompatibleRouter.java => CompatibleRouter2.java} | 2 +-
.../{CompatibleRouter.java => NewRouter.java} | 23 +-
.../{CompatibleRouter.java => RouterTest.java} | 40 +-
.../dubbo/serialization/SerializationTest.java | 8 +-
.../org/apache/dubbo/service/ComplexObject.java | 15 +-
.../services/org.apache.dubbo.remoting.Dispatcher | 18 +
dubbo-config/dubbo-config-api/pom.xml | 2 +-
.../org/apache/dubbo/config/AbstractConfig.java | 38 +-
.../dubbo/config/AbstractInterfaceConfig.java | 46 +-
.../apache/dubbo/config/AbstractMethodConfig.java | 2 +-
.../dubbo/config/AbstractReferenceConfig.java | 4 +-
.../apache/dubbo/config/AbstractServiceConfig.java | 9 +-
.../org/apache/dubbo/config/ApplicationConfig.java | 3 +-
.../org/apache/dubbo/config/ArgumentConfig.java | 12 +-
.../apache/dubbo/config/ConfigCenterConfig.java | 18 +-
.../org/apache/dubbo/config/ConsumerConfig.java | 16 +-
.../apache/dubbo/config/MetadataReportConfig.java | 2 +-
.../java/org/apache/dubbo/config/MethodConfig.java | 45 +-
.../java/org/apache/dubbo/config/ModuleConfig.java | 6 +-
.../org/apache/dubbo/config/ProtocolConfig.java | 8 +-
.../org/apache/dubbo/config/ProviderConfig.java | 4 +-
.../org/apache/dubbo/config/ReferenceConfig.java | 143 +-
.../org/apache/dubbo/config/ServiceConfig.java | 189 +-
.../apache/dubbo/config/annotation/Argument.java} | 35 +-
.../org/apache/dubbo/config/annotation/Method.java | 69 +
.../apache/dubbo/config/annotation/Reference.java | 10 +-
.../apache/dubbo/config/annotation/Service.java | 6 +
.../dubbo/config/builders/AbstractBuilder.java | 69 +
.../config/builders/AbstractInterfaceBuilder.java | 294 +++
.../AbstractMethodBuilder.java} | 406 ++--
.../config/builders/AbstractReferenceBuilder.java | 142 ++
.../config/builders/AbstractServiceBuilder.java | 246 +++
.../dubbo/config/builders/ApplicationBuilder.java | 193 ++
.../ArgumentBuilder.java} | 46 +-
.../dubbo/config/builders/ConfigCenterBuilder.java | 148 ++
.../dubbo/config/builders/ConsumerBuilder.java | 118 ++
.../dubbo/config/builders/DubboBuilders.java | 72 +
.../config/builders/MetadataReportBuilder.java | 140 ++
.../dubbo/config/builders/MethodBuilder.java | 237 +++
.../dubbo/config/builders/ModuleBuilder.java | 132 ++
.../dubbo/config/builders/MonitorBuilder.java | 137 ++
.../dubbo/config/builders/ProtocolBuilder.java | 419 ++++
.../dubbo/config/builders/ProviderBuilder.java | 293 +++
.../dubbo/config/builders/ReferenceBuilder.java | 134 ++
.../dubbo/config/builders/RegistryBuilder.java | 309 +++
.../dubbo/config/builders/ServiceBuilder.java | 152 ++
.../dubbo/config/utils/ReferenceConfigCache.java | 55 +-
.../apache/dubbo/config/AbstractConfigTest.java | 226 ++-
.../dubbo/config/AbstractInterfaceConfigTest.java | 324 ++--
.../dubbo/config/AbstractMethodConfigTest.java | 4 +-
.../dubbo/config/AbstractReferenceConfigTest.java | 4 +-
.../dubbo/config/AbstractServiceConfigTest.java | 4 +-
.../apache/dubbo/config/ApplicationConfigTest.java | 13 +-
.../apache/dubbo/config/ArgumentConfigTest.java | 4 +-
.../dubbo/config/ConfigCenterConfigTest.java | 7 +-
.../apache/dubbo/config/ConsumerConfigTest.java | 4 +-
.../org/apache/dubbo/config/MethodConfigTest.java | 56 +-
.../org/apache/dubbo/config/ModuleConfigTest.java | 18 +-
.../org/apache/dubbo/config/MonitorConfigTest.java | 4 +-
.../apache/dubbo/config/ProtocolConfigTest.java | 4 +-
.../apache/dubbo/config/ProviderConfigTest.java | 4 +-
.../apache/dubbo/config/ReferenceConfigTest.java | 53 +-
.../apache/dubbo/config/RegistryConfigTest.java | 4 +-
.../org/apache/dubbo/config/ServiceConfigTest.java | 83 +-
.../dubbo/config/builders/AbstractBuilderTest.java | 125 ++
.../builders/AbstractInterfaceBuilderTest.java | 310 +++
.../config/builders/AbstractMethodBuilderTest.java | 195 ++
.../builders/AbstractReferenceBuilderTest.java | 148 ++
.../builders/AbstractServiceBuilderTest.java | 245 +++
.../config/builders/ApplicationBuilderTest.java | 255 +++
.../dubbo/config/builders/ArgumentBuilderTest.java | 63 +
.../config/builders/ConfigCenterBuilderTest.java | 177 ++
.../dubbo/config/builders/ConsumerBuilderTest.java | 95 +
.../config/builders/MetadataReportBuilderTest.java | 151 ++
.../dubbo/config/builders/MethodBuilderTest.java | 189 ++
.../dubbo/config/builders/ModuleBuilderTest.java | 112 ++
.../dubbo/config/builders/MonitorBuilderTest.java | 135 ++
.../dubbo/config/builders/ProtocolBuilderTest.java | 338 ++++
.../dubbo/config/builders/ProviderBuilderTest.java | 227 +++
.../config/builders/ReferenceBuilderTest.java | 114 ++
.../dubbo/config/builders/RegistryBuilderTest.java | 256 +++
.../dubbo/config/builders/ServiceBuilderTest.java | 131 ++
.../org/apache/dubbo/config/cache/CacheTest.java | 16 +-
.../DelegateProviderMetaDataInvokerTest.java | 8 +-
.../config/url/ExporterSideConfigUrlTest.java | 14 +-
.../dubbo/config/url/InvokerSideConfigUrlTest.java | 18 +-
.../org/apache/dubbo/config/url/UrlTestBase.java | 2 +-
.../config/utils/ReferenceConfigCacheTest.java | 20 +-
dubbo-config/dubbo-config-spring/pom.xml | 37 +-
.../apache/dubbo/config/spring/AnnotationBean.java | 321 ---
.../apache/dubbo/config/spring/ReferenceBean.java | 13 +-
.../apache/dubbo/config/spring/ServiceBean.java | 662 ++++---
.../AbstractAnnotationConfigBeanBuilder.java | 4 +-
.../AnnotationInjectedBeanPostProcessor.java | 531 +++++
.../DubboConfigBindingBeanPostProcessor.java | 2 +-
.../ReferenceAnnotationBeanPostProcessor.java | 591 ++----
.../factory/annotation/ReferenceBeanBuilder.java | 59 +-
.../ServiceAnnotationBeanPostProcessor.java | 39 +-
.../factory/annotation/ServiceBeanNameBuilder.java | 113 ++
.../annotation/DubboConfigBindingRegistrar.java | 8 +-
.../annotation/DubboConfigConfiguration.java | 1 +
...java => DubboConfigConfigurationRegistrar.java} | 26 +-
.../context/annotation/EnableDubboConfig.java | 2 +-
.../annotation/EnableDubboConfigBinding.java | 2 +
.../context/event/ServiceBeanExportedEvent.java | 47 +-
.../properties/DefaultDubboConfigBinder.java | 3 +-
.../converter/StringArrayToStringConverter.java | 37 -
.../schema/AnnotationBeanDefinitionParser.java | 4 +-
.../spring/schema/DubboBeanDefinitionParser.java | 10 +-
.../spring/status/DataSourceStatusChecker.java | 34 +-
.../util/AnnotatedBeanDefinitionRegistryUtils.java | 62 +
.../dubbo/config/spring/util/AnnotationUtils.java | 230 ++-
.../dubbo/config/spring/util/BeanFactoryUtils.java | 59 +-
.../util/{ObjectUtils.java => ClassUtils.java} | 26 +-
.../dubbo/config/spring/util/ObjectUtils.java | 14 +-
.../config/spring/util/PropertySourcesUtils.java | 60 +-
.../src/main/resources/META-INF/compat/dubbo.xsd | 25 -
.../src/main/resources/META-INF/dubbo.xsd | 6 +
.../config/spring/AbstractRegistryService.java | 6 +-
.../org/apache/dubbo/config/spring/ConfigTest.java | 2041 ++++++++++----------
.../dubbo/config/spring/ServiceBeanTest.java | 7 +-
.../config/spring/SimpleRegistryExporter.java | 8 +-
.../dubbo/config/spring/SimpleRegistryService.java | 3 +-
.../spring/action/DemoActionByAnnotation.java | 67 +-
.../annotation/consumer/AnnotationAction.java | 74 +-
.../AnnotationPropertyValuesAdapterTest.java | 6 +-
.../DubboConfigBindingBeanPostProcessorTest.java | 6 +-
.../ReferenceAnnotationBeanPostProcessorTest.java | 215 +--
.../annotation/ReferenceBeanBuilderTest.java | 126 ++
.../ServiceAnnotationBeanPostProcessorTest.java | 46 +-
.../ServiceAnnotationTestConfiguration.java} | 31 +-
.../annotation/ServiceBeanNameBuilderTest.java | 75 +
.../factory/config/YamlPropertySourceFactory.java | 76 +
.../config/YamlPropertySourceFactoryTest.java | 71 +
.../DubboComponentScanRegistrarTest.java | 32 +-
.../DubboConfigBindingRegistrarTest.java | 12 +-
.../DubboConfigBindingsRegistrarTest.java | 8 +-
.../annotation/DubboConfigConfigurationTest.java | 30 +-
.../context/annotation/EnableDubboConfigTest.java | 28 +-
.../spring/context/annotation/EnableDubboTest.java | 75 +-
.../annotation/consumer/ConsumerConfiguration.java | 6 +-
.../consumer/test/TestConsumerConfiguration.java | 10 +-
.../annotation/provider/DefaultHelloService.java | 1 +
.../annotation/provider/DemoServiceImpl.java | 1 +
.../annotation/provider/ProviderConfiguration.java | 8 +-
.../DubboComponentScanRegistrarTest.java | 40 +-
.../DubboConfigBindingRegistrarTest.java | 17 +-
.../DubboConfigBindingsRegistrarTest.java | 14 +-
.../annotation/DubboConfigConfigurationTest.java | 32 +-
.../annotation/EnableDubboConfigTest.java | 30 +-
.../{ => context}/annotation/EnableDubboTest.java | 50 +-
.../annotation/consumer/ConsumerConfiguration.java | 8 +-
.../consumer/test/TestConsumerConfiguration.java | 12 +-
.../annotation/provider/DefaultHelloService.java | 3 +-
.../annotation/provider/DemoServiceImpl.java | 5 +-
.../annotation/provider/HelloServiceImpl.java} | 17 +-
.../annotation/provider/ProviderConfiguration.java | 8 +-
.../properties/DefaultDubboConfigBinderTest.java | 42 +-
.../properties/DefaultDubboConfigBinderTest.java | 15 +-
.../converter/StringArrayToMapConverterTest.java | 52 -
.../StringArrayToStringConverterTest.java | 46 -
.../extension/SpringExtensionFactoryTest.java | 22 +-
.../spring/schema/DubboNamespaceHandlerTest.java | 39 +-
.../spring/status/DataSourceStatusCheckerTest.java | 12 +-
.../spring/status/SpringStatusCheckerTest.java | 14 +-
.../config/spring/util/BeanFactoryUtilsTest.java | 20 +-
.../spring/util/PropertySourcesUtilsTest.java | 49 +-
.../src/test/resources/META-INF/default.properties | 2 +-
.../resources/META-INF/dubbb-consumer.properties | 12 +
...ovider.properties => dubbb-provider.properties} | 6 +-
.../resources/META-INF/dubbo-consumer.properties | 4 +-
.../resources/META-INF/dubbo-provider.properties | 8 +-
.../src/test/resources/META-INF/dubbo.yml | 8 +
dubbo-config/pom.xml | 2 +-
dubbo-configcenter/dubbo-configcenter-api/pom.xml | 5 +-
.../dubbo/configcenter/ConfigChangeEvent.java | 25 +-
.../mock/AbstractDynamicConfigurationTest.java | 8 +-
.../dubbo-configcenter-apollo/pom.xml | 5 +-
.../support/apollo/ApolloDynamicConfiguration.java | 39 +-
.../dubbo-configcenter-consul/pom.xml | 44 +
.../consul/ConsulDynamicConfiguration.java | 166 ++
.../consul/ConsulDynamicConfigurationFactory.java} | 9 +-
....dubbo.configcenter.DynamicConfigurationFactory | 1 +
dubbo-configcenter/dubbo-configcenter-etcd/pom.xml | 46 +
.../support/etcd/EtcdDynamicConfiguration.java | 187 ++
.../etcd/EtcdDynamicConfigurationFactory.java} | 10 +-
....dubbo.configcenter.DynamicConfigurationFactory | 1 +
.../support/etcd/EtcdDynamicConfigurationTest.java | 141 ++
.../dubbo-configcenter-zookeeper/pom.xml | 20 +-
.../support/zookeeper/CacheListener.java | 91 +-
.../zookeeper/ZookeeperDynamicConfiguration.java | 71 +-
.../ZookeeperDynamicConfigurationFactory.java | 11 +-
.../ZookeeperDynamicConfigurationTest.java | 35 +-
dubbo-configcenter/pom.xml | 9 +-
dubbo-container/dubbo-container-api/pom.xml | 4 +-
.../java/org/apache/dubbo/container/Container.java | 4 +-
.../main/java/org/apache/dubbo/container/Main.java | 6 +-
.../main/resources/META-INF/assembly/bin/start.sh | 2 +-
dubbo-container/dubbo-container-log4j/pom.xml | 2 +-
.../dubbo/container/log4j/Log4jContainer.java | 5 +-
.../dubbo/container/log4j/Log4jContainerTest.java | 2 +-
dubbo-container/dubbo-container-logback/pom.xml | 2 +-
.../dubbo/container/logback/LogbackContainer.java | 4 +-
.../container/logback/LogbackContainerTest.java | 2 +-
dubbo-container/dubbo-container-spring/pom.xml | 84 +-
.../dubbo/container/spring/SpringContainer.java | 8 +-
.../container/spring/SpringContainerTest.java | 6 +-
dubbo-container/pom.xml | 2 +-
.../dubbo-demo-annotation-consumer/pom.xml | 6 +-
.../dubbo-demo-annotation-provider/pom.xml | 6 +-
dubbo-demo/dubbo-demo-annotation/pom.xml | 6 +-
.../dubbo-demo-api/dubbo-demo-api-consumer/pom.xml | 6 +-
.../dubbo-demo-api/dubbo-demo-api-provider/pom.xml | 6 +-
dubbo-demo/dubbo-demo-api/pom.xml | 6 +-
dubbo-demo/dubbo-demo-interface/pom.xml | 2 +-
.../dubbo-demo-xml/dubbo-demo-xml-consumer/pom.xml | 2 +-
.../dubbo-demo-xml/dubbo-demo-xml-provider/pom.xml | 2 +-
dubbo-demo/dubbo-demo-xml/pom.xml | 6 +-
dubbo-demo/pom.xml | 2 +-
dubbo-dependencies-bom/pom.xml | 95 +-
.../dubbo-dependencies-zookeeper/pom.xml | 81 +
dubbo-dependencies/pom.xml | 36 +
dubbo-distribution/pom.xml | 4 +-
dubbo-distribution/src/assembly/source-release.xml | 4 +
dubbo-filter/dubbo-filter-cache/pom.xml | 94 +-
.../apache/dubbo/cache/support/jcache/JCache.java | 3 +-
.../apache/dubbo/cache/filter/CacheFilterTest.java | 82 +-
.../support/expiring/ExpiringCacheFactoryTest.java | 4 +-
.../cache/support/jcache/JCacheFactoryTest.java | 6 +-
.../cache/support/lru/LruCacheFactoryTest.java | 4 +-
.../threadlocal/ThreadLocalCacheFactoryTest.java | 4 +-
dubbo-filter/dubbo-filter-validation/pom.xml | 142 +-
.../validation/filter/ValidationFilterTest.java | 40 +-
.../support/jvalidation/JValidationTest.java | 24 +-
.../support/jvalidation/JValidatorTest.java | 24 +-
dubbo-filter/pom.xml | 2 +-
.../dubbo-metadata-definition/pom.xml | 6 +-
.../metadata/definition/TypeDefinitionBuilder.java | 23 +-
.../definition/builder/ArrayTypeBuilder.java | 10 +-
.../definition/builder/CollectionTypeBuilder.java | 16 +-
.../definition/builder/EnumTypeBuilder.java | 7 +-
.../definition/builder/MapTypeBuilder.java | 10 +-
.../definition/model/MethodDefinition.java | 8 +-
.../definition/model/ServiceDefinition.java | 8 +-
.../metadata/definition/model/TypeDefinition.java | 8 +-
.../definition/util/JaketConfigurationUtils.java | 8 +-
.../dubbo/metadata/definition/MetadataTest.java | 56 +-
.../definition/ServiceDefinitionBuildderTest.java | 44 +-
.../metadata/definition/service/ComplexObject.java | 4 +-
.../dubbo-metadata-report-api/pom.xml | 15 +-
.../integration/MetadataReportService.java | 8 +-
.../metadata/support/AbstractMetadataReport.java | 71 +-
.../identifier/MetadataIdentifierTest.java | 9 +-
.../integration/MetadataReportServiceTest.java | 46 +-
.../store/test/JTestMetadataReport4Test.java | 3 +-
.../test/JTestMetadataReportFactory4Test.java | 9 +-
.../support/AbstractMetadataReportFactoryTest.java | 12 +-
.../support/AbstractMetadataReportTest.java | 86 +-
.../dubbo-metadata-report-consul/pom.xml | 43 +
.../store/consul/ConsulMetadataReport.java | 64 +
.../store/consul/ConsulMetadataReportFactory.java | 66 +-
...ache.dubbo.metadata.store.MetadataReportFactory | 1 +
.../dubbo-metadata-report-redis/pom.xml | 6 +-
.../store/redis/RedisMetadataReportTest.java | 18 +-
.../dubbo-metadata-report-zookeeper/pom.xml | 6 +-
.../zookeeper/ZookeeperMetadataReportTest.java | 30 +-
dubbo-metadata-report/pom.xml | 7 +-
dubbo-metrics/dubbo-metrics-api/pom.xml | 30 -
.../org/apache/dubbo/metrics/BucketCounter.java | 57 -
.../java/org/apache/dubbo/metrics/Compass.java | 75 -
.../main/java/org/apache/dubbo/metrics/Gauge.java | 42 -
.../org/apache/dubbo/metrics/IMetricManager.java | 104 -
.../main/java/org/apache/dubbo/metrics/Metric.java | 29 -
.../java/org/apache/dubbo/metrics/MetricLevel.java | 53 -
.../org/apache/dubbo/metrics/MetricManager.java | 108 --
.../java/org/apache/dubbo/metrics/MetricName.java | 389 ----
.../org/apache/dubbo/metrics/MetricRegistry.java | 157 --
.../org/apache/dubbo/metrics/NOPMetricManager.java | 292 ---
.../apache/dubbo/metrics/MetricManagerTest.java | 53 -
.../org/apache/dubbo/metrics/MetricNameTest.java | 138 --
dubbo-metrics/pom.xml | 41 -
dubbo-monitor/dubbo-monitor-api/pom.xml | 46 +-
.../monitor/support/AbstractMonitorFactory.java | 2 +-
.../dubbo/monitor/support/MetricsFilter.java | 102 +
.../dubbo/internal/org.apache.dubbo.rpc.Filter | 3 +-
.../apache/dubbo/monitor/service/DemoService.java | 14 +-
.../support/AbstractMonitorFactoryTest.java | 10 +-
.../dubbo/monitor/support/MetricsFilterTest.java | 167 ++
.../dubbo/monitor/support/MonitorFilterTest.java | 44 +-
dubbo-monitor/dubbo-monitor-default/pom.xml | 2 +-
.../apache/dubbo/monitor/dubbo/DubboMonitor.java | 3 +-
.../dubbo/monitor/dubbo/DubboMonitorFactory.java | 135 +-
.../monitor/dubbo/DubboMonitorFactoryTest.java | 8 +-
.../dubbo/monitor/dubbo/DubboMonitorTest.java | 58 +-
.../apache/dubbo/monitor/dubbo/StatisticsTest.java | 45 +-
dubbo-monitor/pom.xml | 2 +-
dubbo-plugin/dubbo-qos/pom.xml | 2 +-
.../org/apache/dubbo/qos/command/impl/Online.java | 3 +-
.../dubbo/qos/protocol/QosProtocolWrapper.java | 12 +-
.../java/org/apache/dubbo/qos/server/Server.java | 2 +-
.../qos/server/handler/HttpProcessHandler.java | 14 +-
.../qos/server/handler/QosProcessHandler.java | 10 +
.../main/java/org/apache/dubbo/qos/textui/TKv.java | 8 +-
.../java/org/apache/dubbo/qos/textui/TTable.java | 5 +-
.../java/org/apache/dubbo/qos/textui/TTree.java | 8 +-
.../qos/command/CommandContextFactoryTest.java | 6 +-
.../dubbo/qos/command/CommandContextTest.java | 8 +-
.../qos/command/DefaultCommandExecutorTest.java | 13 +-
.../apache/dubbo/qos/command/GreetingCommand.java | 3 +-
.../command/decoder/HttpCommandDecoderTest.java | 4 +-
.../command/decoder/TelnetCommandDecoderTest.java | 4 +-
.../apache/dubbo/qos/command/impl/HelpTest.java | 4 +-
.../org/apache/dubbo/qos/command/impl/LsTest.java | 4 +-
.../apache/dubbo/qos/command/impl/OfflineTest.java | 4 +-
.../apache/dubbo/qos/command/impl/OnlineTest.java | 6 +-
.../apache/dubbo/qos/command/impl/QuitTest.java | 4 +-
.../dubbo/qos/command/util/CommandHelperTest.java | 10 +-
.../dubbo/qos/protocol/QosProtocolWrapperTest.java | 12 +-
.../qos/server/handler/HttpProcessHandlerTest.java | 4 +-
.../server/handler/LocalHostPermitHandlerTest.java | 4 +-
.../qos/server/handler/QosProcessHandlerTest.java | 2 +-
.../server/handler/TelnetProcessHandlerTest.java | 4 +-
.../java/org/apache/dubbo/qos/textui/TKvTest.java | 10 +-
.../org/apache/dubbo/qos/textui/TLadderTest.java | 12 +-
.../org/apache/dubbo/qos/textui/TTableTest.java | 20 +-
.../org/apache/dubbo/qos/textui/TTreeTest.java | 4 +-
dubbo-plugin/pom.xml | 2 +-
dubbo-registry/dubbo-registry-api/pom.xml | 2 +-
.../registry/integration/RegistryDirectory.java | 105 +-
.../registry/integration/RegistryProtocol.java | 57 +-
.../dubbo/registry/support/AbstractRegistry.java | 119 +-
.../registry/support/AbstractRegistryFactory.java | 8 +-
.../dubbo/registry/support/FailbackRegistry.java | 3 +-
.../registry/support/ProviderConsumerRegTable.java | 6 +-
.../dubbo/registry/PerformanceRegistryTest.java | 6 +-
.../support/AbstractRegistryFactoryTest.java | 18 +-
.../registry/support/AbstractRegistryTest.java | 307 +--
.../registry/support/FailbackRegistryTest.java | 20 +-
dubbo-registry/dubbo-registry-consul/pom.xml | 43 +
.../dubbo/registry/consul/ConsulRegistry.java | 300 +++
.../registry/consul/ConsulRegistryFactory.java | 19 +-
.../org.apache.dubbo.registry.RegistryFactory | 1 +
dubbo-registry/dubbo-registry-default/pom.xml | 2 +-
.../apache/dubbo/registry/dubbo/DubboRegistry.java | 20 +-
.../dubbo/registry/dubbo/DubboRegistryFactory.java | 13 +-
.../dubbo/registry/dubbo/DubboRegistryTest.java | 8 +-
.../registry/dubbo/RegistryDirectoryTest.java | 290 +--
.../dubbo/registry/dubbo/RegistryProtocolTest.java | 31 +-
.../registry/dubbo/RegistryStatusCheckerTest.java | 14 +-
.../registry/dubbo/SimpleRegistryExporter.java | 8 +-
.../src/test/resources/log4j.xml | 7 +-
dubbo-registry/dubbo-registry-etcd3/pom.xml | 53 +
.../apache/dubbo/registry/etcd/EtcdRegistry.java | 362 ++++
.../dubbo/registry/etcd/EtcdRegistryFactory.java | 53 +
.../org.apache.dubbo.registry.RegistryFactory | 1 +
.../dubbo/registry/etcd/EtcdRegistryTest.java | 316 +++
dubbo-registry/dubbo-registry-multicast/pom.xml | 2 +-
.../registry/multicast/MulticastRegistry.java | 74 +-
.../multicast/MulticastRegistryFactoryTest.java | 4 +-
.../registry/multicast/MulticastRegistryTest.java | 77 +-
dubbo-registry/dubbo-registry-redis/pom.xml | 2 +-
.../apache/dubbo/registry/redis/RedisRegistry.java | 109 +-
.../dubbo/registry/redis/RedisRegistryTest.java | 22 +-
dubbo-registry/dubbo-registry-zookeeper/pom.xml | 2 +-
.../registry/zookeeper/ZookeeperRegistry.java | 74 +-
.../zookeeper/ZookeeperRegistryFactory.java | 4 +
.../registry/zookeeper/ZookeeperRegistryTest.java | 44 +-
dubbo-registry/pom.xml | 4 +-
dubbo-remoting/dubbo-remoting-api/pom.xml | 2 +-
.../java/org/apache/dubbo/remoting/Client.java | 4 +-
.../org/apache/dubbo/remoting/IdleSensible.java | 24 +-
.../java/org/apache/dubbo/remoting/Server.java | 4 +-
.../apache/dubbo/remoting/exchange/Request.java | 8 +-
.../apache/dubbo/remoting/exchange/Response.java | 4 +
.../remoting/exchange/codec/ExchangeCodec.java | 7 +-
.../remoting/exchange/support/DefaultFuture.java | 7 +-
.../exchange/support/header/AbstractTimerTask.java | 10 +
...ReconnectTimerTask.java => CloseTimerTask.java} | 34 +-
.../support/header/HeaderExchangeClient.java | 78 +-
.../support/header/HeaderExchangeServer.java | 84 +-
.../support/header/ReconnectTimerTask.java | 34 +-
.../dubbo/remoting/telnet/codec/TelnetCodec.java | 16 +-
.../telnet/support/TelnetHandlerAdapter.java | 19 +-
.../telnet/support/command/HelpTelnetHandler.java | 3 +-
.../telnet/support/command/LogTelnetHandler.java | 10 +-
.../support/command/StatusTelnetHandler.java | 5 +-
.../dubbo/remoting/transport/AbstractClient.java | 131 +-
.../dubbo/remoting/transport/AbstractServer.java | 2 +-
.../transport/ChannelHandlerDispatcher.java | 3 +-
.../apache/dubbo/remoting/ChanelHandlerTest.java | 6 +-
.../dubbo/remoting/PerformanceClientCloseTest.java | 6 +-
.../dubbo/remoting/PerformanceClientFixedTest.java | 6 +-
.../dubbo/remoting/PerformanceClientTest.java | 6 +-
.../dubbo/remoting/PerformanceServerTest.java | 6 +-
.../remoting/buffer/AbstractChannelBufferTest.java | 162 +-
.../remoting/buffer/ChannelBufferStreamTest.java | 12 +-
.../remoting/buffer/DirectChannelBufferTest.java | 4 +-
.../remoting/buffer/DynamicChannelBufferTest.java | 4 +-
.../remoting/buffer/HeapChannelBufferTest.java | 4 +-
.../dubbo/remoting/codec/ExchangeCodecTest.java | 132 +-
.../dubbo/remoting/codec/TelnetCodecTest.java | 58 +-
.../exchange/support/DefaultFutureTest.java | 15 +-
.../support/header/HeaderExchangeChannelTest.java | 139 +-
.../exchange/support/header/HeartBeatTaskTest.java | 14 +-
.../handler/ConnectChannelHandlerTest.java | 64 +-
.../handler/HeaderExchangeHandlerTest.java | 56 +-
.../handler/WrappedChannelHandlerTest.java | 24 +-
.../remoting/transport/AbstractCodecTest.java | 6 +-
.../remoting/transport/codec/CodecAdapterTest.java | 4 +-
.../transport/codec/DeprecatedExchangeCodec.java | 4 +-
.../transport/codec/DeprecatedTelnetCodec.java | 2 +-
dubbo-remoting/dubbo-remoting-etcd3/pom.xml | 52 +
.../dubbo/remoting/etcd/AbstractRetryPolicy.java | 42 +-
.../apache/dubbo/remoting/etcd/ChildListener.java | 9 +-
.../org/apache/dubbo/remoting/etcd/EtcdClient.java | 183 ++
.../dubbo/remoting/etcd/EtcdTransporter.java | 47 +
.../apache/dubbo/remoting/etcd/RetryPolicy.java | 22 +-
.../apache/dubbo/remoting/etcd/StateListener.java | 11 +-
.../etcd/jetcd/ConnectionStateListener.java | 22 +-
.../dubbo/remoting/etcd/jetcd/JEtcdClient.java | 433 +++++
.../remoting/etcd/jetcd/JEtcdClientWrapper.java | 714 +++++++
.../remoting/etcd/jetcd/JEtcdTransporter.java | 22 +-
.../dubbo/remoting/etcd/jetcd/RetryLoops.java | 95 +
.../dubbo/remoting/etcd/jetcd/RetryNTimes.java | 73 +-
.../dubbo/remoting/etcd/option/Constants.java | 16 +-
.../dubbo/remoting/etcd/option/OptionUtil.java | 76 +
.../remoting/etcd/support/AbstractEtcdClient.java | 194 ++
.../org.apache.dubbo.remoting.etcd.EtcdTransporter | 1 +
.../dubbo/remoting/etcd/jetcd/JEtcdClientTest.java | 426 ++++
.../etcd/jetcd/JEtcdClientWrapperTest.java | 186 ++
dubbo-remoting/dubbo-remoting-grizzly/pom.xml | 2 +-
.../transport/grizzly/GrizzlyTransporterTest.java | 4 +-
dubbo-remoting/dubbo-remoting-http/pom.xml | 2 +-
.../remoting/http/tomcat/TomcatHttpServer.java | 3 +
.../remoting/http/jetty/JettyHttpBinderTest.java | 2 +-
.../remoting/http/tomcat/TomcatHttpBinderTest.java | 3 +-
dubbo-remoting/dubbo-remoting-mina/pom.xml | 2 +-
.../dubbo/remoting/transport/mina/MinaServer.java | 2 +-
.../transport/mina/ClientToServerTest.java | 23 +-
.../remoting/transport/mina/ClientsTest.java | 29 +-
dubbo-remoting/dubbo-remoting-netty/pom.xml | 29 +-
.../transport/netty/NettyBackedChannelBuffer.java | 2 +-
.../remoting/transport/netty/NettyServer.java | 3 +-
.../support/header/HeartbeatHandlerTest.java | 19 +-
.../transport/netty/ClientReconnectTest.java | 47 +-
.../transport/netty/ClientToServerTest.java | 19 +-
.../remoting/transport/netty/ClientsTest.java | 29 +-
.../remoting/transport/netty/NettyClientTest.java | 14 +-
.../remoting/transport/netty/NettyStringTest.java | 12 +-
.../remoting/transport/netty/ThreadNameTest.java | 14 +-
.../src/test/resources/log4j.xml | 1 +
dubbo-remoting/dubbo-remoting-netty4/pom.xml | 2 +-
.../transport/netty4/NettyBackedChannelBuffer.java | 122 +-
.../remoting/transport/netty4/NettyClient.java | 12 +-
.../transport/netty4/NettyClientHandler.java | 81 +-
.../transport/netty4/NettyCodecAdapter.java | 14 +-
.../remoting/transport/netty4/NettyServer.java | 12 +
.../transport/netty4/NettyServerHandler.java | 20 +-
.../transport/netty4/logging/FormattingTuple.java | 4 +-
.../transport/netty4/logging/MessageFormatter.java | 9 +-
.../transport/netty4/ClientReconnectTest.java | 20 +-
.../transport/netty4/ClientToServerTest.java | 20 +-
.../remoting/transport/netty4/ClientsTest.java | 28 +-
.../transport/netty4/NettyTransporterTest.java | 7 +-
dubbo-remoting/dubbo-remoting-p2p/pom.xml | 5 +-
.../p2p/exchange/support/FileExchangeGroup.java | 5 +-
.../dubbo/remoting/p2p/support/FileGroup.java | 5 +-
.../support/MulticastExchangeNetworkerTest.java | 4 +-
.../remoting/p2p/support/FileNetworkerTest.java | 30 +-
.../p2p/support/MulticastNetworkerTest.java | 4 +-
dubbo-remoting/dubbo-remoting-zookeeper/pom.xml | 45 +-
.../dubbo/remoting/zookeeper/DataListener.java | 14 +-
.../apache/dubbo/remoting/zookeeper/EventType.java | 65 +
.../dubbo/remoting/zookeeper/ZookeeperClient.java | 16 +
.../zookeeper/curator/CuratorZookeeperClient.java | 158 +-
.../curator/CuratorZookeeperTransporter.java | 2 +-
.../zookeeper/support/AbstractZookeeperClient.java | 47 +-
.../support/AbstractZookeeperTransporter.java | 1 +
.../zookeeper/zkclient/ZkClientWrapper.java | 144 --
.../zkclient/ZkclientZookeeperClient.java | 168 --
...e.dubbo.remoting.zookeeper.ZookeeperTransporter | 3 +-
.../curator/CuratorZookeeperClientTest.java | 81 +-
.../curator/CuratorZookeeperTransporterTest.java | 20 +-
.../support/AbstractZookeeperTransporterTest.java | 100 +-
.../zookeeper/zkclient/ZkClientWrapperTest.java | 56 -
.../zkclient/ZkclientZookeeperClientTest.java | 140 --
.../zkclient/ZkclientZookeeperTransporterTest.java | 53 -
dubbo-remoting/pom.xml | 3 +-
dubbo-rpc/dubbo-rpc-api/pom.xml | 94 +-
.../java/org/apache/dubbo/rpc/AbstractResult.java | 4 +-
.../main/java/org/apache/dubbo/rpc/RpcContext.java | 6 +-
.../java/org/apache/dubbo/rpc/RpcException.java | 5 +-
.../java/org/apache/dubbo/rpc/RpcInvocation.java | 3 +-
.../apache/dubbo/rpc/filter/AccessLogFilter.java | 222 +--
.../apache/dubbo/rpc/filter/ActiveLimitFilter.java | 6 +-
.../org/apache/dubbo/rpc/filter/ContextFilter.java | 3 +-
.../org/apache/dubbo/rpc/filter/GenericFilter.java | 3 +-
.../org/apache/dubbo/rpc/filter/TimeoutFilter.java | 40 +-
.../dubbo/rpc/filter/tps/DefaultTPSLimiter.java | 15 +-
.../org/apache/dubbo/rpc/filter/tps/StatItem.java | 37 +-
.../rpc/listener/ListenerExporterWrapper.java | 5 +-
.../dubbo/rpc/listener/ListenerInvokerWrapper.java | 5 +-
.../apache/dubbo/rpc/protocol/AbstractInvoker.java | 9 +-
.../dubbo/rpc/protocol/AbstractProxyProtocol.java | 6 +-
.../dubbo/rpc/proxy/jdk/JdkProxyFactory.java | 2 +-
.../rpc/proxy/wrapper/StubProxyFactoryWrapper.java | 14 +-
.../apache/dubbo/rpc/service/GenericService.java | 2 +-
.../apache/dubbo/rpc/support/AccessLogData.java | 266 +++
.../org/apache/dubbo/rpc/support/MockInvoker.java | 5 +-
.../apache/dubbo/rpc/support/ProtocolUtils.java | 3 +-
.../org/apache/dubbo/rpc/support/RpcUtils.java | 5 +-
.../java/org/apache/dubbo/rpc/RpcContextTest.java | 80 +-
.../java/org/apache/dubbo/rpc/RpcResultTest.java | 14 +-
.../dubbo/rpc/filter/AccessLogFilterTest.java | 6 +-
.../dubbo/rpc/filter/ActiveLimitFilterTest.java | 43 +-
.../dubbo/rpc/filter/ClassLoaderFilterTest.java | 6 +-
.../rpc/filter/CompatibleFilterFilterTest.java | 10 +-
.../rpc/filter/ConsumerContextFilterTest.java | 4 +-
.../apache/dubbo/rpc/filter/ContextFilterTest.java | 4 +-
.../dubbo/rpc/filter/DeprecatedFilterTest.java | 4 +-
.../apache/dubbo/rpc/filter/EchoFilterTest.java | 4 +-
.../dubbo/rpc/filter/ExceptionFilterTest.java | 16 +-
.../dubbo/rpc/filter/ExecuteLimitFilterTest.java | 14 +-
.../apache/dubbo/rpc/filter/GenericFilterTest.java | 64 +-
.../dubbo/rpc/filter/GenericImplFilterTest.java | 18 +-
.../apache/dubbo/rpc/filter/TimeoutFilterTest.java | 8 +-
.../apache/dubbo/rpc/filter/TokenFilterTest.java | 48 +-
.../rpc/filter/tps/DefaultTPSLimiterTest.java | 79 +
.../apache/dubbo/rpc/filter/tps/StatItemTest.java | 10 +-
.../rpc/filter/{ => tps}/TpsLimitFilterTest.java | 42 +-
.../apache/dubbo/rpc/proxy/AbstractProxyTest.java | 18 +-
.../rpc/proxy/InvokerInvocationHandlerTest.java | 10 +-
.../org/apache/dubbo/rpc/support/RpcUtilsTest.java | 48 +-
.../dubbo-rpc-api/src/test/resources/log4j.xml | 1 +
dubbo-rpc/dubbo-rpc-dubbo/pom.xml | 2 +-
.../rpc/protocol/dubbo/CallbackServiceCodec.java | 34 +-
.../rpc/protocol/dubbo/DecodeableRpcResult.java | 91 +-
.../dubbo/rpc/protocol/dubbo/DubboCodec.java | 8 +-
.../dubbo/rpc/protocol/dubbo/DubboProtocol.java | 375 +++-
.../protocol/dubbo/LazyConnectExchangeClient.java | 22 +-
.../dubbo/ReferenceCountExchangeClient.java | 45 +-
.../rpc/protocol/dubbo/filter/FutureFilter.java | 10 +-
.../rpc/protocol/dubbo/filter/TraceFilter.java | 11 +-
.../protocol/dubbo/telnet/InvokeTelnetHandler.java | 269 +--
.../protocol/dubbo/telnet/LogTelnetHandler.java | 11 +-
.../protocol/dubbo/telnet/SelectTelnetHandler.java | 60 +
.../dubbo/telnet/ShutdownTelnetHandler.java | 63 +
.../protocol/dubbo/telnet/TraceTelnetHandler.java | 9 +-
.../org.apache.dubbo.remoting.telnet.TelnetHandler | 4 +-
.../protocol/dubbo/DubboInvokerAvilableTest.java | 46 +-
.../rpc/protocol/dubbo/DubboLazyConnectTest.java | 41 +-
.../rpc/protocol/dubbo/DubboProtocolTest.java | 18 +-
.../rpc/protocol/dubbo/ExplicitCallbackTest.java | 128 +-
.../dubbo/rpc/protocol/dubbo/FutureFilterTest.java | 33 +-
.../rpc/protocol/dubbo/ImplicitCallBackTest.java | 96 +-
.../dubbo/rpc/protocol/dubbo/MultiThreadTest.java | 14 +-
.../dubbo/ReferenceCountExchangeClientTest.java | 152 +-
.../dubbo/rpc/protocol/dubbo/RpcFilterTest.java | 16 +-
.../dubbo/decode/DubboTelnetDecodeTest.java | 477 +++++
.../dubbo/decode/LocalEmbeddedChannel.java | 25 +-
.../rpc/protocol/dubbo/decode/MockChannel.java | 115 ++
.../protocol/dubbo/decode/MockChannelHandler.java | 61 +
.../rpc/protocol/dubbo/decode/MockHandler.java | 77 +-
.../rpc/protocol/dubbo/support/DemoService.java | 3 +-
.../protocol/dubbo/support/DemoServiceImpl.java | 10 +-
.../dubbo/rpc/protocol/dubbo/support/EnumBak.java | 22 +-
.../dubbo/rpc/protocol/dubbo/support/Man.java} | 82 +-
.../dubbo/telnet/ChangeTelnetHandlerTest.java | 16 +-
.../dubbo/telnet/CurrentTelnetHandlerTest.java | 6 +-
.../dubbo/telnet/InvokerTelnetHandlerTest.java | 16 +-
.../dubbo/telnet/ListTelnetHandlerTest.java | 18 +-
.../dubbo/telnet/LogTelnetHandlerTest.java | 4 +-
.../dubbo/telnet/PortTelnetHandlerTest.java | 16 +-
.../dubbo/telnet/SelectTelnetHandlerTest.java | 117 ++
...lerTest.java => ShutdownTelnetHandlerTest.java} | 36 +-
.../dubbo/rpc/service/GenericServiceTest.java | 70 +-
.../dubbo/rpc/validation/ValidationTest.java | 88 +-
.../dubbo-rpc-dubbo/src/test/resources/log4j.xml | 12 +-
dubbo-rpc/dubbo-rpc-hessian/pom.xml | 7 +-
.../rpc/protocol/hessian/HessianProtocolTest.java | 46 +-
dubbo-rpc/dubbo-rpc-http/pom.xml | 112 +-
.../dubbo/rpc/protocol/http/HttpProtocol.java | 3 +-
.../dubbo/rpc/protocol/http/HttpProtocolTest.java | 51 +-
dubbo-rpc/dubbo-rpc-injvm/pom.xml | 2 +-
.../dubbo/rpc/protocol/injvm/InjvmInvoker.java | 4 +-
.../dubbo/rpc/protocol/injvm/InjvmProtocol.java | 19 +-
.../rpc/protocol/injvm/InjvmProtocolTest.java | 12 +-
.../dubbo/rpc/protocol/injvm/ProtocolTest.java | 12 +-
dubbo-rpc/dubbo-rpc-memcached/pom.xml | 2 +-
dubbo-rpc/dubbo-rpc-redis/pom.xml | 104 +-
.../rpc/protocol/redis/RedisProtocolTest.java | 84 +-
dubbo-rpc/dubbo-rpc-rest/pom.xml | 29 +-
.../dubbo/rpc/protocol/rest/RestProtocol.java | 82 +-
.../dubbo/rpc/protocol/rest/RpcContextFilter.java | 6 +-
.../dubbo/rpc/protocol/rest/DemoService.java | 29 +-
.../rest/DemoServiceImpl.java} | 78 +-
.../dubbo/rpc/protocol/rest/RestProtocolTest.java | 139 +-
.../rpc/protocol/rest/RpcExceptionMapperTest.java | 8 +-
.../DubboSwaggerApiListingResourceTest.java | 10 +-
.../dubbo/rpc/protol/rest/RestProtocolTest.java | 78 -
.../apache/dubbo/rpc/protol/rest/RestService.java | 36 -
dubbo-rpc/dubbo-rpc-rmi/pom.xml | 2 +-
.../apache/dubbo/rpc/protocol/rmi/RmiProtocol.java | 59 +-
.../rpc/protocol/rmi/RmiRemoteInvocation.java | 8 +-
.../apache/dubbo/rpc/protocol/rmi/DemoService.java | 2 +
.../dubbo/rpc/protocol/rmi/DemoServiceImpl.java | 4 +
.../dubbo/rpc/protocol/rmi/RmiProtocolTest.java | 24 +-
.../rpc/protocol/rsocket/RSocketProtocol.java | 23 +-
.../rpc/protocol/rsocket/RSocketProtocolTest.java | 9 +-
dubbo-rpc/dubbo-rpc-thrift/pom.xml | 2 +-
.../dubbo/rpc/protocol/thrift/ThriftCodec.java | 17 +-
.../dubbo/rpc/protocol/thrift/ThriftProtocol.java | 4 +-
.../src/test/java/ClassNameTest.java | 12 +-
.../dubbo/rpc/protocol/thrift/AbstractTest.java | 8 +-
.../rpc/protocol/thrift/ServerExceptionTest.java | 25 +-
.../protocol/thrift/ServiceMethodNotFoundTest.java | 16 +-
.../dubbo/rpc/protocol/thrift/ThriftCodecTest.java | 98 +-
.../rpc/protocol/thrift/ThriftProtocolTest.java | 12 +-
.../dubbo/rpc/protocol/thrift/ThriftUtilsTest.java | 20 +-
dubbo-rpc/dubbo-rpc-webservice/pom.xml | 150 +-
.../webservice/WebserviceProtocolTest.java | 15 +-
dubbo-rpc/pom.xml | 2 +-
.../dubbo-serialization-api/pom.xml | 2 +-
.../apache/dubbo/common/serialize/Cleanable.java | 6 +
.../apache/dubbo/common/serialize/DataInput.java | 2 +-
.../apache/dubbo/common/serialize/DataOutput.java | 8 +-
.../apache/dubbo/common/serialize/ObjectInput.java | 25 +-
.../dubbo/common/serialize/ObjectOutput.java | 2 +-
.../dubbo/common/serialize/Serialization.java | 23 +-
.../support/SerializableClassRegistry.java | 14 +
.../serialize/support/SerializationOptimizer.java | 8 +-
.../dubbo-serialization-fastjson/pom.xml | 2 +-
.../serialize/fastjson/FastJsonObjectInput.java | 3 +
.../serialize/fastjson/FastJsonObjectOutput.java | 3 +
.../serialize/fastjson/FastJsonSerialization.java | 7 +
.../dubbo-serialization-fst/pom.xml | 2 +-
.../dubbo/common/serialize/fst/FstFactory.java | 3 +
.../dubbo/common/serialize/fst/FstObjectInput.java | 4 +-
.../common/serialize/fst/FstObjectOutput.java | 4 +-
.../common/serialize/fst/FstSerialization.java | 7 +
.../dubbo-serialization-hessian2/pom.xml | 2 +-
.../serialize/hessian2/Hessian2ObjectInput.java | 2 +-
.../serialize/hessian2/Hessian2ObjectOutput.java | 2 +-
.../serialize/hessian2/Hessian2Serialization.java | 7 +
.../dubbo-serialization-jdk/pom.xml | 2 +-
.../serialize/java/CompactedJavaSerialization.java | 7 +
.../serialize/java/CompactedObjectInputStream.java | 2 +-
.../java/CompactedObjectOutputStream.java | 2 +-
.../common/serialize/java/JavaObjectInput.java | 2 +-
.../common/serialize/java/JavaObjectOutput.java | 2 +-
.../common/serialize/java/JavaSerialization.java | 7 +
.../nativejava/NativeJavaObjectInput.java | 3 +
.../nativejava/NativeJavaObjectOutput.java | 3 +
.../nativejava/NativeJavaSerialization.java | 7 +
.../dubbo-serialization-kryo/pom.xml | 2 +-
.../common/serialize/kryo/KryoObjectInput.java | 3 +
.../common/serialize/kryo/KryoObjectOutput.java | 3 +
.../common/serialize/kryo/KryoSerialization.java | 3 +
.../dubbo-serialization-protostuff/pom.xml | 6 +-
.../protostuff/ProtostuffObjectInput.java | 15 +-
.../protostuff/ProtostuffObjectOutput.java | 15 +-
.../protostuff/ProtostuffSerialization.java | 7 +
.../protostuff/delegate/TimeDelegate.java | 3 +
.../serialize/protostuff/utils/WrapperUtils.java | 15 +
.../dubbo-serialization-test/pom.xml | 6 +-
.../base/AbstractSerializationPersonFailTest.java | 9 +-
.../base/AbstractSerializationPersonOkTest.java | 2 +-
.../serialize/base/AbstractSerializationTest.java | 48 +-
.../fastjson/FastJsonObjectInputTest.java | 23 +-
.../fastjson/FastJsonObjectOutputTest.java | 8 +-
.../fastjson/FastJsonSerializationTest.java | 8 +-
.../dubbo/common/serialize/fst/FstFactoryTest.java | 4 +-
.../common/serialize/fst/FstObjectInputTest.java | 14 +-
.../common/serialize/fst/FstObjectOutputTest.java | 12 +-
.../common/serialize/fst/FstSerializationTest.java | 7 +-
.../serialize/hessian2/Hessian2PersonOkTest.java | 16 +-
.../hessian2/Hessian2SerializationTest.java | 16 +-
.../common/serialize/kryo/ReflectionUtilsTest.java | 6 +-
.../protostuff/ProtostuffSerializationTest.java | 7 +-
.../support/SerializableClassRegistryTest.java | 4 +-
.../src/test/resources/log4j.xml | 1 +
dubbo-serialization/pom.xml | 2 +-
.../dubbo-test-spring3/pom.xml | 2 +-
dubbo-test/dubbo-test-compatibility/pom.xml | 29 +-
dubbo-test/dubbo-test-integration/pom.xml | 2 +-
dubbo-test/pom.xml | 430 ++---
pom.xml | 147 +-
882 files changed, 28404 insertions(+), 14697 deletions(-)
diff --git a/.travis.yml b/.travis.yml
index 3230677..e3821cb 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -2,7 +2,9 @@ language: java
sudo: false # faster builds
jdk:
+ - openjdk11
- oraclejdk11
+ - openjdk8
- oraclejdk8
cache:
@@ -16,3 +18,6 @@ script:
after_success:
- bash <(curl -s https://codecov.io/bash)
+
+after_failure:
+ - if [ -f dubbo.log ]; then echo "------TAIL of dubbo.log------"; tail -n 1000 dubbo.log; echo "------END of dubbo.log------"; fi
diff --git a/CHANGES.md b/CHANGES.md
index 12e003d..78711eb 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -1,61 +1,68 @@
# Release Notes
## 2.7.0
-环境要求:需要Java 8及以上版本支持
-请在[这里]()了解关于升级2.7.x版本的注意事项和兼容性问题
+Requirements: **Java 8+** required
-## New Features
+Please check [here](https://github.com/apache/incubator-dubbo/blob/2.7.0-release/CHANGES.md#upgrading-and-compatibility-notifications) for notes and possible compatibility issues for upgrading from 2.6.x or lower to 2.7.0.
-- 服务治理规则增强。
- - 更丰富的服务治理规则,新增应用级别条件路由、Tag路由等
- - 治理规则与注册中心解耦,增加对Apollo等第三方专业配置中心的支持,更易于扩展
- - 新增应用级别的动态配置规则
- - 规则体使用更易读、易用YAML格式
+### New Features
-- 外部化配置。支持读取托管在远程的集中式配置中心的dubbo.properties,实现应用配置的集中式管控。
+- Enhancement of service governance rules.
+ - Enriched Routing Rules.
+ 1. Conditional Routing. Supports both application-level and service-level conditions.
+ 2. Tag Routing. Newly introduced to better support traffic isolation, such as grey deployment.
+ - Decoupling governance rules with the registry, making it easier to extend. Apollo and Zookeeper are available in this version. Nacos support is on the way...
+ - Application-level Dynamic Configuration support.
+ - Use YAML as the configuration language, which is more friendly to read and use.
-- 更精炼的注册中心URL,进一步减轻注册中心存储和同步压力,初步实现地址和配置的职责分离。
+- Externalized Configuration. Supports reading `dubbo.properties` hosted in remote centralized configuration center - centralized configuration.
-- 新增服务元数据中心,负责存储包括服务静态化配置、服务定义(如方法签名)等数据,默认提供Zookeeper, Redis支持。此功能也是OPS实现服务测试、Mock等治理能力的基础。
+- Simplified registry URL. With lower Registry memory use and less notification pressure from Service Directory, separates Configuration notification from Service Discovery.
-- 异步编程模式增强(限定于Dubbo协议)
- - 原生CompletableFuture<T>签名接口支持
- - 服务端异步支持
- - 异步Filter链
+- Metadata Center. A totally new concept since 2.7.0, used to store service metadata including static configuration, service definition, method signature, etc.. By default, Zookeeper and Redis are supported as the backend storage. Will work as the basis of service testing, mock and other service governance features going to be supported in [Dubbo-Admin](https://github.com/apache/incubator-dubbo-admin).
-- 新增Protobuf序列化协议扩展
+- Asynchronous Programming Model (only works for Dubbo protocol now)
+ - Built-in support for the method with CompletableFuture<T> signature.
+ - Server-side asynchronous support, with an AsyncContext API works like Servlet 3.0.
+ - Asynchronous filter chain callback.
-- 新增ExpiringCache缓存策略扩展
+- Serialization Extension: Protobuf.
-## Enhancements / Bugfixes
+- Caching Policy Extension: Expiring Cache.
-- 负载均衡策略优化,包括ConsitentHash(#2190) 、LeastActive(#2171)、Random(#2597) 、RoundRobin(#2586) (#2650)
+### Enhancements / Bugfixes
-- 升级第三方依赖:默认通信框架为netty 4、默认ZK客户端为Curator、Jetty 9k
+- Load Balancing strategy enhancement: ConsitentHash #2190, LeastActive #2171, Random #2597, RoundRobin #2650.
-- 增加地址读取时对IPV6的支持(#2079)
+- Third-party dependency upgrading.
+ - Switch default remoting to Netty 4.
+ - Switch default Zookeeper client to Curator.
+ - Upgrade Jetty to 9.x.
-- 性能优化,链接关闭的情况下使得Consumer快速返回 (#2185)
+- IPV6 support #2079.
-- 修复Jdk原生类型在kryo中的序列化问题 (#2178)
+- Performance tuning, check hanging requests on a closed channel, make them return directly #2185.
-- 修复Provider端反序列化失败后,没有及早通知Consumer端的问题 (#1903)
+- Fixed the serialization problem of JDK primitive types in Kryo #2178.
+- Fixed the problem of failing to notify Consumer as early as possible after the Provider side deserialization failed #1903.
-## 升级与兼容性
+### Upgrading and Compatibility Notifications
-此次版本发布我们遵循了保持和老版本兼容的原则,尤其是在一些可能会破坏2.7版本与低版本互操作性的问题上,我们增加了一些兼容性代码,典型如服务治理规则、Package重命名、注册URL简化等。
+We have always keep compatibility in mind during the whole process of 2.7.0. We even want old users to upgrade with only on pom version upgrade, but it's hard to achieve that, especially when considering that we have the package renamed in this version, so we had some tradeoffs. If you only used the Dubbo's most basic features, you may have little problems of upgrading, but if you have used some advanced features or have some SPI extensions inside, you'd better read the upgrade notificat [...]
-1. Package重命名
+1. Interoperability between 2.7.0 and lower versions
-com.alibaba.dubbo -> org.apache.dubbo
+2. Package renaming
-2. 注册URL简化
+ com.alibaba.dubbo -> org.apache.dubbo
-3. 服务治理规则
+3. Simplification of registered URLs
-4. 配置
+4. Service Governance Rules
+
+5. Configuration
## 2.6.5
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index b987b16..e5ed3a9 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -13,7 +13,7 @@ The mailing list is the recommended way for discussing almost anything that rela
- [dev@dubbo.incubator.apache.org](mailto:dev-subscribe@dubbo.incubator.apache.org): the develop mailing list, you can ask question here if you have encountered any problem when using or developing Dubbo.
- [commits@dubbo.incubator.apache.org](mailto:commits-subscribe@dubbo.incubator.apache.org): all the commits will be sent to this mailing list. You can subscribe to it if you are interested in Dubbo's development.
-- [notification@dubbo.incubator.apache.org](mailto:notification-subscribe@dubbo.incubator.apache.org): all the Github [issue](https://github.com/apache/incubator-dubbo/issues) updates and [pull request](https://github.com/apache/incubator-dubbo/pulls) updates will be sent to this mailing list.
+- [notifications@dubbo.incubator.apache.org](mailto:notifications-subscribe@dubbo.incubator.apache.org): all the Github [issue](https://github.com/apache/incubator-dubbo/issues) updates and [pull request](https://github.com/apache/incubator-dubbo/pulls) updates will be sent to this mailing list.
### Reporting issue
diff --git a/LICENSE b/LICENSE
index b856223..11eea3b 100644
--- a/LICENSE
+++ b/LICENSE
@@ -208,15 +208,6 @@ Apache Dubbo includes a number of submodules with separate copyright notices
and license terms. Your use of these submodules is subject to the terms and
conditions of the following licenses.
-For the org.apache.dubbo.common.concurrent package:
-
-This product bundles and repackages the following code in Google Guava 16.0.1, which is available under a
-"Apache License 2.0" license. For details, see https://github.com/google/guava/blob/v16.0.1/COPYING.
-
- * com.google.common.util.concurrent.ExecutionList
- * com.google.common.util.concurrent.ListenableFuture
- * com.google.common.util.concurrent.ListenableFutureTask
-
For the package org.apache.dubbo.common.threadlocal and org.apache.dubbo.common.timer:
This product contains a modified portion of 'Netty', an event-driven asynchronous network application framework also
@@ -229,3 +220,8 @@ This product contains a modified portion of 'Netty', an event-driven asynchronou
* io.netty.util.Timeout
* io.netty.util.HashedWheelTimer
+For the org.apache.dubbo.common.utils.CIDRUtils :
+
+This product contains a modified portion of 'edazdarevic.commons.net.CIDRUtils',
+ under a "MIT License" license, see https://github.com/edazdarevic/CIDRUtils/blob/master/CIDRUtils.java
+
diff --git a/README.md b/README.md
index 5b00da2..09c12ff 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,7 @@
[](https://travis-ci.org/apache/incubator-dubbo)
[](https://codecov.io/gh/apache/incubator-dubbo)
-
+

[](http://isitmaintained.com/project/apache/incubator-dubbo "Average time to resolve an issue")
[](http://isitmaintained.com/project/apache/incubator-dubbo "Percentage of issues still open")
@@ -29,26 +29,26 @@ We are now collecting dubbo user info in order to help us to improve Dubbo bette
## Getting started
-The following code snippet comes from [Dubbo Samples](https://github.com/dubbo/dubbo-samples/tree/master/dubbo-samples-api). You may clone the sample project and step into `dubbo-samples-api` sub directory before read on.
+The following code snippet comes from [Dubbo Samples](https://github.com/apache/incubator-dubbo-samples/tree/master/dubbo-samples-api). You may clone the sample project and step into `dubbo-samples-api` sub directory before read on.
```bash
-# git clone https://github.com/dubbo/dubbo-samples.git
-# cd dubbo-samples/dubbo-samples-api
+# git clone https://github.com/apache/incubator-dubbo-samples.git
+# cd incubator-dubbo-samples/dubbo-samples-api
```
-There's a [README](https://github.com/dubbo/dubbo-samples/blob/master/dubbo-samples-api/README.md) file under `dubbo-samples-api` directory. Read it and try this sample out by following the instructions.
+There's a [README](https://github.com/apache/incubator-dubbo-samples/tree/master/dubbo-samples-api/README.md) file under `dubbo-samples-api` directory. Read it and try this sample out by following the instructions.
### Maven dependency
```xml
<properties>
- <dubbo.version>2.6.5</dubbo.version>
+ <dubbo.version>2.7.0</dubbo.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
- <groupId>com.alibaba</groupId>
+ <groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-dependencies-bom</artifactId>
<version>${dubbo.version}</version>
<type>pom</type>
@@ -59,7 +59,7 @@ There's a [README](https://github.com/dubbo/dubbo-samples/blob/master/dubbo-samp
<dependencies>
<dependency>
- <groupId>com.alibaba</groupId>
+ <groupId>org.apache.dubbo</groupId>
<artifactId>dubbo</artifactId>
<version>${dubbo.version}</version>
</dependency>
@@ -67,27 +67,39 @@ There's a [README](https://github.com/dubbo/dubbo-samples/blob/master/dubbo-samp
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.apache.curator</groupId>
+ <artifactId>curator-framework</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.curator</groupId>
+ <artifactId>curator-recipes</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.zookeeper</groupId>
+ <artifactId>zookeeper</artifactId>
+ </dependency>
</dependencies>
```
### Define service interfaces
```java
-package org.apache.dubbo.demo.api;
+package org.apache.dubbo.samples.api;
public interface GreetingService {
String sayHello(String name);
}
```
-*See [api/GreetingService.java](https://github.com/dubbo/dubbo-samples/blob/master/dubbo-samples-api/src/main/java/org/apache/dubbo/samples/api/GreetingsService.java) on GitHub.*
+*See [api/GreetingService.java](https://github.com/apache/incubator-dubbo-samples/blob/master/dubbo-samples-api/src/main/java/org/apache/dubbo/samples/api/GreetingsService.java) on GitHub.*
### Implement service interface for the provider
```java
-package org.apache.dubbo.demo.provider;
+package org.apache.dubbo.samples.provider;
-import org.apache.dubbo.demo.GreetingService;
+import org.apache.dubbo.samples.api.GreetingService;
public class GreetingServiceImpl implements GreetingService {
public String sayHello(String name) {
@@ -96,17 +108,17 @@ public class GreetingServiceImpl implements GreetingService {
}
```
-*See [provider/GreetingServiceImpl.java](https://github.com/dubbo/dubbo-samples/blob/master/dubbo-samples-api/src/main/java/org/apache/dubbo/samples/provider/GreetingsServiceImpl.java) on GitHub.*
+*See [provider/GreetingServiceImpl.java](https://github.com/apache/incubator-dubbo-samples/blob/master/dubbo-samples-api/src/main/java/org/apache/dubbo/samples/provider/GreetingsServiceImpl.java) on GitHub.*
### Start service provider
```java
package org.apache.dubbo.demo.provider;
-import com.alibaba.dubbo.config.ApplicationConfig;
-import com.alibaba.dubbo.config.RegistryConfig;
-import com.alibaba.dubbo.config.ServiceConfig;
-import org.apache.dubbo.demo.GreetingService;
+import org.apache.dubbo.config.ApplicationConfig;
+import org.apache.dubbo.config.RegistryConfig;
+import org.apache.dubbo.config.ServiceConfig;
+import org.apache.dubbo.samples.api.GreetingService;
import java.io.IOException;
@@ -124,7 +136,7 @@ public class Application {
}
```
-*See [provider/Application.java](https://github.com/dubbo/dubbo-samples/blob/master/dubbo-samples-api/src/main/java/org/apache/dubbo/samples/provider/Application.java) on GitHub.*
+*See [provider/Application.java](https://github.com/apache/incubator-dubbo-samples/blob/master/dubbo-samples-api/src/main/java/org/apache/dubbo/samples/provider/Application.java) on GitHub.*
### Build and run the provider
@@ -138,10 +150,10 @@ public class Application {
```java
package org.apache.dubbo.demo.consumer;
-import com.alibaba.dubbo.config.ApplicationConfig;
-import com.alibaba.dubbo.config.ReferenceConfig;
-import com.alibaba.dubbo.config.RegistryConfig;
-import org.apache.dubbo.demo.GreetingService;
+import org.apache.dubbo.config.ApplicationConfig;
+import org.apache.dubbo.config.ReferenceConfig;
+import org.apache.dubbo.config.RegistryConfig;
+import org.apache.dubbo.samples.api.GreetingService;
public class Application {
public static void main(String[] args) {
@@ -164,7 +176,7 @@ public class Application {
The consumer will print out `Hello world` on the screen.
-*See [consumer/Application.java](https://github.com/dubbo/dubbo-samples/blob/master/dubbo-samples-api/src/main/java/org/apache/dubbo/samples/consumer/Application.java) on GitHub.*
+*See [consumer/Application.java](https://github.com/apache/incubator-dubbo-samples/blob/master/dubbo-samples-api/src/main/java/org/apache/dubbo/samples/consumer/Application.java) on GitHub.*
### Next steps
@@ -197,7 +209,7 @@ See [CONTRIBUTING](https://github.com/apache/incubator-dubbo/blob/master/CONTRI
* blog post
* translation on documentation
* use cases about how Dubbo is being used in enterprise system.
-* Improve the [dubbo-ops/dubbo-monitor](https://github.com/apache/incubator-dubbo-ops).
+* Improve the [dubbo-admin/dubbo-monitor](https://github.com/apache/incubator-dubbo-admin).
* Contribute to the projects listed in [ecosystem](https://github.com/dubbo).
* Any form of contribution that is not mentioned above.
* If you would like to contribute, please send an email to dev@dubbo.incubator.apache.org to let us know!
@@ -208,21 +220,22 @@ Please follow the [template](https://github.com/apache/incubator-dubbo/issues/ne
## Reporting a security vulnerability
-Please report security vulnerability to [us](security@dubbo.incubator.apache.org) privately.
+Please report security vulnerability to [us](mailto:security@dubbo.incubator.apache.org) privately.
-## Dubbo eco system
+## Dubbo ecosystem
* [Dubbo Ecosystem Entry](https://github.com/dubbo) - A GitHub group `dubbo` to gather all Dubbo relevant projects not appropriate in [apache](https://github.com/apache) group yet
* [Dubbo Website](https://github.com/apache/incubator-dubbo-website) - Apache Dubbo (incubating) official website
-* [Dubbo Samples](https://github.com/dubbo/dubbo-samples) - samples for Apache Dubbo (incubating)
+* [Dubbo Samples](https://github.com/apache/incubator-dubbo-samples) - samples for Apache Dubbo (incubating)
* [Dubbo Spring Boot](https://github.com/apache/incubator-dubbo-spring-boot-project) - Spring Boot Project for Dubbo
-* [Dubbo OPS](https://github.com/apache/incubator-dubbo-ops) - The reference implementation for Dubbo admin
+* [Dubbo Admin](https://github.com/apache/incubator-dubbo-admin) - The reference implementation for Dubbo admin
#### Language
* [Node.js](https://github.com/dubbo/dubbo2.js)
* [Python](https://github.com/dubbo/dubbo-client-py)
* [PHP](https://github.com/dubbo/dubbo-php-framework)
+* [Go](https://github.com/dubbo/dubbo-go)
## License
diff --git a/codestyle/checkstyle.xml b/codestyle/checkstyle.xml
index f721d51..fa4d735 100644
--- a/codestyle/checkstyle.xml
+++ b/codestyle/checkstyle.xml
@@ -20,6 +20,7 @@
<module name="NoLineWrap"/>
<module name="OuterTypeFilename"/>
<module name="UnusedImports"/>
+ <module name="RedundantImport"/>
<!--<module name="CustomImportOrder">-->
<!--<property name="specialImportsRegExp" value="org.apache.dubbo.*"/>-->
diff --git a/dubbo-all/pom.xml b/dubbo-all/pom.xml
index 0c67ab9..a4a0b5c 100644
--- a/dubbo-all/pom.xml
+++ b/dubbo-all/pom.xml
@@ -19,11 +19,11 @@
<parent>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-parent</artifactId>
- <version>2.7.0-SNAPSHOT</version>
+ <version>2.7.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>dubbo</artifactId>
- <version>2.7.0-SNAPSHOT</version>
+ <version>2.7.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>dubbo-all</name>
<description>The all in one project of dubbo</description>
@@ -236,6 +236,20 @@
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
+ <artifactId>dubbo-registry-consul</artifactId>
+ <version>${project.version}</version>
+ <scope>compile</scope>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.dubbo</groupId>
+ <artifactId>dubbo-registry-etcd3</artifactId>
+ <version>${project.version}</version>
+ <scope>compile</scope>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-monitor-api</artifactId>
<version>${project.version}</version>
<scope>compile</scope>
@@ -348,6 +362,20 @@
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
+ <artifactId>dubbo-configcenter-consul</artifactId>
+ <version>${project.version}</version>
+ <scope>compile</scope>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.dubbo</groupId>
+ <artifactId>dubbo-configcenter-etcd</artifactId>
+ <version>${project.version}</version>
+ <scope>compile</scope>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-compatible</artifactId>
<version>${project.version}</version>
<scope>compile</scope>
@@ -381,6 +409,13 @@
<scope>compile</scope>
<optional>true</optional>
</dependency>
+ <dependency>
+ <groupId>org.apache.dubbo</groupId>
+ <artifactId>dubbo-metadata-report-consul</artifactId>
+ <version>${project.version}</version>
+ <scope>compile</scope>
+ <optional>true</optional>
+ </dependency>
<!-- Transitive dependencies -->
<dependency>
@@ -395,14 +430,27 @@
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
</dependency>
+ <dependency>
+ <groupId>com.google.code.gson</groupId>
+ <artifactId>gson</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.yaml</groupId>
+ <artifactId>snakeyaml</artifactId>
+ </dependency>
<!-- Temporarily add this part to exclude transitive dependency -->
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>${junit_version}</version>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <version>${junit_jupiter_version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-params</artifactId>
+ <version>${junit_jupiter_version}</version>
<scope>test</scope>
- <optional>true</optional>
</dependency>
<dependency>
<groupId>cglib</groupId>
@@ -459,6 +507,8 @@
<include>org.apache.dubbo:dubbo-registry-multicast</include>
<include>org.apache.dubbo:dubbo-registry-zookeeper</include>
<include>org.apache.dubbo:dubbo-registry-redis</include>
+ <include>org.apache.dubbo:dubbo-registry-consul</include>
+ <include>org.apache.dubbo:dubbo-registry-etcd3</include>
<include>org.apache.dubbo:dubbo-monitor-api</include>
<include>org.apache.dubbo:dubbo-monitor-default</include>
<include>org.apache.dubbo:dubbo-config-api</include>
@@ -479,11 +529,13 @@
<include>org.apache.dubbo:dubbo-configcenter-definition</include>
<include>org.apache.dubbo:dubbo-configcenter-apollo</include>
<include>org.apache.dubbo:dubbo-configcenter-zookeeper</include>
+ <include>org.apache.dubbo:dubbo-configcenter-consul</include>
+ <include>org.apache.dubbo:dubbo-configcenter-etcd</include>
<include>org.apache.dubbo:dubbo-metadata-report-api</include>
<include>org.apache.dubbo:dubbo-metadata-definition</include>
<include>org.apache.dubbo:dubbo-metadata-report-redis</include>
<include>org.apache.dubbo:dubbo-metadata-report-zookeeper</include>
- <include>com.google.code.gson:gson</include>
+ <include>org.apache.dubbo:dubbo-metadata-report-consul</include>
</includes>
</artifactSet>
<transformers>
@@ -601,12 +653,27 @@
<resource>META-INF/dubbo/internal/org.apache.dubbo.qos.command.BaseCommand
</resource>
</transformer>
- <transformer
- implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
+ <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/dubbo/internal/org.apache.dubbo.configcenter.DynamicConfigurationFactory
</resource>
</transformer>
+ <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
+ <resource>META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory
+ </resource>
+ </transformer>
</transformers>
+ <filters>
+ <filter>
+ <artifact>org.apache.dubbo:dubbo</artifact>
+ <excludes>
+ <!-- These two line is optional, it can remove some warn log -->
+ <exclude>com/**</exclude>
+ <exclude>org/**</exclude>
+ <!-- This one is required -->
+ <exclude>META-INF/dubbo/**</exclude>
+ </excludes>
+ </filter>
+ </filters>
</configuration>
</execution>
</executions>
diff --git a/dubbo-bom/pom.xml b/dubbo-bom/pom.xml
index dd87f68..47875b8 100644
--- a/dubbo-bom/pom.xml
+++ b/dubbo-bom/pom.xml
@@ -6,12 +6,12 @@
<parent>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-parent</artifactId>
- <version>2.7.0-SNAPSHOT</version>
+ <version>2.7.1-SNAPSHOT</version>
</parent>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-bom</artifactId>
- <version>2.7.0-SNAPSHOT</version>
+ <version>2.7.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>dubbo-bom</name>
@@ -140,6 +140,11 @@
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
+ <artifactId>dubbo-remoting-etcd3</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-rpc-api</artifactId>
<version>${project.version}</version>
</dependency>
@@ -220,6 +225,16 @@
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
+ <artifactId>dubbo-registry-etcd3</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.dubbo</groupId>
+ <artifactId>dubbo-registry-consul</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-monitor-api</artifactId>
<version>${project.version}</version>
</dependency>
@@ -305,6 +320,11 @@
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
+ <artifactId>dubbo-metadata-report-consul</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-configcenter-api</artifactId>
<version>${project.version}</version>
</dependency>
@@ -320,6 +340,16 @@
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
+ <artifactId>dubbo-configcenter-consul</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.dubbo</groupId>
+ <artifactId>dubbo-configcenter-etcd</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-metadata-definition</artifactId>
<version>${project.version}</version>
</dependency>
diff --git a/dubbo-cluster/pom.xml b/dubbo-cluster/pom.xml
index 6688160..58d0367 100644
--- a/dubbo-cluster/pom.xml
+++ b/dubbo-cluster/pom.xml
@@ -19,7 +19,7 @@
<parent>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-parent</artifactId>
- <version>2.7.0-SNAPSHOT</version>
+ <version>2.7.1-SNAPSHOT</version>
</parent>
<artifactId>dubbo-cluster</artifactId>
<packaging>jar</packaging>
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 8d5f02c..b85a046 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
@@ -98,6 +98,7 @@ public interface Configurator extends Comparable<Configurator> {
* 1. the url with a specific host ip should have higher priority than 0.0.0.0
* 2. if two url has the same host, compare by priority value;
*/
+ @Override
default int compareTo(Configurator o) {
if (o == null) {
return -1;
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 5addb8e..fadefde 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
@@ -32,6 +32,9 @@ import java.util.List;
* @see org.apache.dubbo.rpc.cluster.Directory#list(Invocation)
*/
public interface Router extends Comparable<Router> {
+
+ int DEFAULT_PRIORITY = Integer.MAX_VALUE;
+
/**
* Get the router url.
*
@@ -85,4 +88,12 @@ public interface Router extends Comparable<Router> {
* @return router's priority
*/
int getPriority();
+
+ @Override
+ default int compareTo(Router o) {
+ if (o == null) {
+ throw new IllegalArgumentException();
+ }
+ return Integer.compare(this.getPriority(), o.getPriority());
+ }
}
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 1d57773..bc9beb4 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
@@ -20,7 +20,7 @@ import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.cluster.configurator.AbstractConfigurator;
/**
- * AbsentConfigurator
+ * OverrideConfigurator
*
*/
public class OverrideConfigurator extends AbstractConfigurator {
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 051b4bd..a63aa55 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
@@ -21,7 +21,7 @@ import org.apache.dubbo.rpc.cluster.Configurator;
import org.apache.dubbo.rpc.cluster.ConfiguratorFactory;
/**
- * AbsentConfiguratorFactory
+ * OverrideConfiguratorFactory
*
*/
public class OverrideConfiguratorFactory implements ConfiguratorFactory {
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 bffa1d6..76d6f2d 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
@@ -130,7 +130,7 @@ public class ConfigParser {
sb.append(item.getSide());
}
Map<String, String> parameters = item.getParameters();
- if (parameters == null || parameters.isEmpty()) {
+ if (CollectionUtils.isEmptyMap(parameters)) {
throw new IllegalStateException("Invalid configurator rule, please specify at least one parameter " +
"you want to change in the rule.");
}
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 385fa10..c5a26a3 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
@@ -19,6 +19,7 @@ package org.apache.dubbo.rpc.cluster.directory;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
+import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
@@ -29,7 +30,6 @@ import java.util.List;
/**
* StaticDirectory
- *
*/
public class StaticDirectory<T> extends AbstractDirectory<T> {
private static final Logger logger = LoggerFactory.getLogger(StaticDirectory.class);
@@ -49,9 +49,10 @@ public class StaticDirectory<T> extends AbstractDirectory<T> {
}
public StaticDirectory(URL url, List<Invoker<T>> invokers, RouterChain<T> routerChain) {
- super(url == null && invokers != null && !invokers.isEmpty() ? invokers.get(0).getUrl() : url, routerChain);
- if (invokers == null || invokers.isEmpty())
+ super(url == null && CollectionUtils.isNotEmpty(invokers) ? invokers.get(0).getUrl() : url, routerChain);
+ if (CollectionUtils.isEmpty(invokers)) {
throw new IllegalArgumentException("invokers == null");
+ }
this.invokers = invokers;
}
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 feb9202..78151ed 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
@@ -18,6 +18,7 @@ package org.apache.dubbo.rpc.cluster.loadbalance;
import org.apache.dubbo.common.Constants;
import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.LoadBalance;
@@ -44,7 +45,7 @@ public abstract class AbstractLoadBalance implements LoadBalance {
@Override
public <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) {
- if (invokers == null || invokers.isEmpty()) {
+ if (CollectionUtils.isEmpty(invokers)) {
return null;
}
if (invokers.size() == 1) {
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 8671cde..83d6f8c 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
@@ -22,7 +22,7 @@ import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.support.RpcUtils;
-import java.io.UnsupportedEncodingException;
+import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
@@ -33,7 +33,6 @@ import java.util.concurrent.ConcurrentMap;
/**
* ConsistentHashLoadBalance
- *
*/
public class ConsistentHashLoadBalance extends AbstractLoadBalance {
public static final String NAME = "consistenthash";
@@ -126,12 +125,7 @@ public class ConsistentHashLoadBalance extends AbstractLoadBalance {
throw new IllegalStateException(e.getMessage(), e);
}
md5.reset();
- byte[] bytes;
- try {
- bytes = value.getBytes("UTF-8");
- } catch (UnsupportedEncodingException e) {
- throw new IllegalStateException(e.getMessage(), e);
- }
+ byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
md5.update(bytes);
return md5.digest();
}
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 da4bd7c..657ad86 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
@@ -20,11 +20,8 @@ import org.apache.dubbo.common.URL;
import org.apache.dubbo.configcenter.DynamicConfiguration;
import org.apache.dubbo.rpc.cluster.Router;
-/**
- * TODO Extract more code to here if necessary
- */
public abstract class AbstractRouter implements Router {
- protected int priority;
+ protected int priority = DEFAULT_PRIORITY;
protected boolean force = false;
protected URL url;
@@ -66,10 +63,6 @@ public abstract class AbstractRouter implements Router {
}
@Override
- public int compareTo(Router o) {
- return (this.getPriority() >= o.getPriority()) ? 1 : -1;
- }
-
public int getPriority() {
return priority;
}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java
index 434ef8c..6549cda 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java
@@ -20,13 +20,13 @@ import org.apache.dubbo.common.Constants;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
+import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
-import org.apache.dubbo.rpc.cluster.Router;
import org.apache.dubbo.rpc.cluster.router.AbstractRouter;
import java.text.ParseException;
@@ -43,7 +43,7 @@ import java.util.regex.Pattern;
* ConditionRouter
*
*/
-public class ConditionRouter extends AbstractRouter implements Comparable<Router> {
+public class ConditionRouter extends AbstractRouter {
public static final String NAME = "condition";
private static final Logger logger = LoggerFactory.getLogger(ConditionRouter.class);
@@ -101,7 +101,7 @@ public class ConditionRouter extends AbstractRouter implements Comparable<Router
String separator = matcher.group(1);
String content = matcher.group(2);
// Start part of the condition expression.
- if (separator == null || separator.length() == 0) {
+ if (StringUtils.isEmpty(separator)) {
pair = new MatchPair();
condition.put(content, pair);
}
@@ -163,7 +163,7 @@ public class ConditionRouter extends AbstractRouter implements Comparable<Router
return invokers;
}
- if (invokers == null || invokers.isEmpty()) {
+ if (CollectionUtils.isEmpty(invokers)) {
return invokers;
}
try {
@@ -205,11 +205,11 @@ public class ConditionRouter extends AbstractRouter implements Comparable<Router
}
boolean matchWhen(URL url, Invocation invocation) {
- return whenCondition == null || whenCondition.isEmpty() || matchCondition(whenCondition, url, null, invocation);
+ return CollectionUtils.isEmptyMap(whenCondition) || matchCondition(whenCondition, url, null, invocation);
}
private boolean matchThen(URL url, URL param) {
- return !(thenCondition == null || thenCondition.isEmpty()) && matchCondition(thenCondition, url, param, null);
+ return CollectionUtils.isNotEmptyMap(thenCondition) && matchCondition(thenCondition, url, param, null);
}
private boolean matchCondition(Map<String, MatchPair> condition, URL url, URL param, Invocation invocation) {
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppRouter.java
index 9c723df..31a5df1 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppRouter.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppRouter.java
@@ -25,8 +25,13 @@ import org.apache.dubbo.configcenter.DynamicConfiguration;
*/
public class AppRouter extends ListenableRouter {
public static final String NAME = "APP_ROUTER";
+ /**
+ * AppRouter should after ServiceRouter
+ */
+ private static final int APP_ROUTER_DEFAULT_PRIORITY = 150;
public AppRouter(DynamicConfiguration configuration, URL url) {
super(configuration, url, url.getParameter(Constants.APPLICATION_KEY));
+ this.priority = APP_ROUTER_DEFAULT_PRIORITY;
}
}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ListenableRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ListenableRouter.java
index 65a4eec..564f371 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ListenableRouter.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ListenableRouter.java
@@ -44,7 +44,7 @@ import java.util.stream.Collectors;
public abstract class ListenableRouter extends AbstractRouter implements ConfigurationListener {
public static final String NAME = "LISTENABLE_ROUTER";
private static final String RULE_SUFFIX = ".condition-router";
- public static final int DEFAULT_PRIORITY = 200;
+
private static final Logger logger = LoggerFactory.getLogger(ListenableRouter.class);
private ConditionRouterRule routerRule;
private List<ConditionRouter> conditionRouters = Collections.emptyList();
@@ -120,7 +120,7 @@ public abstract class ListenableRouter extends AbstractRouter implements Configu
String routerKey = ruleKey + RULE_SUFFIX;
configuration.addListener(routerKey, this);
String rule = configuration.getConfig(routerKey);
- if (rule != null) {
+ if (StringUtils.isNotEmpty(rule)) {
this.process(new ConfigChangeEvent(routerKey, rule));
}
}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceRouter.java
index c76f2a7..ed3748e 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceRouter.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceRouter.java
@@ -24,8 +24,13 @@ import org.apache.dubbo.configcenter.DynamicConfiguration;
*/
public class ServiceRouter extends ListenableRouter {
public static final String NAME = "SERVICE_ROUTER";
+ /**
+ * ServiceRouter should before AppRouter
+ */
+ private static final int SERVICE_ROUTER_DEFAULT_PRIORITY = 140;
public ServiceRouter(DynamicConfiguration configuration, URL url) {
super(configuration, url, url.getEncodedServiceKey());
+ this.priority = SERVICE_ROUTER_DEFAULT_PRIORITY;
}
}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterFactory.java
index 2d50942..1dd446c 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterFactory.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterFactory.java
@@ -18,6 +18,7 @@ package org.apache.dubbo.rpc.cluster.router.file;
import org.apache.dubbo.common.Constants;
import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.utils.IOUtils;
import org.apache.dubbo.rpc.cluster.Router;
import org.apache.dubbo.rpc.cluster.RouterFactory;
@@ -55,9 +56,12 @@ public class FileRouterFactory implements RouterFactory {
// FIXME: this code looks useless
boolean runtime = url.getParameter(Constants.RUNTIME_KEY, false);
- URL script = url.setProtocol(protocol).addParameter(Constants.TYPE_KEY, type)
+ URL script = URLBuilder.from(url)
+ .setProtocol(protocol)
+ .addParameter(Constants.TYPE_KEY, type)
.addParameter(Constants.RUNTIME_KEY, runtime)
- .addParameterAndEncoded(Constants.RULE_KEY, rule);
+ .addParameterAndEncoded(Constants.RULE_KEY, rule)
+ .build();
return routerFactory.getRouter(script);
} catch (IOException e) {
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 896638a..78ada66 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
@@ -22,7 +22,6 @@ import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
-import org.apache.dubbo.rpc.cluster.Router;
import org.apache.dubbo.rpc.cluster.router.AbstractRouter;
import java.util.ArrayList;
@@ -31,11 +30,15 @@ import java.util.List;
/**
* A specific Router designed to realize mock feature.
* If a request is configured to use mock, then this router guarantees that only the invokers with protocol MOCK appear in final the invoker list, all other invokers will be excluded.
- *
*/
public class MockInvokersSelector extends AbstractRouter {
public static final String NAME = "MOCK_ROUTER";
+ private static final int MOCK_INVOKERS_DEFAULT_PRIORITY = Integer.MIN_VALUE;
+
+ public MockInvokersSelector() {
+ this.priority = MOCK_INVOKERS_DEFAULT_PRIORITY;
+ }
@Override
public <T> List<Invoker<T>> route(final List<Invoker<T>> invokers,
@@ -95,15 +98,4 @@ public class MockInvokersSelector extends AbstractRouter {
return hasMockProvider;
}
- /**
- * Always stay on the top of the list
- *
- * @param o
- * @return
- */
- @Override
- public int compareTo(Router o) {
- return 1;
- }
-
}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouter.java
index 496a0dc..0b47d2e 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouter.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouter.java
@@ -20,6 +20,7 @@ import org.apache.dubbo.common.Constants;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
+import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcContext;
@@ -37,73 +38,75 @@ import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
+import java.util.stream.Collectors;
/**
* ScriptRouter
*/
public class ScriptRouter extends AbstractRouter {
public static final String NAME = "SCRIPT_ROUTER";
+ private static final int SCRIPT_ROUTER_DEFAULT_PRIORITY = 0;
private static final Logger logger = LoggerFactory.getLogger(ScriptRouter.class);
private static final Map<String, ScriptEngine> engines = new ConcurrentHashMap<>();
private final ScriptEngine engine;
- private final int priority;
-
private final String rule;
+ private CompiledScript function;
+
public ScriptRouter(URL url) {
this.url = url;
- String type = url.getParameter(Constants.TYPE_KEY);
- this.priority = url.getParameter(Constants.PRIORITY_KEY, 0);
- String rule = url.getParameterAndDecoded(Constants.RULE_KEY);
- if (type == null || type.length() == 0) {
- type = Constants.DEFAULT_SCRIPT_TYPE_KEY;
- }
- if (rule == null || rule.length() == 0) {
- throw new IllegalStateException("route rule can not be empty. rule:" + rule);
+ this.priority = url.getParameter(Constants.PRIORITY_KEY, SCRIPT_ROUTER_DEFAULT_PRIORITY);
+
+ engine = getEngine(url);
+ rule = getRule(url);
+ try {
+ Compilable compilable = (Compilable) engine;
+ function = compilable.compile(rule);
+ } catch (ScriptException e) {
+ logger.error("route error, rule has been ignored. rule: " + rule +
+ ", url: " + RpcContext.getContext().getUrl(), e);
}
- ScriptEngine engine = engines.get(type);
- if (engine == null) {
- engine = new ScriptEngineManager().getEngineByName(type);
- if (engine == null) {
- throw new IllegalStateException("unsupported route rule type: " + type + ", rule: " + rule);
- }
- engines.put(type, engine);
+
+
+ }
+
+ /**
+ * get rule from url parameters.
+ */
+ private String getRule(URL url) {
+ String vRule = url.getParameterAndDecoded(Constants.RULE_KEY);
+ if (StringUtils.isEmpty(vRule)) {
+ throw new IllegalStateException("route rule can not be empty.");
}
- this.engine = engine;
- this.rule = rule;
+ return vRule;
}
- @Override
- public URL getUrl() {
- return url;
+ /**
+ * create ScriptEngine instance by type from url parameters, then cache it
+ */
+ private ScriptEngine getEngine(URL url) {
+ String type = url.getParameter(Constants.TYPE_KEY, Constants.DEFAULT_SCRIPT_TYPE_KEY);
+
+ return engines.computeIfAbsent(type, t -> {
+ ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName(type);
+ if (scriptEngine == null) {
+ throw new IllegalStateException("unsupported route engine type: " + type);
+ }
+ return scriptEngine;
+ });
}
@Override
- @SuppressWarnings("unchecked")
public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
try {
- List<Invoker<T>> invokersCopy = new ArrayList<>(invokers);
- Compilable compilable = (Compilable) engine;
- Bindings bindings = engine.createBindings();
- bindings.put("invokers", invokersCopy);
- bindings.put("invocation", invocation);
- bindings.put("context", RpcContext.getContext());
- CompiledScript function = compilable.compile(rule);
- Object obj = function.eval(bindings);
- if (obj instanceof Invoker[]) {
- invokersCopy = Arrays.asList((Invoker<T>[]) obj);
- } else if (obj instanceof Object[]) {
- invokersCopy = new ArrayList<Invoker<T>>();
- for (Object inv : (Object[]) obj) {
- invokersCopy.add((Invoker<T>) inv);
- }
- } else {
- invokersCopy = (List<Invoker<T>>) obj;
+ Bindings bindings = createBindings(invokers, invocation);
+ if (function == null) {
+ return invokers;
}
- return invokersCopy;
+ return getRoutedInvokers(function.eval(bindings));
} catch (ScriptException e) {
logger.error("route error, rule has been ignored. rule: " + rule + ", method:" +
invocation.getMethodName() + ", url: " + RpcContext.getContext().getUrl(), e);
@@ -111,6 +114,32 @@ public class ScriptRouter extends AbstractRouter {
}
}
+ /**
+ * get routed invokers from result of script rule evaluation
+ */
+ @SuppressWarnings("unchecked")
+ protected <T> List<Invoker<T>> getRoutedInvokers(Object obj) {
+ if (obj instanceof Invoker[]) {
+ return Arrays.asList((Invoker<T>[]) obj);
+ } else if (obj instanceof Object[]) {
+ return Arrays.stream((Object[]) obj).map(item -> (Invoker<T>) item).collect(Collectors.toList());
+ } else {
+ return (List<Invoker<T>>) obj;
+ }
+ }
+
+ /**
+ * create bindings for script engine
+ */
+ private <T> Bindings createBindings(List<Invoker<T>> invokers, Invocation invocation) {
+ Bindings bindings = engine.createBindings();
+ // create a new List of invokers
+ bindings.put("invokers", new ArrayList<>(invokers));
+ bindings.put("invocation", invocation);
+ bindings.put("context", RpcContext.getContext());
+ return bindings;
+ }
+
@Override
public boolean isRuntime() {
return this.url.getParameter(Constants.RUNTIME_KEY, false);
@@ -120,4 +149,5 @@ public class ScriptRouter extends AbstractRouter {
public boolean isForce() {
return url.getParameter(Constants.FORCE_KEY, false);
}
+
}
diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java
index 6c4e94e..d03efca 100644
--- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java
+++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java
@@ -21,6 +21,7 @@ import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
+import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.configcenter.ConfigChangeEvent;
import org.apache.dubbo.configcenter.ConfigChangeType;
@@ -29,11 +30,11 @@ import org.apache.dubbo.configcenter.DynamicConfiguration;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
-import org.apache.dubbo.rpc.cluster.Router;
import org.apache.dubbo.rpc.cluster.router.AbstractRouter;
import org.apache.dubbo.rpc.cluster.router.tag.model.TagRouterRule;
import org.apache.dubbo.rpc.cluster.router.tag.model.TagRuleParser;
+import java.net.UnknownHostException;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@@ -44,9 +45,9 @@ import static org.apache.dubbo.common.Constants.TAG_KEY;
/**
* TagRouter, "application.tag-router"
*/
-public class TagRouter extends AbstractRouter implements Comparable<Router>, ConfigurationListener {
+public class TagRouter extends AbstractRouter implements ConfigurationListener {
public static final String NAME = "TAG_ROUTER";
- private static final int DEFAULT_PRIORITY = 100;
+ private static final int TAG_ROUTER_DEFAULT_PRIORITY = 100;
private static final Logger logger = LoggerFactory.getLogger(TagRouter.class);
private static final String RULE_SUFFIX = ".tag-router";
@@ -55,6 +56,7 @@ public class TagRouter extends AbstractRouter implements Comparable<Router>, Con
public TagRouter(DynamicConfiguration configuration, URL url) {
super(configuration, url);
+ this.priority = TAG_ROUTER_DEFAULT_PRIORITY;
}
@Override
@@ -87,8 +89,10 @@ public class TagRouter extends AbstractRouter implements Comparable<Router>, Con
return invokers;
}
- if (tagRouterRule == null || !tagRouterRule.isValid() || !tagRouterRule.isEnabled()) {
- return invokers;
+ // since the rule can be changed by config center, we should copy one to use.
+ final TagRouterRule tagRouterRuleCopy = tagRouterRule;
+ if (tagRouterRuleCopy == null || !tagRouterRuleCopy.isValid() || !tagRouterRuleCopy.isEnabled()) {
+ return filterUsingStaticTag(invokers, url, invocation);
}
List<Invoker<T>> result = invokers;
@@ -97,12 +101,12 @@ public class TagRouter extends AbstractRouter implements Comparable<Router>, Con
// if we are requesting for a Provider with a specific tag
if (StringUtils.isNotEmpty(tag)) {
- List<String> addresses = tagRouterRule.getTagnameToAddresses().get(tag);
+ List<String> addresses = tagRouterRuleCopy.getTagnameToAddresses().get(tag);
// filter by dynamic tag group first
if (CollectionUtils.isNotEmpty(addresses)) {
result = filterInvoker(invokers, invoker -> addressMatches(invoker.getUrl(), addresses));
// if result is not null OR it's null but force=true, return result directly
- if (CollectionUtils.isNotEmpty(result) || tagRouterRule.isForce()) {
+ if (CollectionUtils.isNotEmpty(result) || tagRouterRuleCopy.isForce()) {
return result;
}
} else {
@@ -112,19 +116,19 @@ public class TagRouter extends AbstractRouter implements Comparable<Router>, Con
}
// 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) || isForceUse(invocation)) {
+ if (CollectionUtils.isNotEmpty(result) || isForceUseTag(invocation)) {
return result;
}
// FAILOVER: return all Providers without any tags.
else {
List<Invoker<T>> tmp = filterInvoker(invokers, invoker -> addressNotMatches(invoker.getUrl(),
- tagRouterRule.getAddresses()));
+ tagRouterRuleCopy.getAddresses()));
return filterInvoker(tmp, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(TAG_KEY)));
}
} else {
// List<String> addresses = tagRouterRule.filter(providerApp);
// return all addresses in dynamic tag group.
- List<String> addresses = tagRouterRule.getAddresses();
+ List<String> addresses = tagRouterRuleCopy.getAddresses();
if (CollectionUtils.isNotEmpty(addresses)) {
result = filterInvoker(invokers, invoker -> addressNotMatches(invoker.getUrl(), addresses));
// 1. all addresses are in dynamic tag group, return empty list.
@@ -136,14 +140,40 @@ public class TagRouter extends AbstractRouter implements Comparable<Router>, Con
}
return filterInvoker(result, invoker -> {
String localTag = invoker.getUrl().getParameter(TAG_KEY);
- return StringUtils.isEmpty(localTag) || !tagRouterRule.getTagNames().contains(localTag);
+ return StringUtils.isEmpty(localTag) || !tagRouterRuleCopy.getTagNames().contains(localTag);
});
}
}
- @Override
- public int getPriority() {
- return DEFAULT_PRIORITY;
+ /**
+ * If there's no dynamic tag rule being set, use static tag in URL.
+ * <p>
+ * A typical scenario is a Consumer using version 2.7.x calls Providers using version 2.6.x or lower,
+ * the Consumer should always respect the tag in provider URL regardless of whether a dynamic tag rule has been set to it or not.
+ * <p>
+ * TODO, to guarantee consistent behavior of interoperability between 2.6- and 2.7+, this method should has the same logic with the TagRouter in 2.6.x.
+ *
+ * @param invokers
+ * @param url
+ * @param invocation
+ * @param <T>
+ * @return
+ */
+ private <T> List<Invoker<T>> filterUsingStaticTag(List<Invoker<T>> invokers, URL url, Invocation invocation) {
+ List<Invoker<T>> result = invokers;
+ // Dynamic param
+ 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(Constants.TAG_KEY)));
+ if (CollectionUtils.isEmpty(result) && !isForceUseTag(invocation)) {
+ result = filterInvoker(invokers, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(Constants.TAG_KEY)));
+ }
+ } else {
+ result = filterInvoker(invokers, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(Constants.TAG_KEY)));
+ }
+ return result;
}
@Override
@@ -157,7 +187,7 @@ public class TagRouter extends AbstractRouter implements Comparable<Router>, Con
return tagRouterRule != null && tagRouterRule.isForce();
}
- private boolean isForceUse(Invocation invocation) {
+ private boolean isForceUseTag(Invocation invocation) {
return Boolean.valueOf(invocation.getAttachment(FORCE_USE_TAG, url.getParameter(FORCE_USE_TAG, "false")));
}
@@ -168,11 +198,26 @@ public class TagRouter extends AbstractRouter implements Comparable<Router>, Con
}
private boolean addressMatches(URL url, List<String> addresses) {
- return addresses != null && addresses.contains(url.getAddress());
+ return addresses != null && checkAddressMatch(addresses, url.getHost(), url.getPort());
}
private boolean addressNotMatches(URL url, List<String> addresses) {
- return addresses == null || !addresses.contains(url.getAddress());
+ return addresses == null || !checkAddressMatch(addresses, url.getHost(), url.getPort());
+ }
+
+ private boolean checkAddressMatch(List<String> addresses, String host, int port) {
+ for (String address : addresses) {
+ try {
+ if (NetUtils.matchIpExpression(address, host, port)) {
+ return true;
+ }
+ } catch (UnknownHostException e) {
+ logger.error("The format of ip address is invalid in tag route. Address :" + address, e);
+ } catch (Exception e) {
+ logger.error("The format of ip address is invalid in tag route. Address :" + address, e);
+ }
+ }
+ return false;
}
public void setApplication(String app) {
@@ -181,7 +226,7 @@ public class TagRouter extends AbstractRouter implements Comparable<Router>, Con
@Override
public <T> void notify(List<Invoker<T>> invokers) {
- if (invokers == null || invokers.isEmpty()) {
+ if (CollectionUtils.isEmpty(invokers)) {
return;
}
@@ -204,7 +249,7 @@ public class TagRouter extends AbstractRouter implements Comparable<Router>, Con
configuration.addListener(key, this);
application = providerApplication;
String rawRule = configuration.getConfig(key);
- if (rawRule != null) {
+ if (StringUtils.isNotEmpty(rawRule)) {
this.process(new ConfigChangeEvent(key, rawRule));
}
}
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 63486aa..abc9cf2 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
@@ -109,10 +109,10 @@ public abstract class AbstractClusterInvoker<T> implements Invoker<T> {
* @param invokers invoker candidates
* @param selected exclude selected invokers or not
* @return the invoker which will final to do invoke.
- * @throws RpcException
+ * @throws RpcException exception
*/
protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation,
- List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException {
+ List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException {
if (CollectionUtils.isEmpty(invokers)) {
return null;
@@ -120,7 +120,7 @@ public abstract class AbstractClusterInvoker<T> implements Invoker<T> {
String methodName = invocation == null ? StringUtils.EMPTY : invocation.getMethodName();
boolean sticky = invokers.get(0).getUrl()
- .getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY);
+ .getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY);
//ignore overloaded method
if (stickyInvoker != null && !invokers.contains(stickyInvoker)) {
@@ -142,7 +142,7 @@ public abstract class AbstractClusterInvoker<T> implements Invoker<T> {
}
private Invoker<T> doSelect(LoadBalance loadbalance, Invocation invocation,
- List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException {
+ List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException {
if (CollectionUtils.isEmpty(invokers)) {
return null;
@@ -180,19 +180,20 @@ public abstract class AbstractClusterInvoker<T> implements Invoker<T> {
* Reselect, use invokers not in `selected` first, if all invokers are in `selected`,
* just pick an available one using loadbalance policy.
*
- * @param loadbalance
- * @param invocation
- * @param invokers
- * @param selected
- * @return
- * @throws RpcException
+ * @param loadbalance load balance policy
+ * @param invocation invocation
+ * @param invokers invoker candidates
+ * @param selected exclude selected invokers or not
+ * @param availablecheck check invoker available if true
+ * @return the reselect result to do invoke
+ * @throws RpcException exception
*/
private Invoker<T> reselect(LoadBalance loadbalance, Invocation invocation,
- List<Invoker<T>> invokers, List<Invoker<T>> selected, boolean availablecheck) throws RpcException {
+ List<Invoker<T>> invokers, List<Invoker<T>> selected, boolean availablecheck) throws RpcException {
//Allocating one in advance, this list is certain to be used.
List<Invoker<T>> reselectInvokers = new ArrayList<>(
- invokers.size() > 1 ? (invokers.size() - 1) : invokers.size());
+ invokers.size() > 1 ? (invokers.size() - 1) : invokers.size());
// First, try picking a invoker not in `selected`.
for (Invoker<T> invoker : invokers) {
@@ -242,7 +243,6 @@ public abstract class AbstractClusterInvoker<T> implements Invoker<T> {
}
protected void checkWhetherDestroyed() {
-
if (destroyed.get()) {
throw new RpcException("Rpc cluster invoker for " + getInterface() + " on consumer " + NetUtils.getLocalHost()
+ " use dubbo version " + Version.getVersion()
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 8901e4c..37b3e71 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
@@ -84,7 +84,9 @@ public class ClusterUtils {
String remoteGroup = map.get(Constants.GROUP_KEY);
String remoteRelease = map.get(Constants.RELEASE_KEY);
map.putAll(localMap);
- map.put(Constants.GROUP_KEY, remoteGroup);
+ if (StringUtils.isNotEmpty(remoteGroup)) {
+ map.put(Constants.GROUP_KEY, remoteGroup);
+ }
// we should always keep the Provider RELEASE_KEY not overrode by the the value on Consumer side.
map.remove(Constants.RELEASE_KEY);
if (StringUtils.isNotEmpty(remoteRelease)) {
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 293d3bd..009f4df 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
@@ -20,6 +20,7 @@ import org.apache.dubbo.common.Constants;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
+import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
@@ -103,7 +104,7 @@ public class MockClusterInvoker<T> implements Invoker<T> {
Invoker<T> minvoker;
List<Invoker<T>> mockInvokers = selectMockInvoker(invocation);
- if (mockInvokers == null || mockInvokers.isEmpty()) {
+ if (CollectionUtils.isEmpty(mockInvokers)) {
minvoker = (Invoker<T>) new MockInvoker(directory.getUrl());
} else {
minvoker = mockInvokers.get(0);
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 f8fdb31..b10fa01 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
@@ -28,9 +28,9 @@ import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.RpcResult;
import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+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;
@@ -56,7 +56,7 @@ public class StickyTest {
);
private int runs = 1;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
dic = mock(Directory.class);
invocation = new RpcInvocation();
@@ -77,26 +77,26 @@ public class StickyTest {
public void testStickyNoCheck() {
int count = testSticky(null, false);
System.out.println(count);
- Assert.assertTrue(count > 0 && count <= runs);
+ Assertions.assertTrue(count > 0 && count <= runs);
}
@Test
public void testStickyForceCheck() {
int count = testSticky(null, true);
- Assert.assertTrue(count == 0 || count == runs);
+ Assertions.assertTrue(count == 0 || count == runs);
}
@Test
public void testMethodStickyNoCheck() {
int count = testSticky("method1", false);
System.out.println(count);
- Assert.assertTrue(count > 0 && count <= runs);
+ Assertions.assertTrue(count > 0 && count <= runs);
}
@Test
public void testMethodStickyForceCheck() {
int count = testSticky("method1", true);
- Assert.assertTrue(count == 0 || count == runs);
+ Assertions.assertTrue(count == 0 || count == runs);
}
@Test
@@ -104,7 +104,7 @@ public class StickyTest {
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);
- Assert.assertTrue(count1 == count2);
+ Assertions.assertTrue(count1 == count2);
}
}
@@ -129,7 +129,7 @@ public class StickyTest {
int count = 0;
for (int i = 0; i < runs; i++) {
- Assert.assertEquals(null, clusterinvoker.invoke(invocation));
+ Assertions.assertEquals(null, clusterinvoker.invoke(invocation));
if (invoker1 == clusterinvoker.getSelectedInvoker()) {
count++;
}
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 9b3789d..36ef868 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,8 +20,8 @@ import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.rpc.cluster.configurator.consts.UrlConstant;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
/**
* OverrideConfiguratorTest
@@ -34,16 +34,16 @@ public class AbsentConfiguratorTest {
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));
- Assert.assertEquals("200", url.getParameter("timeout"));
+ Assertions.assertEquals("200", url.getParameter("timeout"));
url = configurator.configure(URL.valueOf(UrlConstant.URL_ONE));
- Assert.assertEquals("1000", url.getParameter("timeout"));
+ Assertions.assertEquals("1000", url.getParameter("timeout"));
url = configurator.configure(URL.valueOf(UrlConstant.APPLICATION_BAR_SIDE_CONSUMER_11));
- Assert.assertNull(url.getParameter("timeout"));
+ Assertions.assertNull(url.getParameter("timeout"));
url = configurator.configure(URL.valueOf(UrlConstant.TIMEOUT_1000_SIDE_CONSUMER_11));
- Assert.assertEquals("1000", url.getParameter("timeout"));
+ Assertions.assertEquals("1000", url.getParameter("timeout"));
}
@Test
@@ -51,18 +51,18 @@ public class AbsentConfiguratorTest {
AbsentConfigurator configurator = new AbsentConfigurator(URL.valueOf("override://" + NetUtils.getLocalHost() + "/com.foo.BarService?timeout=200"));
URL url = configurator.configure(URL.valueOf(UrlConstant.URL_CONSUMER));
- Assert.assertEquals("200", url.getParameter("timeout"));
+ Assertions.assertEquals("200", url.getParameter("timeout"));
url = configurator.configure(URL.valueOf(UrlConstant.URL_ONE));
- Assert.assertEquals("1000", url.getParameter("timeout"));
+ Assertions.assertEquals("1000", url.getParameter("timeout"));
AbsentConfigurator configurator1 = new AbsentConfigurator(URL.valueOf(UrlConstant.SERVICE_TIMEOUT_200));
url = configurator1.configure(URL.valueOf(UrlConstant.APPLICATION_BAR_SIDE_CONSUMER_10));
- Assert.assertNull(url.getParameter("timeout"));
+ Assertions.assertNull(url.getParameter("timeout"));
url = configurator1.configure(URL.valueOf(UrlConstant.TIMEOUT_1000_SIDE_CONSUMER_10));
- Assert.assertEquals("1000", url.getParameter("timeout"));
+ Assertions.assertEquals("1000", url.getParameter("timeout"));
}
}
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 1f665ba..f2b7d3d 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
@@ -21,8 +21,8 @@ import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.rpc.cluster.configurator.absent.AbsentConfigurator;
import org.apache.dubbo.rpc.cluster.configurator.consts.UrlConstant;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
/**
* OverrideConfiguratorTest
@@ -34,16 +34,16 @@ public class OverrideConfiguratorTest {
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));
- Assert.assertEquals("200", url.getParameter("timeout"));
+ Assertions.assertEquals("200", url.getParameter("timeout"));
url = configurator.configure(URL.valueOf(UrlConstant.URL_ONE));
- Assert.assertEquals("200", url.getParameter("timeout"));
+ Assertions.assertEquals("200", url.getParameter("timeout"));
url = configurator.configure(URL.valueOf(UrlConstant.APPLICATION_BAR_SIDE_CONSUMER_11));
- Assert.assertNull(url.getParameter("timeout"));
+ Assertions.assertNull(url.getParameter("timeout"));
url = configurator.configure(URL.valueOf(UrlConstant.TIMEOUT_1000_SIDE_CONSUMER_11));
- Assert.assertEquals("1000", url.getParameter("timeout"));
+ Assertions.assertEquals("1000", url.getParameter("timeout"));
}
@Test
@@ -51,18 +51,18 @@ public class OverrideConfiguratorTest {
OverrideConfigurator configurator = new OverrideConfigurator(URL.valueOf("override://" + NetUtils.getLocalHost() + "/com.foo.BarService?timeout=200"));
URL url = configurator.configure(URL.valueOf(UrlConstant.URL_CONSUMER));
- Assert.assertEquals("200", url.getParameter("timeout"));
+ Assertions.assertEquals("200", url.getParameter("timeout"));
url = configurator.configure(URL.valueOf(UrlConstant.URL_ONE));
- Assert.assertEquals("200", url.getParameter("timeout"));
+ Assertions.assertEquals("200", url.getParameter("timeout"));
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));
- Assert.assertNull(url.getParameter("timeout"));
+ Assertions.assertNull(url.getParameter("timeout"));
url = configurator1.configure(URL.valueOf(UrlConstant.TIMEOUT_1000_SIDE_CONSUMER_10));
- Assert.assertEquals("1000", url.getParameter("timeout"));
+ Assertions.assertEquals("1000", 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 0c365c0..6bfe3e0 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
@@ -21,12 +21,13 @@ import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.cluster.configurator.parser.model.ConfigItem;
import org.apache.dubbo.rpc.cluster.configurator.parser.model.ConfiguratorConfig;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import org.yaml.snakeyaml.TypeDescription;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
+import java.io.IOException;
import java.io.InputStream;
import java.util.List;
@@ -35,129 +36,135 @@ import java.util.List;
*/
public class ConfigParserTest {
- private String streamToString(InputStream stream) {
- try {
- byte[] bytes = new byte[stream.available()];
- stream.read(bytes);
- return new String(bytes);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
+ private String streamToString(InputStream stream) throws IOException {
+ byte[] bytes = new byte[stream.available()];
+ stream.read(bytes);
+ return new String(bytes);
}
@Test
- public void snakeYamlBasicTest() {
- InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceNoApp.yml");
+ public void snakeYamlBasicTest() throws IOException {
+ try (InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceNoApp.yml")) {
- Constructor constructor = new Constructor(ConfiguratorConfig.class);
- TypeDescription carDescription = new TypeDescription(ConfiguratorConfig.class);
- carDescription.addPropertyParameters("items", ConfigItem.class);
- constructor.addTypeDescription(carDescription);
+ Constructor constructor = new Constructor(ConfiguratorConfig.class);
+ TypeDescription carDescription = new TypeDescription(ConfiguratorConfig.class);
+ carDescription.addPropertyParameters("items", ConfigItem.class);
+ constructor.addTypeDescription(carDescription);
- Yaml yaml = new Yaml(constructor);
- ConfiguratorConfig config = yaml.load(yamlStream);
- System.out.println(config);
+ Yaml yaml = new Yaml(constructor);
+ ConfiguratorConfig config = yaml.load(yamlStream);
+ System.out.println(config);
+ }
}
@Test
public void parseConfiguratorsServiceNoAppTest() throws Exception {
- InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceNoApp.yml");
- List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
- Assert.assertNotNull(urls);
- Assert.assertEquals(2, urls.size());
- URL url = urls.get(0);
- Assert.assertEquals(url.getAddress(), "127.0.0.1:20880");
- Assert.assertEquals(url.getParameter(Constants.WEIGHT_KEY, 0), 222);
+ try (InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceNoApp.yml")) {
+ List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
+ Assertions.assertNotNull(urls);
+ Assertions.assertEquals(2, urls.size());
+ URL url = urls.get(0);
+ Assertions.assertEquals(url.getAddress(), "127.0.0.1:20880");
+ Assertions.assertEquals(url.getParameter(Constants.WEIGHT_KEY, 0), 222);
+ }
}
@Test
public void parseConfiguratorsServiceGroupVersionTest() throws Exception {
- InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceGroupVersion.yml");
- List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
- Assert.assertNotNull(urls);
- Assert.assertEquals(1, urls.size());
- URL url = urls.get(0);
- Assert.assertEquals("testgroup", url.getParameter(Constants.GROUP_KEY));
- Assert.assertEquals("1.0.0", url.getParameter(Constants.VERSION_KEY));
+ try (InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceGroupVersion.yml")) {
+ List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
+ Assertions.assertNotNull(urls);
+ Assertions.assertEquals(1, urls.size());
+ URL url = urls.get(0);
+ Assertions.assertEquals("testgroup", url.getParameter(Constants.GROUP_KEY));
+ Assertions.assertEquals("1.0.0", url.getParameter(Constants.VERSION_KEY));
+ }
}
@Test
- public void parseConfiguratorsServiceMultiAppsTest() {
- InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceMultiApps.yml");
- List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
- Assert.assertNotNull(urls);
- Assert.assertEquals(4, urls.size());
- URL url = urls.get(0);
- Assert.assertEquals("127.0.0.1", url.getAddress());
- Assert.assertEquals(6666, url.getParameter(Constants.TIMEOUT_KEY, 0));
- Assert.assertNotNull(url.getParameter(Constants.APPLICATION_KEY));
+ public void parseConfiguratorsServiceMultiAppsTest() throws IOException {
+ try (InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceMultiApps.yml")) {
+ List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
+ Assertions.assertNotNull(urls);
+ Assertions.assertEquals(4, urls.size());
+ URL url = urls.get(0);
+ Assertions.assertEquals("127.0.0.1", url.getAddress());
+ Assertions.assertEquals(6666, url.getParameter(Constants.TIMEOUT_KEY, 0));
+ Assertions.assertNotNull(url.getParameter(Constants.APPLICATION_KEY));
+ }
}
- @Test(expected = IllegalStateException.class)
+ @Test
public void parseConfiguratorsServiceNoRuleTest() {
- InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceNoRule.yml");
- ConfigParser.parseConfigurators(streamToString(yamlStream));
- Assert.fail();
+ Assertions.assertThrows(IllegalStateException.class, () -> {
+ try (InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceNoRule.yml")) {
+ ConfigParser.parseConfigurators(streamToString(yamlStream));
+ Assertions.fail();
+ }
+ });
}
@Test
- public void parseConfiguratorsAppMultiServicesTest() {
- InputStream yamlStream = this.getClass().getResourceAsStream("/AppMultiServices.yml");
- String yamlFile = streamToString(yamlStream);
- List<URL> urls = ConfigParser.parseConfigurators(yamlFile);
- Assert.assertNotNull(urls);
- Assert.assertEquals(4, urls.size());
- URL url = urls.get(0);
- Assert.assertEquals("127.0.0.1", url.getAddress());
- Assert.assertEquals("service1", url.getServiceInterface());
- Assert.assertEquals(6666, url.getParameter(Constants.TIMEOUT_KEY, 0));
- Assert.assertEquals("random", url.getParameter(Constants.LOADBALANCE_KEY));
- Assert.assertEquals(url.getParameter(Constants.APPLICATION_KEY), "demo-consumer");
+ public void parseConfiguratorsAppMultiServicesTest() throws IOException {
+ try (InputStream yamlStream = this.getClass().getResourceAsStream("/AppMultiServices.yml")) {
+ String yamlFile = streamToString(yamlStream);
+ List<URL> urls = ConfigParser.parseConfigurators(yamlFile);
+ Assertions.assertNotNull(urls);
+ Assertions.assertEquals(4, urls.size());
+ URL url = urls.get(0);
+ Assertions.assertEquals("127.0.0.1", url.getAddress());
+ Assertions.assertEquals("service1", url.getServiceInterface());
+ Assertions.assertEquals(6666, url.getParameter(Constants.TIMEOUT_KEY, 0));
+ Assertions.assertEquals("random", url.getParameter(Constants.LOADBALANCE_KEY));
+ Assertions.assertEquals(url.getParameter(Constants.APPLICATION_KEY), "demo-consumer");
+ }
}
@Test
- public void parseConfiguratorsAppAnyServicesTest() {
- InputStream yamlStream = this.getClass().getResourceAsStream("/AppAnyServices.yml");
- List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
- Assert.assertNotNull(urls);
- Assert.assertEquals(2, urls.size());
- URL url = urls.get(0);
- Assert.assertEquals("127.0.0.1", url.getAddress());
- Assert.assertEquals("*", url.getServiceInterface());
- Assert.assertEquals(6666, url.getParameter(Constants.TIMEOUT_KEY, 0));
- Assert.assertEquals("random", url.getParameter(Constants.LOADBALANCE_KEY));
- Assert.assertEquals(url.getParameter(Constants.APPLICATION_KEY), "demo-consumer");
+ public void parseConfiguratorsAppAnyServicesTest() throws IOException {
+ try (InputStream yamlStream = this.getClass().getResourceAsStream("/AppAnyServices.yml")) {
+ List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
+ Assertions.assertNotNull(urls);
+ Assertions.assertEquals(2, urls.size());
+ URL url = urls.get(0);
+ Assertions.assertEquals("127.0.0.1", url.getAddress());
+ Assertions.assertEquals("*", url.getServiceInterface());
+ Assertions.assertEquals(6666, url.getParameter(Constants.TIMEOUT_KEY, 0));
+ Assertions.assertEquals("random", url.getParameter(Constants.LOADBALANCE_KEY));
+ Assertions.assertEquals(url.getParameter(Constants.APPLICATION_KEY), "demo-consumer");
+ }
}
@Test
- public void parseConfiguratorsAppNoServiceTest() {
- InputStream yamlStream = this.getClass().getResourceAsStream("/AppNoService.yml");
- List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
- Assert.assertNotNull(urls);
- Assert.assertEquals(1, urls.size());
- URL url = urls.get(0);
- Assert.assertEquals("127.0.0.1", url.getAddress());
- Assert.assertEquals("*", url.getServiceInterface());
- Assert.assertEquals(6666, url.getParameter(Constants.TIMEOUT_KEY, 0));
- Assert.assertEquals("random", url.getParameter(Constants.LOADBALANCE_KEY));
- Assert.assertEquals(url.getParameter(Constants.APPLICATION_KEY), "demo-consumer");
+ public void parseConfiguratorsAppNoServiceTest() throws IOException {
+ try (InputStream yamlStream = this.getClass().getResourceAsStream("/AppNoService.yml")) {
+ List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
+ Assertions.assertNotNull(urls);
+ Assertions.assertEquals(1, urls.size());
+ URL url = urls.get(0);
+ Assertions.assertEquals("127.0.0.1", url.getAddress());
+ Assertions.assertEquals("*", url.getServiceInterface());
+ Assertions.assertEquals(6666, url.getParameter(Constants.TIMEOUT_KEY, 0));
+ Assertions.assertEquals("random", url.getParameter(Constants.LOADBALANCE_KEY));
+ Assertions.assertEquals(url.getParameter(Constants.APPLICATION_KEY), "demo-consumer");
+ }
}
@Test
- public void parseConsumerSpecificProvidersTest() {
- InputStream yamlStream = this.getClass().getResourceAsStream("/ConsumerSpecificProviders.yml");
- List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
- Assert.assertNotNull(urls);
- Assert.assertEquals(1, urls.size());
- URL url = urls.get(0);
- Assert.assertEquals("127.0.0.1", url.getAddress());
- Assert.assertEquals("*", url.getServiceInterface());
- Assert.assertEquals(6666, url.getParameter(Constants.TIMEOUT_KEY, 0));
- Assert.assertEquals("random", url.getParameter(Constants.LOADBALANCE_KEY));
- Assert.assertEquals("127.0.0.1:20880", url.getParameter(Constants.OVERRIDE_PROVIDERS_KEY));
- Assert.assertEquals(url.getParameter(Constants.APPLICATION_KEY), "demo-consumer");
+ public void parseConsumerSpecificProvidersTest() throws IOException {
+ try (InputStream yamlStream = this.getClass().getResourceAsStream("/ConsumerSpecificProviders.yml")) {
+ List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
+ Assertions.assertNotNull(urls);
+ Assertions.assertEquals(1, urls.size());
+ URL url = urls.get(0);
+ Assertions.assertEquals("127.0.0.1", url.getAddress());
+ Assertions.assertEquals("*", url.getServiceInterface());
+ Assertions.assertEquals(6666, url.getParameter(Constants.TIMEOUT_KEY, 0));
+ Assertions.assertEquals("random", url.getParameter(Constants.LOADBALANCE_KEY));
+ Assertions.assertEquals("127.0.0.1:20880", url.getParameter(Constants.OVERRIDE_PROVIDERS_KEY));
+ Assertions.assertEquals(url.getParameter(Constants.APPLICATION_KEY), "demo-consumer");
+ }
}
}
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 ac538b7..706f141 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
@@ -25,8 +25,8 @@ import org.apache.dubbo.rpc.cluster.Router;
import org.apache.dubbo.rpc.cluster.router.MockInvoker;
import org.apache.dubbo.rpc.cluster.router.condition.ConditionRouterFactory;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
@@ -56,10 +56,10 @@ public class StaticDirectoryTest {
List<Invoker<String>> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation());
StaticDirectory<String> staticDirectory = new StaticDirectory<>(filteredInvokers);
boolean isAvailable = staticDirectory.isAvailable();
- Assert.assertTrue(!isAvailable);
+ Assertions.assertTrue(!isAvailable);
List<Invoker<String>> newInvokers = staticDirectory.list(new MockDirInvocation());
- Assert.assertTrue(newInvokers.size() > 0);
+ Assertions.assertTrue(newInvokers.size() > 0);
staticDirectory.destroy();
- Assert.assertEquals(0, newInvokers.size());
+ Assertions.assertEquals(0, newInvokers.size());
}
}
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 278725f..48bef62 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
@@ -18,8 +18,8 @@ package org.apache.dubbo.rpc.cluster.loadbalance;
import org.apache.dubbo.rpc.Invoker;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
@@ -28,27 +28,27 @@ import java.util.concurrent.atomic.AtomicLong;
@SuppressWarnings("rawtypes")
public class ConsistentHashLoadBalanceTest extends LoadBalanceBaseTest {
- @Test
- public void testConsistentHashLoadBalance() {
- int runs = 10000;
- long unHitedInvokerCount = 0;
- Map<Invoker, Long> hitedInvokers = new HashMap<>();
- Map<Invoker, AtomicLong> counter = getInvokeCounter(runs, ConsistentHashLoadBalance.NAME);
- for (Invoker minvoker : counter.keySet()) {
- Long count = counter.get(minvoker).get();
-
- if (count == 0) {
- unHitedInvokerCount++;
- } else {
- hitedInvokers.put(minvoker, count);
- }
- }
-
- Assert.assertEquals("the number of unHitedInvoker should be counter.size() - 1", counter.size() - 1,
- unHitedInvokerCount);
- Assert.assertEquals("the number of hitedInvoker should be 1", 1, hitedInvokers.size());
- Assert.assertEquals("the number of hited count should be the number of runs", runs,
- hitedInvokers.values().iterator().next().intValue());
- }
+ @Test
+ public void testConsistentHashLoadBalance() {
+ int runs = 10000;
+ long unHitedInvokerCount = 0;
+ Map<Invoker, Long> hitedInvokers = new HashMap<>();
+ Map<Invoker, AtomicLong> counter = getInvokeCounter(runs, ConsistentHashLoadBalance.NAME);
+ for (Invoker minvoker : counter.keySet()) {
+ Long count = counter.get(minvoker).get();
+
+ if (count == 0) {
+ unHitedInvokerCount++;
+ } else {
+ hitedInvokers.put(minvoker, count);
+ }
+ }
+
+ 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");
+ }
}
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 c54e9a0..00b5c14 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
@@ -17,15 +17,16 @@
package org.apache.dubbo.rpc.cluster.loadbalance;
import org.apache.dubbo.rpc.Invoker;
-import org.junit.Assert;
-import org.junit.Ignore;
-import org.junit.Test;
+
+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;
public class LeastActiveBalanceTest extends LoadBalanceBaseTest {
- @Ignore
+ @Disabled
@Test
public void testLeastActiveLoadBalance_select() {
int runs = 10000;
@@ -33,8 +34,8 @@ public class LeastActiveBalanceTest extends LoadBalanceBaseTest {
for (Map.Entry<Invoker, AtomicLong> entry : counter.entrySet()) {
Long count = entry.getValue().get();
// System.out.println(count);
- Assert.assertTrue("abs diff shoud < avg",
- Math.abs(count - runs / (0f + invokers.size())) < runs / (0f + invokers.size()));
+ Assertions.assertTrue(
+ Math.abs(count - runs / (0f + invokers.size())) < runs / (0f + invokers.size()), "abs diff shoud < avg");
}
}
@@ -56,13 +57,13 @@ public class LeastActiveBalanceTest extends LoadBalanceBaseTest {
sumInvoker2++;
}
// never select invoker3 because it's active is more than invoker1 and invoker2
- Assert.assertTrue("select is not the least active one", !selected.getUrl().getProtocol().equals("test3"));
+ Assertions.assertTrue(!selected.getUrl().getProtocol().equals("test3"), "select is not the least active one");
}
// the sumInvoker1 : sumInvoker2 approximately equal to 1: 9
System.out.println(sumInvoker1);
System.out.println(sumInvoker2);
- Assert.assertEquals("select failed!", sumInvoker1 + sumInvoker2, loop);
+ Assertions.assertEquals(sumInvoker1 + sumInvoker2, loop, "select failed!");
}
}
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 2248aef..ec43e38 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
@@ -24,10 +24,10 @@ import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.RpcStatus;
import org.apache.dubbo.rpc.cluster.LoadBalance;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
import com.alibaba.fastjson.JSON;
import org.mockito.Mockito;
@@ -63,14 +63,14 @@ public class LoadBalanceBaseTest {
/**
* @throws java.lang.Exception
*/
- @BeforeClass
+ @BeforeAll
public static void setUpBeforeClass() throws Exception {
}
/**
* @throws java.lang.Exception
*/
- @Before
+ @BeforeEach
public void setUp() throws Exception {
invocation = mock(Invocation.class);
@@ -136,20 +136,20 @@ public class LoadBalanceBaseTest {
@Test
public void testLoadBalanceWarmup() {
- Assert.assertEquals(1, calculateDefaultWarmupWeight(0));
- Assert.assertEquals(1, calculateDefaultWarmupWeight(13));
- Assert.assertEquals(1, calculateDefaultWarmupWeight(6 * 1000));
- Assert.assertEquals(2, calculateDefaultWarmupWeight(12 * 1000));
- Assert.assertEquals(10, calculateDefaultWarmupWeight(60 * 1000));
- Assert.assertEquals(50, calculateDefaultWarmupWeight(5 * 60 * 1000));
- Assert.assertEquals(50, calculateDefaultWarmupWeight(5 * 60 * 1000 + 23));
- Assert.assertEquals(50, calculateDefaultWarmupWeight(5 * 60 * 1000 + 5999));
- Assert.assertEquals(51, calculateDefaultWarmupWeight(5 * 60 * 1000 + 6000));
- Assert.assertEquals(90, calculateDefaultWarmupWeight(9 * 60 * 1000));
- Assert.assertEquals(98, calculateDefaultWarmupWeight(10 * 60 * 1000 - 12 * 1000));
- Assert.assertEquals(99, calculateDefaultWarmupWeight(10 * 60 * 1000 - 6 * 1000));
- Assert.assertEquals(100, calculateDefaultWarmupWeight(10 * 60 * 1000));
- Assert.assertEquals(100, calculateDefaultWarmupWeight(20 * 60 * 1000));
+ Assertions.assertEquals(1, calculateDefaultWarmupWeight(0));
+ Assertions.assertEquals(1, calculateDefaultWarmupWeight(13));
+ Assertions.assertEquals(1, calculateDefaultWarmupWeight(6 * 1000));
+ Assertions.assertEquals(2, calculateDefaultWarmupWeight(12 * 1000));
+ Assertions.assertEquals(10, calculateDefaultWarmupWeight(60 * 1000));
+ Assertions.assertEquals(50, calculateDefaultWarmupWeight(5 * 60 * 1000));
+ Assertions.assertEquals(50, calculateDefaultWarmupWeight(5 * 60 * 1000 + 23));
+ Assertions.assertEquals(50, calculateDefaultWarmupWeight(5 * 60 * 1000 + 5999));
+ Assertions.assertEquals(51, calculateDefaultWarmupWeight(5 * 60 * 1000 + 6000));
+ Assertions.assertEquals(90, calculateDefaultWarmupWeight(9 * 60 * 1000));
+ Assertions.assertEquals(98, calculateDefaultWarmupWeight(10 * 60 * 1000 - 12 * 1000));
+ Assertions.assertEquals(99, calculateDefaultWarmupWeight(10 * 60 * 1000 - 6 * 1000));
+ Assertions.assertEquals(100, calculateDefaultWarmupWeight(10 * 60 * 1000));
+ Assertions.assertEquals(100, calculateDefaultWarmupWeight(20 * 60 * 1000));
}
/**
@@ -209,7 +209,7 @@ public class LoadBalanceBaseTest {
protected Invoker<LoadBalanceBaseTest> weightInvoker3;
protected Invoker<LoadBalanceBaseTest> weightInvokerTmp;
- @Before
+ @BeforeEach
public void before() throws Exception {
weightInvoker1 = mock(Invoker.class, Mockito.withSettings().stubOnly());
weightInvoker2 = mock(Invoker.class, Mockito.withSettings().stubOnly());
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 3b65ee3..f18a07d 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
@@ -18,8 +18,9 @@ package org.apache.dubbo.rpc.cluster.loadbalance;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcStatus;
-import org.junit.Assert;
-import org.junit.Test;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
@@ -34,7 +35,7 @@ public class RandomLoadBalanceTest extends LoadBalanceBaseTest {
Map<Invoker, AtomicLong> counter = getInvokeCounter(runs, RandomLoadBalance.NAME);
for (Map.Entry<Invoker, AtomicLong> entry : counter.entrySet()) {
Long count = entry.getValue().get();
- Assert.assertTrue("abs diff should < avg", Math.abs(count - runs / (0f + invokers.size())) < runs / (0f + invokers.size()));
+ Assertions.assertTrue(Math.abs(count - runs / (0f + invokers.size())) < runs / (0f + invokers.size()), "abs diff should < avg");
}
for (int i = 0; i < 5; i++) {
@@ -46,11 +47,11 @@ public class RandomLoadBalanceTest extends LoadBalanceBaseTest {
for (Map.Entry<Invoker, AtomicLong> entry : counter.entrySet()) {
Long count = entry.getValue().get();
}
- Assert.assertEquals(runs, counter.get(invoker1).intValue());
- Assert.assertEquals(0, counter.get(invoker2).intValue());
- Assert.assertEquals(0, counter.get(invoker3).intValue());
- Assert.assertEquals(0, counter.get(invoker4).intValue());
- Assert.assertEquals(0, counter.get(invoker5).intValue());
+ Assertions.assertEquals(runs, counter.get(invoker1).intValue());
+ Assertions.assertEquals(0, counter.get(invoker2).intValue());
+ Assertions.assertEquals(0, counter.get(invoker3).intValue());
+ Assertions.assertEquals(0, counter.get(invoker4).intValue());
+ Assertions.assertEquals(0, counter.get(invoker5).intValue());
}
@Test
@@ -81,7 +82,7 @@ public class RandomLoadBalanceTest extends LoadBalanceBaseTest {
System.out.println(sumInvoker1);
System.out.println(sumInvoker2);
System.out.println(sumInvoker3);
- Assert.assertEquals("select failed!", sumInvoker1 + sumInvoker2 + sumInvoker3, loop);
+ 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 66488bf..86d4130 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
@@ -17,9 +17,10 @@
package org.apache.dubbo.rpc.cluster.loadbalance;
import org.apache.dubbo.rpc.Invoker;
-import org.junit.Assert;
-import org.junit.Ignore;
-import org.junit.Test;
+
+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;
@@ -30,7 +31,7 @@ import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
-@Ignore
+@Disabled
public class RoundRobinLoadBalanceTest extends LoadBalanceBaseTest {
private void assertStrictWRRResult(int loop, Map<Invoker, InvokeResult> resultMap) {
@@ -38,11 +39,11 @@ public class RoundRobinLoadBalanceTest extends LoadBalanceBaseTest {
for (InvokeResult invokeResult : resultMap.values()) {
int count = (int) invokeResult.getCount().get();
// Because it's a strictly round robin, so the abs delta should be < 10 too
- Assert.assertTrue("delta with expected count should < 10",
- Math.abs(invokeResult.getExpected(loop) - count) < 10);
+ Assertions.assertTrue(
+ Math.abs(invokeResult.getExpected(loop) - count) < 10, "delta with expected count should < 10");
invokeCount += count;
}
- Assert.assertEquals("select failed!", invokeCount, loop);
+ Assertions.assertEquals(invokeCount, loop, "select failed!");
}
@Test
@@ -51,7 +52,7 @@ public class RoundRobinLoadBalanceTest extends LoadBalanceBaseTest {
Map<Invoker, AtomicLong> counter = getInvokeCounter(runs, RoundRobinLoadBalance.NAME);
for (Map.Entry<Invoker, AtomicLong> entry : counter.entrySet()) {
Long count = entry.getValue().get();
- Assert.assertTrue("abs diff should < 1", Math.abs(count - runs / (0f + invokers.size())) < 1f);
+ Assertions.assertTrue(Math.abs(count - runs / (0f + invokers.size())) < 1f, "abs diff should < 1");
}
}
@@ -62,7 +63,7 @@ public class RoundRobinLoadBalanceTest extends LoadBalanceBaseTest {
final int runs = 10000;
List<Thread> threads = new ArrayList<Thread>();
int threadNum = 10;
- for (int i = 0; i < threadNum; i ++) {
+ for (int i = 0; i < threadNum; i++) {
threads.add(new Thread() {
@Override
public void run() {
@@ -109,15 +110,15 @@ public class RoundRobinLoadBalanceTest extends LoadBalanceBaseTest {
assertStrictWRRResult(loop, resultMap);
// inner nodes cache judgement
- RoundRobinLoadBalance lb = (RoundRobinLoadBalance)getLoadBalance(RoundRobinLoadBalance.NAME);
- Assert.assertEquals(weightInvokers.size(), lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size());
+ RoundRobinLoadBalance lb = (RoundRobinLoadBalance) getLoadBalance(RoundRobinLoadBalance.NAME);
+ Assertions.assertEquals(weightInvokers.size(), lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size());
weightInvokers.remove(weightInvokerTmp);
resultMap = getWeightedInvokeResult(loop, RoundRobinLoadBalance.NAME);
assertStrictWRRResult(loop, resultMap);
- Assert.assertNotEquals(weightInvokers.size(), lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size());
+ Assertions.assertNotEquals(weightInvokers.size(), lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size());
} finally {
//prevent other UT's failure
weightInvokers.remove(weightInvokerTmp);
@@ -134,13 +135,13 @@ public class RoundRobinLoadBalanceTest extends LoadBalanceBaseTest {
recycleTimeField.setAccessible(true);
recycleTimeField.setInt(RoundRobinLoadBalance.class, 10);
} catch (NoSuchFieldException e) {
- Assert.assertTrue("getField failed", true);
+ Assertions.assertTrue(true, "getField failed");
} catch (SecurityException e) {
- Assert.assertTrue("getField failed", true);
+ Assertions.assertTrue(true, "getField failed");
} catch (IllegalArgumentException e) {
- Assert.assertTrue("getField failed", true);
+ Assertions.assertTrue(true, "getField failed");
} catch (IllegalAccessException e) {
- Assert.assertTrue("getField failed", true);
+ Assertions.assertTrue(true, "getField failed");
}
}
@@ -152,15 +153,15 @@ public class RoundRobinLoadBalanceTest extends LoadBalanceBaseTest {
assertStrictWRRResult(loop, resultMap);
// inner nodes cache judgement
- RoundRobinLoadBalance lb = (RoundRobinLoadBalance)getLoadBalance(RoundRobinLoadBalance.NAME);
- Assert.assertEquals(weightInvokers.size(), lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size());
+ RoundRobinLoadBalance lb = (RoundRobinLoadBalance) getLoadBalance(RoundRobinLoadBalance.NAME);
+ Assertions.assertEquals(weightInvokers.size(), lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size());
weightInvokers.remove(weightInvokerTmp);
resultMap = getWeightedInvokeResult(loop, RoundRobinLoadBalance.NAME);
assertStrictWRRResult(loop, resultMap);
- Assert.assertEquals(weightInvokers.size(), lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size());
+ Assertions.assertEquals(weightInvokers.size(), lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size());
} finally {
//prevent other UT's failure
weightInvokers.remove(weightInvokerTmp);
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 e4c30a4..788d1af 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
@@ -16,8 +16,8 @@
*/
package org.apache.dubbo.rpc.cluster.merger;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.lang.reflect.Array;
import java.util.ArrayList;
@@ -36,9 +36,9 @@ public class ResultMergerTest {
public void testMergerFactoryIllegalArgumentException() {
try {
MergerFactory.getMerger(null);
- Assert.fail("expected IllegalArgumentException for null argument");
+ Assertions.fail("expected IllegalArgumentException for null argument");
} catch (IllegalArgumentException exception) {
- Assert.assertEquals("returnType is null", exception.getMessage());
+ Assertions.assertEquals("returnType is null", exception.getMessage());
}
}
@@ -51,9 +51,9 @@ public class ResultMergerTest {
Integer[] integerArray = {3, 4, 5};
try {
Object result = ArrayMerger.INSTANCE.merge(stringArray, null, integerArray);
- Assert.fail("expected IllegalArgumentException for different arguments' types");
+ Assertions.fail("expected IllegalArgumentException for different arguments' types");
} catch (IllegalArgumentException exception) {
- Assert.assertEquals("Arguments' types are different", exception.getMessage());
+ Assertions.assertEquals("Arguments' types are different", exception.getMessage());
}
}
@@ -67,11 +67,11 @@ public class ResultMergerTest {
String[] stringArray3 = {};
Object result = ArrayMerger.INSTANCE.merge(stringArray1, stringArray2, stringArray3, null);
- Assert.assertTrue(result.getClass().isArray());
- Assert.assertEquals(6, Array.getLength(result));
- Assert.assertTrue(String.class.isInstance(Array.get(result, 0)));
+ Assertions.assertTrue(result.getClass().isArray());
+ Assertions.assertEquals(6, Array.getLength(result));
+ Assertions.assertTrue(String.class.isInstance(Array.get(result, 0)));
for (int i = 0; i < 6; i++) {
- Assert.assertEquals(String.valueOf(i + 1), Array.get(result, i));
+ Assertions.assertEquals(String.valueOf(i + 1), Array.get(result, i));
}
Integer[] intArray1 = {1, 2, 3};
@@ -79,21 +79,21 @@ public class ResultMergerTest {
Integer[] intArray3 = {7};
// trigger ArrayMerger
result = MergerFactory.getMerger(Integer[].class).merge(intArray1, intArray2, intArray3, null);
- Assert.assertTrue(result.getClass().isArray());
- Assert.assertEquals(7, Array.getLength(result));
- Assert.assertTrue(Integer.class == result.getClass().getComponentType());
+ Assertions.assertTrue(result.getClass().isArray());
+ Assertions.assertEquals(7, Array.getLength(result));
+ Assertions.assertTrue(Integer.class == result.getClass().getComponentType());
for (int i = 0; i < 7; i++) {
- Assert.assertEquals(i + 1, Array.get(result, i));
+ Assertions.assertEquals(i + 1, Array.get(result, i));
}
result = ArrayMerger.INSTANCE.merge(null);
- Assert.assertEquals(0, Array.getLength(result));
+ Assertions.assertEquals(0, Array.getLength(result));
result = ArrayMerger.INSTANCE.merge(null, null);
- Assert.assertEquals(0, Array.getLength(result));
+ Assertions.assertEquals(0, Array.getLength(result));
result = ArrayMerger.INSTANCE.merge(null, new Object[0]);
- Assert.assertEquals(0, Array.getLength(result));
+ Assertions.assertEquals(0, Array.getLength(result));
}
/**
@@ -104,17 +104,17 @@ public class ResultMergerTest {
boolean[] arrayOne = {true, false};
boolean[] arrayTwo = {false};
boolean[] result = MergerFactory.getMerger(boolean[].class).merge(arrayOne, arrayTwo, null);
- Assert.assertEquals(3, result.length);
+ Assertions.assertEquals(3, result.length);
boolean[] mergedResult = {true, false, false};
for (int i = 0; i < mergedResult.length; i++) {
- Assert.assertEquals(mergedResult[i], result[i]);
+ Assertions.assertEquals(mergedResult[i], result[i]);
}
result = MergerFactory.getMerger(boolean[].class).merge(null);
- Assert.assertEquals(0, result.length);
+ Assertions.assertEquals(0, result.length);
result = MergerFactory.getMerger(boolean[].class).merge(null, null);
- Assert.assertEquals(0, result.length);
+ Assertions.assertEquals(0, result.length);
}
/**
@@ -125,17 +125,17 @@ public class ResultMergerTest {
byte[] arrayOne = {1, 2};
byte[] arrayTwo = {1, 32};
byte[] result = MergerFactory.getMerger(byte[].class).merge(arrayOne, arrayTwo, null);
- Assert.assertEquals(4, result.length);
+ Assertions.assertEquals(4, result.length);
byte[] mergedResult = {1, 2, 1, 32};
for (int i = 0; i < mergedResult.length; i++) {
- Assert.assertEquals(mergedResult[i], result[i]);
+ Assertions.assertEquals(mergedResult[i], result[i]);
}
result = MergerFactory.getMerger(byte[].class).merge(null);
- Assert.assertEquals(0, result.length);
+ Assertions.assertEquals(0, result.length);
result = MergerFactory.getMerger(byte[].class).merge(null, null);
- Assert.assertEquals(0, result.length);
+ Assertions.assertEquals(0, result.length);
}
/**
@@ -146,17 +146,17 @@ public class ResultMergerTest {
char[] arrayOne = "hello".toCharArray();
char[] arrayTwo = "world".toCharArray();
char[] result = MergerFactory.getMerger(char[].class).merge(arrayOne, arrayTwo, null);
- Assert.assertEquals(10, result.length);
+ Assertions.assertEquals(10, result.length);
char[] mergedResult = "helloworld".toCharArray();
for (int i = 0; i < mergedResult.length; i++) {
- Assert.assertEquals(mergedResult[i], result[i]);
+ Assertions.assertEquals(mergedResult[i], result[i]);
}
result = MergerFactory.getMerger(char[].class).merge(null);
- Assert.assertEquals(0, result.length);
+ Assertions.assertEquals(0, result.length);
result = MergerFactory.getMerger(char[].class).merge(null, null);
- Assert.assertEquals(0, result.length);
+ Assertions.assertEquals(0, result.length);
}
/**
@@ -167,17 +167,17 @@ public class ResultMergerTest {
double[] arrayOne = {1.2d, 3.5d};
double[] arrayTwo = {2d, 34d};
double[] result = MergerFactory.getMerger(double[].class).merge(arrayOne, arrayTwo, null);
- Assert.assertEquals(4, result.length);
+ Assertions.assertEquals(4, result.length);
double[] mergedResult = {1.2d, 3.5d, 2d, 34d};
for (int i = 0; i < mergedResult.length; i++) {
- Assert.assertTrue(mergedResult[i] == result[i]);
+ Assertions.assertTrue(mergedResult[i] == result[i]);
}
result = MergerFactory.getMerger(double[].class).merge(null);
- Assert.assertEquals(0, result.length);
+ Assertions.assertEquals(0, result.length);
result = MergerFactory.getMerger(double[].class).merge(null, null);
- Assert.assertEquals(0, result.length);
+ Assertions.assertEquals(0, result.length);
}
/**
@@ -188,17 +188,17 @@ public class ResultMergerTest {
float[] arrayOne = {1.2f, 3.5f};
float[] arrayTwo = {2f, 34f};
float[] result = MergerFactory.getMerger(float[].class).merge(arrayOne, arrayTwo, null);
- Assert.assertEquals(4, result.length);
+ Assertions.assertEquals(4, result.length);
double[] mergedResult = {1.2f, 3.5f, 2f, 34f};
for (int i = 0; i < mergedResult.length; i++) {
- Assert.assertTrue(mergedResult[i] == result[i]);
+ Assertions.assertTrue(mergedResult[i] == result[i]);
}
result = MergerFactory.getMerger(float[].class).merge(null);
- Assert.assertEquals(0, result.length);
+ Assertions.assertEquals(0, result.length);
result = MergerFactory.getMerger(float[].class).merge(null, null);
- Assert.assertEquals(0, result.length);
+ Assertions.assertEquals(0, result.length);
}
/**
@@ -209,17 +209,17 @@ public class ResultMergerTest {
int[] arrayOne = {1, 2};
int[] arrayTwo = {2, 34};
int[] result = MergerFactory.getMerger(int[].class).merge(arrayOne, arrayTwo, null);
- Assert.assertEquals(4, result.length);
+ Assertions.assertEquals(4, result.length);
double[] mergedResult = {1, 2, 2, 34};
for (int i = 0; i < mergedResult.length; i++) {
- Assert.assertTrue(mergedResult[i] == result[i]);
+ Assertions.assertTrue(mergedResult[i] == result[i]);
}
result = MergerFactory.getMerger(int[].class).merge(null);
- Assert.assertEquals(0, result.length);
+ Assertions.assertEquals(0, result.length);
result = MergerFactory.getMerger(int[].class).merge(null, null);
- Assert.assertEquals(0, result.length);
+ Assertions.assertEquals(0, result.length);
}
/**
@@ -238,7 +238,7 @@ public class ResultMergerTest {
}};
List result = MergerFactory.getMerger(List.class).merge(list1, list2, null);
- Assert.assertEquals(5, result.size());
+ Assertions.assertEquals(5, result.size());
ArrayList<String> expected = new ArrayList<String>() {{
add(null);
add("1");
@@ -246,13 +246,13 @@ public class ResultMergerTest {
add("3");
add("4");
}};
- Assert.assertEquals(expected, result);
+ Assertions.assertEquals(expected, result);
result = MergerFactory.getMerger(List.class).merge(null);
- Assert.assertEquals(0, result.size());
+ Assertions.assertEquals(0, result.size());
result = MergerFactory.getMerger(List.class).merge(null, null);
- Assert.assertEquals(0, result.size());
+ Assertions.assertEquals(0, result.size());
}
/**
@@ -269,20 +269,20 @@ public class ResultMergerTest {
put("444", 2323);
}};
Map<Object, Object> result = MergerFactory.getMerger(Map.class).merge(mapOne, mapTwo, null);
- Assert.assertEquals(4, result.size());
+ Assertions.assertEquals(4, result.size());
Map<String, Integer> mergedResult = new HashMap<String, Integer>() {{
put("11", 222);
put("223", 11);
put("3333", 3232);
put("444", 2323);
}};
- Assert.assertEquals(mergedResult, result);
+ Assertions.assertEquals(mergedResult, result);
result = MergerFactory.getMerger(Map.class).merge(null);
- Assert.assertEquals(0, result.size());
+ Assertions.assertEquals(0, result.size());
result = MergerFactory.getMerger(Map.class).merge(null, null);
- Assert.assertEquals(0, result.size());
+ Assertions.assertEquals(0, result.size());
}
/**
@@ -293,17 +293,17 @@ public class ResultMergerTest {
long[] arrayOne = {1l, 2l};
long[] arrayTwo = {2l, 34l};
long[] result = MergerFactory.getMerger(long[].class).merge(arrayOne, arrayTwo, null);
- Assert.assertEquals(4, result.length);
+ Assertions.assertEquals(4, result.length);
double[] mergedResult = {1l, 2l, 2l, 34l};
for (int i = 0; i < mergedResult.length; i++) {
- Assert.assertTrue(mergedResult[i] == result[i]);
+ Assertions.assertTrue(mergedResult[i] == result[i]);
}
result = MergerFactory.getMerger(long[].class).merge(null);
- Assert.assertEquals(0, result.length);
+ Assertions.assertEquals(0, result.length);
result = MergerFactory.getMerger(long[].class).merge(null, null);
- Assert.assertEquals(0, result.length);
+ Assertions.assertEquals(0, result.length);
}
/**
@@ -324,8 +324,8 @@ public class ResultMergerTest {
Set result = MergerFactory.getMerger(Set.class).merge(set1, set2, null);
- Assert.assertEquals(4, result.size());
- Assert.assertEquals(new HashSet<String>() {
+ Assertions.assertEquals(4, result.size());
+ Assertions.assertEquals(new HashSet<String>() {
{
add(null);
add("1");
@@ -335,10 +335,10 @@ public class ResultMergerTest {
}, result);
result = MergerFactory.getMerger(Set.class).merge(null);
- Assert.assertEquals(0, result.size());
+ Assertions.assertEquals(0, result.size());
result = MergerFactory.getMerger(Set.class).merge(null, null);
- Assert.assertEquals(0, result.size());
+ Assertions.assertEquals(0, result.size());
}
/**
@@ -349,16 +349,16 @@ public class ResultMergerTest {
short[] arrayOne = {1, 2};
short[] arrayTwo = {2, 34};
short[] result = MergerFactory.getMerger(short[].class).merge(arrayOne, arrayTwo, null);
- Assert.assertEquals(4, result.length);
+ Assertions.assertEquals(4, result.length);
double[] mergedResult = {1, 2, 2, 34};
for (int i = 0; i < mergedResult.length; i++) {
- Assert.assertTrue(mergedResult[i] == result[i]);
+ Assertions.assertTrue(mergedResult[i] == result[i]);
}
result = MergerFactory.getMerger(short[].class).merge(null);
- Assert.assertEquals(0, result.length);
+ Assertions.assertEquals(0, result.length);
result = MergerFactory.getMerger(short[].class).merge(null, null);
- Assert.assertEquals(0, result.length);
+ Assertions.assertEquals(0, result.length);
}
}
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 76d9ef7..1235869 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
@@ -19,15 +19,15 @@ package org.apache.dubbo.rpc.cluster.router;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
-@Ignore("FIXME This is not a formal UT")
+@Disabled("FIXME This is not a formal UT")
public class ConfigConditionRouterTest {
private static CuratorFramework client;
- @Before
+ @BeforeEach
public void init() {
client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", 60 * 1000, 60 * 1000,
new ExponentialBackoffRetry(1000, 3));
diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/TagRouterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/TagRouterTest.java
index a2e45e1..98cdaf4 100644
--- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/TagRouterTest.java
+++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/TagRouterTest.java
@@ -19,15 +19,15 @@ package org.apache.dubbo.rpc.cluster.router;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
-@Ignore("FIXME This is not a formal UT")
+@Disabled("FIXME This is not a formal UT")
public class TagRouterTest {
private static CuratorFramework client;
- @Before
+ @BeforeEach
public void init() {
client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", 60 * 1000, 60 * 1000,
new ExponentialBackoffRetry(1000, 3));
diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java
index f7b85b8..a10949d 100644
--- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java
+++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java
@@ -26,10 +26,10 @@ import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.Router;
import org.apache.dubbo.rpc.cluster.router.MockInvoker;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+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;
@@ -38,11 +38,11 @@ public class ConditionRouterTest {
private URL SCRIPT_URL = URL.valueOf("condition://0.0.0.0/com.foo.BarService");
- @BeforeClass
+ @BeforeAll
public static void setUpBeforeClass() throws Exception {
}
- @Before
+ @BeforeEach
public void setUp() throws Exception {
}
@@ -56,31 +56,31 @@ public class ConditionRouterTest {
Router router = new ConditionRouterFactory().getRouter(getRouteUrl(" => host = 1.2.3.4"));
boolean matchWhen = ((ConditionRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
- Assert.assertEquals(true, matchWhen);
+ Assertions.assertEquals(true, matchWhen);
router = new ConditionRouterFactory().getRouter(getRouteUrl("host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4"));
matchWhen = ((ConditionRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
- Assert.assertEquals(true, matchWhen);
+ Assertions.assertEquals(true, matchWhen);
router = new ConditionRouterFactory().getRouter(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 = ((ConditionRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
- Assert.assertEquals(false, matchWhen);
+ Assertions.assertEquals(false, matchWhen);
router = new ConditionRouterFactory().getRouter(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 = ((ConditionRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
- Assert.assertEquals(true, matchWhen);
+ Assertions.assertEquals(true, matchWhen);
router = new ConditionRouterFactory().getRouter(getRouteUrl("host !=4.4.4.* & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4"));
matchWhen = ((ConditionRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
- Assert.assertEquals(true, matchWhen);
+ Assertions.assertEquals(true, matchWhen);
router = new ConditionRouterFactory().getRouter(getRouteUrl("host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.1 => host = 1.2.3.4"));
matchWhen = ((ConditionRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
- Assert.assertEquals(false, matchWhen);
+ Assertions.assertEquals(false, matchWhen);
router = new ConditionRouterFactory().getRouter(getRouteUrl("host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.2 => host = 1.2.3.4"));
matchWhen = ((ConditionRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
- Assert.assertEquals(true, matchWhen);
+ Assertions.assertEquals(true, matchWhen);
}
@Test
@@ -121,12 +121,12 @@ public class ConditionRouterTest {
List<Invoker<String>> filteredInvokers4 = router4.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation());
List<Invoker<String>> filteredInvokers5 = router5.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation());
List<Invoker<String>> filteredInvokers6 = router6.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation());
- Assert.assertEquals(1, filteredInvokers1.size());
- Assert.assertEquals(0, filteredInvokers2.size());
- Assert.assertEquals(0, filteredInvokers3.size());
- Assert.assertEquals(1, filteredInvokers4.size());
- Assert.assertEquals(2, filteredInvokers5.size());
- Assert.assertEquals(1, filteredInvokers6.size());
+ Assertions.assertEquals(1, filteredInvokers1.size());
+ Assertions.assertEquals(0, filteredInvokers2.size());
+ Assertions.assertEquals(0, filteredInvokers3.size());
+ Assertions.assertEquals(1, filteredInvokers4.size());
+ Assertions.assertEquals(2, filteredInvokers5.size());
+ Assertions.assertEquals(1, filteredInvokers6.size());
}
@Test
@@ -136,23 +136,23 @@ public class ConditionRouterTest {
Router router = new ConditionRouterFactory().getRouter(getRouteUrl("methods=getFoo => host = 1.2.3.4"));
boolean matchWhen = ((ConditionRouter) router).matchWhen(
URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=setFoo,getFoo,findFoo"), invocation);
- Assert.assertEquals(true, matchWhen);
+ Assertions.assertEquals(true, matchWhen);
// Exactly one method, match
matchWhen = ((ConditionRouter) router).matchWhen(
URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=getFoo"), invocation);
- Assert.assertEquals(true, matchWhen);
+ Assertions.assertEquals(true, matchWhen);
// Method routing and Other condition routing can work together
Router router2 = new ConditionRouterFactory()
.getRouter(getRouteUrl("methods=getFoo & host!=1.1.1.1 => host = 1.2.3.4"));
matchWhen = ((ConditionRouter) router2).matchWhen(
URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=getFoo"), invocation);
- Assert.assertEquals(false, matchWhen);
+ Assertions.assertEquals(false, matchWhen);
Router router3 = new ConditionRouterFactory()
.getRouter(getRouteUrl("methods=getFoo & host=1.1.1.1 => host = 1.2.3.4"));
matchWhen = ((ConditionRouter) router3).matchWhen(
URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=getFoo"), invocation);
- Assert.assertEquals(true, matchWhen);
+ Assertions.assertEquals(true, matchWhen);
// Test filter condition
List<Invoker<String>> invokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
@@ -169,14 +169,14 @@ public class ConditionRouterTest {
Constants.FORCE_KEY, String.valueOf(true)));
List<Invoker<String>> filteredInvokers1 = router4.route(invokers,
URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), invocation);
- Assert.assertEquals(1, filteredInvokers1.size());
+ Assertions.assertEquals(1, filteredInvokers1.size());
Router router5 = new ConditionRouterFactory().getRouter(getRouteUrl(
"host = " + NetUtils.getLocalHost() + " & methods = unvalidmethod => " + " host = 10.20.3.3")
.addParameter(Constants.FORCE_KEY, String.valueOf(true)));
List<Invoker<String>> filteredInvokers2 = router5.route(invokers,
URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), invocation);
- Assert.assertEquals(3, filteredInvokers2.size());
+ Assertions.assertEquals(3, filteredInvokers2.size());
// Request a non-exists method
}
@@ -188,7 +188,7 @@ public class ConditionRouterTest {
invokers.add(new MockInvoker<String>());
invokers.add(new MockInvoker<String>());
List<Invoker<String>> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation());
- Assert.assertEquals(0, filteredInvokers.size());
+ Assertions.assertEquals(0, filteredInvokers.size());
}
@Test
@@ -199,7 +199,7 @@ public class ConditionRouterTest {
invokers.add(new MockInvoker<String>());
invokers.add(new MockInvoker<String>());
List<Invoker<String>> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation());
- Assert.assertEquals(0, filteredInvokers.size());
+ Assertions.assertEquals(0, filteredInvokers.size());
}
@Test
@@ -210,7 +210,7 @@ public class ConditionRouterTest {
invokers.add(new MockInvoker<String>(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService")));
invokers.add(new MockInvoker<String>(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService")));
List<Invoker<String>> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation());
- Assert.assertEquals(invokers, filteredInvokers);
+ Assertions.assertEquals(invokers, filteredInvokers);
}
@Test
@@ -224,9 +224,9 @@ public class ConditionRouterTest {
invokers.add(invoker2);
invokers.add(invoker3);
List<Invoker<String>> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation());
- Assert.assertEquals(2, filteredInvokers.size());
- Assert.assertEquals(invoker2, filteredInvokers.get(0));
- Assert.assertEquals(invoker3, filteredInvokers.get(1));
+ Assertions.assertEquals(2, filteredInvokers.size());
+ Assertions.assertEquals(invoker2, filteredInvokers.get(0));
+ Assertions.assertEquals(invoker3, filteredInvokers.get(1));
}
@Test
@@ -240,9 +240,9 @@ public class ConditionRouterTest {
invokers.add(invoker2);
invokers.add(invoker3);
List<Invoker<String>> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation());
- Assert.assertEquals(2, filteredInvokers.size());
- Assert.assertEquals(invoker2, filteredInvokers.get(0));
- Assert.assertEquals(invoker3, filteredInvokers.get(1));
+ Assertions.assertEquals(2, filteredInvokers.size());
+ Assertions.assertEquals(invoker2, filteredInvokers.get(0));
+ Assertions.assertEquals(invoker3, filteredInvokers.get(1));
}
@Test
@@ -256,9 +256,9 @@ public class ConditionRouterTest {
invokers.add(invoker2);
invokers.add(invoker3);
List<Invoker<String>> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation());
- Assert.assertEquals(2, filteredInvokers.size());
- Assert.assertEquals(invoker2, filteredInvokers.get(0));
- Assert.assertEquals(invoker3, filteredInvokers.get(1));
+ Assertions.assertEquals(2, filteredInvokers.size());
+ Assertions.assertEquals(invoker2, filteredInvokers.get(0));
+ Assertions.assertEquals(invoker3, filteredInvokers.get(1));
}
@Test
@@ -272,9 +272,9 @@ public class ConditionRouterTest {
invokers.add(invoker2);
invokers.add(invoker3);
List<Invoker<String>> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation());
- Assert.assertEquals(2, filteredInvokers.size());
- Assert.assertEquals(invoker2, filteredInvokers.get(0));
- Assert.assertEquals(invoker3, filteredInvokers.get(1));
+ Assertions.assertEquals(2, filteredInvokers.size());
+ Assertions.assertEquals(invoker2, filteredInvokers.get(0));
+ Assertions.assertEquals(invoker3, filteredInvokers.get(1));
}
@Test
@@ -288,7 +288,7 @@ public class ConditionRouterTest {
invokers.add(invoker2);
invokers.add(invoker3);
List<Invoker<String>> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation());
- Assert.assertEquals(invokers, filteredInvokers);
+ Assertions.assertEquals(invokers, filteredInvokers);
}
@Test
@@ -302,7 +302,7 @@ public class ConditionRouterTest {
invokers.add(invoker2);
invokers.add(invoker3);
List<Invoker<String>> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation());
- Assert.assertEquals(0, filteredInvokers.size());
+ Assertions.assertEquals(0, filteredInvokers.size());
}
}
\ No newline at end of file
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 1ccb947..c4cb85d 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
@@ -31,10 +31,10 @@ import org.apache.dubbo.rpc.cluster.RouterFactory;
import org.apache.dubbo.rpc.cluster.directory.StaticDirectory;
import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+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;
@@ -55,11 +55,11 @@ public class FileRouterEngineTest {
Result result = new RpcResult();
private RouterFactory routerFactory = ExtensionLoader.getExtensionLoader(RouterFactory.class).getAdaptiveExtension();
- @BeforeClass
+ @BeforeAll
public static void setUpBeforeClass() throws Exception {
}
- @Before
+ @BeforeEach
public void setUp() throws Exception {
invokers.add(invoker1);
invokers.add(invoker2);
@@ -78,7 +78,7 @@ public class FileRouterEngineTest {
for (int i = 0; i < 100; i++) {
sinvoker.invoke(invocation);
Invoker<FileRouterEngineTest> invoker = sinvoker.getSelectedInvoker();
- Assert.assertEquals(invoker2, invoker);
+ Assertions.assertEquals(invoker2, invoker);
}
}
@@ -95,7 +95,7 @@ public class FileRouterEngineTest {
for (int i = 0; i < 100; i++) {
sinvoker.invoke(invocation);
Invoker<FileRouterEngineTest> invoker = sinvoker.getSelectedInvoker();
- Assert.assertEquals(invoker1, invoker);
+ Assertions.assertEquals(invoker1, invoker);
}
}
@@ -113,7 +113,7 @@ public class FileRouterEngineTest {
for (int i = 0; i < 100; i++) {
sinvoker.invoke(invocation);
Invoker<FileRouterEngineTest> invoker = sinvoker.getSelectedInvoker();
- Assert.assertEquals(invoker1, invoker);
+ Assertions.assertEquals(invoker1, invoker);
}
}
{
@@ -125,7 +125,7 @@ public class FileRouterEngineTest {
for (int i = 0; i < 100; i++) {
sinvoker.invoke(invocation);
Invoker<FileRouterEngineTest> invoker = sinvoker.getSelectedInvoker();
- Assert.assertEquals(invoker2, invoker);
+ Assertions.assertEquals(invoker2, invoker);
}
}
}
diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouterTest.java
index 3d94b16..45e4e7f 100644
--- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouterTest.java
+++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouterTest.java
@@ -17,29 +17,30 @@
package org.apache.dubbo.rpc.cluster.router.script;
-import java.util.ArrayList;
-import java.util.List;
-
import org.apache.dubbo.common.Constants;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.Router;
import org.apache.dubbo.rpc.cluster.router.MockInvoker;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+
+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;
public class ScriptRouterTest {
private URL SCRIPT_URL = URL.valueOf("script://javascript?type=javascript");
- @BeforeClass
+ @BeforeAll
public static void setUpBeforeClass() throws Exception {
}
- @Before
+ @BeforeEach
public void setUp() throws Exception {
}
@@ -55,7 +56,7 @@ public class ScriptRouterTest {
invokers.add(new MockInvoker<String>());
invokers.add(new MockInvoker<String>());
List<Invoker<String>> filteredInvokers = router.route(invokers, invokers.get(0).getUrl(), new RpcInvocation());
- Assert.assertEquals(invokers, filteredInvokers);
+ Assertions.assertEquals(invokers, filteredInvokers);
}
@Test
@@ -78,53 +79,53 @@ public class ScriptRouterTest {
invokers.add(invoker2);
invokers.add(invoker3);
List<Invoker<String>> filteredInvokers = router.route(invokers, invokers.get(0).getUrl(), new RpcInvocation());
- Assert.assertEquals(2, filteredInvokers.size());
- Assert.assertEquals(invoker2, filteredInvokers.get(0));
- Assert.assertEquals(invoker3, filteredInvokers.get(1));
+ Assertions.assertEquals(2, filteredInvokers.size());
+ Assertions.assertEquals(invoker2, filteredInvokers.get(0));
+ Assertions.assertEquals(invoker3, filteredInvokers.get(1));
}
@Test
public void testRouteHostFilter() {
- List<Invoker<String>> invokers = new ArrayList<Invoker<String>>();
- MockInvoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.1:20880/com.dubbo.HelloService"));
- MockInvoker<String> invoker2 = new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.2:20880/com.dubbo.HelloService"));
- MockInvoker<String> invoker3 = new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.3:20880/com.dubbo.HelloService"));
+ List<Invoker<String>> invokers = new ArrayList<Invoker<String>>();
+ MockInvoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.1:20880/com.dubbo.HelloService"));
+ MockInvoker<String> invoker2 = new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.2:20880/com.dubbo.HelloService"));
+ MockInvoker<String> invoker3 = new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.3:20880/com.dubbo.HelloService"));
invokers.add(invoker1);
invokers.add(invoker2);
invokers.add(invoker3);
-
- 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) ";
+
Router router = new ScriptRouterFactory().getRouter(getRouteUrl(script));
List<Invoker<String>> routeResult = router.route(invokers, invokers.get(0).getUrl(), new RpcInvocation());
- Assert.assertEquals(1, routeResult.size());
- Assert.assertEquals(invoker2,routeResult.get(0));
+ Assertions.assertEquals(1, routeResult.size());
+ Assertions.assertEquals(invoker2, routeResult.get(0));
}
-
+
@Test
public void testRoute_throwException() {
- List<Invoker<String>> invokers = new ArrayList<Invoker<String>>();
- MockInvoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.1:20880/com.dubbo.HelloService"));
- MockInvoker<String> invoker2 = new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.2:20880/com.dubbo.HelloService"));
- MockInvoker<String> invoker3 = new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.3:20880/com.dubbo.HelloService"));
+ List<Invoker<String>> invokers = new ArrayList<Invoker<String>>();
+ MockInvoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.1:20880/com.dubbo.HelloService"));
+ MockInvoker<String> invoker2 = new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.2:20880/com.dubbo.HelloService"));
+ MockInvoker<String> invoker3 = new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.3:20880/com.dubbo.HelloService"));
invokers.add(invoker1);
invokers.add(invoker2);
invokers.add(invoker3);
-
+
String script = "/";
Router router = new ScriptRouterFactory().getRouter(getRouteUrl(script));
List<Invoker<String>> routeResult = router.route(invokers, invokers.get(0).getUrl(), new RpcInvocation());
- Assert.assertEquals(3, routeResult.size());
+ Assertions.assertEquals(3, routeResult.size());
}
}
\ No newline at end of file
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 76bfc0d..130cdb5 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
@@ -35,11 +35,11 @@ import org.apache.dubbo.rpc.cluster.loadbalance.LeastActiveLoadBalance;
import org.apache.dubbo.rpc.cluster.loadbalance.RandomLoadBalance;
import org.apache.dubbo.rpc.cluster.loadbalance.RoundRobinLoadBalance;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.ArrayList;
@@ -72,17 +72,17 @@ public class AbstractClusterInvokerTest {
Invoker<IHelloService> mockedInvoker1;
- @BeforeClass
+ @BeforeAll
public static void setUpBeforeClass() throws Exception {
}
- @After
+ @AfterEach
public void teardown() throws Exception {
RpcContext.getContext().clearAttachments();
}
@SuppressWarnings({"unchecked"})
- @Before
+ @BeforeEach
public void setUp() throws Exception {
invocation.setMethodName("sayHello");
@@ -148,7 +148,7 @@ public class AbstractClusterInvokerTest {
// setup attachment
RpcContext.getContext().setAttachment(attachKey, attachValue);
Map<String, String> attachments = RpcContext.getContext().getAttachments();
- Assert.assertTrue("set attachment failed!", attachments != null && attachments.size() == 1);
+ Assertions.assertTrue( attachments != null && attachments.size() == 1,"set attachment failed!");
cluster = new AbstractClusterInvoker(dic) {
@Override
@@ -156,7 +156,7 @@ public class AbstractClusterInvokerTest {
throws RpcException {
// attachment will be bind to invocation
String value = invocation.getAttachment(attachKey);
- Assert.assertTrue("binding attachment failed!", value != null && value.equals(attachValue));
+ Assertions.assertTrue(value != null && value.equals(attachValue),"binding attachment failed!");
return null;
}
};
@@ -168,16 +168,16 @@ public class AbstractClusterInvokerTest {
@Test
public void testSelect_Invokersize0() throws Exception {
LoadBalance l = cluster.initLoadBalance(invokers, invocation);
- Assert.assertNotNull("cluster.initLoadBalance returns null!", l);
+ Assertions.assertNotNull(l,"cluster.initLoadBalance returns null!");
{
Invoker invoker = cluster.select(l, null, null, null);
- Assert.assertEquals(null, invoker);
+ Assertions.assertEquals(null, invoker);
}
{
invokers.clear();
selectedInvokers.clear();
Invoker invoker = cluster.select(l, null, invokers, null);
- Assert.assertEquals(null, invoker);
+ Assertions.assertEquals(null, invoker);
}
}
@@ -186,9 +186,9 @@ public class AbstractClusterInvokerTest {
invokers.clear();
invokers.add(invoker1);
LoadBalance l = cluster.initLoadBalance(invokers, invocation);
- Assert.assertNotNull("cluster.initLoadBalance returns null!", l);
+ Assertions.assertNotNull(l,"cluster.initLoadBalance returns null!");
Invoker invoker = cluster.select(l, null, invokers, null);
- Assert.assertEquals(invoker1, invoker);
+ Assertions.assertEquals(invoker1, invoker);
}
@Test
@@ -197,18 +197,18 @@ public class AbstractClusterInvokerTest {
invokers.add(invoker2);
invokers.add(invoker4);
LoadBalance l = cluster.initLoadBalance(invokers, invocation);
- Assert.assertNotNull("cluster.initLoadBalance returns null!", l);
+ Assertions.assertNotNull(l,"cluster.initLoadBalance returns null!");
{
selectedInvokers.clear();
selectedInvokers.add(invoker4);
Invoker invoker = cluster.select(l, invocation, invokers, selectedInvokers);
- Assert.assertEquals(invoker2, invoker);
+ Assertions.assertEquals(invoker2, invoker);
}
{
selectedInvokers.clear();
selectedInvokers.add(invoker2);
Invoker invoker = cluster.select(l, invocation, invokers, selectedInvokers);
- Assert.assertEquals(invoker4, invoker);
+ Assertions.assertEquals(invoker4, invoker);
}
}
@@ -228,8 +228,8 @@ public class AbstractClusterInvokerTest {
initlistsize5();
Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers);
- Assert.assertEquals(false, sinvoker.isAvailable());
- Assert.assertEquals(invoker1, sinvoker);
+ Assertions.assertEquals(false, sinvoker.isAvailable());
+ Assertions.assertEquals(invoker1, sinvoker);
}
@@ -246,7 +246,7 @@ public class AbstractClusterInvokerTest {
selectedInvokers.add(invoker4);
selectedInvokers.add(invoker5);
Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers);
- Assert.assertSame(invoker1, sinvoker);
+ Assertions.assertSame(invoker1, sinvoker);
}
{
//Boundary condition test .
@@ -256,7 +256,7 @@ public class AbstractClusterInvokerTest {
selectedInvokers.add(invoker4);
selectedInvokers.add(invoker5);
Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers);
- Assert.assertSame(invoker2, sinvoker);
+ Assertions.assertSame(invoker2, sinvoker);
}
{
//Boundary condition test .
@@ -266,7 +266,7 @@ public class AbstractClusterInvokerTest {
selectedInvokers.add(invoker4);
selectedInvokers.add(invoker5);
Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers);
- Assert.assertSame(invoker3, sinvoker);
+ Assertions.assertSame(invoker3, sinvoker);
}
{
//Boundary condition test .
@@ -276,7 +276,7 @@ public class AbstractClusterInvokerTest {
selectedInvokers.add(invoker3);
selectedInvokers.add(invoker4);
Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers);
- Assert.assertSame(invoker5, sinvoker);
+ Assertions.assertSame(invoker5, sinvoker);
}
{
//Boundary condition test .
@@ -287,7 +287,7 @@ public class AbstractClusterInvokerTest {
selectedInvokers.add(invoker4);
selectedInvokers.add(invoker5);
Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers);
- Assert.assertTrue(invokers.contains(sinvoker));
+ Assertions.assertTrue(invokers.contains(sinvoker));
}
}
@@ -305,7 +305,7 @@ public class AbstractClusterInvokerTest {
selectedInvokers.add(invoker3);
selectedInvokers.add(invoker5);
Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers);
- Assert.assertTrue(sinvoker == invoker4);
+ Assertions.assertTrue(sinvoker == invoker4);
}
{
//Boundary condition test .
@@ -315,14 +315,14 @@ public class AbstractClusterInvokerTest {
selectedInvokers.add(invoker4);
selectedInvokers.add(invoker5);
Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers);
- Assert.assertTrue(sinvoker == invoker2 || sinvoker == invoker4);
+ Assertions.assertTrue(sinvoker == invoker2 || sinvoker == invoker4);
}
{
//Boundary condition test .
for (int i = 0; i < 100; i++) {
selectedInvokers.clear();
Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers);
- Assert.assertTrue(sinvoker == invoker2 || sinvoker == invoker4);
+ Assertions.assertTrue(sinvoker == invoker2 || sinvoker == invoker4);
}
}
{
@@ -333,7 +333,7 @@ public class AbstractClusterInvokerTest {
selectedInvokers.add(invoker3);
selectedInvokers.add(invoker5);
Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers);
- Assert.assertTrue(sinvoker == invoker2 || sinvoker == invoker4);
+ Assertions.assertTrue(sinvoker == invoker2 || sinvoker == invoker4);
}
}
{
@@ -346,7 +346,7 @@ public class AbstractClusterInvokerTest {
selectedInvokers.add(invoker4);
selectedInvokers.add(invoker5);
Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers);
- Assert.assertTrue(sinvoker == invoker2 || sinvoker == invoker4);
+ Assertions.assertTrue(sinvoker == invoker2 || sinvoker == invoker4);
}
}
}
@@ -357,12 +357,12 @@ public class AbstractClusterInvokerTest {
int min = 1000, max = 5000;
Double d = (Math.random() * (max - min + 1) + min);
int runs = d.intValue();
- Assert.assertTrue(runs > min);
+ Assertions.assertTrue(runs > min);
LoadBalance lb = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(lbname);
initlistsize5();
for (int i = 0; i < runs; i++) {
Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers);
- Assert.assertEquals(true, sinvoker.isAvailable());
+ Assertions.assertEquals(true, sinvoker.isAvailable());
Mockito.clearInvocations(invoker1, invoker2, invoker3, invoker4, invoker5);
}
@@ -370,7 +370,7 @@ public class AbstractClusterInvokerTest {
selectedInvokers.clear();
selectedInvokers.add(invoker1);
Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers);
- Assert.assertEquals(true, sinvoker.isAvailable());
+ Assertions.assertEquals(true, sinvoker.isAvailable());
Mockito.clearInvocations(invoker1, invoker2, invoker3, invoker4, invoker5);
}
@@ -378,7 +378,7 @@ public class AbstractClusterInvokerTest {
selectedInvokers.clear();
selectedInvokers.add(invoker2);
Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers);
- Assert.assertEquals(true, sinvoker.isAvailable());
+ Assertions.assertEquals(true, sinvoker.isAvailable());
Mockito.clearInvocations(invoker1, invoker2, invoker3, invoker4, invoker5);
}
@@ -387,7 +387,7 @@ public class AbstractClusterInvokerTest {
selectedInvokers.add(invoker2);
selectedInvokers.add(invoker4);
Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers);
- Assert.assertEquals(true, sinvoker.isAvailable());
+ Assertions.assertEquals(true, sinvoker.isAvailable());
Mockito.clearInvocations(invoker1, invoker2, invoker3, invoker4, invoker5);
}
@@ -397,7 +397,7 @@ public class AbstractClusterInvokerTest {
selectedInvokers.add(invoker3);
selectedInvokers.add(invoker5);
Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers);
- Assert.assertEquals(true, sinvoker.isAvailable());
+ Assertions.assertEquals(true, sinvoker.isAvailable());
Mockito.clearInvocations(invoker1, invoker2, invoker3, invoker4, invoker5);
}
@@ -408,7 +408,7 @@ public class AbstractClusterInvokerTest {
selectedInvokers.add(invoker2);
selectedInvokers.add(invoker3);
Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers);
- Assert.assertEquals(true, sinvoker.isAvailable());
+ Assertions.assertEquals(true, sinvoker.isAvailable());
Mockito.clearInvocations(invoker1, invoker2, invoker3, invoker4, invoker5);
}
@@ -438,10 +438,10 @@ public class AbstractClusterInvokerTest {
Long count = entry.getValue().get();
// System.out.println(count);
if (entry.getKey().isAvailable())
- Assert.assertTrue("count should > avg", count > runs / invokers.size());
+ Assertions.assertTrue(count > runs / invokers.size(),"count should > avg");
}
- Assert.assertEquals(runs, counter.get(invoker2).get() + counter.get(invoker4).get());
+ Assertions.assertEquals(runs, counter.get(invoker2).get() + counter.get(invoker4).get());
;
}
@@ -491,23 +491,23 @@ public class AbstractClusterInvokerTest {
FailoverClusterInvoker<DemoService> failoverClusterInvoker = new FailoverClusterInvoker<DemoService>(directory);
try {
failoverClusterInvoker.invoke(new RpcInvocation("sayHello", new Class<?>[0], new Object[0]));
- Assert.fail();
+ Assertions.fail();
} catch (RpcException e) {
- Assert.assertEquals(RpcException.TIMEOUT_EXCEPTION, e.getCode());
+ Assertions.assertEquals(RpcException.TIMEOUT_EXCEPTION, e.getCode());
}
ForkingClusterInvoker<DemoService> forkingClusterInvoker = new ForkingClusterInvoker<DemoService>(directory);
try {
forkingClusterInvoker.invoke(new RpcInvocation("sayHello", new Class<?>[0], new Object[0]));
- Assert.fail();
+ Assertions.fail();
} catch (RpcException e) {
- Assert.assertEquals(RpcException.TIMEOUT_EXCEPTION, e.getCode());
+ Assertions.assertEquals(RpcException.TIMEOUT_EXCEPTION, e.getCode());
}
FailfastClusterInvoker<DemoService> failfastClusterInvoker = new FailfastClusterInvoker<DemoService>(directory);
try {
failfastClusterInvoker.invoke(new RpcInvocation("sayHello", new Class<?>[0], new Object[0]));
- Assert.fail();
+ Assertions.fail();
} catch (RpcException e) {
- Assert.assertEquals(RpcException.TIMEOUT_EXCEPTION, e.getCode());
+ Assertions.assertEquals(RpcException.TIMEOUT_EXCEPTION, e.getCode());
}
}
@@ -525,10 +525,10 @@ public class AbstractClusterInvokerTest {
mockedInvocation.setMethodName("sayHello");
mockedInvocation.setAttachment(Constants.INVOCATION_NEED_MOCK, "true");
List<Invoker<IHelloService>> mockedInvokers = dic.list(mockedInvocation);
- Assert.assertEquals(1, mockedInvokers.size());
+ Assertions.assertEquals(1, mockedInvokers.size());
List<Invoker<IHelloService>> invokers = dic.list(invocation);
- Assert.assertEquals(5, invokers.size());
+ Assertions.assertEquals(5, invokers.size());
}
public static interface IHelloService {
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 65cc1b2..c010a15 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
@@ -19,8 +19,9 @@ package org.apache.dubbo.rpc.cluster.support;
import org.apache.dubbo.common.Constants;
import org.apache.dubbo.common.URL;
-import org.junit.Assert;
-import org.junit.Test;
+import org.apache.dubbo.common.URLBuilder;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
public class ClusterUtilsTest {
@@ -31,7 +32,8 @@ public class ClusterUtilsTest {
.setUsername("username")
.setPassword("password");
- providerURL = providerURL.addParameter(Constants.GROUP_KEY, "dubbo")
+ providerURL = URLBuilder.from(providerURL)
+ .addParameter(Constants.GROUP_KEY, "dubbo")
.addParameter(Constants.VERSION_KEY, "1.2.3")
.addParameter(Constants.DUBBO_VERSION_KEY, "2.3.7")
.addParameter(Constants.THREADPOOL_KEY, "fixed")
@@ -45,36 +47,38 @@ public class ClusterUtilsTest {
.addParameter(Constants.DEFAULT_KEY_PREFIX + Constants.CORE_THREADS_KEY, Integer.MAX_VALUE)
.addParameter(Constants.DEFAULT_KEY_PREFIX + Constants.QUEUES_KEY, Integer.MAX_VALUE)
.addParameter(Constants.DEFAULT_KEY_PREFIX + Constants.ALIVE_KEY, Integer.MAX_VALUE)
- .addParameter(Constants.DEFAULT_KEY_PREFIX + Constants.THREAD_NAME_KEY, "test");
+ .addParameter(Constants.DEFAULT_KEY_PREFIX + Constants.THREAD_NAME_KEY, "test")
+ .build();
- URL consumerURL = URL.valueOf("dubbo://localhost:55555");
- consumerURL = consumerURL.addParameter(Constants.PID_KEY, "1234");
- consumerURL = consumerURL.addParameter(Constants.THREADPOOL_KEY, "foo");
+ URL consumerURL = new URLBuilder(Constants.DUBBO_PROTOCOL, "localhost", 55555)
+ .addParameter(Constants.PID_KEY, "1234")
+ .addParameter(Constants.THREADPOOL_KEY, "foo")
+ .build();
URL url = ClusterUtils.mergeUrl(providerURL, consumerURL.getParameters());
- Assert.assertFalse(url.hasParameter(Constants.THREADS_KEY));
- Assert.assertFalse(url.hasParameter(Constants.DEFAULT_KEY_PREFIX + Constants.THREADS_KEY));
+ Assertions.assertFalse(url.hasParameter(Constants.THREADS_KEY));
+ Assertions.assertFalse(url.hasParameter(Constants.DEFAULT_KEY_PREFIX + Constants.THREADS_KEY));
- Assert.assertFalse(url.hasParameter(Constants.DEFAULT_KEY_PREFIX + Constants.THREADPOOL_KEY));
+ Assertions.assertFalse(url.hasParameter(Constants.DEFAULT_KEY_PREFIX + Constants.THREADPOOL_KEY));
- Assert.assertFalse(url.hasParameter(Constants.CORE_THREADS_KEY));
- Assert.assertFalse(url.hasParameter(Constants.DEFAULT_KEY_PREFIX + Constants.CORE_THREADS_KEY));
+ Assertions.assertFalse(url.hasParameter(Constants.CORE_THREADS_KEY));
+ Assertions.assertFalse(url.hasParameter(Constants.DEFAULT_KEY_PREFIX + Constants.CORE_THREADS_KEY));
- Assert.assertFalse(url.hasParameter(Constants.QUEUES_KEY));
- Assert.assertFalse(url.hasParameter(Constants.DEFAULT_KEY_PREFIX + Constants.QUEUES_KEY));
+ Assertions.assertFalse(url.hasParameter(Constants.QUEUES_KEY));
+ Assertions.assertFalse(url.hasParameter(Constants.DEFAULT_KEY_PREFIX + Constants.QUEUES_KEY));
- Assert.assertFalse(url.hasParameter(Constants.ALIVE_KEY));
- Assert.assertFalse(url.hasParameter(Constants.DEFAULT_KEY_PREFIX + Constants.ALIVE_KEY));
+ Assertions.assertFalse(url.hasParameter(Constants.ALIVE_KEY));
+ Assertions.assertFalse(url.hasParameter(Constants.DEFAULT_KEY_PREFIX + Constants.ALIVE_KEY));
- Assert.assertFalse(url.hasParameter(Constants.THREAD_NAME_KEY));
- Assert.assertFalse(url.hasParameter(Constants.DEFAULT_KEY_PREFIX + Constants.THREAD_NAME_KEY));
+ Assertions.assertFalse(url.hasParameter(Constants.THREAD_NAME_KEY));
+ Assertions.assertFalse(url.hasParameter(Constants.DEFAULT_KEY_PREFIX + Constants.THREAD_NAME_KEY));
- Assert.assertEquals(url.getPath(), "path");
- Assert.assertEquals(url.getUsername(), "username");
- Assert.assertEquals(url.getPassword(), "password");
- Assert.assertEquals(url.getParameter(Constants.PID_KEY), "1234");
- Assert.assertEquals(url.getParameter(Constants.THREADPOOL_KEY), "foo");
+ Assertions.assertEquals(url.getPath(), "path");
+ Assertions.assertEquals(url.getUsername(), "username");
+ Assertions.assertEquals(url.getPassword(), "password");
+ Assertions.assertEquals(url.getParameter(Constants.PID_KEY), "1234");
+ Assertions.assertEquals(url.getParameter(Constants.THREADPOOL_KEY), "foo");
}
}
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 fa9ac1a..413d9b9 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,14 +26,14 @@ import org.apache.dubbo.rpc.RpcResult;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.filter.DemoService;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+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.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -54,7 +54,7 @@ public class FailSafeClusterInvokerTest {
* @throws java.lang.Exception
*/
- @Before
+ @BeforeEach
public void setUp() throws Exception {
dic = mock(Directory.class);
@@ -85,7 +85,7 @@ public class FailSafeClusterInvokerTest {
resetInvokerToException();
FailsafeClusterInvoker<DemoService> invoker = new FailsafeClusterInvoker<DemoService>(dic);
invoker.invoke(invocation);
- Assert.assertNull(RpcContext.getContext().getInvoker());
+ Assertions.assertNull(RpcContext.getContext().getInvoker());
}
@Test()
@@ -95,7 +95,7 @@ public class FailSafeClusterInvokerTest {
FailsafeClusterInvoker<DemoService> invoker = new FailsafeClusterInvoker<DemoService>(dic);
Result ret = invoker.invoke(invocation);
- Assert.assertSame(result, ret);
+ Assertions.assertSame(result, ret);
}
@Test()
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 581d52e..ad96a66 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,3 +1,4 @@
+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -27,27 +28,30 @@ import org.apache.dubbo.rpc.RpcResult;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.log4j.Level;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.FixMethodOrder;
-import org.junit.Test;
+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.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
- /**
- * FailbackClusterInvokerTest
- *
- * add annotation @FixMethodOrder, the testARetryFailed Method must to first execution
+/**
+ * FailbackClusterInvokerTest
+ * <p>
+ * add annotation @TestMethodOrder, the testARetryFailed Method must to first execution
*/
-@SuppressWarnings("unchecked")
-@FixMethodOrder(org.junit.runners.MethodSorters.NAME_ASCENDING)
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class FailbackClusterInvokerTest {
List<Invoker<FailbackClusterInvokerTest>> invokers = new ArrayList<Invoker<FailbackClusterInvokerTest>>();
@@ -61,7 +65,7 @@ public class FailbackClusterInvokerTest {
* @throws java.lang.Exception
*/
- @Before
+ @BeforeEach
public void setUp() throws Exception {
dic = mock(Directory.class);
@@ -74,6 +78,15 @@ public class FailbackClusterInvokerTest {
invokers.add(invoker);
}
+ @AfterEach
+ public void tearDown() {
+
+ dic = null;
+ invocation = new RpcInvocation();
+ invokers.clear();
+ }
+
+
private void resetInvokerToException() {
given(invoker.invoke(invocation)).willThrow(new RuntimeException());
given(invoker.getUrl()).willReturn(url);
@@ -87,16 +100,18 @@ public class FailbackClusterInvokerTest {
}
@Test
+ @Order(1)
public void testInvokeException() {
resetInvokerToException();
FailbackClusterInvoker<FailbackClusterInvokerTest> invoker = new FailbackClusterInvoker<FailbackClusterInvokerTest>(
dic);
invoker.invoke(invocation);
- Assert.assertNull(RpcContext.getContext().getInvoker());
+ Assertions.assertNull(RpcContext.getContext().getInvoker());
DubboAppender.clear();
}
- @Test()
+ @Test
+ @Order(2)
public void testInvokeNoException() {
resetInvokerToNoException();
@@ -104,10 +119,11 @@ public class FailbackClusterInvokerTest {
FailbackClusterInvoker<FailbackClusterInvokerTest> invoker = new FailbackClusterInvoker<FailbackClusterInvokerTest>(
dic);
Result ret = invoker.invoke(invocation);
- Assert.assertSame(result, ret);
+ Assertions.assertSame(result, ret);
}
- @Test()
+ @Test
+ @Order(3)
public void testNoInvoke() {
dic = mock(Directory.class);
@@ -130,7 +146,9 @@ public class FailbackClusterInvokerTest {
LogUtil.stop();
}
- @Test()
+ @Disabled
+ @Test
+ @Order(4)
public void testARetryFailed() throws Exception {
//Test retries and
@@ -143,15 +161,15 @@ public class FailbackClusterInvokerTest {
invoker.invoke(invocation);
invoker.invoke(invocation);
invoker.invoke(invocation);
- Assert.assertNull(RpcContext.getContext().getInvoker());
+ Assertions.assertNull(RpcContext.getContext().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
CountDownLatch countDown = new CountDownLatch(1);
countDown.await(15000L, TimeUnit.MILLISECONDS);
LogUtil.stop();
- Assert.assertEquals("must have four error message ", 4, LogUtil.findMessage(Level.ERROR, "Failed retry to invoke method"));
- Assert.assertEquals("must have two error message ", 2, LogUtil.findMessage(Level.ERROR, "Failed retry times exceed threshold"));
- Assert.assertEquals("must have one error message ", 1, LogUtil.findMessage(Level.ERROR, "Failback background works error"));
+ 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
}
}
\ No newline at end of file
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 41dc79c..d8dd653 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,22 +25,20 @@ import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.RpcResult;
import org.apache.dubbo.rpc.cluster.Directory;
-import org.junit.Assert;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+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.Assert.assertFalse;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* FailfastClusterInvokerTest
- *
*/
@SuppressWarnings("unchecked")
public class FailfastClusterInvokerTest {
@@ -55,7 +53,7 @@ public class FailfastClusterInvokerTest {
* @throws java.lang.Exception
*/
- @Before
+ @BeforeEach
public void setUp() throws Exception {
dic = mock(Directory.class);
@@ -81,12 +79,14 @@ public class FailfastClusterInvokerTest {
given(invoker1.getInterface()).willReturn(FailfastClusterInvokerTest.class);
}
- @Test(expected = RpcException.class)
+ @Test
public void testInvokeExceptoin() {
- resetInvoker1ToException();
- FailfastClusterInvoker<FailfastClusterInvokerTest> invoker = new FailfastClusterInvoker<FailfastClusterInvokerTest>(dic);
- invoker.invoke(invocation);
- Assert.assertSame(invoker1, RpcContext.getContext().getInvoker());
+ Assertions.assertThrows(RpcException.class, () -> {
+ resetInvoker1ToException();
+ FailfastClusterInvoker<FailfastClusterInvokerTest> invoker = new FailfastClusterInvoker<FailfastClusterInvokerTest>(dic);
+ invoker.invoke(invocation);
+ Assertions.assertSame(invoker1, RpcContext.getContext().getInvoker());
+ });
}
@Test()
@@ -96,7 +96,7 @@ public class FailfastClusterInvokerTest {
FailfastClusterInvoker<FailfastClusterInvokerTest> invoker = new FailfastClusterInvoker<FailfastClusterInvokerTest>(dic);
Result ret = invoker.invoke(invocation);
- Assert.assertSame(result, ret);
+ Assertions.assertSame(result, ret);
}
@Test()
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 136ba2a..ff29a61 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
@@ -27,18 +27,18 @@ import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.directory.StaticDirectory;
import org.apache.dubbo.rpc.protocol.AbstractInvoker;
-import org.junit.Before;
-import org.junit.Test;
+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 static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -61,7 +61,7 @@ public class FailoverClusterInvokerTest {
* @throws java.lang.Exception
*/
- @Before
+ @BeforeEach
public void setUp() throws Exception {
dic = mock(Directory.class);
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 5b44c83..b3d343a 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,15 +25,15 @@ import org.apache.dubbo.rpc.RpcResult;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.cluster.Directory;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+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 static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -52,7 +52,7 @@ public class ForkingClusterInvokerTest {
private Directory<ForkingClusterInvokerTest> dic;
private Result result = new RpcResult();
- @Before
+ @BeforeEach
public void setUp() throws Exception {
dic = mock(Directory.class);
@@ -111,9 +111,9 @@ public class ForkingClusterInvokerTest {
try {
invoker.invoke(invocation);
- Assert.fail();
+ Assertions.fail();
} catch (RpcException expected) {
- Assert.assertTrue(expected.getMessage().contains("Failed to forking invoke provider"));
+ Assertions.assertTrue(expected.getMessage().contains("Failed to forking invoke provider"));
assertFalse(expected.getCause() instanceof RpcException);
}
}
@@ -130,16 +130,16 @@ public class ForkingClusterInvokerTest {
RpcContext.getContext().setAttachment(attachKey, attachValue);
Map<String, String> attachments = RpcContext.getContext().getAttachments();
- Assert.assertTrue("set attachment failed!", attachments != null && attachments.size() == 1);
+ Assertions.assertTrue(attachments != null && attachments.size() == 1, "set attachment failed!");
try {
invoker.invoke(invocation);
- Assert.fail();
+ Assertions.fail();
} catch (RpcException expected) {
- Assert.assertTrue("Succeeded to forking invoke provider !", expected.getMessage().contains("Failed 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<String, String> afterInvoke = RpcContext.getContext().getAttachments();
- Assert.assertTrue("clear attachment failed!", afterInvoke != null && afterInvoke.size() == 0);
+ Assertions.assertTrue(afterInvoke != null && afterInvoke.size() == 0, "clear attachment failed!");
}
@Test()
@@ -150,7 +150,7 @@ public class ForkingClusterInvokerTest {
ForkingClusterInvoker<ForkingClusterInvokerTest> invoker = new ForkingClusterInvoker<ForkingClusterInvokerTest>(
dic);
Result ret = invoker.invoke(invocation);
- Assert.assertSame(result, ret);
+ Assertions.assertSame(result, ret);
}
}
\ No newline at end of file
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 ba0b617..8a4089c 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
@@ -24,9 +24,9 @@ import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcResult;
import org.apache.dubbo.rpc.cluster.Directory;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
@@ -38,7 +38,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -86,7 +86,7 @@ public class MergeableClusterInvokerTest {
}
}
- @Before
+ @BeforeEach
public void setUp() throws Exception {
directory = mock(Directory.class);
@@ -155,7 +155,7 @@ public class MergeableClusterInvokerTest {
// invoke
Result result = mergeableClusterInvoker.invoke(invocation);
- Assert.assertTrue(result.getValue() instanceof Menu);
+ Assertions.assertTrue(result.getValue() instanceof Menu);
Menu menu = (Menu) result.getValue();
Map<String, List<String>> expected = new HashMap<String, List<String>>();
merge(expected, firstMenuMap);
@@ -219,7 +219,7 @@ public class MergeableClusterInvokerTest {
mergeableClusterInvoker = new MergeableClusterInvoker<MenuService>(directory);
Result result = mergeableClusterInvoker.invoke(invocation);
- Assert.assertNull(result.getValue());
+ Assertions.assertNull(result.getValue());
}
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 f305f91..618e970 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
@@ -31,9 +31,9 @@ import org.apache.dubbo.rpc.cluster.directory.StaticDirectory;
import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker;
import org.apache.dubbo.rpc.support.MockProtocol;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+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;
@@ -43,7 +43,7 @@ public class MockClusterInvokerTest {
List<Invoker<IHelloService>> invokers = new ArrayList<Invoker<IHelloService>>();
- @Before
+ @BeforeEach
public void beforeMethod() {
invokers.clear();
}
@@ -67,13 +67,13 @@ public class MockClusterInvokerTest {
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
- Assert.assertEquals("something", ret.getValue());
+ Assertions.assertEquals("something", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("sayHello");
ret = cluster.invoke(invocation);
- Assert.assertEquals(null, ret.getValue());
+ Assertions.assertEquals(null, ret.getValue());
}
/**
@@ -95,19 +95,19 @@ public class MockClusterInvokerTest {
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
- Assert.assertEquals("aa", ret.getValue());
+ Assertions.assertEquals("aa", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething2");
ret = cluster.invoke(invocation);
- Assert.assertEquals(null, ret.getValue());
+ Assertions.assertEquals(null, ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("sayHello");
ret = cluster.invoke(invocation);
- Assert.assertEquals(null, ret.getValue());
+ Assertions.assertEquals(null, ret.getValue());
}
@@ -131,19 +131,19 @@ public class MockClusterInvokerTest {
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
- Assert.assertEquals("aa", ret.getValue());
+ Assertions.assertEquals("aa", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething2");
ret = cluster.invoke(invocation);
- Assert.assertEquals(null, ret.getValue());
+ Assertions.assertEquals(null, ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("sayHello");
ret = cluster.invoke(invocation);
- Assert.assertEquals(null, ret.getValue());
+ Assertions.assertEquals(null, ret.getValue());
}
@Test
@@ -162,7 +162,7 @@ public class MockClusterInvokerTest {
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("sayHello");
Result ret = cluster.invoke(invocation);
- Assert.assertEquals(null, ret.getValue());
+ Assertions.assertEquals(null, ret.getValue());
}
/**
@@ -178,25 +178,25 @@ public class MockClusterInvokerTest {
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
- Assert.assertEquals("something", ret.getValue());
+ Assertions.assertEquals("something", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething2");
ret = cluster.invoke(invocation);
- Assert.assertEquals("y", ret.getValue());
+ Assertions.assertEquals("y", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething3");
ret = cluster.invoke(invocation);
- Assert.assertEquals("something3", ret.getValue());
+ Assertions.assertEquals("something3", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("sayHello");
ret = cluster.invoke(invocation);
- Assert.assertEquals(null, ret.getValue());
+ Assertions.assertEquals(null, ret.getValue());
}
/**
@@ -213,20 +213,20 @@ public class MockClusterInvokerTest {
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
- Assert.assertEquals("x", ret.getValue());
+ Assertions.assertEquals("x", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething2");
ret = cluster.invoke(invocation);
- Assert.assertEquals("y", ret.getValue());
+ Assertions.assertEquals("y", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething3");
try {
ret = cluster.invoke(invocation);
- Assert.fail();
+ Assertions.fail();
} catch (RpcException e) {
}
@@ -247,25 +247,25 @@ public class MockClusterInvokerTest {
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
- Assert.assertEquals("x", ret.getValue());
+ Assertions.assertEquals("x", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething2");
ret = cluster.invoke(invocation);
- Assert.assertEquals("y", ret.getValue());
+ Assertions.assertEquals("y", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething3");
ret = cluster.invoke(invocation);
- Assert.assertEquals(null, ret.getValue());
+ Assertions.assertEquals(null, ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("sayHello");
ret = cluster.invoke(invocation);
- Assert.assertEquals(null, ret.getValue());
+ Assertions.assertEquals(null, ret.getValue());
}
/**
@@ -283,25 +283,25 @@ public class MockClusterInvokerTest {
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
- Assert.assertEquals("x", ret.getValue());
+ Assertions.assertEquals("x", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething2");
ret = cluster.invoke(invocation);
- Assert.assertEquals("y", ret.getValue());
+ Assertions.assertEquals("y", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething3");
ret = cluster.invoke(invocation);
- Assert.assertEquals("z", ret.getValue());
+ Assertions.assertEquals("z", ret.getValue());
//If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("sayHello");
ret = cluster.invoke(invocation);
- Assert.assertEquals("z", ret.getValue());
+ Assertions.assertEquals("z", ret.getValue());
}
/**
@@ -319,25 +319,25 @@ public class MockClusterInvokerTest {
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
- Assert.assertEquals("x", ret.getValue());
+ Assertions.assertEquals("x", ret.getValue());
//If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething2");
ret = cluster.invoke(invocation);
- Assert.assertEquals("y", ret.getValue());
+ Assertions.assertEquals("y", ret.getValue());
//If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething3");
ret = cluster.invoke(invocation);
- Assert.assertEquals("z", ret.getValue());
+ Assertions.assertEquals("z", ret.getValue());
//If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("sayHello");
ret = cluster.invoke(invocation);
- Assert.assertEquals("z", ret.getValue());
+ Assertions.assertEquals("z", ret.getValue());
}
/**
@@ -353,19 +353,19 @@ public class MockClusterInvokerTest {
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
- Assert.assertEquals("x", ret.getValue());
+ Assertions.assertEquals("x", ret.getValue());
//If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething2");
ret = cluster.invoke(invocation);
- Assert.assertEquals("x", ret.getValue());
+ Assertions.assertEquals("x", ret.getValue());
//If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("sayHello");
ret = cluster.invoke(invocation);
- Assert.assertEquals("x", ret.getValue());
+ Assertions.assertEquals("x", ret.getValue());
}
/**
@@ -381,14 +381,14 @@ public class MockClusterInvokerTest {
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
- Assert.assertEquals("x", ret.getValue());
+ Assertions.assertEquals("x", ret.getValue());
//If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething3");
try {
ret = cluster.invoke(invocation);
- Assert.fail("fail invoke");
+ Assertions.fail("fail invoke");
} catch (RpcException e) {
}
@@ -407,7 +407,7 @@ public class MockClusterInvokerTest {
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
- Assert.assertEquals("somethingmock", ret.getValue());
+ Assertions.assertEquals("somethingmock", ret.getValue());
}
/**
@@ -423,7 +423,7 @@ public class MockClusterInvokerTest {
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
- Assert.assertEquals("somethingmock", ret.getValue());
+ Assertions.assertEquals("somethingmock", ret.getValue());
}
/**
@@ -438,7 +438,7 @@ public class MockClusterInvokerTest {
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
- Assert.assertEquals("somethingmock", ret.getValue());
+ Assertions.assertEquals("somethingmock", ret.getValue());
}
@Test
@@ -451,8 +451,8 @@ public class MockClusterInvokerTest {
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
- Assert.assertTrue("result type must be String but was : " + ret.getValue().getClass(), ret.getValue() instanceof String);
- Assert.assertEquals("1688", (String) ret.getValue());
+ Assertions.assertTrue(ret.getValue() instanceof String, "result type must be String but was : " + ret.getValue().getClass());
+ Assertions.assertEquals("1688", (String) ret.getValue());
}
@Test
@@ -465,8 +465,8 @@ public class MockClusterInvokerTest {
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getInt1");
Result ret = cluster.invoke(invocation);
- Assert.assertTrue("result type must be integer but was : " + ret.getValue().getClass(), ret.getValue() instanceof Integer);
- Assert.assertEquals(new Integer(1688), (Integer) ret.getValue());
+ 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
@@ -479,8 +479,8 @@ public class MockClusterInvokerTest {
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getBoolean1");
Result ret = cluster.invoke(invocation);
- Assert.assertTrue("result type must be Boolean but was : " + ret.getValue().getClass(), ret.getValue() instanceof Boolean);
- Assert.assertEquals(true, Boolean.parseBoolean(ret.getValue().toString()));
+ Assertions.assertTrue(ret.getValue() instanceof Boolean, "result type must be Boolean but was : " + ret.getValue().getClass());
+ Assertions.assertEquals(true, Boolean.parseBoolean(ret.getValue().toString()));
}
@Test
@@ -493,7 +493,7 @@ public class MockClusterInvokerTest {
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getBoolean2");
Result ret = cluster.invoke(invocation);
- Assert.assertEquals(true, Boolean.parseBoolean(ret.getValue().toString()));
+ Assertions.assertEquals(true, Boolean.parseBoolean(ret.getValue().toString()));
}
@SuppressWarnings("unchecked")
@@ -507,7 +507,7 @@ public class MockClusterInvokerTest {
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getListString");
Result ret = cluster.invoke(invocation);
- Assert.assertEquals(0, ((List<String>) ret.getValue()).size());
+ Assertions.assertEquals(0, ((List<String>) ret.getValue()).size());
}
@SuppressWarnings("unchecked")
@@ -522,8 +522,8 @@ public class MockClusterInvokerTest {
invocation.setMethodName("getListString");
Result ret = cluster.invoke(invocation);
List<String> rl = (List<String>) ret.getValue();
- Assert.assertEquals(2, rl.size());
- Assert.assertEquals("hi", rl.get(0));
+ Assertions.assertEquals(2, rl.size());
+ Assertions.assertEquals("hi", rl.get(0));
}
@SuppressWarnings("unchecked")
@@ -537,7 +537,7 @@ public class MockClusterInvokerTest {
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getUsers");
Result ret = cluster.invoke(invocation);
- Assert.assertEquals(0, ((List<User>) ret.getValue()).size());
+ Assertions.assertEquals(0, ((List<User>) ret.getValue()).size());
}
@SuppressWarnings("unchecked")
@@ -553,8 +553,8 @@ public class MockClusterInvokerTest {
Result ret = cluster.invoke(invocation);
List<User> rl = (List<User>) ret.getValue();
System.out.println(rl);
- Assert.assertEquals(2, rl.size());
- Assert.assertEquals("hi1", ((User) rl.get(0)).getName());
+ Assertions.assertEquals(2, rl.size());
+ Assertions.assertEquals("hi1", ((User) rl.get(0)).getName());
}
@Test
@@ -583,9 +583,9 @@ public class MockClusterInvokerTest {
invocation.setMethodName("getBoolean2");
try {
cluster.invoke(invocation);
- Assert.fail();
+ Assertions.fail();
} catch (RpcException e) {
- Assert.assertFalse("not custem exception", e.isBiz());
+ Assertions.assertFalse(e.isBiz(), "not custem exception");
}
}
@@ -600,7 +600,7 @@ public class MockClusterInvokerTest {
invocation.setMethodName("getBoolean2");
try {
cluster.invoke(invocation).recreate();
- Assert.fail();
+ Assertions.fail();
} catch (MyMockException e) {
}
@@ -617,9 +617,9 @@ public class MockClusterInvokerTest {
invocation.setMethodName("getBoolean2");
try {
cluster.invoke(invocation);
- Assert.fail();
+ Assertions.fail();
} catch (Exception e) {
- Assert.assertTrue(e.getCause() instanceof IllegalStateException);
+ Assertions.assertTrue(e.getCause() instanceof IllegalStateException);
}
}
@@ -634,9 +634,9 @@ public class MockClusterInvokerTest {
invocation.setMethodName("getBoolean2");
try {
cluster.invoke(invocation);
- Assert.fail();
+ Assertions.fail();
} catch (RpcException e) {
- Assert.assertTrue(e.isTimeout());
+ Assertions.assertTrue(e.isTimeout());
}
}
diff --git a/dubbo-cluster/src/test/resources/log4j.xml b/dubbo-cluster/src/test/resources/log4j.xml
index df9d68a..eb0c9f1 100644
--- a/dubbo-cluster/src/test/resources/log4j.xml
+++ b/dubbo-cluster/src/test/resources/log4j.xml
@@ -18,6 +18,7 @@
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
<appender name="DUBBO" class="org.apache.dubbo.common.utils.DubboAppender">
+ <param name="File" value="../dubbo.log"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="[%d{dd/MM/yy HH:mm:ss:SSS z}] %t %5p %c{2}: %m%n"/>
</layout>
diff --git a/dubbo-common/pom.xml b/dubbo-common/pom.xml
index 22a1322..bd3347f 100644
--- a/dubbo-common/pom.xml
+++ b/dubbo-common/pom.xml
@@ -20,7 +20,7 @@
<parent>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-parent</artifactId>
- <version>2.7.0-SNAPSHOT</version>
+ <version>2.7.1-SNAPSHOT</version>
</parent>
<artifactId>dubbo-common</artifactId>
<packaging>jar</packaging>
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java
index 9b4e259..c6724b8 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java
@@ -97,7 +97,10 @@ public class Constants {
public static final String DEFAULT_PROXY = "javassist";
- public static final int DEFAULT_PAYLOAD = 8 * 1024 * 1024; // 8M
+ /**
+ * 8M
+ */
+ public static final int DEFAULT_PAYLOAD = 8 * 1024 * 1024;
public static final String DEFAULT_CLUSTER = "failover";
@@ -143,7 +146,13 @@ public class Constants {
public static final int DEFAULT_ALIVE = 60 * 1000;
- public static final int DEFAULT_CONNECTIONS = 0;
+ /**
+ * By default, a consumer JVM instance and a provider JVM instance share a long TCP connection (except when connections are set),
+ * which can set the number of long TCP connections shared to avoid the bottleneck of sharing a single long TCP connection.
+ */
+ public static final String DEFAULT_SHARE_CONNECTIONS = "1";
+
+ public static final String SHARE_CONNECTIONS_KEY = "shareconnections";
public static final int DEFAULT_ACCEPTS = 0;
@@ -155,15 +164,20 @@ public class Constants {
public static final int DEFAULT_CONNECT_TIMEOUT = 3000;
-// public static final int DEFAULT_REGISTRY_CONNECT_TIMEOUT = 5000;
-
+ /**
+ * public static final int DEFAULT_REGISTRY_CONNECT_TIMEOUT = 5000;
+ */
public static final int DEFAULT_RETRIES = 2;
public static final int DEFAULT_FAILBACK_TASKS = 100;
public static final int DEFAULT_FAILBACK_TIMES = 3;
- // default buffer size is 8k.
+ public static final int MAX_PROXY_COUNT = 65535;
+
+ /**
+ * default buffer size is 8k.
+ */
public static final int DEFAULT_BUFFER_SIZE = 8 * 1024;
public static final Integer DEFAULT_METADATA_REPORT_RETRY_TIMES = 100;
@@ -186,7 +200,9 @@ public class Constants {
public static final String LOADBALANCE_KEY = "loadbalance";
- // key for router type, for e.g., "script"/"file", corresponding to ScriptRouterFactory.NAME, FileRouterFactory.NAME
+ /**
+ * key for router type, for e.g., "script"/"file", corresponding to ScriptRouterFactory.NAME, FileRouterFactory.NAME
+ */
public static final String ROUTER_KEY = "router";
public static final String CLUSTER_KEY = "cluster";
@@ -231,7 +247,7 @@ public class Constants {
public static final String PROTOCOL_KEY = "protocol";
- public static final String DOBBO_PROTOCOL = DUBBO;
+ public static final String DUBBO_PROTOCOL = DUBBO;
public static final String ZOOKEEPER_PROTOCOL = "zookeeper";
@@ -298,9 +314,9 @@ public class Constants {
public static final long LEAST_HEARTBEAT_DURATION = 1000;
/**
- * ticks per wheel. Currently only contains two tasks, so 16 locations are enough
+ * ticks per wheel.
*/
- public static final int TICKS_PER_WHEEL = 16;
+ public static final int TICKS_PER_WHEEL = 128;
public static final String HEARTBEAT_TIMEOUT_KEY = "heartbeat.timeout";
@@ -737,6 +753,12 @@ public class Constants {
public static final String HOST_KEY = "host";
+ public static final String PORT_KEY = "port";
+
+ public static final String USERNAME_KEY = "username";
+
+ public static final String PASSWORD_KEY = "password";
+
public static final String ADDRESS_KEY = "address";
public static final String RETRY_TIMES_KEY = "retry.times";
@@ -750,7 +772,9 @@ public class Constants {
public static final String CONFIG_VERSION_KEY = "configVersion";
public static final String COMPATIBLE_CONFIG_KEY = "compatible_config";
- // package version in the manifest
+ /**
+ * package version in the manifest
+ */
public static final String RELEASE_KEY = "release";
public static final String OVERRIDE_PROVIDERS_KEY = "providerAddresses";
@@ -813,8 +837,25 @@ public class Constants {
*/
public static final String PROXY_CLASS_REF = "refClass";
- /*
- * private Constants(){ }
+ public static final String ETCD3_NOTIFY_MAXTHREADS_KEYS = "etcd3.notify.maxthreads";
+
+ public static final int DEFAULT_ETCD3_NOTIFY_THREADS = DEFAULT_IO_THREADS;
+
+ public static final String DEFAULT_ETCD3_NOTIFY_QUEUES_KEY = "etcd3.notify.queues";
+
+ public static final int DEFAULT_GRPC_QUEUES = 300_0000;
+
+ /**
+ * metrics
*/
+ public static final String DUBBO_PROVIDER = "dubbo.provider";
+ public static final String DUBBO_CONSUMER = "dubbo.consumer";
+ public static final String DUBBO_PROVIDER_METHOD = "dubbo.provider.method";
+ public static final String DUBBO_CONSUMER_METHOD = "dubbo.consumer.method";
+ public static final String SERVICE = "service";
+ public static final String METHOD = "method";
+ public static final String DUBBO_GROUP = "dubbo";
+ public static final String METRICS_KEY = "metrics";
+
}
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 529d3fe..333270c 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
@@ -96,13 +96,13 @@ public class Parameters {
public String getParameter(String key) {
String value = parameters.get(key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
value = parameters.get(Constants.HIDE_KEY_PREFIX + key);
}
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
value = parameters.get(Constants.DEFAULT_KEY_PREFIX + key);
}
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
value = parameters.get(Constants.HIDE_KEY_PREFIX + Constants.DEFAULT_KEY_PREFIX + key);
}
return value;
@@ -110,7 +110,7 @@ public class Parameters {
public String getParameter(String key, String defaultValue) {
String value = getParameter(key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
return value;
@@ -118,7 +118,7 @@ public class Parameters {
public int getIntParameter(String key) {
String value = getParameter(key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return 0;
}
return Integer.parseInt(value);
@@ -126,7 +126,7 @@ public class Parameters {
public int getIntParameter(String key, int defaultValue) {
String value = getParameter(key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
return Integer.parseInt(value);
@@ -137,7 +137,7 @@ public class Parameters {
throw new IllegalArgumentException("defaultValue <= 0");
}
String value = getParameter(key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
int i = Integer.parseInt(value);
@@ -149,7 +149,7 @@ public class Parameters {
public boolean getBooleanParameter(String key) {
String value = getParameter(key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return false;
}
return Boolean.parseBoolean(value);
@@ -157,23 +157,23 @@ public class Parameters {
public boolean getBooleanParameter(String key, boolean defaultValue) {
String value = getParameter(key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
return Boolean.parseBoolean(value);
}
- public boolean hasParamter(String key) {
+ public boolean hasParameter(String key) {
String value = getParameter(key);
return value != null && value.length() > 0;
}
public String getMethodParameter(String method, String key) {
String value = parameters.get(method + "." + key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
value = parameters.get(Constants.HIDE_KEY_PREFIX + method + "." + key);
}
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return getParameter(key);
}
return value;
@@ -181,7 +181,7 @@ public class Parameters {
public String getMethodParameter(String method, String key, String defaultValue) {
String value = getMethodParameter(method, key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
return value;
@@ -189,7 +189,7 @@ public class Parameters {
public int getMethodIntParameter(String method, String key) {
String value = getMethodParameter(method, key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return 0;
}
return Integer.parseInt(value);
@@ -197,7 +197,7 @@ public class Parameters {
public int getMethodIntParameter(String method, String key, int defaultValue) {
String value = getMethodParameter(method, key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
return Integer.parseInt(value);
@@ -208,7 +208,7 @@ public class Parameters {
throw new IllegalArgumentException("defaultValue <= 0");
}
String value = getMethodParameter(method, key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
int i = Integer.parseInt(value);
@@ -220,7 +220,7 @@ public class Parameters {
public boolean getMethodBooleanParameter(String method, String key) {
String value = getMethodParameter(method, key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return false;
}
return Boolean.parseBoolean(value);
@@ -228,13 +228,13 @@ public class Parameters {
public boolean getMethodBooleanParameter(String method, String key, boolean defaultValue) {
String value = getMethodParameter(method, key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
return Boolean.parseBoolean(value);
}
- public boolean hasMethodParamter(String method, String key) {
+ public boolean hasMethodParameter(String method, String key) {
String value = getMethodParameter(method, key);
return value != null && value.length() > 0;
}
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 f2eb8da..021cfbf 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
@@ -1,31 +1,31 @@
-/*
- * 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.common;
-
-/**
- * Resetable.
- */
-public interface Resetable {
-
- /**
- * reset.
- *
- * @param url
- */
- void reset(URL url);
-
+/*
+ * 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.common;
+
+/**
+ * Resetable.
+ */
+public interface Resetable {
+
+ /**
+ * reset.
+ *
+ * @param url
+ */
+ void reset(URL url);
+
}
\ No newline at end of file
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 eb096f7..35a3b7b 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
@@ -18,6 +18,7 @@ package org.apache.dubbo.common;
import org.apache.dubbo.common.config.Configuration;
import org.apache.dubbo.common.config.InmemoryConfiguration;
+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.common.utils.StringUtils;
@@ -70,7 +71,8 @@ import java.util.concurrent.ConcurrentHashMap;
* @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;
@@ -149,8 +151,8 @@ public /**final**/ class URL implements Serializable {
}
public URL(String protocol, String username, String password, String host, int port, String path, Map<String, String> parameters) {
- if ((username == null || username.length() == 0)
- && password != null && password.length() > 0) {
+ if (StringUtils.isEmpty(username)
+ && StringUtils.isNotEmpty(password)) {
throw new IllegalArgumentException("Invalid url, password without username!");
}
this.protocol = protocol;
@@ -164,9 +166,9 @@ public /**final**/ class URL implements Serializable {
}
this.path = path;
if (parameters == null) {
- parameters = new HashMap<String, String>();
+ parameters = new HashMap<>();
} else {
- parameters = new HashMap<String, String>(parameters);
+ parameters = new HashMap<>(parameters);
}
this.parameters = Collections.unmodifiableMap(parameters);
}
@@ -189,10 +191,10 @@ public /**final**/ class URL implements Serializable {
int port = 0;
String path = null;
Map<String, String> parameters = null;
- int i = url.indexOf("?"); // seperator between body and parameters
+ int i = url.indexOf("?"); // separator between body and parameters
if (i >= 0) {
- String[] parts = url.substring(i + 1).split("\\&");
- parameters = new HashMap<String, String>();
+ String[] parts = url.substring(i + 1).split("&");
+ parameters = new HashMap<>();
for (String part : parts) {
part = part.trim();
if (part.length() > 0) {
@@ -263,7 +265,7 @@ public /**final**/ class URL implements Serializable {
if (reserveParams == null || reserveParams.length == 0) {
return result;
}
- Map<String, String> newMap = new HashMap<String, String>(reserveParams.length);
+ Map<String, String> newMap = new HashMap<>(reserveParams.length);
Map<String, String> oldMap = result.getParameters();
for (String reserveParam : reserveParams) {
String tmp = oldMap.get(reserveParam);
@@ -275,7 +277,7 @@ public /**final**/ class URL implements Serializable {
}
public static URL valueOf(URL url, String[] reserveParams, String[] reserveParamPrefixs) {
- Map<String, String> newMap = new HashMap<String, String>();
+ Map<String, String> newMap = new HashMap<>();
Map<String, String> oldMap = url.getParameters();
if (reserveParamPrefixs != null && reserveParamPrefixs.length != 0) {
for (Map.Entry<String, String> entry : oldMap.entrySet()) {
@@ -300,7 +302,7 @@ public /**final**/ class URL implements Serializable {
}
public static String encode(String value) {
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return "";
}
try {
@@ -311,7 +313,7 @@ public /**final**/ class URL implements Serializable {
}
public static String decode(String value) {
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return "";
}
try {
@@ -346,8 +348,8 @@ public /**final**/ class URL implements Serializable {
}
public String getAuthority() {
- if ((username == null || username.length() == 0)
- && (password == null || password.length() == 0)) {
+ if (StringUtils.isEmpty(username)
+ && StringUtils.isEmpty(password)) {
return null;
}
return (username == null ? "" : username)
@@ -413,7 +415,7 @@ public /**final**/ class URL implements Serializable {
public String getBackupAddress(int defaultPort) {
StringBuilder address = new StringBuilder(appendDefaultPort(getAddress(), defaultPort));
String[] backups = getParameter(Constants.BACKUP_KEY, new String[0]);
- if (backups != null && backups.length > 0) {
+ if (ArrayUtils.isNotEmpty(backups)) {
for (String backup : backups) {
address.append(",");
address.append(appendDefaultPort(backup, defaultPort));
@@ -423,7 +425,7 @@ public /**final**/ class URL implements Serializable {
}
public List<URL> getBackupUrls() {
- List<URL> urls = new ArrayList<URL>();
+ List<URL> urls = new ArrayList<>();
urls.add(this);
String[] backups = getParameter(Constants.BACKUP_KEY, new String[0]);
if (backups != null && backups.length > 0) {
@@ -434,9 +436,8 @@ public /**final**/ class URL implements Serializable {
return urls;
}
- private String appendDefaultPort(String address, int defaultPort) {
- if (address != null && address.length() > 0
- && defaultPort > 0) {
+ static String appendDefaultPort(String address, int defaultPort) {
+ if (address != null && address.length() > 0 && defaultPort > 0) {
int i = address.indexOf(':');
if (i < 0) {
return address + ":" + defaultPort;
@@ -476,7 +477,7 @@ public /**final**/ class URL implements Serializable {
public String getParameter(String key) {
String value = parameters.get(key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
value = parameters.get(Constants.DEFAULT_KEY_PREFIX + key);
}
return value;
@@ -484,7 +485,7 @@ public /**final**/ class URL implements Serializable {
public String getParameter(String key, String defaultValue) {
String value = getParameter(key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
return value;
@@ -492,7 +493,7 @@ public /**final**/ class URL implements Serializable {
public String[] getParameter(String key, String[] defaultValue) {
String value = getParameter(key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
return Constants.COMMA_SPLIT_PATTERN.split(value);
@@ -509,14 +510,14 @@ public /**final**/ class URL implements Serializable {
private Map<String, Number> getNumbers() {
if (numbers == null) { // concurrent initialization is tolerant
- numbers = new ConcurrentHashMap<String, Number>();
+ numbers = new ConcurrentHashMap<>();
}
return numbers;
}
private Map<String, URL> getUrls() {
if (urls == null) { // concurrent initialization is tolerant
- urls = new ConcurrentHashMap<String, URL>();
+ urls = new ConcurrentHashMap<>();
}
return urls;
}
@@ -527,7 +528,7 @@ public /**final**/ class URL implements Serializable {
return u;
}
String value = getParameterAndDecoded(key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return null;
}
u = URL.valueOf(value);
@@ -541,7 +542,7 @@ public /**final**/ class URL implements Serializable {
return n.doubleValue();
}
String value = getParameter(key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
double d = Double.parseDouble(value);
@@ -555,7 +556,7 @@ public /**final**/ class URL implements Serializable {
return n.floatValue();
}
String value = getParameter(key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
float f = Float.parseFloat(value);
@@ -569,7 +570,7 @@ public /**final**/ class URL implements Serializable {
return n.longValue();
}
String value = getParameter(key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
long l = Long.parseLong(value);
@@ -583,7 +584,7 @@ public /**final**/ class URL implements Serializable {
return n.intValue();
}
String value = getParameter(key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
int i = Integer.parseInt(value);
@@ -597,7 +598,7 @@ public /**final**/ class URL implements Serializable {
return n.shortValue();
}
String value = getParameter(key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
short s = Short.parseShort(value);
@@ -611,7 +612,7 @@ public /**final**/ class URL implements Serializable {
return n.byteValue();
}
String value = getParameter(key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
byte b = Byte.parseByte(value);
@@ -687,7 +688,7 @@ public /**final**/ class URL implements Serializable {
public char getParameter(String key, char defaultValue) {
String value = getParameter(key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
return value.charAt(0);
@@ -695,7 +696,7 @@ public /**final**/ class URL implements Serializable {
public boolean getParameter(String key, boolean defaultValue) {
String value = getParameter(key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
return Boolean.parseBoolean(value);
@@ -716,7 +717,7 @@ public /**final**/ class URL implements Serializable {
public String getMethodParameter(String method, String key) {
String value = parameters.get(method + "." + key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return getParameter(key);
}
return value;
@@ -724,7 +725,7 @@ public /**final**/ class URL implements Serializable {
public String getMethodParameter(String method, String key, String defaultValue) {
String value = getMethodParameter(method, key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
return value;
@@ -734,10 +735,10 @@ public /**final**/ class URL implements Serializable {
String methodKey = method + "." + key;
Number n = getNumbers().get(methodKey);
if (n != null) {
- return n.intValue();
+ return n.doubleValue();
}
String value = getMethodParameter(method, key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
double d = Double.parseDouble(value);
@@ -749,10 +750,10 @@ public /**final**/ class URL implements Serializable {
String methodKey = method + "." + key;
Number n = getNumbers().get(methodKey);
if (n != null) {
- return n.intValue();
+ return n.floatValue();
}
String value = getMethodParameter(method, key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
float f = Float.parseFloat(value);
@@ -764,10 +765,10 @@ public /**final**/ class URL implements Serializable {
String methodKey = method + "." + key;
Number n = getNumbers().get(methodKey);
if (n != null) {
- return n.intValue();
+ return n.longValue();
}
String value = getMethodParameter(method, key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
long l = Long.parseLong(value);
@@ -782,7 +783,7 @@ public /**final**/ class URL implements Serializable {
return n.intValue();
}
String value = getMethodParameter(method, key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
int i = Integer.parseInt(value);
@@ -797,7 +798,7 @@ public /**final**/ class URL implements Serializable {
return n.shortValue();
}
String value = getMethodParameter(method, key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
short s = Short.parseShort(value);
@@ -812,7 +813,7 @@ public /**final**/ class URL implements Serializable {
return n.byteValue();
}
String value = getMethodParameter(method, key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
byte b = Byte.parseByte(value);
@@ -888,7 +889,7 @@ public /**final**/ class URL implements Serializable {
public char getMethodParameter(String method, String key, char defaultValue) {
String value = getMethodParameter(method, key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
return value.charAt(0);
@@ -896,7 +897,7 @@ public /**final**/ class URL implements Serializable {
public boolean getMethodParameter(String method, String key, boolean defaultValue) {
String value = getMethodParameter(method, key);
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return defaultValue;
}
return Boolean.parseBoolean(value);
@@ -934,7 +935,7 @@ public /**final**/ class URL implements Serializable {
}
public URL addParameterAndEncoded(String key, String value) {
- if (value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(value)) {
return this;
}
return addParameter(key, encode(value));
@@ -994,8 +995,8 @@ public /**final**/ class URL implements Serializable {
}
public URL addParameter(String key, String value) {
- if (key == null || key.length() == 0
- || value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(key)
+ || StringUtils.isEmpty(value)) {
return this;
}
// if value doesn't change, return immediately
@@ -1003,20 +1004,20 @@ public /**final**/ class URL implements Serializable {
return this;
}
- Map<String, String> map = new HashMap<String, String>(getParameters());
+ Map<String, String> map = new HashMap<>(getParameters());
map.put(key, value);
return new URL(protocol, username, password, host, port, path, map);
}
public URL addParameterIfAbsent(String key, String value) {
- if (key == null || key.length() == 0
- || value == null || value.length() == 0) {
+ if (StringUtils.isEmpty(key)
+ || StringUtils.isEmpty(value)) {
return this;
}
if (hasParameter(key)) {
return this;
}
- Map<String, String> map = new HashMap<String, String>(getParameters());
+ Map<String, String> map = new HashMap<>(getParameters());
map.put(key, value);
return new URL(protocol, username, password, host, port, path, map);
}
@@ -1028,7 +1029,7 @@ public /**final**/ class URL implements Serializable {
* @return A new URL
*/
public URL addParameters(Map<String, String> parameters) {
- if (parameters == null || parameters.size() == 0) {
+ if (CollectionUtils.isEmptyMap(parameters)) {
return this;
}
@@ -1052,16 +1053,16 @@ public /**final**/ class URL implements Serializable {
return this;
}
- Map<String, String> map = new HashMap<String, String>(getParameters());
+ Map<String, String> map = new HashMap<>(getParameters());
map.putAll(parameters);
return new URL(protocol, username, password, host, port, path, map);
}
public URL addParametersIfAbsent(Map<String, String> parameters) {
- if (parameters == null || parameters.size() == 0) {
+ if (CollectionUtils.isEmptyMap(parameters)) {
return this;
}
- Map<String, String> map = new HashMap<String, String>(parameters);
+ Map<String, String> map = new HashMap<>(parameters);
map.putAll(getParameters());
return new URL(protocol, username, password, host, port, path, map);
}
@@ -1073,7 +1074,7 @@ public /**final**/ class URL implements Serializable {
if (pairs.length % 2 != 0) {
throw new IllegalArgumentException("Map pairs can not be odd number.");
}
- Map<String, String> map = new HashMap<String, String>();
+ Map<String, String> map = new HashMap<>();
int len = pairs.length / 2;
for (int i = 0; i < len; i++) {
map.put(pairs[2 * i], pairs[2 * i + 1]);
@@ -1082,21 +1083,21 @@ public /**final**/ class URL implements Serializable {
}
public URL addParameterString(String query) {
- if (query == null || query.length() == 0) {
+ if (StringUtils.isEmpty(query)) {
return this;
}
return addParameters(StringUtils.parseQueryString(query));
}
public URL removeParameter(String key) {
- if (key == null || key.length() == 0) {
+ if (StringUtils.isEmpty(key)) {
return this;
}
return removeParameters(key);
}
public URL removeParameters(Collection<String> keys) {
- if (keys == null || keys.isEmpty()) {
+ if (CollectionUtils.isEmpty(keys)) {
return this;
}
return removeParameters(keys.toArray(new String[0]));
@@ -1106,7 +1107,7 @@ public /**final**/ class URL implements Serializable {
if (keys == null || keys.length == 0) {
return this;
}
- Map<String, String> map = new HashMap<String, String>(getParameters());
+ Map<String, String> map = new HashMap<>(getParameters());
for (String key : keys) {
map.remove(key);
}
@@ -1117,50 +1118,50 @@ public /**final**/ class URL implements Serializable {
}
public URL clearParameters() {
- return new URL(protocol, username, password, host, port, path, new HashMap<String, String>());
+ return new URL(protocol, username, password, host, port, path, new HashMap<>());
}
public String getRawParameter(String key) {
- if ("protocol".equals(key)) {
+ if (Constants.PROTOCOL_KEY.equals(key)) {
return protocol;
}
- if ("username".equals(key)) {
+ if (Constants.USERNAME_KEY.equals(key)) {
return username;
}
- if ("password".equals(key)) {
+ if (Constants.PASSWORD_KEY.equals(key)) {
return password;
}
- if ("host".equals(key)) {
+ if (Constants.HOST_KEY.equals(key)) {
return host;
}
- if ("port".equals(key)) {
+ if (Constants.PORT_KEY.equals(key)) {
return String.valueOf(port);
}
- if ("path".equals(key)) {
+ if (Constants.PATH_KEY.equals(key)) {
return path;
}
return getParameter(key);
}
public Map<String, String> toMap() {
- Map<String, String> map = new HashMap<String, String>(parameters);
+ Map<String, String> map = new HashMap<>(parameters);
if (protocol != null) {
- map.put("protocol", protocol);
+ map.put(Constants.PROTOCOL_KEY, protocol);
}
if (username != null) {
- map.put("username", username);
+ map.put(Constants.USERNAME_KEY, username);
}
if (password != null) {
- map.put("password", password);
+ map.put(Constants.USERNAME_KEY, password);
}
if (host != null) {
- map.put("host", host);
+ map.put(Constants.HOST_KEY, host);
}
if (port > 0) {
- map.put("port", String.valueOf(port));
+ map.put(Constants.PORT_KEY, String.valueOf(port));
}
if (path != null) {
- map.put("path", path);
+ map.put(Constants.PATH_KEY, path);
}
return map;
}
@@ -1213,10 +1214,10 @@ public /**final**/ class URL implements Serializable {
}
private void buildParameters(StringBuilder buf, boolean concat, String[] parameters) {
- if (getParameters() != null && getParameters().size() > 0) {
- List<String> includes = (parameters == null || parameters.length == 0 ? null : Arrays.asList(parameters));
+ if (CollectionUtils.isNotEmptyMap(getParameters())) {
+ List<String> includes = (ArrayUtils.isEmpty(parameters) ? null : Arrays.asList(parameters));
boolean first = true;
- for (Map.Entry<String, String> entry : new TreeMap<String, String>(getParameters()).entrySet()) {
+ for (Map.Entry<String, String> entry : new TreeMap<>(getParameters()).entrySet()) {
if (entry.getKey() != null && entry.getKey().length() > 0
&& (includes == null || includes.contains(entry.getKey()))) {
if (first) {
@@ -1241,11 +1242,11 @@ public /**final**/ class URL implements Serializable {
private String buildString(boolean appendUser, boolean appendParameter, boolean useIP, boolean useService, String... parameters) {
StringBuilder buf = new StringBuilder();
- if (protocol != null && protocol.length() > 0) {
+ if (StringUtils.isNotEmpty(protocol)) {
buf.append(protocol);
buf.append("://");
}
- if (appendUser && username != null && username.length() > 0) {
+ if (appendUser && StringUtils.isNotEmpty(username)) {
buf.append(username);
if (password != null && password.length() > 0) {
buf.append(":");
@@ -1296,7 +1297,7 @@ public /**final**/ class URL implements Serializable {
}
/**
- * The format is '{group}/{interfaceName/path}*{version}'
+ * The format is '{group}*{interfaceName}:{version}'
*
* @return
*/
@@ -1306,18 +1307,36 @@ public /**final**/ class URL implements Serializable {
return serviceKey;
}
+ /**
+ * The format of return value is '{group}/{interfaceName}:{version}'
+ * @return
+ */
public String getServiceKey() {
String inf = getServiceInterface();
if (inf == null) {
return null;
}
+ return buildKey(inf, getParameter(Constants.GROUP_KEY), getParameter(Constants.VERSION_KEY));
+ }
+
+ /**
+ * The format of return value is '{group}/{path/interfaceName}:{version}'
+ * @return
+ */
+ public String getPathKey() {
+ String inf = StringUtils.isNotEmpty(path) ? path : getServiceInterface();
+ if (inf == null) {
+ return null;
+ }
+ return buildKey(inf, getParameter(Constants.GROUP_KEY), getParameter(Constants.VERSION_KEY));
+ }
+
+ public static String buildKey(String path, String group, String version) {
StringBuilder buf = new StringBuilder();
- String group = getParameter(Constants.GROUP_KEY);
if (group != null && group.length() > 0) {
buf.append(group).append("/");
}
- buf.append(inf);
- String version = getParameter(Constants.VERSION_KEY);
+ buf.append(path);
if (version != null && version.length() > 0) {
buf.append(":").append(version);
}
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
new file mode 100644
index 0000000..c938737
--- /dev/null
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/URLBuilder.java
@@ -0,0 +1,350 @@
+/*
+ * 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.common;
+
+import org.apache.dubbo.common.utils.CollectionUtils;
+import org.apache.dubbo.common.utils.StringUtils;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+
+public final class URLBuilder {
+ private String protocol;
+
+ private String username;
+
+ private String password;
+
+ // by default, host to registry
+ private String host;
+
+ // by default, port to registry
+ private int port;
+
+ private String path;
+
+ private Map<String, String> parameters;
+
+ public URLBuilder() {
+ protocol = null;
+ username = null;
+ password = null;
+ host = null;
+ port = 0;
+ path = null;
+ parameters = new HashMap<>();
+ }
+
+ public URLBuilder(String protocol, String host, int port) {
+ this(protocol, null, null, host, port, null, null);
+ }
+
+ public URLBuilder(String protocol, String host, int port, String[] pairs) {
+ this(protocol, null, null, host, port, null, CollectionUtils.toStringMap(pairs));
+ }
+
+ public URLBuilder(String protocol, String host, int port, Map<String, String> parameters) {
+ this(protocol, null, null, host, port, null, parameters);
+ }
+
+ public URLBuilder(String protocol, String host, int port, String path) {
+ this(protocol, null, null, host, port, path, null);
+ }
+
+ public URLBuilder(String protocol, String host, int port, String path, String... pairs) {
+ this(protocol, null, null, host, port, path, CollectionUtils.toStringMap(pairs));
+ }
+
+ public URLBuilder(String protocol, String host, int port, String path, Map<String, String> parameters) {
+ this(protocol, null, null, host, port, path, parameters);
+ }
+
+ public URLBuilder(String protocol, String username, String password, String host, int port, String path, Map<String, String> parameters) {
+ this.protocol = protocol;
+ this.username = username;
+ this.password = password;
+ this.host = host;
+ this.port = port;
+ this.path = path;
+ this.parameters = parameters != null ? parameters : new HashMap<>();
+ }
+
+ public static URLBuilder from(URL url) {
+ String protocol = url.getProtocol();
+ String username = url.getUsername();
+ String password = url.getPassword();
+ String host = url.getHost();
+ int port = url.getPort();
+ String path = url.getPath();
+ Map<String, String> parameters = new HashMap<>(url.getParameters());
+ return new URLBuilder(
+ protocol,
+ username,
+ password,
+ host,
+ port,
+ path,
+ parameters);
+ }
+
+ public URL build() {
+ if (StringUtils.isEmpty(username) && StringUtils.isNotEmpty(password)) {
+ throw new IllegalArgumentException("Invalid url, password without username!");
+ }
+ port = port < 0 ? 0 : port;
+ // trim the leading "/"
+ int firstNonSlash = 0;
+ if (path != null) {
+ while (firstNonSlash < path.length() && path.charAt(firstNonSlash) == '/') {
+ firstNonSlash++;
+ }
+ if (firstNonSlash >= path.length()) {
+ path = "";
+ } else if (firstNonSlash > 0) {
+ path = path.substring(firstNonSlash);
+ }
+ }
+ return new URL(protocol, username, password, host, port, path, parameters);
+ }
+
+
+ public URLBuilder setProtocol(String protocol) {
+ this.protocol = protocol;
+ return this;
+ }
+
+ public URLBuilder setUsername(String username) {
+ this.username = username;
+ return this;
+ }
+
+ public URLBuilder setPassword(String password) {
+ this.password = password;
+ return this;
+ }
+
+ public URLBuilder setHost(String host) {
+ this.host = host;
+ return this;
+ }
+
+ public URLBuilder setPort(int port) {
+ this.port = port;
+ return this;
+ }
+
+ public URLBuilder setAddress(String address) {
+ int i = address.lastIndexOf(':');
+ String host;
+ int port = this.port;
+ if (i >= 0) {
+ host = address.substring(0, i);
+ port = Integer.parseInt(address.substring(i + 1));
+ } else {
+ host = address;
+ }
+ this.host = host;
+ this.port = port;
+ return this;
+ }
+
+ public URLBuilder setPath(String path) {
+ this.path = path;
+ return this;
+ }
+
+ public URLBuilder addParameterAndEncoded(String key, String value) {
+ if (StringUtils.isEmpty(value)) {
+ return this;
+ }
+ return addParameter(key, URL.encode(value));
+ }
+
+ public URLBuilder addParameter(String key, boolean value) {
+ return addParameter(key, String.valueOf(value));
+ }
+
+ public URLBuilder addParameter(String key, char value) {
+ return addParameter(key, String.valueOf(value));
+ }
+
+ public URLBuilder addParameter(String key, byte value) {
+ return addParameter(key, String.valueOf(value));
+ }
+
+ public URLBuilder addParameter(String key, short value) {
+ return addParameter(key, String.valueOf(value));
+ }
+
+ public URLBuilder addParameter(String key, int value) {
+ return addParameter(key, String.valueOf(value));
+ }
+
+ public URLBuilder addParameter(String key, long value) {
+ return addParameter(key, String.valueOf(value));
+ }
+
+ public URLBuilder addParameter(String key, float value) {
+ return addParameter(key, String.valueOf(value));
+ }
+
+ public URLBuilder addParameter(String key, double value) {
+ return addParameter(key, String.valueOf(value));
+ }
+
+ public URLBuilder addParameter(String key, Enum<?> value) {
+ if (value == null) {
+ return this;
+ }
+ return addParameter(key, String.valueOf(value));
+ }
+
+ public URLBuilder addParameter(String key, Number value) {
+ if (value == null) {
+ return this;
+ }
+ return addParameter(key, String.valueOf(value));
+ }
+
+ public URLBuilder addParameter(String key, CharSequence value) {
+ if (value == null || value.length() == 0) {
+ return this;
+ }
+ return addParameter(key, String.valueOf(value));
+ }
+
+ public URLBuilder addParameter(String key, String value) {
+ if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
+ return this;
+ }
+ // if value doesn't change, return immediately
+ if (value.equals(parameters.get(key))) { // value != null
+ return this;
+ }
+
+ parameters.put(key, value);
+ return this;
+ }
+
+ public URLBuilder addParameterIfAbsent(String key, String value) {
+ if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
+ return this;
+ }
+ if (hasParameter(key)) {
+ return this;
+ }
+ parameters.put(key, value);
+ return this;
+ }
+
+ public URLBuilder addParameters(Map<String, String> parameters) {
+ if (CollectionUtils.isEmptyMap(parameters)) {
+ return this;
+ }
+
+ boolean hasAndEqual = true;
+ for (Map.Entry<String, String> entry : parameters.entrySet()) {
+ String oldValue = this.parameters.get(entry.getKey());
+ String newValue = entry.getValue();
+ if (!Objects.equals(oldValue, newValue)) {
+ hasAndEqual = false;
+ break;
+ }
+ }
+ // return immediately if there's no change
+ if (hasAndEqual) {
+ return this;
+ }
+
+ this.parameters.putAll(parameters);
+ return this;
+ }
+
+ public URLBuilder addParametersIfAbsent(Map<String, String> parameters) {
+ if (CollectionUtils.isEmptyMap(parameters)) {
+ return this;
+ }
+ this.parameters.putAll(parameters);
+ return this;
+ }
+
+ public URLBuilder addParameters(String... pairs) {
+ if (pairs == null || pairs.length == 0) {
+ return this;
+ }
+ if (pairs.length % 2 != 0) {
+ throw new IllegalArgumentException("Map pairs can not be odd number.");
+ }
+ Map<String, String> map = new HashMap<>();
+ int len = pairs.length / 2;
+ for (int i = 0; i < len; i++) {
+ map.put(pairs[2 * i], pairs[2 * i + 1]);
+ }
+ return addParameters(map);
+ }
+
+ public URLBuilder addParameterString(String query) {
+ if (StringUtils.isEmpty(query)) {
+ return this;
+ }
+ return addParameters(StringUtils.parseQueryString(query));
+ }
+
+ public URLBuilder removeParameter(String key) {
+ if (StringUtils.isEmpty(key)) {
+ return this;
+ }
+ return removeParameters(key);
+ }
+
+ public URLBuilder removeParameters(Collection<String> keys) {
+ if (CollectionUtils.isEmpty(keys)) {
+ return this;
+ }
+ return removeParameters(keys.toArray(new String[0]));
+ }
+
+ public URLBuilder removeParameters(String... keys) {
+ if (keys == null || keys.length == 0) {
+ return this;
+ }
+ for (String key : keys) {
+ parameters.remove(key);
+ }
+ return this;
+ }
+
+ public URLBuilder clearParameters() {
+ parameters.clear();
+ return this;
+ }
+
+ public boolean hasParameter(String key) {
+ String value = getParameter(key);
+ return value != null && value.length() > 0;
+ }
+
+ public String getParameter(String key) {
+ String value = parameters.get(key);
+ if (StringUtils.isEmpty(value)) {
+ value = parameters.get(Constants.DEFAULT_KEY_PREFIX + key);
+ }
+ return value;
+ }
+}
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 9f69ae8..0ab48a6 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
@@ -21,6 +21,7 @@ import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ClassHelper;
import org.apache.dubbo.common.utils.StringUtils;
+import java.io.IOException;
import java.net.URL;
import java.security.CodeSource;
import java.util.Enumeration;
@@ -28,12 +29,16 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
/**
* Version
*/
public final class Version {
private static final Logger logger = LoggerFactory.getLogger(Version.class);
+
+ private static final Pattern PREFIX_DIGITS_PATTERN = Pattern.compile("^([0-9]*).*");
// Dubbo RPC protocol version, for compatibility, it must not be between 2.0.10 ~ 2.6.2
public static final String DEFAULT_DUBBO_PROTOCOL_VERSION = "2.0.2";
@@ -89,7 +94,7 @@ public final class Version {
}
public static boolean isSupportResponseAttachment(String version) {
- if (version == null || version.length() == 0) {
+ if (StringUtils.isEmpty(version)) {
return false;
}
// for previous dubbo version(2.0.10/020010~2.6.2/020602), this version is the jar's version, so they need to
@@ -120,75 +125,53 @@ public final class Version {
String[] vArr = version.split("\\.");
int len = vArr.length;
for (int i = 0; i < len; i++) {
- v += Integer.parseInt(getDigital(vArr[i])) * Math.pow(10, (len - i - 1) * 2);
+ v += Integer.parseInt(getPrefixDigits(vArr[i])) * Math.pow(10, (len - i - 1) * 2);
}
return v;
}
- private static String getDigital(String v) {
- int index = 0;
- for (int i = 0; i < v.length(); i++) {
- char c = v.charAt(i);
- if (Character.isDigit(c)) {
- if (i == v.length() - 1) {
- index = i + 1;
- } else {
- index = i;
- }
- } else {
- index = i;
- break;
- }
- }
- return v.substring(0, index);
- }
-
- private static boolean hasResource(String path) {
- try {
- return Version.class.getClassLoader().getResource(path) != null;
- } catch (Throwable t) {
- return false;
+ /**
+ * get prefix digits from given version string
+ */
+ private static String getPrefixDigits(String v) {
+ Matcher matcher = PREFIX_DIGITS_PATTERN.matcher(v);
+ if (matcher.find()) {
+ return matcher.group(1);
}
+ return "";
}
public static String getVersion(Class<?> cls, String defaultVersion) {
try {
// find version info from MANIFEST.MF first
- String version = cls.getPackage().getImplementationVersion();
- if (version == null || version.length() == 0) {
- version = cls.getPackage().getSpecificationVersion();
- }
- if (version == null || version.length() == 0) {
- // guess version fro 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);
- } else {
- String file = codeSource.getLocation().getFile();
- if (file != null && file.length() > 0 && file.endsWith(".jar")) {
- file = file.substring(0, file.length() - 4);
- int i = file.lastIndexOf('/');
- if (i >= 0) {
- file = file.substring(i + 1);
- }
- i = file.indexOf("-");
- if (i >= 0) {
- file = file.substring(i + 1);
- }
- while (file.length() > 0 && !Character.isDigit(file.charAt(0))) {
- i = file.indexOf("-");
- if (i >= 0) {
- file = file.substring(i + 1);
- } else {
- break;
- }
- }
- version = file;
- }
+ Package pkg = cls.getPackage();
+ String version = null;
+ if (pkg != null) {
+ version = pkg.getImplementationVersion();
+ if (!StringUtils.isEmpty(version)) {
+ return version;
+ }
+
+ version = pkg.getSpecificationVersion();
+ if (!StringUtils.isEmpty(version)) {
+ return version;
}
}
+
+ // guess version fro 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);
+ return defaultVersion;
+ }
+
+ String file = codeSource.getLocation().getFile();
+ if (!StringUtils.isEmpty(file) && file.endsWith(".jar")) {
+ version = getFromFile(file);
+ }
+
// return default version if no version info is found
- return version == null || version.length() == 0 ? defaultVersion : version;
+ return StringUtils.isEmpty(version) ? defaultVersion : version;
} catch (Throwable e) {
// return default version when any exception is thrown
logger.error("return default version, ignore exception " + e.getMessage(), e);
@@ -196,6 +179,37 @@ public final class Version {
}
}
+ /**
+ * get version from file: path/to/group-module-x.y.z.jar, returns x.y.z
+ */
+ private static String getFromFile(String file) {
+ // remove suffix ".jar": "path/to/group-module-x.y.z"
+ file = file.substring(0, file.length() - 4);
+
+ // remove path: "group-module-x.y.z"
+ int i = file.lastIndexOf('/');
+ if (i >= 0) {
+ file = file.substring(i + 1);
+ }
+
+ // remove group: "module-x.y.z"
+ i = file.indexOf("-");
+ if (i >= 0) {
+ file = file.substring(i + 1);
+ }
+
+ // remove module: "x.y.z"
+ while (file.length() > 0 && !Character.isDigit(file.charAt(0))) {
+ i = file.indexOf("-");
+ if (i >= 0) {
+ file = file.substring(i + 1);
+ } else {
+ break;
+ }
+ }
+ return file;
+ }
+
public static void checkDuplicate(Class<?> cls, boolean failOnError) {
checkDuplicate(cls.getName().replace('.', '/') + ".class", failOnError);
}
@@ -207,17 +221,7 @@ public final class Version {
public static void checkDuplicate(String path, boolean failOnError) {
try {
// search in caller's classloader
- Enumeration<URL> urls = ClassHelper.getCallerClassLoader(Version.class).getResources(path);
- Set<String> files = new HashSet<String>();
- while (urls.hasMoreElements()) {
- URL url = urls.nextElement();
- if (url != null) {
- String file = url.getFile();
- if (file != null && file.length() > 0) {
- files.add(file);
- }
- }
- }
+ Set<String> files = getResources(path);
// duplicated jar is found
if (files.size() > 1) {
String error = "Duplicate class " + path + " in " + files.size() + " jar " + files;
@@ -232,4 +236,22 @@ public final class Version {
}
}
+ /**
+ * search resources in caller's classloader
+ */
+ private static Set<String> getResources(String path) throws IOException {
+ Enumeration<URL> urls = ClassHelper.getCallerClassLoader(Version.class).getResources(path);
+ Set<String> files = new HashSet<String>();
+ while (urls.hasMoreElements()) {
+ URL url = urls.nextElement();
+ if (url != null) {
+ String file = url.getFile();
+ if (file != null && file.length() > 0) {
+ files.add(file);
+ }
+ }
+ }
+ return files;
+ }
+
}
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 c044c7b..40ae885 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
@@ -16,6 +16,7 @@
*/
package org.apache.dubbo.common.bytecode;
+import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.common.utils.ClassHelper;
import org.apache.dubbo.common.utils.ReflectUtils;
@@ -29,6 +30,7 @@ import javassist.CtNewConstructor;
import javassist.CtNewMethod;
import javassist.LoaderClassPath;
import javassist.NotFoundException;
+import org.apache.dubbo.common.utils.StringUtils;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
@@ -165,7 +167,7 @@ public final class ClassGenerator {
StringBuilder sb = new StringBuilder();
sb.append(modifier(mod)).append(' ').append(ReflectUtils.getName(type)).append(' ');
sb.append(name);
- if (def != null && def.length() > 0) {
+ if (StringUtils.isNotEmpty(def)) {
sb.append('=');
sb.append(def);
}
@@ -198,7 +200,7 @@ public final class ClassGenerator {
sb.append(" arg").append(i);
}
sb.append(')');
- if (ets != null && ets.length > 0) {
+ if (ArrayUtils.isNotEmpty(ets)) {
sb.append(" throws ");
for (int i = 0; i < ets.length; i++) {
if (i > 0) {
@@ -250,7 +252,7 @@ public final class ClassGenerator {
sb.append(" arg").append(i);
}
sb.append(')');
- if (ets != null && ets.length > 0) {
+ if (ArrayUtils.isNotEmpty(ets)) {
sb.append(" throws ");
for (int i = 0; i < ets.length; i++) {
if (i > 0) {
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 150e946..e72faae 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
@@ -16,6 +16,7 @@
*/
package org.apache.dubbo.common.bytecode;
+import org.apache.dubbo.common.Constants;
import org.apache.dubbo.common.utils.ClassHelper;
import org.apache.dubbo.common.utils.ReflectUtils;
@@ -38,12 +39,7 @@ import java.util.concurrent.atomic.AtomicLong;
*/
public abstract class Proxy {
- public static final InvocationHandler RETURN_NULL_INVOKER = new InvocationHandler() {
- @Override
- public Object invoke(Object proxy, Method method, Object[] args) {
- return null;
- }
- };
+ public static final InvocationHandler RETURN_NULL_INVOKER = (proxy, method, args) -> null;
public static final InvocationHandler THROW_UNSUPPORTED_INVOKER = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) {
@@ -77,7 +73,7 @@ public abstract class Proxy {
* @return Proxy instance.
*/
public static Proxy getProxy(ClassLoader cl, Class<?>... ics) {
- if (ics.length > 65535) {
+ if (ics.length > Constants.MAX_PROXY_COUNT) {
throw new IllegalArgumentException("interface limit exceeded");
}
@@ -107,11 +103,7 @@ public abstract class Proxy {
// get cache by class loader.
Map<String, Object> cache;
synchronized (ProxyCacheMap) {
- cache = ProxyCacheMap.get(cl);
- if (cache == null) {
- cache = new HashMap<String, Object>();
- ProxyCacheMap.put(cl, cache);
- }
+ cache = ProxyCacheMap.computeIfAbsent(cl, k -> new HashMap<>());
}
Proxy proxy = null;
@@ -144,8 +136,8 @@ public abstract class Proxy {
try {
ccp = ClassGenerator.newInstance(cl);
- Set<String> worked = new HashSet<String>();
- List<Method> methods = new ArrayList<Method>();
+ Set<String> worked = new HashSet<>();
+ List<Method> methods = new ArrayList<>();
for (int i = 0; i < ics.length; i++) {
if (!Modifier.isPublic(ics[i].getModifiers())) {
@@ -175,7 +167,7 @@ public abstract class Proxy {
for (int j = 0; j < pts.length; j++) {
code.append(" args[").append(j).append("] = ($w)$").append(j + 1).append(";");
}
- code.append(" Object ret = handler.invoke(this, methods[" + ix + "], 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(";");
}
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 76113ba..6d3f42b 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
@@ -137,10 +137,10 @@ public abstract class Wrapper {
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<String, Class<?>> pts = new HashMap<String, Class<?>>(); // <property name, property types>
- Map<String, Method> ms = new LinkedHashMap<String, Method>(); // <method desc, Method instance>
- List<String> mns = new ArrayList<String>(); // method names.
- List<String> dmns = new ArrayList<String>(); // declaring method names.
+ Map<String, Class<?>> pts = new HashMap<>(); // <property name, property types>
+ Map<String, Method> ms = new LinkedHashMap<>(); // <method desc, Method instance>
+ List<String> mns = new ArrayList<>(); // method names.
+ List<String> dmns = new ArrayList<>(); // declaring method names.
// get all public field.
for (Field f : c.getFields()) {
@@ -160,51 +160,49 @@ public abstract class Wrapper {
boolean hasMethod = hasMethods(methods);
if (hasMethod) {
c3.append(" try{");
- }
- for (Method m : methods) {
- if (m.getDeclaringClass() == Object.class) //ignore Object's method.
- {
- continue;
- }
+ for (Method m : methods) {
+ //ignore Object's method.
+ if (m.getDeclaringClass() == Object.class) {
+ continue;
+ }
- String mn = m.getName();
- c3.append(" if( \"").append(mn).append("\".equals( $2 ) ");
- int len = m.getParameterTypes().length;
- c3.append(" && ").append(" $3.length == ").append(len);
+ String mn = m.getName();
+ c3.append(" if( \"").append(mn).append("\".equals( $2 ) ");
+ int len = m.getParameterTypes().length;
+ c3.append(" && ").append(" $3.length == ").append(len);
- boolean override = false;
- for (Method m2 : methods) {
- if (m != m2 && m.getName().equals(m2.getName())) {
- override = true;
- break;
+ boolean override = false;
+ for (Method m2 : methods) {
+ if (m != m2 && m.getName().equals(m2.getName())) {
+ override = true;
+ break;
+ }
}
- }
- if (override) {
- 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("\")");
+ if (override) {
+ 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(" ) { ");
+ c3.append(" ) { ");
- if (m.getReturnType() == Void.TYPE) {
- 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(");");
- }
+ if (m.getReturnType() == Void.TYPE) {
+ 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(" }");
+ c3.append(" }");
- mns.add(mn);
- if (m.getDeclaringClass() == c) {
- dmns.add(mn);
+ mns.add(mn);
+ if (m.getDeclaringClass() == c) {
+ dmns.add(mn);
+ }
+ ms.put(ReflectUtils.getDesc(m), m);
}
- ms.put(ReflectUtils.getDesc(m), m);
- }
- if (hasMethod) {
c3.append(" } catch(Throwable e) { ");
c3.append(" throw new java.lang.reflect.InvocationTargetException(e); ");
c3.append(" }");
@@ -216,7 +214,7 @@ public abstract class Wrapper {
Matcher matcher;
for (Map.Entry<String, Method> entry : ms.entrySet()) {
String md = entry.getKey();
- Method method = (Method) entry.getValue();
+ 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("(); }");
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 e4db9a8..365cb7f 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
@@ -16,6 +16,8 @@
*/
package org.apache.dubbo.common.compiler.support;
+import org.apache.dubbo.common.utils.StringUtils;
+
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Array;
@@ -56,12 +58,12 @@ public class ClassUtils {
public static Class<?> forName(String[] packages, String className) {
try {
- return _forName(className);
+ return classForName(className);
} catch (ClassNotFoundException e) {
if (packages != null && packages.length > 0) {
for (String pkg : packages) {
try {
- return _forName(pkg + "." + className);
+ return classForName(pkg + "." + className);
} catch (ClassNotFoundException e2) {
}
}
@@ -72,14 +74,14 @@ public class ClassUtils {
public static Class<?> forName(String className) {
try {
- return _forName(className);
+ return classForName(className);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
- public static Class<?> _forName(String className) throws ClassNotFoundException {
- switch(className){
+ public static Class<?> classForName(String className) throws ClassNotFoundException {
+ switch (className) {
case "boolean":
return boolean.class;
case "byte":
@@ -112,6 +114,7 @@ public class ClassUtils {
return float[].class;
case "double[]":
return double[].class;
+ default:
}
try {
return arrayForName(className);
@@ -290,7 +293,7 @@ public class ClassUtils {
}
public static boolean isBeforeJava5(String javaVersion) {
- return (javaVersion == null || javaVersion.length() == 0 || "1.0".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));
}
@@ -428,5 +431,17 @@ public class ClassUtils {
}
return map;
}
+
+ /**
+ * get simple class name from qualified class name
+ */
+ public static String getSimpleClassName(String qualifiedName) {
+ if (null == qualifiedName) {
+ return null;
+ }
+
+ 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
new file mode 100644
index 0000000..0dc8f88
--- /dev/null
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/CtClassBuilder.java
@@ -0,0 +1,174 @@
+/*
+ * 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.common.compiler.support;
+
+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;
+import javassist.CtField;
+import javassist.CtNewConstructor;
+import javassist.CtNewMethod;
+import javassist.LoaderClassPath;
+import javassist.NotFoundException;
+
+/**
+ * CtClassBuilder is builder for CtClass
+ * <p>
+ * contains all the information, including:
+ * <p>
+ * class name, imported packages, super class name, implemented interfaces, constructors, fields, methods.
+ */
+public class CtClassBuilder {
+
+ private String className;
+
+ private String superClassName = "java.lang.Object";
+
+ private List<String> imports = new ArrayList<>();
+
+ private Map<String, String> fullNames = new HashMap<>();
+
+ private List<String> ifaces = new ArrayList<>();
+
+ private List<String> constructors = new ArrayList<>();
+
+ private List<String> fields = new ArrayList<>();
+
+ private List<String> methods = new ArrayList<>();
+
+ public String getClassName() {
+ return className;
+ }
+
+ public void setClassName(String className) {
+ this.className = className;
+ }
+
+ public String getSuperClassName() {
+ return superClassName;
+ }
+
+ public void setSuperClassName(String superClassName) {
+ this.superClassName = getQualifiedClassName(superClassName);
+ }
+
+ public List<String> getImports() {
+ return imports;
+ }
+
+ public void addImports(String pkg) {
+ int pi = pkg.lastIndexOf('.');
+ if (pi > 0) {
+ String pkgName = pkg.substring(0, pi);
+ this.imports.add(pkgName);
+ if (!pkg.endsWith(".*")) {
+ fullNames.put(pkg.substring(pi + 1), pkg);
+ }
+ }
+ }
+
+ public List<String> getInterfaces() {
+ return ifaces;
+ }
+
+ public void addInterface(String iface) {
+ this.ifaces.add(getQualifiedClassName(iface));
+ }
+
+ public List<String> getConstructors() {
+ return constructors;
+ }
+
+ public void addConstructor(String constructor) {
+ this.constructors.add(constructor);
+ }
+
+ public List<String> getFields() {
+ return fields;
+ }
+
+ public void addField(String field) {
+ this.fields.add(field);
+ }
+
+ public List<String> getMethods() {
+ return methods;
+ }
+
+ public void addMethod(String method) {
+ this.methods.add(method);
+ }
+
+ /**
+ * get full qualified class name
+ *
+ * @param className super class name, maybe qualified or not
+ */
+ protected String getQualifiedClassName(String className) {
+ if (className.contains(".")) {
+ return className;
+ }
+
+ if (fullNames.containsKey(className)) {
+ return fullNames.get(className);
+ }
+
+ return ClassUtils.forName(imports.toArray(new String[0]), className).getName();
+ }
+
+ /**
+ * build CtClass object
+ */
+ public CtClass build(ClassLoader classLoader) throws NotFoundException, CannotCompileException {
+ ClassPool pool = new ClassPool(true);
+ pool.appendClassPath(new LoaderClassPath(classLoader));
+
+ // create class
+ CtClass ctClass = pool.makeClass(className, pool.get(superClassName));
+
+ // add imported packages
+ imports.stream().forEach(pool::importPackage);
+
+ // add implemented interfaces
+ for (String iface : ifaces) {
+ ctClass.addInterface(pool.get(iface));
+ }
+
+ // add constructors
+ for (String constructor : constructors) {
+ ctClass.addConstructor(CtNewConstructor.make(constructor, ctClass));
+ }
+
+ // add fields
+ for (String field : fields) {
+ ctClass.addField(CtField.make(field, ctClass));
+ }
+
+ // add methods
+ for (String method : methods) {
+ ctClass.addMethod(CtNewMethod.make(method, ctClass));
+ }
+
+ 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 5beb8e4..11f76b1 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,17 +18,9 @@ package org.apache.dubbo.common.compiler.support;
import org.apache.dubbo.common.utils.ClassHelper;
-import javassist.ClassPool;
import javassist.CtClass;
-import javassist.CtField;
-import javassist.CtNewConstructor;
-import javassist.CtNewMethod;
-import javassist.LoaderClassPath;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
+import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -49,77 +41,46 @@ public class JavassistCompiler extends AbstractCompiler {
@Override
public Class<?> doCompile(String name, String source) throws Throwable {
- int i = name.lastIndexOf('.');
- String className = i < 0 ? name : name.substring(i + 1);
- ClassPool pool = new ClassPool(true);
- pool.appendClassPath(new LoaderClassPath(ClassHelper.getCallerClassLoader(getClass())));
+ CtClassBuilder builder = new CtClassBuilder();
+ builder.setClassName(name);
+
+ // process imported classes
Matcher matcher = IMPORT_PATTERN.matcher(source);
- List<String> importPackages = new ArrayList<String>();
- Map<String, String> fullNames = new HashMap<String, String>();
while (matcher.find()) {
- String pkg = matcher.group(1);
- if (pkg.endsWith(".*")) {
- String pkgName = pkg.substring(0, pkg.length() - 2);
- pool.importPackage(pkgName);
- importPackages.add(pkgName);
- } else {
- int pi = pkg.lastIndexOf('.');
- if (pi > 0) {
- String pkgName = pkg.substring(0, pi);
- pool.importPackage(pkgName);
- importPackages.add(pkgName);
- fullNames.put(pkg.substring(pi + 1), pkg);
- }
- }
+ builder.addImports(matcher.group(1).trim());
}
- String[] packages = importPackages.toArray(new String[0]);
+
+ // process extended super class
matcher = EXTENDS_PATTERN.matcher(source);
- CtClass cls;
if (matcher.find()) {
- String extend = matcher.group(1).trim();
- String extendClass;
- if (extend.contains(".")) {
- extendClass = extend;
- } else if (fullNames.containsKey(extend)) {
- extendClass = fullNames.get(extend);
- } else {
- extendClass = ClassUtils.forName(packages, extend).getName();
- }
- cls = pool.makeClass(name, pool.get(extendClass));
- } else {
- cls = pool.makeClass(name);
+ builder.setSuperClassName(matcher.group(1).trim());
}
+
+ // process implemented interfaces
matcher = IMPLEMENTS_PATTERN.matcher(source);
if (matcher.find()) {
String[] ifaces = matcher.group(1).trim().split("\\,");
- for (String iface : ifaces) {
- iface = iface.trim();
- String ifaceClass;
- if (iface.contains(".")) {
- ifaceClass = iface;
- } else if (fullNames.containsKey(iface)) {
- ifaceClass = fullNames.get(iface);
- } else {
- ifaceClass = ClassUtils.forName(packages, iface).getName();
- }
- cls.addInterface(pool.get(ifaceClass));
- }
+ Arrays.stream(ifaces).forEach(i -> builder.addInterface(i.trim()));
}
- String body = source.substring(source.indexOf("{") + 1, source.length() - 1);
+
+ // process constructors, fields, methods
+ String body = source.substring(source.indexOf('{') + 1, source.length() - 1);
String[] methods = METHODS_PATTERN.split(body);
- for (String method : methods) {
- method = method.trim();
- if (method.length() > 0) {
- if (method.startsWith(className)) {
- cls.addConstructor(CtNewConstructor.make("public " + method, cls));
- } else if (FIELD_PATTERN.matcher(method).matches()) {
- cls.addField(CtField.make("private " + method, cls));
- } else {
- cls.addMethod(CtNewMethod.make("public " + method, cls));
- }
+ String className = ClassUtils.getSimpleClassName(name);
+ Arrays.stream(methods).map(String::trim).filter(m -> !m.isEmpty()).forEach(method-> {
+ if (method.startsWith(className)) {
+ builder.addConstructor("public " + method);
+ } else if (FIELD_PATTERN.matcher(method).matches()) {
+ builder.addField("private " + method);
+ } else {
+ builder.addMethod("public " + method);
}
- }
- return cls.toClass(ClassHelper.getCallerClassLoader(getClass()), JavassistCompiler.class.getProtectionDomain());
+ });
+
+ // compile
+ ClassLoader classLoader = ClassHelper.getCallerClassLoader(getClass());
+ CtClass cls = builder.build(classLoader);
+ return cls.toClass(classLoader, JavassistCompiler.class.getProtectionDomain());
}
}
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/ExecutionList.java b/dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/ExecutionList.java
deleted file mode 100644
index c88626c..0000000
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/ExecutionList.java
+++ /dev/null
@@ -1,180 +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.common.concurrent;
-
-import org.apache.dubbo.common.logger.Logger;
-import org.apache.dubbo.common.logger.LoggerFactory;
-import org.apache.dubbo.common.utils.NamedThreadFactory;
-
-import java.util.concurrent.Executor;
-import java.util.concurrent.SynchronousQueue;
-import java.util.concurrent.ThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-
-/**
- * <p>A list of listeners, each with an associated {@code Executor}, that
- * guarantees that every {@code Runnable} that is {@linkplain #add added} will
- * be executed after {@link #execute()} is called. Any {@code Runnable} added
- * after the call to {@code execute} is still guaranteed to execute. There is no
- * guarantee, however, that listeners will be executed in the order that they
- * are added.
- * <p>
- * <p>Exceptions thrown by a listener will be propagated up to the executor.
- * Any exception thrown during {@code Executor.execute} (e.g., a {@code
- * RejectedExecutionException} or an exception thrown by {@linkplain
- * MoreExecutors#sameThreadExecutor inline execution}) will be caught and
- * logged.
- */
-public final class ExecutionList {
- // Logger to log exceptions caught when running runnables.
- static final Logger logger = LoggerFactory.getLogger(ExecutionList.class.getName());
-
- /**
- * The runnable, executor pairs to execute. This acts as a stack threaded through the
- * {@link RunnableExecutorPair#next} field.
- */
- private RunnableExecutorPair runnables;
-
- private boolean executed;
-
- private static final Executor DEFAULT_EXECUTOR = new ThreadPoolExecutor(1, 10, 60000L, TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>(), new NamedThreadFactory("DubboFutureCallbackDefault", true));
-
- /**
- * Creates a new, empty {@link ExecutionList}.
- */
- public ExecutionList() {
- }
-
- /**
- * Adds the {@code Runnable} and accompanying {@code Executor} to the list of
- * listeners to execute. If execution has already begun, the listener is
- * executed immediately.
- * <p>
- * <p>Note: For fast, lightweight listeners that would be safe to execute in
- * any thread, consider {@link MoreExecutors#sameThreadExecutor}. For heavier
- * listeners, {@code sameThreadExecutor()} carries some caveats: First, the
- * thread that the listener runs in depends on whether the {@code
- * ExecutionList} has been executed at the time it is added. In particular,
- * listeners may run in the thread that calls {@code add}. Second, the thread
- * that calls {@link #execute} may be an internal implementation thread, such
- * as an RPC network thread, and {@code sameThreadExecutor()} listeners may
- * run in this thread. Finally, during the execution of a {@code
- * sameThreadExecutor} listener, all other registered but unexecuted
- * listeners are prevented from running, even if those listeners are to run
- * in other executors.
- */
- public void add(Runnable runnable, Executor executor) {
- // Fail fast on a null. We throw NPE here because the contract of
- // Executor states that it throws NPE on null listener, so we propagate
- // that contract up into the add method as well.
- if (runnable == null) {
- throw new NullPointerException("Runnable can not be null!");
- }
- if (executor == null) {
- logger.info("Executor for listenablefuture is null, will use default executor!");
- executor = DEFAULT_EXECUTOR;
- }
- // Lock while we check state. We must maintain the lock while adding the
- // new pair so that another thread can't run the list out from under us.
- // We only add to the list if we have not yet started execution.
- synchronized (this) {
- if (!executed) {
- runnables = new RunnableExecutorPair(runnable, executor, runnables);
- return;
- }
- }
- // Execute the runnable immediately. Because of scheduling this may end up
- // getting called before some of the previously added runnables, but we're
- // OK with that. If we want to change the contract to guarantee ordering
- // among runnables we'd have to modify the logic here to allow it.
- executeListener(runnable, executor);
- }
-
- /**
- * Runs this execution list, executing all existing pairs in the order they
- * were added. However, note that listeners added after this point may be
- * executed before those previously added, and note that the execution order
- * of all listeners is ultimately chosen by the implementations of the
- * supplied executors.
- * <p>
- * <p>This method is idempotent. Calling it several times in parallel is
- * semantically equivalent to calling it exactly once.
- *
- * @since 10.0 (present in 1.0 as {@code run})
- */
- public void execute() {
- // Lock while we update our state so the add method above will finish adding
- // any listeners before we start to run them.
- RunnableExecutorPair list;
- synchronized (this) {
- if (executed) {
- return;
- }
- executed = true;
- list = runnables;
- runnables = null; // allow GC to free listeners even if this stays around for a while.
- }
- // If we succeeded then list holds all the runnables we to execute. The pairs in the stack are
- // in the opposite order from how they were added so we need to reverse the list to fulfill our
- // contract.
- // This is somewhat annoying, but turns out to be very fast in practice. Alternatively, we
- // could drop the contract on the method that enforces this queue like behavior since depending
- // on it is likely to be a bug anyway.
-
- // N.B. All writes to the list and the next pointers must have happened before the above
- // synchronized block, so we can iterate the list without the lock held here.
- RunnableExecutorPair reversedList = null;
- while (list != null) {
- RunnableExecutorPair tmp = list;
- list = list.next;
- tmp.next = reversedList;
- reversedList = tmp;
- }
- while (reversedList != null) {
- executeListener(reversedList.runnable, reversedList.executor);
- reversedList = reversedList.next;
- }
- }
-
- /**
- * Submits the given runnable to the given {@link Executor} catching and logging all
- * {@linkplain RuntimeException runtime exceptions} thrown by the executor.
- */
- private static void executeListener(Runnable runnable, Executor executor) {
- try {
- executor.execute(runnable);
- } catch (RuntimeException e) {
- // Log it and keep going, bad runnable and/or executor. Don't
- // punish the other runnables if we're given a bad one. We only
- // catch RuntimeException because we want Errors to propagate up.
- logger.error("RuntimeException while executing runnable "
- + runnable + " with executor " + executor, e);
- }
- }
-
- private static final class RunnableExecutorPair {
- final Runnable runnable;
- final Executor executor;
- RunnableExecutorPair next;
-
- RunnableExecutorPair(Runnable runnable, Executor executor, RunnableExecutorPair next) {
- this.runnable = runnable;
- this.executor = executor;
- this.next = next;
- }
- }
-}
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 572296c..e2431f2 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
@@ -38,7 +38,7 @@ public class ConfigurationUtils {
public static int getServerShutdownTimeout() {
int timeout = Constants.DEFAULT_SERVER_SHUTDOWN_TIMEOUT;
Configuration configuration = Environment.getInstance().getConfiguration();
- String value = configuration.getString(Constants.SHUTDOWN_WAIT_KEY);
+ String value = StringUtils.trim(configuration.getString(Constants.SHUTDOWN_WAIT_KEY));
if (value != null && value.length() > 0) {
try {
@@ -47,7 +47,7 @@ public class ConfigurationUtils {
// ignore
}
} else {
- value = configuration.getString(Constants.SHUTDOWN_WAIT_SECONDS_KEY);
+ value = StringUtils.trim(configuration.getString(Constants.SHUTDOWN_WAIT_SECONDS_KEY));
if (value != null && value.length() > 0) {
try {
timeout = Integer.parseInt(value) * 1000;
@@ -64,7 +64,7 @@ public class ConfigurationUtils {
}
public static String getProperty(String property, String defaultValue) {
- return Environment.getInstance().getConfiguration().getString(property, defaultValue);
+ return StringUtils.trim(Environment.getInstance().getConfiguration().getString(property, defaultValue));
}
public static Map<String, String> parseProperties(String content) throws IOException {
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
new file mode 100644
index 0000000..fcce47f
--- /dev/null
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/AdaptiveClassCodeGenerator.java
@@ -0,0 +1,381 @@
+/*
+ * 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.common.extension;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.Parameter;
+import java.util.Arrays;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.LoggerFactory;
+import org.apache.dubbo.common.utils.StringUtils;
+
+/**
+ * Code generator for Adaptive class
+ */
+public class AdaptiveClassCodeGenerator {
+
+ private static final Logger logger = LoggerFactory.getLogger(AdaptiveClassCodeGenerator.class);
+
+ private static final String CLASSNAME_INVOCATION = "org.apache.dubbo.rpc.Invocation";
+
+ private static final String CODE_PACKAGE = "package %s;\n";
+
+ private static final String CODE_IMPORTS = "import %s;\n";
+
+ private static final String CODE_CLASS_DECLARATION = "public class %s$Adaptive implements %s {\n";
+
+ private static final String CODE_METHOD_DECLARATION = "public %s %s(%s) %s {\n%s}\n";
+
+ private static final String CODE_METHOD_ARGUMENT = "%s arg%d";
+
+ 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_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";
+
+ 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_EXTENSION_ASSIGNMENT = "%s extension = (%<s)%s.getExtensionLoader(%s.class).getExtension(extName);\n";
+
+ private final Class<?> type;
+
+ private String defaultExtName;
+
+ public AdaptiveClassCodeGenerator(Class<?> type, String defaultExtName) {
+ this.type = type;
+ this.defaultExtName = defaultExtName;
+ }
+
+ /**
+ * test if given type has at least one method annotated with <code>SPI</code>
+ */
+ private boolean hasAdaptiveMethod() {
+ return Arrays.stream(type.getMethods()).anyMatch(m -> m.isAnnotationPresent(Adaptive.class));
+ }
+
+ /**
+ * generate and return class code
+ */
+ public String generate() {
+ // no need to generate adaptive class since there's no adaptive method found.
+ if (!hasAdaptiveMethod()) {
+ throw new IllegalStateException("No adaptive method exist on extension " + type.getName() + ", refuse to create the adaptive class!");
+ }
+
+ StringBuilder code = new StringBuilder();
+ code.append(generatePackageInfo());
+ code.append(generateImports());
+ code.append(generateClassDeclaration());
+
+ Method[] methods = type.getMethods();
+ for (Method method : methods) {
+ code.append(generateMethod(method));
+ }
+ code.append("}");
+
+ if (logger.isDebugEnabled()) {
+ logger.debug(code.toString());
+ }
+ return code.toString();
+ }
+
+ /**
+ * generate package info
+ */
+ private String generatePackageInfo() {
+ return String.format(CODE_PACKAGE, type.getPackage().getName());
+ }
+
+ /**
+ * generate imports
+ */
+ private String generateImports() {
+ return String.format(CODE_IMPORTS, ExtensionLoader.class.getName());
+ }
+
+ /**
+ * generate class declaration
+ */
+ private String generateClassDeclaration() {
+ return String.format(CODE_CLASS_DECLARATION, type.getSimpleName(), type.getCanonicalName());
+ }
+
+ /**
+ * generate method not annotated with Adaptive with throwing unsupported exception
+ */
+ private String generateUnsupported(Method method) {
+ return String.format(CODE_UNSUPPORTED, method, type.getName());
+ }
+
+ /**
+ * get index of parameter with type URL
+ */
+ private int getUrlTypeIndex(Method method) {
+ int urlTypeIndex = -1;
+ Class<?>[] pts = method.getParameterTypes();
+ for (int i = 0; i < pts.length; ++i) {
+ if (pts[i].equals(URL.class)) {
+ urlTypeIndex = i;
+ break;
+ }
+ }
+ return urlTypeIndex;
+ }
+
+ /**
+ * generate method declaration
+ */
+ private String generateMethod(Method method) {
+ String methodReturnType = method.getReturnType().getCanonicalName();
+ String methodName = method.getName();
+ String methodContent = generateMethodContent(method);
+ String methodArgs = generateMethodArguments(method);
+ String methodThrows = generateMethodThrows(method);
+ return String.format(CODE_METHOD_DECLARATION, methodReturnType, methodName, methodArgs, methodThrows, methodContent);
+ }
+
+ /**
+ * generate method arguments
+ */
+ private String generateMethodArguments(Method method) {
+ Class<?>[] pts = method.getParameterTypes();
+ return IntStream.range(0, pts.length)
+ .mapToObj(i -> String.format(CODE_METHOD_ARGUMENT, pts[i].getCanonicalName(), i))
+ .collect(Collectors.joining(", "));
+ }
+
+ /**
+ * generate method throws
+ */
+ private String generateMethodThrows(Method method) {
+ Class<?>[] ets = method.getExceptionTypes();
+ if (ets.length > 0) {
+ String list = Arrays.stream(ets).map(Class::getCanonicalName).collect(Collectors.joining(", "));
+ return String.format(CODE_METHOD_THROWS, list);
+ } else {
+ return "";
+ }
+ }
+
+ /**
+ * generate method URL argument null check
+ */
+ private String generateUrlNullCheck(int index) {
+ return String.format(CODE_URL_NULL_CHECK, index, URL.class.getName(), index);
+ }
+
+ /**
+ * generate method content
+ */
+ private String generateMethodContent(Method method) {
+ Adaptive adaptiveAnnotation = method.getAnnotation(Adaptive.class);
+ StringBuilder code = new StringBuilder(512);
+ if (adaptiveAnnotation == null) {
+ return generateUnsupported(method);
+ } else {
+ int urlTypeIndex = getUrlTypeIndex(method);
+
+ // found parameter in URL type
+ if (urlTypeIndex != -1) {
+ // Null Point check
+ code.append(generateUrlNullCheck(urlTypeIndex));
+ } else {
+ // did not find parameter in URL type
+ code.append(generateUrlAssignmentIndirectly(method));
+ }
+
+ String[] value = getMethodAdaptiveValue(adaptiveAnnotation);
+
+ boolean hasInvocation = hasInvocationArgument(method);
+
+ code.append(generateInvocationArgumentNullCheck(method));
+
+ code.append(generateExtNameAssignment(value, hasInvocation));
+ // check extName == null?
+ code.append(generateExtNameNullCheck(value));
+
+ code.append(generateExtensionAssignment());
+
+ // return statement
+ code.append(generateReturnAndInovation(method));
+ }
+
+ return code.toString();
+ }
+
+ /**
+ * generate code for variable extName null check
+ */
+ private String generateExtNameNullCheck(String[] value) {
+ return String.format(CODE_EXT_NAME_NULL_CHECK, type.getName(), Arrays.toString(value));
+ }
+
+ /**
+ * generate extName assigment code
+ */
+ private String generateExtNameAssignment(String[] value, boolean hasInvocation) {
+ // TODO: refactor it
+ String getNameCode = null;
+ for (int i = value.length - 1; i >= 0; --i) {
+ if (i == value.length - 1) {
+ if (null != defaultExtName) {
+ if (!"protocol".equals(value[i])) {
+ if (hasInvocation) {
+ 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);
+ }
+ } else {
+ if (!"protocol".equals(value[i])) {
+ if (hasInvocation) {
+ getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName);
+ } else {
+ getNameCode = String.format("url.getParameter(\"%s\")", value[i]);
+ }
+ } else {
+ getNameCode = "url.getProtocol()";
+ }
+ }
+ } else {
+ if (!"protocol".equals(value[i])) {
+ if (hasInvocation) {
+ getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName);
+ } else {
+ getNameCode = String.format("url.getParameter(\"%s\", %s)", value[i], getNameCode);
+ }
+ } else {
+ getNameCode = String.format("url.getProtocol() == null ? (%s) : url.getProtocol()", getNameCode);
+ }
+ }
+ }
+
+ return String.format(CODE_EXT_NAME_ASSIGNMENT, getNameCode);
+ }
+
+ /**
+ * @return
+ */
+ private String generateExtensionAssignment() {
+ return String.format(CODE_EXTENSION_ASSIGNMENT, type.getName(), ExtensionLoader.class.getSimpleName(), type.getName());
+ }
+
+ /**
+ * generate method invocation statement and return it if necessary
+ */
+ private String generateReturnAndInovation(Method method) {
+ String returnStatement = method.getReturnType().equals(void.class) ? "" : "return ";
+
+ String args = Arrays.stream(method.getParameters()).map(Parameter::getName).collect(Collectors.joining(", "));
+
+ return returnStatement + String.format("extension.%s(%s);\n", method.getName(), args);
+ }
+
+ /**
+ * test if method has argument of type <code>Invocation</code>
+ */
+ private boolean hasInvocationArgument(Method method) {
+ Class<?>[] pts = method.getParameterTypes();
+ return Arrays.stream(pts).anyMatch(p -> CLASSNAME_INVOCATION.equals(p.getName()));
+ }
+
+ /**
+ * generate code to test argument of type <code>Invocation</code> is null
+ */
+ private String generateInvocationArgumentNullCheck(Method method) {
+ Class<?>[] pts = method.getParameterTypes();
+ return IntStream.range(0, pts.length).filter(i -> CLASSNAME_INVOCATION.equals(pts[i].getName()))
+ .mapToObj(i -> String.format(CODE_INVOCATION_ARGUMENT_NULL_CHECK, i, i))
+ .findFirst().orElse("");
+ }
+
+ /**
+ * get value of adaptive annotation or if empty return splitted simple name
+ */
+ private String[] getMethodAdaptiveValue(Adaptive adaptiveAnnotation) {
+ String[] value = adaptiveAnnotation.value();
+ // 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};
+ }
+ return value;
+ }
+
+ /**
+ * get parameter with type <code>URL</code> from method parameter:
+ * <p>
+ * test if parameter has method which returns type <code>URL</code>
+ * <p>
+ * if not found, throws IllegalStateException
+ */
+ private String generateUrlAssignmentIndirectly(Method method) {
+ Class<?>[] pts = method.getParameterTypes();
+
+ // find URL getter method
+ for (int i = 0; i < pts.length; ++i) {
+ for (Method m : pts[i].getMethods()) {
+ String name = m.getName();
+ if ((name.startsWith("get") || name.length() > 3)
+ && Modifier.isPublic(m.getModifiers())
+ && !Modifier.isStatic(m.getModifiers())
+ && m.getParameterTypes().length == 0
+ && m.getReturnType() == URL.class) {
+ return generateGetUrlNullCheck(i, pts[i], name);
+ }
+ }
+ }
+
+ // getter method not found, throw
+ throw new IllegalStateException("Failed to create adaptive class for interface " + type.getName()
+ + ": not found url parameter or url attribute in parameters of method " + method.getName());
+
+ }
+
+ /**
+ * 1, test if argi is null
+ * 2, test if argi.getXX() returns null
+ * 3, assign url with argi.getXX()
+ */
+ 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",
+ index, type.getName()));
+ 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/ExtensionLoader.java b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionLoader.java
index 578ff65..3f2709e 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
@@ -21,17 +21,19 @@ import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.support.ActivateComparator;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
+import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.common.utils.ClassHelper;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import org.apache.dubbo.common.utils.ConfigUtils;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.common.utils.StringUtils;
-
+import org.apache.dubbo.common.utils.CollectionUtils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -70,9 +72,9 @@ public class ExtensionLoader<T> {
private static final Pattern NAME_SEPARATOR = Pattern.compile("\\s*[,]+\\s*");
- private static final ConcurrentMap<Class<?>, ExtensionLoader<?>> EXTENSION_LOADERS = new ConcurrentHashMap<Class<?>, ExtensionLoader<?>>();
+ private static final ConcurrentMap<Class<?>, ExtensionLoader<?>> EXTENSION_LOADERS = new ConcurrentHashMap<>();
- private static final ConcurrentMap<Class<?>, Object> EXTENSION_INSTANCES = new ConcurrentHashMap<Class<?>, Object>();
+ private static final ConcurrentMap<Class<?>, Object> EXTENSION_INSTANCES = new ConcurrentHashMap<>();
// ==============================
@@ -80,20 +82,20 @@ public class ExtensionLoader<T> {
private final ExtensionFactory objectFactory;
- private final ConcurrentMap<Class<?>, String> cachedNames = new ConcurrentHashMap<Class<?>, String>();
+ private final ConcurrentMap<Class<?>, String> cachedNames = new ConcurrentHashMap<>();
- private final Holder<Map<String, Class<?>>> cachedClasses = new Holder<Map<String, Class<?>>>();
+ private final Holder<Map<String, Class<?>>> cachedClasses = new Holder<>();
- private final Map<String, Object> cachedActivates = new ConcurrentHashMap<String, Object>();
- private final ConcurrentMap<String, Holder<Object>> cachedInstances = new ConcurrentHashMap<String, Holder<Object>>();
- private final Holder<Object> cachedAdaptiveInstance = new Holder<Object>();
+ private final Map<String, Object> cachedActivates = new ConcurrentHashMap<>();
+ private final ConcurrentMap<String, Holder<Object>> cachedInstances = new ConcurrentHashMap<>();
+ private final Holder<Object> cachedAdaptiveInstance = new Holder<>();
private volatile Class<?> cachedAdaptiveClass = null;
private String cachedDefaultName;
private volatile Throwable createAdaptiveInstanceError;
private Set<Class<?>> cachedWrapperClasses;
- private Map<String, IllegalStateException> exceptions = new ConcurrentHashMap<String, IllegalStateException>();
+ private Map<String, IllegalStateException> exceptions = new ConcurrentHashMap<>();
private ExtensionLoader(Class<?> type) {
this.type = type;
@@ -110,11 +112,11 @@ public class ExtensionLoader<T> {
throw new IllegalArgumentException("Extension type == null");
}
if (!type.isInterface()) {
- throw new IllegalArgumentException("Extension type(" + type + ") is not interface!");
+ throw new IllegalArgumentException("Extension type (" + type + ") is not an interface!");
}
if (!withExtensionAnnotation(type)) {
- throw new IllegalArgumentException("Extension type(" + type +
- ") is not extension, because WITHOUT @" + SPI.class.getSimpleName() + " Annotation!");
+ throw new IllegalArgumentException("Extension type (" + type +
+ ") is not an extension, because it is NOT annotated with @" + SPI.class.getSimpleName() + "!");
}
ExtensionLoader<T> loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
@@ -187,7 +189,7 @@ public class ExtensionLoader<T> {
*/
public List<T> getActivateExtension(URL url, String key, String group) {
String value = url.getParameter(key);
- return getActivateExtension(url, value == null || value.length() == 0 ? null : Constants.COMMA_SPLIT_PATTERN.split(value), group);
+ return getActivateExtension(url, StringUtils.isEmpty(value) ? null : Constants.COMMA_SPLIT_PATTERN.split(value), group);
}
/**
@@ -200,8 +202,8 @@ public class ExtensionLoader<T> {
* @see org.apache.dubbo.common.extension.Activate
*/
public List<T> getActivateExtension(URL url, String[] values, String group) {
- List<T> exts = new ArrayList<T>();
- List<String> names = values == null ? new ArrayList<String>(0) : Arrays.asList(values);
+ List<T> exts = new ArrayList<>();
+ List<String> names = values == null ? new ArrayList<>(0) : Arrays.asList(values);
if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) {
getExtensionClasses();
for (Map.Entry<String, Object> entry : cachedActivates.entrySet()) {
@@ -228,9 +230,9 @@ public class ExtensionLoader<T> {
}
}
}
- Collections.sort(exts, ActivateComparator.COMPARATOR);
+ exts.sort(ActivateComparator.COMPARATOR);
}
- List<T> usrs = new ArrayList<T>();
+ List<T> usrs = new ArrayList<>();
for (int i = 0; i < names.size(); i++) {
String name = names.get(i);
if (!name.startsWith(Constants.REMOVE_VALUE_PREFIX)
@@ -253,7 +255,7 @@ public class ExtensionLoader<T> {
}
private boolean isMatchGroup(String group, String[] groups) {
- if (group == null || group.length() == 0) {
+ if (StringUtils.isEmpty(group)) {
return true;
}
if (groups != null && groups.length > 0) {
@@ -293,15 +295,20 @@ public class ExtensionLoader<T> {
*/
@SuppressWarnings("unchecked")
public T getLoadedExtension(String name) {
- if (name == null || name.length() == 0) {
+ if (StringUtils.isEmpty(name)) {
throw new IllegalArgumentException("Extension name == null");
}
+ Holder<Object> holder = getOrCreateHolder(name);
+ return (T) holder.get();
+ }
+
+ private Holder<Object> getOrCreateHolder(String name) {
Holder<Object> holder = cachedInstances.get(name);
if (holder == null) {
- cachedInstances.putIfAbsent(name, new Holder<Object>());
+ cachedInstances.putIfAbsent(name, new Holder<>());
holder = cachedInstances.get(name);
}
- return (T) holder.get();
+ return holder;
}
/**
@@ -312,7 +319,7 @@ public class ExtensionLoader<T> {
* @see #getSupportedExtensions()
*/
public Set<String> getLoadedExtensions() {
- return Collections.unmodifiableSet(new TreeSet<String>(cachedInstances.keySet()));
+ return Collections.unmodifiableSet(new TreeSet<>(cachedInstances.keySet()));
}
public Object getLoadedAdaptiveExtensionInstances() {
@@ -325,17 +332,13 @@ public class ExtensionLoader<T> {
*/
@SuppressWarnings("unchecked")
public T getExtension(String name) {
- if (name == null || name.length() == 0) {
+ if (StringUtils.isEmpty(name)) {
throw new IllegalArgumentException("Extension name == null");
}
if ("true".equals(name)) {
return getDefaultExtension();
}
- Holder<Object> holder = cachedInstances.get(name);
- if (holder == null) {
- cachedInstances.putIfAbsent(name, new Holder<Object>());
- holder = cachedInstances.get(name);
- }
+ Holder<Object> holder = getOrCreateHolder(name);
Object instance = holder.get();
if (instance == null) {
synchronized (holder) {
@@ -354,15 +357,14 @@ public class ExtensionLoader<T> {
*/
public T getDefaultExtension() {
getExtensionClasses();
- if (null == cachedDefaultName || cachedDefaultName.length() == 0
- || "true".equals(cachedDefaultName)) {
+ if (StringUtils.isBlank(cachedDefaultName) || "true".equals(cachedDefaultName)) {
return null;
}
return getExtension(cachedDefaultName);
}
public boolean hasExtension(String name) {
- if (name == null || name.length() == 0) {
+ if (StringUtils.isEmpty(name)) {
throw new IllegalArgumentException("Extension name == null");
}
Class<?> c = this.getExtensionClass(name);
@@ -371,7 +373,7 @@ public class ExtensionLoader<T> {
public Set<String> getSupportedExtensions() {
Map<String, Class<?>> clazzes = getExtensionClasses();
- return Collections.unmodifiableSet(new TreeSet<String>(clazzes.keySet()));
+ return Collections.unmodifiableSet(new TreeSet<>(clazzes.keySet()));
}
/**
@@ -394,11 +396,11 @@ public class ExtensionLoader<T> {
if (!type.isAssignableFrom(clazz)) {
throw new IllegalStateException("Input type " +
- clazz + "not implement Extension " + type);
+ clazz + " doesn't implement the Extension " + type);
}
if (clazz.isInterface()) {
throw new IllegalStateException("Input type " +
- clazz + "can not be interface!");
+ clazz + " can't be interface!");
}
if (!clazz.isAnnotationPresent(Adaptive.class)) {
@@ -407,14 +409,14 @@ public class ExtensionLoader<T> {
}
if (cachedClasses.get().containsKey(name)) {
throw new IllegalStateException("Extension name " +
- name + " already existed(Extension " + type + ")!");
+ name + " already exists (Extension " + type + ")!");
}
cachedNames.put(clazz, name);
cachedClasses.get().put(name, clazz);
} else {
if (cachedAdaptiveClass != null) {
- throw new IllegalStateException("Adaptive Extension already existed(Extension " + type + ")!");
+ throw new IllegalStateException("Adaptive Extension already exists (Extension " + type + ")!");
}
cachedAdaptiveClass = clazz;
@@ -435,11 +437,11 @@ public class ExtensionLoader<T> {
if (!type.isAssignableFrom(clazz)) {
throw new IllegalStateException("Input type " +
- clazz + "not implement Extension " + type);
+ clazz + " doesn't implement Extension " + type);
}
if (clazz.isInterface()) {
throw new IllegalStateException("Input type " +
- clazz + "can not be interface!");
+ clazz + " can't be interface!");
}
if (!clazz.isAnnotationPresent(Adaptive.class)) {
@@ -448,7 +450,7 @@ public class ExtensionLoader<T> {
}
if (!cachedClasses.get().containsKey(name)) {
throw new IllegalStateException("Extension name " +
- name + " not existed(Extension " + type + ")!");
+ name + " doesn't exist (Extension " + type + ")!");
}
cachedNames.put(clazz, name);
@@ -456,7 +458,7 @@ public class ExtensionLoader<T> {
cachedInstances.remove(name);
} else {
if (cachedAdaptiveClass == null) {
- throw new IllegalStateException("Adaptive Extension not existed(Extension " + type + ")!");
+ throw new IllegalStateException("Adaptive Extension doesn't exist (Extension " + type + ")!");
}
cachedAdaptiveClass = clazz;
@@ -477,12 +479,12 @@ public class ExtensionLoader<T> {
cachedAdaptiveInstance.set(instance);
} catch (Throwable t) {
createAdaptiveInstanceError = t;
- throw new IllegalStateException("fail to create adaptive instance: " + t.toString(), t);
+ throw new IllegalStateException("Failed to create adaptive instance: " + t.toString(), t);
}
}
}
} else {
- throw new IllegalStateException("fail to create adaptive instance: " + createAdaptiveInstanceError.toString(), createAdaptiveInstanceError);
+ throw new IllegalStateException("Failed to create adaptive instance: " + createAdaptiveInstanceError.toString(), createAdaptiveInstanceError);
}
}
@@ -528,15 +530,15 @@ public class ExtensionLoader<T> {
}
injectExtension(instance);
Set<Class<?>> wrapperClasses = cachedWrapperClasses;
- if (wrapperClasses != null && !wrapperClasses.isEmpty()) {
+ if (CollectionUtils.isNotEmpty(wrapperClasses)) {
for (Class<?> wrapperClass : wrapperClasses) {
instance = injectExtension((T) wrapperClass.getConstructor(type).newInstance(instance));
}
}
return instance;
} catch (Throwable t) {
- throw new IllegalStateException("Extension instance(name: " + name + ", class: " +
- type + ") could not be instantiated: " + t.getMessage(), t);
+ throw new IllegalStateException("Extension instance (name: " + name + ", class: " +
+ type + ") couldn't be instantiated: " + t.getMessage(), t);
}
}
@@ -544,9 +546,7 @@ public class ExtensionLoader<T> {
try {
if (objectFactory != null) {
for (Method method : instance.getClass().getMethods()) {
- if (method.getName().startsWith("set")
- && method.getParameterTypes().length == 1
- && Modifier.isPublic(method.getModifiers())) {
+ if (isSetter(method)) {
/**
* Check {@link DisableInject} to see if we need auto injection for this property
*/
@@ -558,13 +558,13 @@ public class ExtensionLoader<T> {
continue;
}
try {
- String property = method.getName().length() > 3 ? method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4) : "";
+ String property = getSetterProperty(method);
Object object = objectFactory.getExtension(pt, property);
if (object != null) {
method.invoke(instance, object);
}
} catch (Exception e) {
- logger.error("fail to inject via method " + method.getName()
+ logger.error("Failed to inject via method " + method.getName()
+ " of interface " + type.getName() + ": " + e.getMessage(), e);
}
}
@@ -576,6 +576,30 @@ public class ExtensionLoader<T> {
return instance;
}
+ /**
+ * get properties name for setter, for instance: setVersion, return "version"
+ * <p>
+ * 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 true if and only if:
+ * <p>
+ * 1, public
+ * <p>
+ * 2, name starts with "set"
+ * <p>
+ * 3, only has one parameter
+ */
+ private boolean isSetter(Method method) {
+ return method.getName().startsWith("set")
+ && method.getParameterTypes().length == 1
+ && Modifier.isPublic(method.getModifiers());
+ }
+
private Class<?> getExtensionClass(String name) {
if (type == null) {
throw new IllegalArgumentException("Extension type == null");
@@ -602,13 +626,29 @@ public class ExtensionLoader<T> {
// synchronized in getExtensionClasses
private Map<String, Class<?>> loadExtensionClasses() {
+ cacheDefaultExtensionName();
+
+ Map<String, Class<?>> extensionClasses = new HashMap<>();
+ loadDirectory(extensionClasses, DUBBO_INTERNAL_DIRECTORY, type.getName());
+ loadDirectory(extensionClasses, DUBBO_INTERNAL_DIRECTORY, type.getName().replace("org.apache", "com.alibaba"));
+ loadDirectory(extensionClasses, DUBBO_DIRECTORY, type.getName());
+ loadDirectory(extensionClasses, DUBBO_DIRECTORY, type.getName().replace("org.apache", "com.alibaba"));
+ loadDirectory(extensionClasses, SERVICES_DIRECTORY, type.getName());
+ loadDirectory(extensionClasses, SERVICES_DIRECTORY, type.getName().replace("org.apache", "com.alibaba"));
+ return extensionClasses;
+ }
+
+ /**
+ * extract and cache default extension name if exists
+ */
+ private void cacheDefaultExtensionName() {
final SPI defaultAnnotation = type.getAnnotation(SPI.class);
if (defaultAnnotation != null) {
String value = defaultAnnotation.value();
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()
+ throw new IllegalStateException("More than 1 default extension name on extension " + type.getName()
+ ": " + Arrays.toString(names));
}
if (names.length == 1) {
@@ -616,15 +656,6 @@ public class ExtensionLoader<T> {
}
}
}
-
- Map<String, Class<?>> extensionClasses = new HashMap<String, Class<?>>();
- loadDirectory(extensionClasses, DUBBO_INTERNAL_DIRECTORY, type.getName());
- loadDirectory(extensionClasses, DUBBO_INTERNAL_DIRECTORY, type.getName().replace("org.apache", "com.alibaba"));
- loadDirectory(extensionClasses, DUBBO_DIRECTORY, type.getName());
- loadDirectory(extensionClasses, DUBBO_DIRECTORY, type.getName().replace("org.apache", "com.alibaba"));
- loadDirectory(extensionClasses, SERVICES_DIRECTORY, type.getName());
- loadDirectory(extensionClasses, SERVICES_DIRECTORY, type.getName().replace("org.apache", "com.alibaba"));
- return extensionClasses;
}
private void loadDirectory(Map<String, Class<?>> extensionClasses, String dir, String type) {
@@ -644,15 +675,14 @@ public class ExtensionLoader<T> {
}
}
} catch (Throwable t) {
- logger.error("Exception when load extension class(interface: " +
+ logger.error("Exception occurred when loading extension class (interface: " +
type + ", description file: " + fileName + ").", t);
}
}
private void loadResource(Map<String, Class<?>> extensionClasses, ClassLoader classLoader, java.net.URL resourceURL) {
try {
- BufferedReader reader = new BufferedReader(new InputStreamReader(resourceURL.openStream(), "utf-8"));
- try {
+ try (BufferedReader reader = new BufferedReader(new InputStreamReader(resourceURL.openStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
final int ci = line.indexOf('#');
@@ -672,76 +702,117 @@ public class ExtensionLoader<T> {
loadClass(extensionClasses, resourceURL, Class.forName(line, true, classLoader), name);
}
} catch (Throwable t) {
- IllegalStateException e = new IllegalStateException("Failed to load extension class(interface: " + type + ", class line: " + line + ") in " + resourceURL + ", cause: " + t.getMessage(), t);
+ IllegalStateException e = new IllegalStateException("Failed to load extension class (interface: " + type + ", class line: " + line + ") in " + resourceURL + ", cause: " + t.getMessage(), t);
exceptions.put(line, e);
}
}
}
- } finally {
- reader.close();
}
} catch (Throwable t) {
- logger.error("Exception when load extension class(interface: " +
+ logger.error("Exception occurred when loading extension class (interface: " +
type + ", class file: " + resourceURL + ") in " + resourceURL, t);
}
}
private void loadClass(Map<String, Class<?>> extensionClasses, java.net.URL resourceURL, Class<?> clazz, String name) throws NoSuchMethodException {
if (!type.isAssignableFrom(clazz)) {
- throw new IllegalStateException("Error when load extension class(interface: " +
+ throw new IllegalStateException("Error occurred when loading extension class (interface: " +
type + ", class line: " + clazz.getName() + "), class "
- + clazz.getName() + "is not subtype of interface.");
+ + clazz.getName() + " is not subtype of interface.");
}
if (clazz.isAnnotationPresent(Adaptive.class)) {
- if (cachedAdaptiveClass == null) {
- cachedAdaptiveClass = clazz;
- } else if (!cachedAdaptiveClass.equals(clazz)) {
- throw new IllegalStateException("More than 1 adaptive class found: "
- + cachedAdaptiveClass.getClass().getName()
- + ", " + clazz.getClass().getName());
- }
+ cacheAdaptiveClass(clazz);
} else if (isWrapperClass(clazz)) {
- Set<Class<?>> wrappers = cachedWrapperClasses;
- if (wrappers == null) {
- cachedWrapperClasses = new ConcurrentHashSet<Class<?>>();
- wrappers = cachedWrapperClasses;
- }
- wrappers.add(clazz);
+ cacheWrapperClass(clazz);
} else {
clazz.getConstructor();
- if (name == null || name.length() == 0) {
+ 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);
}
}
+
String[] names = NAME_SEPARATOR.split(name);
- if (names != null && names.length > 0) {
- Activate activate = clazz.getAnnotation(Activate.class);
- if (activate != null) {
- cachedActivates.put(names[0], activate);
- } else {
- // support com.alibaba.dubbo.common.extension.Activate
- com.alibaba.dubbo.common.extension.Activate oldActivate = clazz.getAnnotation(com.alibaba.dubbo.common.extension.Activate.class);
- if (oldActivate != null) {
- cachedActivates.put(names[0], oldActivate);
- }
- }
+ if (ArrayUtils.isNotEmpty(names)) {
+ cacheActivateClass(clazz, names[0]);
for (String n : names) {
- if (!cachedNames.containsKey(clazz)) {
- cachedNames.put(clazz, n);
- }
- Class<?> c = extensionClasses.get(n);
- if (c == null) {
- extensionClasses.put(n, clazz);
- } else if (c != clazz) {
- throw new IllegalStateException("Duplicate extension " + type.getName() + " name " + n + " on " + c.getName() + " and " + clazz.getName());
- }
+ cacheName(clazz, n);
+ saveInExtensionClass(extensionClasses, clazz, name);
}
}
}
}
+ /**
+ * cache name
+ */
+ private void cacheName(Class<?> clazz, String name) {
+ if (!cachedNames.containsKey(clazz)) {
+ cachedNames.put(clazz, name);
+ }
+ }
+
+ /**
+ * put clazz in extensionClasses
+ */
+ private void saveInExtensionClass(Map<String, Class<?>> extensionClasses, Class<?> clazz, String name) {
+ Class<?> c = extensionClasses.get(name);
+ if (c == null) {
+ extensionClasses.put(name, clazz);
+ } else if (c != clazz) {
+ throw new IllegalStateException("Duplicate extension " + type.getName() + " name " + name + " on " + c.getName() + " and " + clazz.getName());
+ }
+ }
+
+ /**
+ * cache Activate class which is annotated with <code>Activate</code>
+ * <p>
+ * for compatibility, also cache class with old alibaba Activate annotation
+ */
+ private void cacheActivateClass(Class<?> clazz, String name) {
+ Activate activate = clazz.getAnnotation(Activate.class);
+ if (activate != null) {
+ cachedActivates.put(name, activate);
+ } else {
+ // support com.alibaba.dubbo.common.extension.Activate
+ com.alibaba.dubbo.common.extension.Activate oldActivate = clazz.getAnnotation(com.alibaba.dubbo.common.extension.Activate.class);
+ if (oldActivate != null) {
+ cachedActivates.put(name, oldActivate);
+ }
+ }
+ }
+
+ /**
+ * cache Adaptive class which is annotated with <code>Adaptive</code>
+ */
+ private void cacheAdaptiveClass(Class<?> clazz) {
+ if (cachedAdaptiveClass == null) {
+ cachedAdaptiveClass = clazz;
+ } else if (!cachedAdaptiveClass.equals(clazz)) {
+ throw new IllegalStateException("More than 1 adaptive class found: "
+ + cachedAdaptiveClass.getClass().getName()
+ + ", " + clazz.getClass().getName());
+ }
+ }
+
+ /**
+ * cache wrapper class
+ * <p>
+ * like: ProtocolFilterWrapper, ProtocolListenerWrapper
+ */
+ private void cacheWrapperClass(Class<?> clazz) {
+ if (cachedWrapperClasses == null) {
+ cachedWrapperClasses = new ConcurrentHashSet<>();
+ }
+ cachedWrapperClasses.add(clazz);
+ }
+
+ /**
+ * test if clazz is a wrapper class
+ * <p>
+ * which has Constructor with given class type as its only argument
+ */
private boolean isWrapperClass(Class<?> clazz) {
try {
clazz.getConstructor(type);
@@ -769,7 +840,7 @@ public class ExtensionLoader<T> {
try {
return injectExtension((T) getAdaptiveExtensionClass().newInstance());
} catch (Exception e) {
- throw new IllegalStateException("Can not create adaptive extension " + type + ", cause: " + e.getMessage(), e);
+ throw new IllegalStateException("Can't create adaptive extension " + type + ", cause: " + e.getMessage(), e);
}
}
@@ -782,212 +853,12 @@ public class ExtensionLoader<T> {
}
private Class<?> createAdaptiveExtensionClass() {
- String code = createAdaptiveExtensionClassCode();
+ String code = new AdaptiveClassCodeGenerator(type, cachedDefaultName).generate();
ClassLoader classLoader = findClassLoader();
org.apache.dubbo.common.compiler.Compiler compiler = ExtensionLoader.getExtensionLoader(org.apache.dubbo.common.compiler.Compiler.class).getAdaptiveExtension();
return compiler.compile(code, classLoader);
}
- private String createAdaptiveExtensionClassCode() {
- StringBuilder codeBuilder = new StringBuilder();
- Method[] methods = type.getMethods();
- boolean hasAdaptiveAnnotation = false;
- for (Method m : methods) {
- if (m.isAnnotationPresent(Adaptive.class)) {
- hasAdaptiveAnnotation = true;
- break;
- }
- }
- // no need to generate adaptive class since there's no adaptive method found.
- if (!hasAdaptiveAnnotation) {
- throw new IllegalStateException("No adaptive method on extension " + type.getName() + ", refuse to create the adaptive class!");
- }
-
- codeBuilder.append("package ").append(type.getPackage().getName()).append(";");
- codeBuilder.append("\nimport ").append(ExtensionLoader.class.getName()).append(";");
- codeBuilder.append("\npublic class ").append(type.getSimpleName()).append("$Adaptive").append(" implements ").append(type.getCanonicalName()).append(" {");
-
- for (Method method : methods) {
- Class<?> rt = method.getReturnType();
- Class<?>[] pts = method.getParameterTypes();
- Class<?>[] ets = method.getExceptionTypes();
-
- Adaptive adaptiveAnnotation = method.getAnnotation(Adaptive.class);
- StringBuilder code = new StringBuilder(512);
- if (adaptiveAnnotation == null) {
- code.append("throw new UnsupportedOperationException(\"method ")
- .append(method.toString()).append(" of interface ")
- .append(type.getName()).append(" is not adaptive method!\");");
- } else {
- int urlTypeIndex = -1;
- for (int i = 0; i < pts.length; ++i) {
- if (pts[i].equals(URL.class)) {
- urlTypeIndex = i;
- break;
- }
- }
- // found parameter in URL type
- if (urlTypeIndex != -1) {
- // Null Point check
- String s = String.format("\nif (arg%d == null) throw new IllegalArgumentException(\"url == null\");",
- urlTypeIndex);
- code.append(s);
-
- s = String.format("\n%s url = arg%d;", URL.class.getName(), urlTypeIndex);
- code.append(s);
- }
- // did not find parameter in URL type
- else {
- String attribMethod = null;
-
- // find URL getter method
- LBL_PTS:
- for (int i = 0; i < pts.length; ++i) {
- Method[] ms = pts[i].getMethods();
- for (Method m : ms) {
- String name = m.getName();
- if ((name.startsWith("get") || name.length() > 3)
- && Modifier.isPublic(m.getModifiers())
- && !Modifier.isStatic(m.getModifiers())
- && m.getParameterTypes().length == 0
- && m.getReturnType() == URL.class) {
- urlTypeIndex = i;
- attribMethod = name;
- break LBL_PTS;
- }
- }
- }
- if (attribMethod == null) {
- throw new IllegalStateException("fail to create adaptive class for interface " + type.getName()
- + ": not found url parameter or url attribute in parameters of method " + method.getName());
- }
-
- // Null point check
- String s = String.format("\nif (arg%d == null) throw new IllegalArgumentException(\"%s argument == null\");",
- urlTypeIndex, pts[urlTypeIndex].getName());
- code.append(s);
- s = String.format("\nif (arg%d.%s() == null) throw new IllegalArgumentException(\"%s argument %s() == null\");",
- urlTypeIndex, attribMethod, pts[urlTypeIndex].getName(), attribMethod);
- code.append(s);
-
- s = String.format("%s url = arg%d.%s();", URL.class.getName(), urlTypeIndex, attribMethod);
- code.append(s);
- }
-
- String[] value = adaptiveAnnotation.value();
- // 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};
- }
-
- boolean hasInvocation = false;
- for (int i = 0; i < pts.length; ++i) {
- if (("org.apache.dubbo.rpc.Invocation").equals(pts[i].getName())) {
- // Null Point check
- String s = String.format("\nif (arg%d == null) throw new IllegalArgumentException(\"invocation == null\");", i);
- code.append(s);
- s = String.format("\nString methodName = arg%d.getMethodName();", i);
- code.append(s);
- hasInvocation = true;
- break;
- }
- }
-
- String defaultExtName = cachedDefaultName;
- String getNameCode = null;
- for (int i = value.length - 1; i >= 0; --i) {
- if (i == value.length - 1) {
- if (null != defaultExtName) {
- if (!"protocol".equals(value[i])) {
- if (hasInvocation) {
- 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);
- }
- } else {
- if (!"protocol".equals(value[i])) {
- if (hasInvocation) {
- getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName);
- } else {
- getNameCode = String.format("url.getParameter(\"%s\")", value[i]);
- }
- } else {
- getNameCode = "url.getProtocol()";
- }
- }
- } else {
- if (!"protocol".equals(value[i])) {
- if (hasInvocation) {
- getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName);
- } else {
- getNameCode = String.format("url.getParameter(\"%s\", %s)", value[i], getNameCode);
- }
- } else {
- getNameCode = String.format("url.getProtocol() == null ? (%s) : url.getProtocol()", getNameCode);
- }
- }
- }
- code.append("\nString extName = ").append(getNameCode).append(";");
- // check extName == null?
- String s = String.format("\nif(extName == null) " +
- "throw new IllegalStateException(\"Fail to get extension(%s) name from url(\" + url.toString() + \") use keys(%s)\");",
- type.getName(), Arrays.toString(value));
- code.append(s);
-
- s = String.format("\n%s extension = (%<s)%s.getExtensionLoader(%s.class).getExtension(extName);",
- type.getName(), ExtensionLoader.class.getSimpleName(), type.getName());
- code.append(s);
-
- // return statement
- if (!rt.equals(void.class)) {
- code.append("\nreturn ");
- }
-
- s = String.format("extension.%s(", method.getName());
- code.append(s);
- for (int i = 0; i < pts.length; i++) {
- if (i != 0) {
- code.append(", ");
- }
- code.append("arg").append(i);
- }
- code.append(");");
- }
-
- codeBuilder.append("\npublic ").append(rt.getCanonicalName()).append(" ").append(method.getName()).append("(");
- for (int i = 0; i < pts.length; i++) {
- if (i > 0) {
- codeBuilder.append(", ");
- }
- codeBuilder.append(pts[i].getCanonicalName());
- codeBuilder.append(" ");
- codeBuilder.append("arg").append(i);
- }
- codeBuilder.append(")");
- if (ets.length > 0) {
- codeBuilder.append(" throws ");
- for (int i = 0; i < ets.length; i++) {
- if (i > 0) {
- codeBuilder.append(", ");
- }
- codeBuilder.append(ets[i].getCanonicalName());
- }
- }
- codeBuilder.append(" {");
- codeBuilder.append(code.toString());
- codeBuilder.append("\n}");
- }
- codeBuilder.append("\n}");
- if (logger.isDebugEnabled()) {
- logger.debug(codeBuilder.toString());
- }
- return codeBuilder.toString();
- }
-
@Override
public String toString() {
return this.getClass().getName() + "[" + type.getName() + "]";
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 766099f..5dcedc3 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
@@ -19,7 +19,9 @@ package org.apache.dubbo.common.extension.support;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.extension.SPI;
+import org.apache.dubbo.common.utils.ArrayUtils;
+import java.util.Arrays;
import java.util.Comparator;
/**
@@ -44,75 +46,92 @@ public class ActivateComparator implements Comparator<Object> {
return 0;
}
- // to support com.alibab.dubbo.common.extension.Activate
- String[] a1Before, a2Before, a1After, a2After;
- int a1Order, a2Order;
- Class<?> inf = null;
- if (o1.getClass().getInterfaces().length > 0) {
- inf = o1.getClass().getInterfaces()[0];
+ Class<?> inf = findSpi(o1.getClass());
- if (inf.getInterfaces().length > 0) {
- inf = inf.getInterfaces()[0];
- }
- }
+ ActivateInfo a1 = parseActivate(o1.getClass());
+ ActivateInfo a2 = parseActivate(o2.getClass());
- Activate a1 = o1.getClass().getAnnotation(Activate.class);
- if (a1 != null) {
- a1Before = a1.before();
- a1After = a1.after();
- a1Order = a1.order();
- } else {
- com.alibaba.dubbo.common.extension.Activate oa1 = o1.getClass().getAnnotation(com.alibaba.dubbo.common.extension.Activate.class);
- a1Before = oa1.before();
- a1After = oa1.after();
- a1Order = oa1.order();
- }
- Activate a2 = o2.getClass().getAnnotation(Activate.class);
- if (a2 != null) {
- a2Before = a2.before();
- a2After = a2.after();
- a2Order = a2.order();
- } else {
- com.alibaba.dubbo.common.extension.Activate oa2 = o2.getClass().getAnnotation(com.alibaba.dubbo.common.extension.Activate.class);
- a2Before = oa2.before();
- a2After = oa2.after();
- a2Order = oa2.order();
- }
- if ((a1Before.length > 0 || a1After.length > 0
- || a2Before.length > 0 || a2After.length > 0)
- && inf != null && inf.isAnnotationPresent(SPI.class)) {
+ if ((a1.applicableToCompare() || a2.applicableToCompare()) && inf != null) {
ExtensionLoader<?> extensionLoader = ExtensionLoader.getExtensionLoader(inf);
- if (a1Before.length > 0 || a1After.length > 0) {
+ if (a1.applicableToCompare()) {
String n2 = extensionLoader.getExtensionName(o2.getClass());
- for (String before : a1Before) {
- if (before.equals(n2)) {
- return -1;
- }
+ if (a1.isLess(n2)) {
+ return -1;
}
- for (String after : a1After) {
- if (after.equals(n2)) {
- return 1;
- }
+
+ if (a1.isMore(n2)) {
+ return 1;
}
}
- if (a2Before.length > 0 || a2After.length > 0) {
+
+ if (a2.applicableToCompare()) {
String n1 = extensionLoader.getExtensionName(o1.getClass());
- for (String before : a2Before) {
- if (before.equals(n1)) {
- return 1;
- }
+ if (a2.isLess(n1)) {
+ return 1;
}
- for (String after : a2After) {
- if (after.equals(n1)) {
- return -1;
- }
+
+ if (a2.isMore(n1)) {
+ return -1;
}
}
}
- int n1 = a1 == null ? 0 : a1Order;
- int n2 = a2 == null ? 0 : a2Order;
+ int n1 = a1 == null ? 0 : a1.order;
+ int n2 = a2 == null ? 0 : a2.order;
// never return 0 even if n1 equals n2, otherwise, o1 and o2 will override each other in collection like HashSet
return n1 > n2 ? 1 : -1;
}
+ private Class<?> findSpi(Class clazz) {
+ if (clazz.getInterfaces().length <= 0) {
+ return null;
+ }
+
+ for (Class<?> intf : clazz.getInterfaces()) {
+ if (intf.isAnnotationPresent(SPI.class)) {
+ return intf;
+ } else {
+ Class result = findSpi(intf);
+ if (result != null) {
... 61671 lines suppressed ...