From fc3252ad191f0ffd9f0d56da89cdef67de412191 Mon Sep 17 00:00:00 2001 From: ZssAzrael Date: Sat, 10 Dec 2016 11:45:19 +0800 Subject: [PATCH 0001/1350] =?UTF-8?q?=E7=B1=BB=E5=90=8D=E5=86=99=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dubbo-rpc/dubbo-rpc-memcached/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol b/dubbo-rpc/dubbo-rpc-memcached/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol index 39883b50c1c..6cc8119309f 100644 --- a/dubbo-rpc/dubbo-rpc-memcached/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol +++ b/dubbo-rpc/dubbo-rpc-memcached/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol @@ -1 +1 @@ -memcached=memcom.alibaba.dubbo.rpc.protocol.memcached.MemcachedProtocol \ No newline at end of file +memcached=com.alibaba.dubbo.rpc.protocol.memcached.MemcachedProtocol From c698c7ab9d28fb105bb480f65f8172c7b4c2a34b Mon Sep 17 00:00:00 2001 From: Benson Wang Date: Tue, 7 Mar 2017 23:29:44 +0800 Subject: [PATCH 0002/1350] =?UTF-8?q?@Reference=E5=9C=A8=E6=96=B9=E6=B3=95?= =?UTF-8?q?=E7=BA=A7=E5=88=AB=E6=B3=A8=E5=85=A5=E5=A4=B1=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/alibaba/dubbo/config/spring/AnnotationBean.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/AnnotationBean.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/AnnotationBean.java index c4c5d048fad..dda293fe834 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/AnnotationBean.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/AnnotationBean.java @@ -214,7 +214,7 @@ public Object postProcessBeforeInitialization(Object bean, String beanName) if (reference != null) { Object value = refer(reference, method.getParameterTypes()[0]); if (value != null) { - method.invoke(bean, new Object[] { }); + method.invoke(bean, new Object[] {value}); } } } catch (Throwable e) { From 7055ad374cf4f9b43c696c6c2611b5e53aec9a78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=A8=E6=B5=A9?= Date: Tue, 14 Mar 2017 11:57:06 +0800 Subject: [PATCH 0003/1350] fix #402 `ps -f` is nothing, standard syntax: `ps -ef` --- .../src/main/resources/META-INF/assembly/bin/dump.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dubbo-container/dubbo-container-api/src/main/resources/META-INF/assembly/bin/dump.sh b/dubbo-container/dubbo-container-api/src/main/resources/META-INF/assembly/bin/dump.sh index d1629e4d55a..c0e341ae74c 100755 --- a/dubbo-container/dubbo-container-api/src/main/resources/META-INF/assembly/bin/dump.sh +++ b/dubbo-container/dubbo-container-api/src/main/resources/META-INF/assembly/bin/dump.sh @@ -12,7 +12,7 @@ if [ -z "$SERVER_NAME" ]; then SERVER_NAME=`hostname` fi -PIDS=`ps -f | grep java | grep "$CONF_DIR" |awk '{print $2}'` +PIDS=`ps -ef | grep java | grep "$CONF_DIR" |awk '{print $2}'` if [ -z "$PIDS" ]; then echo "ERROR: The $SERVER_NAME does not started!" exit 1 From 80113d215ba4d842bd5906cf71ed05ef36f1ff80 Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Tue, 18 Apr 2017 11:33:31 +0800 Subject: [PATCH 0004/1350] bump up fastjson's version --- dubbo-maven/pom.xml | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/dubbo-maven/pom.xml b/dubbo-maven/pom.xml index 02016adc1a4..0570127cd89 100644 --- a/dubbo-maven/pom.xml +++ b/dubbo-maven/pom.xml @@ -78,7 +78,7 @@ com.alibaba fastjson - 1.1.18 + 1.2.31 provided diff --git a/pom.xml b/pom.xml index 5a42f99db66..8ffce447d4a 100644 --- a/pom.xml +++ b/pom.xml @@ -89,7 +89,7 @@ 4.1.2 3.2.1-fixed-2 1.4.1 - 1.2.28 + 1.2.31 3.1 0.8 3.3.3 From 3945b83956debcf2127606ef6d88a6d29a080094 Mon Sep 17 00:00:00 2001 From: teaey Date: Mon, 24 Apr 2017 11:08:35 +0800 Subject: [PATCH 0005/1350] Solve the conflict between @Service and @Transactional --- .../java/com/alibaba/dubbo/config/annotation/Service.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/annotation/Service.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/annotation/Service.java index a8444fbb593..701418a489a 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/annotation/Service.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/annotation/Service.java @@ -15,11 +15,7 @@ */ package com.alibaba.dubbo.config.annotation; -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; +import java.lang.annotation.*; /** * Service @@ -30,6 +26,7 @@ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) +@Inherited public @interface Service { Class interfaceClass() default void.class; From f6515ea1299bc407402dc07fce65cf4245c44ef4 Mon Sep 17 00:00:00 2001 From: "ken.lj" Date: Fri, 28 Jul 2017 17:22:28 +0800 Subject: [PATCH 0006/1350] MISC: change project description(include quick start) --- README.md | 232 +++++++++++++----------------------------------------- 1 file changed, 53 insertions(+), 179 deletions(-) diff --git a/README.md b/README.md index 394910543ad..ff8eac3093a 100644 --- a/README.md +++ b/README.md @@ -8,196 +8,70 @@ It contains three key parts, which include: * **Clustering**: a remote procedure call abstraction with load-balancing/failover/clustering capabilities. * **Registration**: a service directory framework for service registration and service event publish/subscription -For more details, please refer to [wiki](https://github.com/alibaba/dubbo/wiki) or [dubbo.io](http://dubbo.io). +For more details, please refer to [dubbo.io](http://dubbo.io). -## Quick Start - - -Export service: - -```xml - - -``` - -Refer to service: - -```xml - - - - - -``` - -## Source Building +## Documentation +* [User's Guide](http://dubbo.io/user-guide/) +* [Developer's Guide](http://dubbo.io/developer-guide/) +* [Admin's Guide](http://dubbo.io/admin-guide/) -0. Install the git and maven command line: - - ```sh -yum install git -or: apt-get install git -cd ~ -wget http://www.apache.org/dist//maven/binaries/apache-maven-2.2.1-bin.tar.gz -tar zxvf apache-maven-2.2.1-bin.tar.gz -vi .bash_profile -append: export PATH=$PATH:~/apache-maven-2.2.1/bin -source .bash_profile -``` - -0. Checkout the dubbo source code: - - ```sh -cd ~ -git clone https://github.com/alibaba/dubbo.git dubbo -git checkout master -or: git checkout -b dubbo-2.4.0 -``` - -0. Import the dubbo source code to eclipse project: - - ```sh -cd ~/dubbo -mvn eclipse:eclipse -``` - - Then configure the project in eclipse by following the steps below: - * Eclipse -> Menu -> File -> Import -> Exsiting Projects to Workspace -> Browse -> Finish - * Context Menu -> Run As -> Java Application: - * dubbo-demo-provider/src/test/java/com.alibaba.dubbo.demo.provider.DemoProvider - * dubbo-demo-consumer/src/test/java/com.alibaba.dubbo.demo.consumer.DemoConsumer - * dubbo-monitor-simple/src/test/java/com.alibaba.dubbo.monitor.simple.SimpleMonitor - * dubbo-registry-simple/src/test/java/com.alibaba.dubbo.registry.simple.SimpleRegistry - * Edit Config: - * dubbo-demo-provider/src/test/resources/dubbo.properties - * dubbo-demo-consumer/src/test/resources/dubbo.properties - * dubbo-monitor-simple/src/test/resources/dubbo.properties - * dubbo-registry-simple/src/test/resources/dubbo.properties - -0. Build the dubbo binary package: - - ```sh -cd ~/dubbo -mvn clean install -Dmaven.test.skip -cd dubbo/target -ls -``` - -0. Install the demo provider: - - ```sh -cd ~/dubbo/dubbo-demo-provider/target -tar zxvf dubbo-demo-provider-2.4.0-assembly.tar.gz -cd dubbo-demo-provider-2.4.0/bin -./start.sh +## Quick Start +This guide gets you started with dubbo with a simple working example. +#### Download the sources(examples) +You’ll need a local copy of the example code to work through this quickstart. Download the demo code from our [Github repository](https://github.com/alibaba/dubbo) (the following command clones the entire repository, but you just need the `dubbo-demo` for this quickstart and other tutorials): + +```sh +$ cd ~ +$ # Clone the repository to get the source code. +$ git clone https://github.com/alibaba/dubbo.git dubbo +$ git checkout master +$ # or: git checkout -b dubbo-2.4.x ``` - -0. Install the demo consumer: - - ```sh -cd ~/dubbo/dubbo-demo-consumer/target -tar zxvf dubbo-demo-consumer-2.4.0-assembly.tar.gz -cd dubbo-demo-consumer-2.4.0/bin -./start.sh -cd ../logs -tail -f stdout.log +#### Build & Run +1. Build the whole sources use the following maven command + +```sh +$ cd ~/dubbo +$ mvn clean install -Dmaven.test.skip +$ # The demo code for this quickstart all stay in the `dubbo-demo` folder +$ cd ./dubbo-demo +$ ls ``` - -0. Install the simple monitor: - - ```sh -cd ~/dubbo/dubbo-simple-monitor/target -tar zxvf dubbo-simple-monitor-2.4.0-assembly.tar.gz -cd dubbo-simple-monitor-2.4.0/bin -./start.sh -http://127.0.0.1:8080 +2. Run demo-provider. Start the provider and export service +```sh +$ # Navigate to the provider part +$ cd ~/dubbo/demo-demo/dubbo-demo-provider/target +$ # unpack +$ tar zxvf dubbo-demo-provider-xxx-assembly.tar.gz +$ cd dubbo-demo-provider-xxx/bin +$ ls ``` -0. Install the simple registry: - - ```sh -cd ~/dubbo/dubbo-simple-registry/target -tar zxvf dubbo-simple-registry-2.4.0-assembly.tar.gz -cd dubbo-simple-registry-2.4.0/bin -./start.sh -cd ~/dubbo/dubbo-demo-provider/conf -vi dubbo.properties -- edit: dubbo.registry.adddress=dubbo://127.0.0.1:9090 -cd ../bin -./restart.sh -cd ~/dubbo/dubbo-demo-consumer/conf -vi dubbo.properties -- edit: dubbo.registry.adddress=dubbo://127.0.0.1:9090 -cd ../bin -./restart.sh -cd ~/dubbo/dubbo-simple-monitor/conf -vi dubbo.properties -- edit: dubbo.registry.adddress=dubbo://127.0.0.1:9090 -cd ../bin -./restart.sh +```sh +$ # Start the provider +$ ./start.sh ``` - -0. Install the zookeeper registry: - - ```sh -cd ~ -wget http://www.apache.org/dist//zookeeper/zookeeper-3.3.3/zookeeper-3.3.3.tar.gz -tar zxvf zookeeper-3.3.3.tar.gz -cd zookeeper-3.3.3/conf -cp zoo_sample.cfg zoo.cfg -vi zoo.cfg -- edit: dataDir=/home/xxx/data -cd ../bin -./zkServer.sh start -cd ~/dubbo/dubbo-demo-provider/conf -vi dubbo.properties -- edit: dubbo.registry.adddress=zookeeper://127.0.0.1:2181 -cd ../bin -./restart.sh -cd ~/dubbo/dubbo-demo-consumer/conf -vi dubbo.properties -- edit: dubbo.registry.adddress=zookeeper://127.0.0.1:2181 -cd ../bin -./restart.sh -cd ~/dubbo/dubbo-simple-monitor/conf -vi dubbo.properties -- edit: dubbo.registry.adddress=zookeeper://127.0.0.1:2181 -cd ../bin -./restart.sh +3. Run demo-consumer. Start the consumer and consume service provided by _the provider_ above + +```sh +$ # Navigate to the consumer part +$ cd ~/dubbo/demo-demo/dubbo-demo-consumer/target +$ # unpack +$ tar zxvf dubbo-demo-consumer-xxx-assembly.tar.gz +$ cd dubbo-demo-consumer-xxx/bin +$ ls ``` -0. Install the redis registry: - - ```sh -cd ~ -wget http://redis.googlecode.com/files/redis-2.4.8.tar.gz -tar xzf redis-2.4.8.tar.gz -cd redis-2.4.8 -make -nohup ./src/redis-server redis.conf & -cd ~/dubbo/dubbo-demo-provider/conf -vi dubbo.properties -- edit: dubbo.registry.adddress=redis://127.0.0.1:6379 -cd ../bin -./restart.sh -cd ~/dubbo/dubbo-demo-consumer/conf -vi dubbo.properties -- edit: dubbo.registry.adddress=redis://127.0.0.1:6379 -cd ../bin -./restart.sh -cd ~/dubbo/dubbo-simple-monitor/conf -vi dubbo.properties -- edit: dubbo.registry.adddress=redis://127.0.0.1:6379 -cd ../bin -./restart.sh +```sh +$ ./start.sh ``` +For a more detailed tutorial of this demo, click [here](http://dubbo.io/#quickstart) -0. Install the admin console: +## Getting Help +* Community +* Releases +* Contributors +* Q&A - ```sh - cd ~/dubbo/dubbo-admin - mvn jetty:run -Ddubbo.registry.address=zookeeper://127.0.0.1:2181 - http://root:root@127.0.0.1:8080 -``` From a2fbe63fc283ef35b1ea72f192f914330b38e1c1 Mon Sep 17 00:00:00 2001 From: "ken.lj" Date: Mon, 31 Jul 2017 10:35:17 +0800 Subject: [PATCH 0007/1350] MISC: edit quick start in README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index ff8eac3093a..fbe860f61b9 100644 --- a/README.md +++ b/README.md @@ -43,8 +43,8 @@ $ ls $ # Navigate to the provider part $ cd ~/dubbo/demo-demo/dubbo-demo-provider/target $ # unpack -$ tar zxvf dubbo-demo-provider-xxx-assembly.tar.gz -$ cd dubbo-demo-provider-xxx/bin +$ tar zxvf dubbo-demo-provider-2.5.4-SNAPSHOT-assembly.tar.gz +$ cd dubbo-demo-provider-2.5.4-SNAPSHOT/bin $ ls ``` @@ -58,8 +58,8 @@ $ ./start.sh $ # Navigate to the consumer part $ cd ~/dubbo/demo-demo/dubbo-demo-consumer/target $ # unpack -$ tar zxvf dubbo-demo-consumer-xxx-assembly.tar.gz -$ cd dubbo-demo-consumer-xxx/bin +$ tar zxvf dubbo-demo-consumer-2.5.4-SNAPSHOT-assembly.tar.gz +$ cd dubbo-demo-consumer-2.5.4-SNAPSHOT/bin $ ls ``` From 5d16d53f8c5a646d95f0102d4db00a4a09ee9f9a Mon Sep 17 00:00:00 2001 From: "ken.lj" Date: Thu, 3 Aug 2017 10:48:32 +0800 Subject: [PATCH 0008/1350] MISC: add tutorial code to dubbo-demo --- .../alibaba/dubbo/demo/consumer/Consumer.java | 20 +++++++++++++++++++ .../META-INF/spring/dubbo-demo-consumer.xml | 9 ++++++++- .../alibaba/dubbo/demo/provider/Provider.java | 17 ++++++++++++++++ .../META-INF/spring/dubbo-demo-provider.xml | 15 ++++++++++++-- 4 files changed, 58 insertions(+), 3 deletions(-) create mode 100644 dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/Consumer.java create mode 100644 dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/provider/Provider.java diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/Consumer.java b/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/Consumer.java new file mode 100644 index 00000000000..00cf74844a2 --- /dev/null +++ b/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/Consumer.java @@ -0,0 +1,20 @@ +package com.alibaba.dubbo.demo.consumer; + +import com.alibaba.dubbo.demo.DemoService; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +/** + * Created by ken.lj on 2017/7/31. + */ +public class Consumer { + + public static void main(String[] args) { + ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"META-INF/spring/dubbo-demo-consumer.xml"}); + context.start(); + + DemoService demoService = (DemoService) context.getBean("demoService"); // 获取远程服务代理 + String hello = demoService.sayHello("world"); // 执行远程方法 + + System.out.println(hello); // 显示调用结果 + } +} diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml index 981599fb175..39d07ab7ca3 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml +++ b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml @@ -20,6 +20,13 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd"> - + + + + + + + + \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/provider/Provider.java b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/provider/Provider.java new file mode 100644 index 00000000000..e11370ce595 --- /dev/null +++ b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/provider/Provider.java @@ -0,0 +1,17 @@ +package com.alibaba.dubbo.demo.provider; + +import org.springframework.context.support.ClassPathXmlApplicationContext; + +/** + * Created by ken.lj on 2017/7/31. + */ +public class Provider { + + public static void main(String[] args) throws Exception{ + ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"META-INF/spring/dubbo-demo-provider.xml"}); + context.start(); + + System.in.read(); // 按任意键退出 + } + +} diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml index ea8026b6ed8..1ae83b1d45c 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml @@ -19,9 +19,20 @@ xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd"> - + + + + + + + + + + + - + + \ No newline at end of file From 17619dfa974457b00fe27cf68ae3f9d266709666 Mon Sep 17 00:00:00 2001 From: "ken.lj" Date: Thu, 24 Aug 2017 18:05:06 +0800 Subject: [PATCH 0009/1350] Reformat code --- dubbo-admin/pom.xml | 274 +- .../alibaba/dubbo/governance/PageContext.java | 22 +- .../i18n/impl/MessageResourceServiceImpl.java | 6 +- .../governance/service/ConfigService.java | 18 +- .../governance/service/ConsumerService.java | 28 +- .../governance/service/OverrideService.java | 22 +- .../governance/service/OwnerService.java | 38 +- .../governance/service/ProviderService.java | 44 +- .../governance/service/RouteService.java | 26 +- .../dubbo/governance/service/UserService.java | 26 +- .../service/impl/AbstractService.java | 32 +- .../service/impl/ConfigServiceImpl.java | 16 +- .../service/impl/ConsumerServiceImpl.java | 124 +- .../service/impl/OverrideServiceImpl.java | 69 +- .../service/impl/OwnerServiceImpl.java | 154 +- .../service/impl/ProviderServiceImpl.java | 397 +- .../service/impl/RouteServiceImpl.java | 66 +- .../service/impl/UserServiceImpl.java | 57 +- .../status/DatabaseStatusChecker.java | 39 +- .../governance/status/LoadStatusChecker.java | 32 +- .../status/MemoryStatusChecker.java | 14 +- .../governance/sync/RegistryServerSync.java | 118 +- .../dubbo/governance/sync/util/Pair.java | 96 +- .../dubbo/governance/sync/util/SyncUtils.java | 134 +- .../governance/web/common/auth/DubboUser.java | 18 +- .../web/common/i18n/LocaleUtil.java | 8 +- .../interceptor/AuthorizationValve.java | 141 +- .../web/common/interceptor/LocaleValve.java | 30 +- .../interceptor/RestfuleUrlRewriter.java | 71 +- .../ServicePrivilegeCheckValve.java | 113 +- .../web/common/module/screen/Error_404.java | 12 +- .../web/common/module/screen/Error_other.java | 12 +- .../web/common/module/screen/Restful.java | 189 +- .../web/common/pulltool/DateFormatUtil.java | 14 +- .../web/common/pulltool/I18nMessageTool.java | 21 +- .../web/common/pulltool/RootContextPath.java | 38 +- .../governance/web/common/pulltool/Tool.java | 566 +- .../web/common/pulltool/ToolUtil.java | 29 +- .../resolver/MapDataResolverFactory.java | 21 +- .../web/common/resolver/ParameterMap.java | 43 +- .../web/common/utils/RelateUserUtils.java | 18 +- .../governance/module/screen/Accesses.java | 150 +- .../governance/module/screen/Addresses.java | 45 +- .../module/screen/Applications.java | 180 +- .../governance/module/screen/Consumers.java | 260 +- .../module/screen/Loadbalances.java | 55 +- .../module/screen/NoServicePrivilege.java | 16 +- .../governance/module/screen/Overrides.java | 279 +- .../web/governance/module/screen/Owners.java | 96 +- .../governance/module/screen/Providers.java | 357 +- .../web/governance/module/screen/Routes.java | 449 +- .../governance/module/screen/Services.java | 134 +- .../web/governance/module/screen/Weights.java | 107 +- .../web/home/module/control/Menu.java | 36 +- .../web/home/module/screen/Disable.java | 59 +- .../web/home/module/screen/Index.java | 29 +- .../web/home/module/screen/Lookup.java | 50 +- .../web/home/module/screen/Reg.java | 10 +- .../web/home/module/screen/Register.java | 53 +- .../web/home/module/screen/Restful.java | 45 +- .../web/home/module/screen/Result.java | 10 +- .../web/home/module/screen/Servicestatus.java | 28 +- .../web/home/module/screen/Shell.java | 78 +- .../web/home/module/screen/Status.java | 36 +- .../web/home/module/screen/Unreg.java | 21 +- .../web/home/module/screen/Unregister.java | 33 +- .../web/home/module/screen/Unregisterall.java | 59 +- .../web/personal/module/screen/Infos.java | 10 +- .../web/personal/module/screen/Passwds.java | 8 +- .../web/sysinfo/module/screen/Dump.java | 31 +- .../web/sysinfo/module/screen/Dumps.java | 19 +- .../web/sysinfo/module/screen/Envs.java | 35 +- .../web/sysinfo/module/screen/Logs.java | 18 +- .../web/sysinfo/module/screen/Statuses.java | 26 +- .../web/sysinfo/module/screen/Versions.java | 28 +- .../web/sysmanage/module/screen/Configs.java | 40 +- .../sysmanage/module/screen/Privileges.java | 8 +- .../web/sysmanage/module/screen/Userown.java | 28 +- .../governance/web/util/ContextUtil.java | 16 +- .../governance/web/util/GovernanceWarmup.java | 30 +- .../dubbo/governance/web/util/Paginator.java | 32 +- .../dubbo/governance/web/util/UrlUtils.java | 4 +- .../governance/web/util/WebConstants.java | 28 +- .../dubbo/registry/common/ChangeListener.java | 14 +- .../dubbo/registry/common/StatusManager.java | 98 +- .../dubbo/registry/common/domain/Access.java | 88 +- .../registry/common/domain/Agreement.java | 30 +- .../registry/common/domain/Approval.java | 22 +- .../common/domain/ApprovalRequisition.java | 26 +- .../dubbo/registry/common/domain/Change.java | 51 +- .../dubbo/registry/common/domain/Cluster.java | 24 +- .../dubbo/registry/common/domain/Config.java | 63 +- .../registry/common/domain/Consumer.java | 96 +- .../registry/common/domain/DependItem.java | 12 +- .../registry/common/domain/Dependency.java | 32 +- .../registry/common/domain/Document.java | 30 +- .../dubbo/registry/common/domain/Entity.java | 90 +- .../registry/common/domain/Favorite.java | 38 +- .../dubbo/registry/common/domain/Feature.java | 16 +- .../dubbo/registry/common/domain/Layer.java | 28 +- .../registry/common/domain/LoadBalance.java | 28 +- .../dubbo/registry/common/domain/Mock.java | 83 +- .../registry/common/domain/Operation.java | 48 +- .../registry/common/domain/Override.java | 116 +- .../dubbo/registry/common/domain/Owner.java | 48 +- .../registry/common/domain/PageList.java | 30 +- .../registry/common/domain/Provider.java | 121 +- .../registry/common/domain/Registry.java | 22 +- .../dubbo/registry/common/domain/Route.java | 172 +- .../registry/common/domain/SearchHistory.java | 48 +- .../dubbo/registry/common/domain/Test.java | 70 +- .../dubbo/registry/common/domain/User.java | 308 +- .../dubbo/registry/common/domain/Weight.java | 46 +- .../registry/common/registry/ConvertUtil.java | 39 +- .../registry/common/route/OverrideUtils.java | 185 +- .../registry/common/route/ParseUtils.java | 153 +- .../registry/common/route/RouteRule.java | 449 +- .../registry/common/route/RouteRuleUtils.java | 113 +- .../registry/common/route/RouteUtils.java | 170 +- .../common/status/DatabaseStatusChecker.java | 39 +- .../common/status/LoadStatusChecker.java | 32 +- .../common/status/MemoryStatusChecker.java | 14 +- .../dubbo/registry/common/util/Coder.java | 69 +- .../dubbo/registry/common/util/Entities.java | 1177 ++- .../registry/common/util/IntHashMap.java | 144 +- .../registry/common/util/LocaleUtils.java | 15 +- .../registry/common/util/MessageSource.java | 46 +- .../registry/common/util/OverrideUtils.java | 190 +- .../common/util/StringEscapeUtils.java | 234 +- .../dubbo/registry/common/util/Tool.java | 147 +- .../resources/META-INF/spring/dubbo-admin.xml | 81 +- .../webapp/META-INF/autoconf/auto-config.xml | 48 +- .../main/webapp/META-INF/autoconf/log4j.xml | 62 +- .../webapp/META-INF/autoconf/resources.xml | 85 +- .../main/webapp/META-INF/autoconf/web.xml.vm | 266 +- .../webapp/SpryAssets/SpryValidationRadio.css | 13 +- .../webapp/SpryAssets/SpryValidationRadio.js | 742 +- .../WEB-INF/common/pipeline-exception.xml | 46 +- .../webapp/WEB-INF/common/pipeline-rpc.xml | 109 +- .../main/webapp/WEB-INF/common/pipeline.xml | 101 +- .../main/webapp/WEB-INF/common/resources.xml | 56 +- .../main/webapp/WEB-INF/common/rewrite.xml | 10 +- .../src/main/webapp/WEB-INF/common/uris.xml | 35 +- .../common/webx-component-and-root.xml | 227 +- .../webapp/WEB-INF/common/webx-component.xml | 24 +- .../main/webapp/WEB-INF/forms/provider.xml | 36 +- .../webapp/WEB-INF/i18n/message_zh.properties | 56 - .../WEB-INF/i18n/message_zh_TW.properties | 53 - dubbo-admin/src/main/webapp/WEB-INF/log4j.xml | 50 +- .../templates/common/screen/error_404.vm | 212 +- .../templates/common/screen/error_other.vm | 190 +- .../templates/governance/layout/default.vm | 499 +- .../governance/layout/noServicePrivilege.vm | 17 +- .../templates/governance/layout/redirect.vm | 17 +- .../governance/screen/accesses/add.vm | 160 +- .../governance/screen/accesses/index.vm | 124 +- .../governance/screen/addresses/index.vm | 67 +- .../governance/screen/addresses/search.vm | 2 +- .../governance/screen/applications/index.vm | 201 +- .../governance/screen/applications/search.vm | 2 +- .../governance/screen/consumers/edit.vm | 208 +- .../governance/screen/consumers/index.vm | 296 +- .../governance/screen/consumers/notified.vm | 193 +- .../governance/screen/consumers/routed.vm | 201 +- .../governance/screen/consumers/show.vm | 213 +- .../governance/screen/loadbalances/add.vm | 179 +- .../governance/screen/loadbalances/edit.vm | 135 +- .../governance/screen/loadbalances/index.vm | 96 +- .../governance/screen/loadbalances/show.vm | 48 +- .../governance/screen/noServicePrivilege.vm | 39 +- .../governance/screen/overrides/add.vm | 341 +- .../governance/screen/overrides/edit.vm | 355 +- .../governance/screen/overrides/index.vm | 124 +- .../governance/screen/overrides/show.vm | 279 +- .../templates/governance/screen/owners/add.vm | 91 +- .../governance/screen/owners/index.vm | 59 +- .../governance/screen/providers/add.vm | 140 +- .../governance/screen/providers/edit.vm | 142 +- .../governance/screen/providers/index.vm | 251 +- .../governance/screen/providers/show.vm | 187 +- .../templates/governance/screen/redirect.vm | 94 +- .../templates/governance/screen/routes/add.vm | 467 +- .../governance/screen/routes/edit.vm | 467 +- .../governance/screen/routes/index.vm | 161 +- .../governance/screen/routes/preview.vm | 15 +- .../governance/screen/routes/routeselect.vm | 133 +- .../governance/screen/routes/show.vm | 142 +- .../governance/screen/services/index.vm | 238 +- .../governance/screen/services/search.vm | 2 +- .../governance/screen/weights/add.vm | 219 +- .../governance/screen/weights/edit.vm | 191 +- .../governance/screen/weights/index.vm | 83 +- .../governance/screen/weights/show.vm | 124 +- .../WEB-INF/templates/home/control/menu.vm | 192 +- .../WEB-INF/templates/home/screen/index.vm | 392 +- .../WEB-INF/templates/home/screen/services.vm | 10 +- .../templates/sysinfo/layout/default.vm | 245 +- .../templates/sysinfo/layout/redirect.vm | 17 +- .../templates/sysinfo/screen/dumps/index.vm | 96 +- .../templates/sysinfo/screen/envs/index.vm | 19 +- .../templates/sysinfo/screen/logs/index.vm | 65 +- .../templates/sysinfo/screen/redirect.vm | 93 +- .../templates/sysinfo/screen/socketConn.vm | 194 +- .../sysinfo/screen/statuses/index.vm | 58 +- .../sysinfo/screen/versions/index.vm | 26 +- .../templates/sysinfo/screen/versions/show.vm | 30 +- dubbo-admin/src/main/webapp/WEB-INF/web.xml | 154 +- .../main/webapp/WEB-INF/webx-governance.xml | 43 +- .../src/main/webapp/WEB-INF/webx-home.xml | 24 +- .../src/main/webapp/WEB-INF/webx-personal.xml | 24 +- .../src/main/webapp/WEB-INF/webx-sysinfo.xml | 24 +- .../main/webapp/WEB-INF/webx-sysmanage.xml | 24 +- dubbo-admin/src/main/webapp/WEB-INF/webx.xml | 112 +- dubbo-admin/src/main/webapp/crossdomain.xml | 2 +- dubbo-admin/src/main/webapp/css/common.css | 1043 ++- dubbo-admin/src/main/webapp/css/dubbo.css | 537 +- dubbo-admin/src/main/webapp/css/skin.css | 365 +- dubbo-admin/src/main/webapp/js/ajax.js | 129 +- dubbo-admin/src/main/webapp/js/box.js | 152 +- dubbo-admin/src/main/webapp/js/dubbo.js | 867 +- .../src/main/webapp/js/jquery.hoverIntent.js | 208 +- .../main/webapp/js/jquery.simplemodal-1.4.js | 1280 +-- dubbo-admin/src/main/webapp/js/menu.js | 98 +- dubbo-admin/src/main/webapp/js/pop.js | 124 +- dubbo-admin/src/main/webapp/js/trcolor.js | 42 +- .../registry/common/domain/PageListTest.java | 14 +- .../registry/common/route/ParseUtilsTest.java | 65 +- .../registry/common/route/RouteRuleTest.java | 307 +- .../common/route/RouteRuleUtilsTest.java | 174 +- .../registry/common/route/RouteUtilsTest.java | 118 +- .../dubbo/registry/common/util/ToolTest.java | 10 +- .../src/test/resources/AgreementData.xml | 26 +- .../src/test/resources/ApprovalData.xml | 22 +- dubbo-admin/src/test/resources/ChangeData.xml | 6 +- .../src/test/resources/ClusterData.xml | 6 +- .../src/test/resources/ConsumerData.xml | 16 +- .../src/test/resources/DocumentData.xml | 2 +- dubbo-admin/src/test/resources/LayerData.xml | 12 +- .../src/test/resources/OperationData.xml | 150 +- .../src/test/resources/ProviderData.xml | 24 +- .../src/test/resources/RegistryData.xml | 9 +- dubbo-admin/src/test/resources/RouteData.xml | 17 +- dubbo-admin/src/test/resources/TestData.xml | 9 +- dubbo-admin/src/test/resources/UserData.xml | 5 +- dubbo-admin/src/test/resources/WeightData.xml | 12 +- dubbo-admin/src/test/resources/log4j.xml | 22 +- dubbo-cluster/pom.xml | 56 +- .../alibaba/dubbo/rpc/cluster/Cluster.java | 6 +- .../dubbo/rpc/cluster/Configurator.java | 7 +- .../rpc/cluster/ConfiguratorFactory.java | 4 +- .../alibaba/dubbo/rpc/cluster/Directory.java | 18 +- .../dubbo/rpc/cluster/LoadBalance.java | 28 +- .../com/alibaba/dubbo/rpc/cluster/Router.java | 18 +- .../dubbo/rpc/cluster/RouterFactory.java | 12 +- .../dubbo/rpc/cluster/RuleConverter.java | 4 +- .../configurator/AbstractConfigurator.java | 32 +- .../absent/AbsentConfigurator.java | 2 +- .../absent/AbsentConfiguratorFactory.java | 2 +- .../override/OverrideConfigurator.java | 4 +- .../override/OverrideConfiguratorFactory.java | 2 +- .../cluster/directory/AbstractDirectory.java | 70 +- .../cluster/directory/StaticDirectory.java | 22 +- .../loadbalance/AbstractLoadBalance.java | 36 +- .../ConsistentHashLoadBalance.java | 28 +- .../loadbalance/LeastActiveLoadBalance.java | 18 +- .../loadbalance/RandomLoadBalance.java | 50 +- .../loadbalance/RoundRobinLoadBalance.java | 126 +- .../dubbo/rpc/cluster/merger/ArrayMerger.java | 2 +- .../cluster/merger/BooleanArrayMerger.java | 6 +- .../rpc/cluster/merger/ByteArrayMerger.java | 2 +- .../rpc/cluster/merger/IntArrayMerger.java | 8 +- .../dubbo/rpc/cluster/merger/ListMerger.java | 4 +- .../dubbo/rpc/cluster/merger/MapMerger.java | 4 +- .../rpc/cluster/merger/MergerFactory.java | 2 +- .../dubbo/rpc/cluster/merger/SetMerger.java | 4 +- .../cluster/router/MockInvokersSelector.java | 112 +- .../router/condition/ConditionRouter.java | 165 +- .../condition/ConditionRouterFactory.java | 2 +- .../router/file/FileRouterFactory.java | 60 +- .../cluster/router/script/ScriptRouter.java | 47 +- .../router/script/ScriptRouterFactory.java | 8 +- .../support/AbstractClusterInvoker.java | 150 +- .../rpc/cluster/support/AvailableCluster.java | 12 +- .../support/AvailableClusterInvoker.java | 40 +- .../rpc/cluster/support/BroadcastCluster.java | 2 +- .../support/BroadcastClusterInvoker.java | 14 +- .../rpc/cluster/support/ClusterUtils.java | 25 +- .../rpc/cluster/support/FailbackCluster.java | 6 +- .../support/FailbackClusterInvoker.java | 32 +- .../rpc/cluster/support/FailfastCluster.java | 4 +- .../support/FailfastClusterInvoker.java | 52 +- .../rpc/cluster/support/FailoverCluster.java | 6 +- .../support/FailoverClusterInvoker.java | 46 +- .../rpc/cluster/support/FailsafeCluster.java | 6 +- .../support/FailsafeClusterInvoker.java | 52 +- .../rpc/cluster/support/ForkingCluster.java | 10 +- .../support/ForkingClusterInvoker.java | 102 +- .../rpc/cluster/support/MergeableCluster.java | 4 +- .../support/MergeableClusterInvoker.java | 172 +- .../support/wrapper/MockClusterInvoker.java | 215 +- .../support/wrapper/MockClusterWrapper.java | 19 +- .../alibaba/dubbo/rpc/cluster/StickyTest.java | 156 +- .../absent/AbsentConfiguratorTest.java | 27 +- .../override/OverrideConfiguratorTest.java | 27 +- .../dubbo/rpc/cluster/filter/DemoService.java | 21 +- .../rpc/cluster/filter/DemoServiceLocal.java | 14 +- .../rpc/cluster/filter/DemoServiceMock.java | 5 +- .../rpc/cluster/filter/DemoServiceStub.java | 2 +- .../dubbo/rpc/cluster/filter/MockService.java | 5 +- .../cluster/loadbalance/LoadBalanceTest.java | 160 +- .../rpc/cluster/merger/ResultMergerTest.java | 54 +- .../dubbo/rpc/cluster/router/MockInvoker.java | 34 +- .../router/condition/ConditionRouterTest.java | 149 +- .../router/file/FileRouterEngineTest.java | 98 +- .../router/script/ScriptRouterTest.java | 82 +- .../support/AbstractClusterInvokerTest.java | 426 +- .../rpc/cluster/support/ClusterUtilsTest.java | 42 +- .../support/FailSafeClusterInvokerTest.java | 66 +- .../support/FailbackClusterInvokerTest.java | 46 +- .../support/FailfastClusterInvokerTest.java | 157 +- .../support/FailoverClusterInvokerTest.java | 237 +- .../support/ForkingClusterInvokerTest.java | 48 +- .../dubbo/rpc/cluster/support/Menu.java | 47 +- .../rpc/cluster/support/MenuService.java | 6 +- .../support/MergeableClusterInvokerTest.java | 169 +- .../wrapper/MockClusterInvokerTest.java | 1211 +-- .../support/wrapper/MyMockException.java | 12 +- dubbo-cluster/src/test/resources/log4j.xml | 22 +- dubbo-common/pom.xml | 98 +- .../com/alibaba/dubbo/common/Constants.java | 526 +- .../com/alibaba/dubbo/common/Extension.java | 12 +- .../java/com/alibaba/dubbo/common/Node.java | 10 +- .../com/alibaba/dubbo/common/Parameters.java | 382 +- .../com/alibaba/dubbo/common/Resetable.java | 8 +- .../java/com/alibaba/dubbo/common/URL.java | 673 +- .../com/alibaba/dubbo/common/Version.java | 89 +- .../common/beanutil/JavaBeanAccessor.java | 12 +- .../common/beanutil/JavaBeanDescriptor.java | 39 +- .../beanutil/JavaBeanSerializeUtil.java | 82 +- .../dubbo/common/bytecode/ClassGenerator.java | 649 +- .../alibaba/dubbo/common/bytecode/Mixin.java | 399 +- .../bytecode/NoSuchMethodException.java | 21 +- .../bytecode/NoSuchPropertyException.java | 21 +- .../alibaba/dubbo/common/bytecode/Proxy.java | 471 +- .../dubbo/common/bytecode/Wrapper.java | 751 +- .../dubbo/common/compiler/Compiler.java | 18 +- .../compiler/support/AbstractCompiler.java | 18 +- .../compiler/support/AdaptiveCompiler.java | 2 +- .../common/compiler/support/ClassUtils.java | 91 +- .../compiler/support/JavassistCompiler.java | 26 +- .../common/compiler/support/JdkCompiler.java | 160 +- .../dubbo/common/extension/Activate.java | 8 +- .../dubbo/common/extension/Adaptive.java | 13 +- .../common/extension/ExtensionFactory.java | 4 +- .../common/extension/ExtensionLoader.java | 428 +- .../alibaba/dubbo/common/extension/SPI.java | 8 +- .../factory/AdaptiveExtensionFactory.java | 14 +- .../factory/SpiExtensionFactory.java | 2 +- .../extension/support/ActivateComparator.java | 12 +- .../com/alibaba/dubbo/common/io/Bytes.java | 1800 ++-- .../alibaba/dubbo/common/io/StreamUtils.java | 230 +- .../common/io/UnsafeByteArrayInputStream.java | 175 +- .../io/UnsafeByteArrayOutputStream.java | 166 +- .../dubbo/common/io/UnsafeStringReader.java | 207 +- .../dubbo/common/io/UnsafeStringWriter.java | 198 +- .../common/json/GenericJSONConverter.java | 835 +- .../alibaba/dubbo/common/json/J2oVisitor.java | 693 +- .../com/alibaba/dubbo/common/json/JSON.java | 1399 ++- .../alibaba/dubbo/common/json/JSONArray.java | 324 +- .../dubbo/common/json/JSONConverter.java | 69 +- .../alibaba/dubbo/common/json/JSONNode.java | 21 +- .../alibaba/dubbo/common/json/JSONObject.java | 373 +- .../alibaba/dubbo/common/json/JSONReader.java | 102 +- .../alibaba/dubbo/common/json/JSONToken.java | 80 +- .../dubbo/common/json/JSONVisitor.java | 151 +- .../alibaba/dubbo/common/json/JSONWriter.java | 555 +- .../dubbo/common/json/ParseException.java | 21 +- .../com/alibaba/dubbo/common/json/Yylex.java | 1512 ++-- .../alibaba/dubbo/common/logger/Level.java | 38 +- .../alibaba/dubbo/common/logger/Logger.java | 226 +- .../dubbo/common/logger/LoggerAdapter.java | 124 +- .../dubbo/common/logger/LoggerFactory.java | 270 +- .../dubbo/common/logger/jcl/JclLogger.java | 87 +- .../common/logger/jcl/JclLoggerAdapter.java | 27 +- .../dubbo/common/logger/jdk/JdkLogger.java | 114 +- .../common/logger/jdk/JdkLoggerAdapter.java | 204 +- .../common/logger/log4j/Log4jLogger.java | 168 +- .../logger/log4j/Log4jLoggerAdapter.java | 164 +- .../common/logger/slf4j/Slf4jLogger.java | 14 +- .../logger/slf4j/Slf4jLoggerAdapter.java | 25 +- .../common/logger/support/FailsafeLogger.java | 240 +- .../dubbo/common/serialize/DataInput.java | 130 +- .../dubbo/common/serialize/DataOutput.java | 158 +- .../dubbo/common/serialize/ObjectInput.java | 38 +- .../dubbo/common/serialize/ObjectOutput.java | 14 +- .../dubbo/common/serialize/Serialization.java | 20 +- .../serialize/support/dubbo/Builder.java | 2798 +++--- .../support/dubbo/ClassDescriptorMapper.java | 31 +- .../support/dubbo/DubboSerialization.java | 8 +- .../support/dubbo/GenericDataFlags.java | 83 +- .../support/dubbo/GenericDataInput.java | 934 +- .../support/dubbo/GenericDataOutput.java | 814 +- .../support/dubbo/GenericObjectInput.java | 456 +- .../support/dubbo/GenericObjectOutput.java | 138 +- .../support/hessian/Hessian2ObjectInput.java | 167 +- .../support/hessian/Hessian2ObjectOutput.java | 162 +- .../hessian/Hessian2Serialization.java | 10 +- .../hessian/Hessian2SerializerFactory.java | 14 +- .../java/CompactedJavaSerialization.java | 8 +- .../java/CompactedObjectInputStream.java | 96 +- .../java/CompactedObjectOutputStream.java | 68 +- .../support/java/JavaObjectInput.java | 91 +- .../support/java/JavaObjectOutput.java | 78 +- .../support/java/JavaSerialization.java | 8 +- .../support/json/FastJsonObjectInput.java | 21 +- .../support/json/FastJsonObjectOutput.java | 16 +- .../support/json/FastJsonSerialization.java | 12 +- .../support/json/JsonObjectInput.java | 27 +- .../support/json/JsonObjectOutput.java | 20 +- .../support/json/JsonSerialization.java | 14 +- .../nativejava/NativeJavaObjectInput.java | 6 +- .../nativejava/NativeJavaObjectOutput.java | 6 +- .../nativejava/NativeJavaSerialization.java | 10 +- .../alibaba/dubbo/common/status/Status.java | 72 +- .../dubbo/common/status/StatusChecker.java | 6 +- .../status/support/LoadStatusChecker.java | 28 +- .../status/support/MemoryStatusChecker.java | 6 +- .../common/status/support/StatusUtils.java | 10 +- .../alibaba/dubbo/common/store/DataStore.java | 2 +- .../common/store/support/SimpleDataStore.java | 10 +- .../dubbo/common/threadpool/ThreadPool.java | 10 +- .../support/AbortPolicyWithReport.java | 22 +- .../support/cached/CachedThreadPool.java | 26 +- .../support/fixed/FixedThreadPool.java | 26 +- .../support/limited/LimitedThreadPool.java | 24 +- .../alibaba/dubbo/common/utils/Assert.java | 3 +- .../common/utils/AtomicPositiveInteger.java | 22 +- .../dubbo/common/utils/ClassHelper.java | 120 +- .../dubbo/common/utils/CollectionUtils.java | 304 +- .../common/utils/CompatibleTypeUtils.java | 58 +- .../dubbo/common/utils/ConcurrentHashSet.java | 167 +- .../dubbo/common/utils/ConfigUtils.java | 198 +- .../dubbo/common/utils/DubboAppender.java | 16 +- .../dubbo/common/utils/ExecutorUtil.java | 36 +- .../alibaba/dubbo/common/utils/Holder.java | 6 +- .../alibaba/dubbo/common/utils/IOUtils.java | 362 +- .../alibaba/dubbo/common/utils/LRUCache.java | 56 +- .../com/alibaba/dubbo/common/utils/Log.java | 22 +- .../alibaba/dubbo/common/utils/LogHelper.java | 6 +- .../alibaba/dubbo/common/utils/LogUtil.java | 18 +- .../common/utils/NamedThreadFactory.java | 56 +- .../alibaba/dubbo/common/utils/NetUtils.java | 186 +- .../alibaba/dubbo/common/utils/PojoUtils.java | 431 +- .../dubbo/common/utils/ReflectUtils.java | 1493 ++- .../com/alibaba/dubbo/common/utils/Stack.java | 231 +- .../dubbo/common/utils/StringUtils.java | 560 +- .../alibaba/dubbo/common/utils/UrlUtils.java | 67 +- .../com/alibaba/dubbo/common/URLTest.java | 28 +- .../alibaba/dubbo/common/beanutil/Bean.java | 18 +- .../beanutil/JavaBeanSerializeUtilTest.java | 313 +- .../common/bytecode/ClassGeneratorTest.java | 119 +- .../dubbo/common/bytecode/MixinTest.java | 115 +- .../dubbo/common/bytecode/ProxyTest.java | 67 +- .../dubbo/common/bytecode/WrapperTest.java | 166 +- .../extensionloader/ExtensionLoaderTest.java | 109 +- .../ExtensionLoader_Adaptive_Test.java | 50 +- ...onLoader_Adaptive_UseJdkCompiler_Test.java | 1 + .../ExtensionLoader_Compatible_Test.java | 3 +- .../common/extensionloader/NoSpiExt.java | 1 - .../compatible/impl/CompatibleExtImpl1.java | 4 +- .../compatible/impl/CompatibleExtImpl2.java | 5 +- .../extensionloader/ext1/SimpleExt.java | 2 +- .../ext1/impl/SimpleExtImpl1.java | 5 +- .../ext1/impl/SimpleExtImpl2.java | 5 +- .../ext1/impl/SimpleExtImpl3.java | 5 +- .../common/extensionloader/ext2/Ext2.java | 2 +- .../extensionloader/ext2/UrlHolder.java | 39 +- .../extensionloader/ext2/impl/Ext2Impl2.java | 3 +- .../extensionloader/ext2/impl/Ext2Impl3.java | 3 +- .../ext3/UseProtocolKeyExt.java | 1 + .../ext3/impl/UseProtocolKeyExtImpl1.java | 2 +- .../ext3/impl/UseProtocolKeyExtImpl2.java | 3 +- .../ext3/impl/UseProtocolKeyExtImpl3.java | 3 +- .../extensionloader/ext4/NoUrlParamExt.java | 4 +- .../extensionloader/ext4/impl/Ext4Impl1.java | 4 +- .../extensionloader/ext4/impl/Ext4Impl2.java | 8 +- .../extensionloader/ext5/impl/Ext5Impl2.java | 1 - .../extensionloader/ext6_inject/Ext6.java | 22 +- .../ext6_inject/impl/DaoImpl.java | 4 +- .../ext6_inject/impl/Ext6Impl1.java | 14 +- .../ext6_inject/impl/Ext6Impl2.java | 38 +- .../ext6_wrap/impl/Ext5Impl2.java | 1 - .../ext6_wrap/impl/Ext5Wrapper1.java | 9 +- .../ext6_wrap/impl/Ext5Wrapper2.java | 7 +- .../extensionloader/ext7/InitErrorExt.java | 2 +- .../ext7/impl/Ext7InitErrorImpl.java | 4 +- .../alibaba/dubbo/common/io/BytesTest.java | 166 +- .../dubbo/common/io/StreamUtilsTest.java | 53 +- .../dubbo/common/json/JSONReaderTest.java | 74 +- .../alibaba/dubbo/common/json/JSONTest.java | 385 +- .../dubbo/common/json/JSONWriterTest.java | 80 +- .../dubbo/common/json/MyException.java | 38 +- .../dubbo/common/model/AnimalEnum.java | 15 +- .../dubbo/common/model/BizException.java | 24 +- .../BizExceptionNoDefaultConstructor.java | 18 +- .../alibaba/dubbo/common/model/Person.java | 46 +- .../common/model/SerializablePerson.java | 47 +- .../dubbo/common/model/media/Image.java | 170 +- .../dubbo/common/model/media/Media.java | 284 +- .../common/model/media/MediaContent.java | 108 +- .../dubbo/common/model/person/BigPerson.java | 70 +- .../common/model/person/FullAddress.java | 122 +- .../dubbo/common/model/person/PersonInfo.java | 102 +- .../dubbo/common/model/person/Phone.java | 74 +- .../serialize/SerializationCompareTest.java | 435 +- .../common/serialize/dubbo/BuilderTest.java | 878 +- .../serialize/dubbo/DataInputOutputTest.java | 213 +- .../common/serialize/dubbo/SimpleDO.java | 42 +- .../AbstractSerializationPersionFailTest.java | 79 +- .../AbstractSerializationPersionOkTest.java | 42 +- .../AbstractSerializationTest.java | 575 +- .../CompactedJavaSerializationTest.java | 23 +- .../serialization/DubboSerializationTest.java | 64 +- .../FastJsonSerializationTest.java | 293 +- .../Hessian2SerializationTest.java | 132 +- .../serialization/JavaSerializationTest.java | 23 +- .../serialization/JsonSerializationTest.java | 278 +- .../store/support/SimpleDataStoreTest.java | 5 +- .../utils/AtomicPositiveIntegerTest.java | 4 +- .../common/utils/CollectionUtilsTest.java | 75 +- .../common/utils/CompatibleTypeUtilsTest.java | 134 +- .../dubbo/common/utils/ConfigUtilsTest.java | 70 +- .../alibaba/dubbo/common/utils/MyEnum.java | 4 +- .../dubbo/common/utils/NetUtilsTest.java | 12 +- .../dubbo/common/utils/ParametersTest.java | 79 +- .../dubbo/common/utils/PojoUtilsTest.java | 551 +- .../dubbo/common/utils/ReflectUtilsTest.java | 279 +- .../dubbo/common/utils/StringUtilsTest.java | 113 +- .../dubbo/common/utils/UrlUtilsTest.java | 20 +- dubbo-common/src/test/resources/log4j.xml | 30 +- dubbo-config/dubbo-config-api/pom.xml | 168 +- .../alibaba/dubbo/config/AbstractConfig.java | 229 +- .../dubbo/config/AbstractInterfaceConfig.java | 186 +- .../dubbo/config/AbstractMethodConfig.java | 50 +- .../dubbo/config/AbstractReferenceConfig.java | 50 +- .../dubbo/config/AbstractServiceConfig.java | 93 +- .../dubbo/config/ApplicationConfig.java | 78 +- .../alibaba/dubbo/config/ArgumentConfig.java | 16 +- .../alibaba/dubbo/config/ConsumerConfig.java | 6 +- .../alibaba/dubbo/config/MethodConfig.java | 76 +- .../alibaba/dubbo/config/ModuleConfig.java | 50 +- .../alibaba/dubbo/config/MonitorConfig.java | 36 +- .../alibaba/dubbo/config/ProtocolConfig.java | 169 +- .../alibaba/dubbo/config/ProviderConfig.java | 128 +- .../alibaba/dubbo/config/ReferenceConfig.java | 359 +- .../alibaba/dubbo/config/RegistryConfig.java | 164 +- .../alibaba/dubbo/config/ServiceConfig.java | 362 +- .../dubbo/config/annotation/Reference.java | 2 +- .../dubbo/config/annotation/Service.java | 9 +- .../dubbo/config/support/Parameter.java | 10 +- .../config/utils/ReferenceConfigCache.java | 89 +- .../dubbo/config/GenericServiceTest.java | 78 +- .../dubbo/config/ReferenceConfigTest.java | 5 +- .../dubbo/config/RpcConfigGetSetProxy.java | 180 +- .../com/alibaba/dubbo/config/api/Box.java | 4 +- .../dubbo/config/api/DemoException.java | 2 +- .../alibaba/dubbo/config/api/DemoService.java | 12 +- .../com/alibaba/dubbo/config/api/User.java | 6 +- .../dubbo/config/cache/CacheService.java | 2 +- .../dubbo/config/cache/CacheServiceImpl.java | 4 +- .../alibaba/dubbo/config/cache/CacheTest.java | 21 +- .../consumer/DemoActionByAnnotation.java | 10 +- .../config/consumer/DemoActionBySetter.java | 4 +- .../config/consumer/DemoInterceptor.java | 6 +- .../config/provider/impl/DemoServiceImpl.java | 12 +- .../impl/DemoServiceImpl_LongWaiting.java | 17 +- .../provider/impl/UnserializableBox.java | 6 +- .../UnserializableBoxDemoServiceImpl.java | 12 +- .../dubbo/config/support/MockProtocol.java | 73 +- .../dubbo/config/support/MockRegistry.java | 62 +- .../config/support/MockRegistryFactory.java | 40 +- .../url/test/ExporterSideConfigUrlTest.java | 97 +- .../url/test/InvokerSideConfigUrlTest.java | 219 +- .../dubbo/config/url/test/UrlTestBase.java | 197 +- .../config/utils/MockReferenceConfig.java | 13 +- .../utils/ReferenceConfigCacheTest.java | 5 +- .../validation/ValidationParameter.java | 9 +- .../config/validation/ValidationService.java | 14 +- .../validation/ValidationServiceImpl.java | 2 +- .../config/validation/ValidationTest.java | 69 +- .../src/test/resources/log4j.xml | 18 +- dubbo-config/dubbo-config-spring/pom.xml | 200 +- .../dubbo/config/spring/AnnotationBean.java | 123 +- .../dubbo/config/spring/ReferenceBean.java | 44 +- .../dubbo/config/spring/ServiceBean.java | 100 +- .../extension/SpringExtensionFactory.java | 12 +- .../schema/DubboBeanDefinitionParser.java | 165 +- .../spring/schema/DubboNamespaceHandler.java | 16 +- .../status/DataSourceStatusChecker.java | 21 +- .../spring/status/SpringStatusChecker.java | 18 +- .../src/main/resources/META-INF/dubbo.xsd | 2308 ++--- .../spring/AbstractRegistryService.java | 60 +- .../dubbo/config/spring/ConfigTest.java | 111 +- .../config/spring/SimpleRegistryExporter.java | 34 +- .../config/spring/SimpleRegistryService.java | 45 +- .../spring/action/DemoActionByAnnotation.java | 10 +- .../spring/action/DemoActionBySetter.java | 4 +- .../config/spring/action/DemoInterceptor.java | 6 +- .../annotation/consumer/AnnotationAction.java | 22 +- .../provider/AnnotationServiceImpl.java | 26 +- .../alibaba/dubbo/config/spring/api/Box.java | 4 +- .../dubbo/config/spring/api/DemoService.java | 20 +- .../config/spring/api/DemoServiceSon.java | 2 +- .../dubbo/config/spring/filter/MockDao.java | 2 +- .../config/spring/filter/MockDaoImpl.java | 2 +- .../config/spring/filter/MockFilter.java | 6 +- .../config/spring/impl/DemoServiceImpl.java | 28 +- .../impl/DemoServiceImpl_LongWaiting.java | 11 +- .../spring/impl/DemoServiceSonImpl.java | 9 +- .../config/spring/impl/UnserializableBox.java | 6 +- .../UnserializableBoxDemoServiceImpl.java | 8 +- .../config/spring/registry/MockRegistry.java | 20 +- .../spring/registry/MockRegistryFactory.java | 20 +- .../config/spring/annotation-consumer.xml | 17 +- .../config/spring/annotation-provider.xml | 14 +- .../spring/annotation-version-consumer.xml | 17 +- .../spring/annotation-version-provider.xml | 14 +- .../config/spring/aop-autowire-byname.xml | 44 +- .../config/spring/aop-autowire-bytype.xml | 44 +- .../config/spring/customize-parameter.xml | 29 +- .../dubbo/config/spring/delay-fixed-time.xml | 30 +- .../config/spring/delay-on-initialized.xml | 30 +- .../demo-provider-UnserializableBox.xml | 30 +- .../spring/demo-provider-long-waiting.xml | 33 +- .../demo-provider-no-methods-interface.xml | 26 +- .../dubbo/config/spring/demo-provider.xml | 30 +- .../dubbo/config/spring/generic-export.xml | 19 +- .../config/spring/init-reference-getUrls.xml | 21 +- .../spring/init-reference-retry-false.xml | 23 +- .../dubbo/config/spring/init-reference.xml | 19 +- .../config/spring/multi-protocol-default.xml | 34 +- .../config/spring/multi-protocol-error.xml | 34 +- .../config/spring/multi-protocol-register.xml | 34 +- .../dubbo/config/spring/multi-protocol.xml | 34 +- .../dubbo/config/spring/multi-registry.xml | 38 +- .../config/spring/override-multi-protocol.xml | 36 +- .../dubbo/config/spring/override-protocol.xml | 30 +- .../config/spring/provider-nested-service.xml | 39 +- .../dubbo/config/spring/service-class.xml | 29 +- .../config/spring/spring-extension-inject.xml | 29 +- .../system-properties-override-default.xml | 17 +- .../spring/system-properties-override.xml | 27 +- .../config/spring/xml-override-properties.xml | 29 +- .../src/test/resources/log4j.xml | 18 +- dubbo-config/pom.xml | 38 +- dubbo-container/dubbo-container-api/pom.xml | 84 +- .../alibaba/dubbo/container/Container.java | 6 +- .../com/alibaba/dubbo/container/Main.java | 60 +- .../alibaba/dubbo/container/page/Menu.java | 8 +- .../dubbo/container/page/MenuComparator.java | 4 +- .../alibaba/dubbo/container/page/Page.java | 28 +- .../dubbo/container/page/PageHandler.java | 6 +- .../dubbo/container/page/PageServlet.java | 50 +- .../dubbo/container/page/ResourceFilter.java | 55 +- .../container/page/pages/HomePageHandler.java | 10 +- .../container/page/pages/LogPageHandler.java | 116 +- .../page/pages/StatusPageHandler.java | 18 +- .../page/pages/SystemPageHandler.java | 47 +- dubbo-container/dubbo-container-jetty/pom.xml | 44 +- .../dubbo/container/jetty/JettyContainer.java | 29 +- .../container/jetty/JettyContainerTest.java | 10 +- dubbo-container/dubbo-container-log4j/pom.xml | 44 +- .../dubbo/container/log4j/Log4jContainer.java | 14 +- .../container/log4j/Log4jContainerTest.java | 8 +- .../dubbo-container-logback/pom.xml | 54 +- .../container/logback/LogbackContainer.java | 143 +- .../logback/LogbackContainerTest.java | 30 +- .../dubbo-container-spring/pom.xml | 52 +- .../container/spring/SpringContainer.java | 20 +- .../container/spring/SpringContainerTest.java | 10 +- .../test/resources/META-INF/spring/test.xml | 12 +- .../src/test/resources/log4j.xml | 18 +- dubbo-container/pom.xml | 44 +- dubbo-demo/dubbo-demo-api/pom.xml | 30 +- .../com/alibaba/dubbo/demo/DemoService.java | 2 +- dubbo-demo/dubbo-demo-consumer/pom.xml | 320 +- .../src/main/assembly/assembly.xml | 44 +- .../alibaba/dubbo/demo/consumer/Consumer.java | 1 + .../dubbo/demo/consumer/DemoAction.java | 14 +- .../META-INF/spring/dubbo-demo-action.xml | 14 +- .../META-INF/spring/dubbo-demo-consumer.xml | 20 +- .../dubbo/demo/consumer/DemoConsumer.java | 8 +- .../src/test/resources/log4j.xml | 18 +- dubbo-demo/dubbo-demo-provider/pom.xml | 320 +- .../src/main/assembly/assembly.xml | 44 +- .../dubbo/demo/provider/DemoServiceImpl.java | 8 +- .../alibaba/dubbo/demo/provider/Provider.java | 2 +- .../META-INF/spring/dubbo-demo-provider.xml | 30 +- .../dubbo/demo/provider/DemoProvider.java | 4 +- .../src/test/resources/log4j.xml | 18 +- dubbo-demo/pom.xml | 40 +- dubbo-filter/dubbo-filter-cache/pom.xml | 54 +- .../java/com/alibaba/dubbo/cache/Cache.java | 2 +- .../com/alibaba/dubbo/cache/CacheFactory.java | 2 +- .../dubbo/cache/filter/CacheFilter.java | 4 +- .../cache/support/AbstractCacheFactory.java | 10 +- .../dubbo/cache/support/jcache/JCache.java | 6 +- .../cache/support/jcache/JCacheFactory.java | 2 +- .../dubbo/cache/support/lru/LruCache.java | 11 +- .../cache/support/lru/LruCacheFactory.java | 2 +- .../support/threadlocal/ThreadLocalCache.java | 8 +- .../threadlocal/ThreadLocalCacheFactory.java | 2 +- dubbo-filter/dubbo-filter-validation/pom.xml | 54 +- .../alibaba/dubbo/validation/Validation.java | 2 +- .../alibaba/dubbo/validation/Validator.java | 2 +- .../validation/filter/ValidationFilter.java | 6 +- .../support/AbstractValidation.java | 8 +- .../support/jvalidation/JValidation.java | 2 +- .../support/jvalidation/JValidator.java | 161 +- dubbo-filter/pom.xml | 38 +- dubbo-maven/pom.xml | 662 +- dubbo-monitor/dubbo-monitor-api/pom.xml | 44 +- .../com/alibaba/dubbo/monitor/Monitor.java | 4 +- .../alibaba/dubbo/monitor/MonitorFactory.java | 6 +- .../alibaba/dubbo/monitor/MonitorService.java | 18 +- .../support/AbstractMonitorFactory.java | 20 +- .../dubbo/monitor/support/MonitorFilter.java | 47 +- .../support/AbstractMonitorFactoryTest.java | 49 +- .../monitor/support/MonitorFilterTest.java | 44 +- dubbo-monitor/dubbo-monitor-default/pom.xml | 68 +- .../dubbo/monitor/dubbo/DubboMonitor.java | 52 +- .../monitor/dubbo/DubboMonitorFactroy.java | 8 +- .../dubbo/monitor/dubbo/Statistics.java | 20 +- .../dubbo/monitor/dubbo/DubboMonitorTest.java | 63 +- .../monitor/dubbo/MockMonitorService.java | 16 +- dubbo-monitor/pom.xml | 38 +- dubbo-registry/dubbo-registry-api/pom.xml | 66 +- .../dubbo/registry/NotifyListener.java | 12 +- .../com/alibaba/dubbo/registry/Registry.java | 4 +- .../dubbo/registry/RegistryFactory.java | 8 +- .../dubbo/registry/RegistryService.java | 32 +- .../integration/RegistryDirectory.java | 339 +- .../integration/RegistryProtocol.java | 329 +- .../registry/pages/RegisteredPageHandler.java | 14 +- .../registry/pages/RegistriesPageHandler.java | 12 +- .../registry/pages/SubscribedPageHandler.java | 14 +- .../status/RegistryStatusChecker.java | 8 +- .../registry/support/AbstractRegistry.java | 179 +- .../support/AbstractRegistryFactory.java | 26 +- .../registry/support/FailbackRegistry.java | 48 +- .../registry/PerformanceRegistryTest.java | 13 +- .../dubbo/registry/PerformanceUtils.java | 29 +- .../dubbo/registry/RegistryTestSupport.java | 32 +- .../support/AbstractRegistryFactoryTest.java | 24 +- .../support/FailbackRegistryTest.java | 46 +- .../src/test/resources/log4j.xml | 22 +- dubbo-registry/dubbo-registry-default/pom.xml | 92 +- .../dubbo/registry/dubbo/DubboRegistry.java | 54 +- .../registry/dubbo/DubboRegistryFactory.java | 58 +- .../dubbo/AbstractRegistryService.java | 60 +- .../dubbo/registry/dubbo/DemoService.java | 21 +- .../dubbo/registry/dubbo/MockChannel.java | 40 +- .../dubbo/registry/dubbo/MockedClient.java | 168 +- .../registry/dubbo/RegistryDirectoryTest.java | 340 +- .../registry/dubbo/RegistryProtocolTest.java | 73 +- .../dubbo/RegistryStatusCheckerTest.java | 15 +- .../dubbo/SimpleRegistryExporter.java | 34 +- .../registry/dubbo/SimpleRegistryService.java | 45 +- .../src/test/resources/log4j.xml | 46 +- .../dubbo-registry-multicast/pom.xml | 44 +- .../registry/multicast/MulticastRegistry.java | 72 +- .../multicast/MulticastRegistryFactory.java | 2 +- .../multicast/MulticastRegistryTest.java | 35 +- dubbo-registry/dubbo-registry-redis/pom.xml | 54 +- .../dubbo/registry/redis/RedisRegistry.java | 138 +- .../registry/redis/RedisRegistryFactory.java | 2 +- .../registry/redis/RedisRegistryTest.java | 17 +- .../dubbo-registry-zookeeper/pom.xml | 54 +- .../registry/zookeeper/ZookeeperRegistry.java | 118 +- .../zookeeper/ZookeeperRegistryFactory.java | 12 +- .../zookeeper/ZookeeperRegistryTest.java | 19 +- dubbo-registry/pom.xml | 44 +- dubbo-remoting/dubbo-remoting-api/pom.xml | 44 +- .../com/alibaba/dubbo/remoting/Channel.java | 24 +- .../dubbo/remoting/ChannelHandler.java | 18 +- .../com/alibaba/dubbo/remoting/Client.java | 10 +- .../com/alibaba/dubbo/remoting/Codec.java | 46 +- .../com/alibaba/dubbo/remoting/Codec2.java | 4 +- .../alibaba/dubbo/remoting/Dispatcher.java | 7 +- .../com/alibaba/dubbo/remoting/Endpoint.java | 28 +- .../dubbo/remoting/ExecutionException.java | 20 +- .../dubbo/remoting/RemotingException.java | 24 +- .../com/alibaba/dubbo/remoting/Server.java | 20 +- .../dubbo/remoting/TimeoutException.java | 17 +- .../alibaba/dubbo/remoting/Transporter.java | 26 +- .../alibaba/dubbo/remoting/Transporters.java | 20 +- .../buffer/AbstractChannelBuffer.java | 10 +- .../buffer/ByteBufferBackedChannelBuffer.java | 46 +- .../dubbo/remoting/buffer/ChannelBuffer.java | 21 +- .../remoting/buffer/ChannelBufferFactory.java | 6 +- .../buffer/ChannelBufferInputStream.java | 6 +- .../buffer/ChannelBufferOutputStream.java | 2 +- .../dubbo/remoting/buffer/ChannelBuffers.java | 5 +- .../buffer/DirectChannelBufferFactory.java | 8 +- .../remoting/buffer/DynamicChannelBuffer.java | 36 +- .../remoting/buffer/HeapChannelBuffer.java | 4 +- .../buffer/HeapChannelBufferFactory.java | 10 +- .../remoting/exchange/ExchangeChannel.java | 10 +- .../remoting/exchange/ExchangeClient.java | 2 +- .../remoting/exchange/ExchangeHandler.java | 4 +- .../remoting/exchange/ExchangeServer.java | 10 +- .../dubbo/remoting/exchange/Exchanger.java | 8 +- .../dubbo/remoting/exchange/Exchangers.java | 24 +- .../dubbo/remoting/exchange/Request.java | 62 +- .../dubbo/remoting/exchange/Response.java | 124 +- .../remoting/exchange/ResponseCallback.java | 6 +- .../remoting/exchange/ResponseFuture.java | 14 +- .../exchange/codec/ExchangeCodec.java | 72 +- .../exchange/support/DefaultFuture.java | 354 +- .../support/ExchangeHandlerAdapter.java | 2 +- .../support/ExchangeHandlerDispatcher.java | 20 +- .../support/ExchangeServerDelegate.java | 20 +- .../exchange/support/MultiMessage.java | 9 +- .../remoting/exchange/support/Replier.java | 4 +- .../exchange/support/ReplierDispatcher.java | 26 +- .../exchange/support/SimpleFuture.java | 6 +- .../support/header/HeaderExchangeChannel.java | 30 +- .../support/header/HeaderExchangeClient.java | 67 +- .../support/header/HeaderExchangeHandler.java | 46 +- .../support/header/HeaderExchangeServer.java | 78 +- .../support/header/HeaderExchanger.java | 4 +- .../support/header/HeartBeatTask.java | 66 +- .../support/header/HeartbeatHandler.java | 20 +- .../dubbo/remoting/telnet/TelnetHandler.java | 4 +- .../remoting/telnet/codec/TelnetCodec.java | 222 +- .../dubbo/remoting/telnet/support/Help.java | 2 +- .../telnet/support/TelnetHandlerAdapter.java | 2 +- .../remoting/telnet/support/TelnetUtils.java | 64 +- .../support/command/ClearTelnetHandler.java | 6 +- .../support/command/ExitTelnetHandler.java | 2 +- .../support/command/HelpTelnetHandler.java | 12 +- .../support/command/LogTelnetHandler.java | 134 +- .../support/command/StatusTelnetHandler.java | 18 +- .../remoting/transport/AbstractChannel.java | 8 +- .../AbstractChannelHandlerDelegate.java | 2 +- .../remoting/transport/AbstractClient.java | 234 +- .../remoting/transport/AbstractCodec.java | 64 +- .../remoting/transport/AbstractEndpoint.java | 40 +- .../remoting/transport/AbstractPeer.java | 13 +- .../remoting/transport/AbstractServer.java | 146 +- .../remoting/transport/ChannelDelegate.java | 13 +- .../transport/ChannelHandlerAdapter.java | 32 +- .../transport/ChannelHandlerDispatcher.java | 16 +- .../remoting/transport/ClientDelegate.java | 19 +- .../remoting/transport/CodecSupport.java | 23 +- .../remoting/transport/DecodeHandler.java | 16 +- .../transport/MultiMessageHandler.java | 7 +- .../remoting/transport/ServerDelegate.java | 22 +- .../transport/codec/CodecAdapter.java | 12 +- .../transport/codec/TransportCodec.java | 10 +- .../dispatcher/ChannelEventRunnable.java | 57 +- .../transport/dispatcher/ChannelHandlers.java | 20 +- .../dispatcher/WrappedChannelHandler.java | 24 +- .../dispatcher/all/AllChannelHandler.java | 42 +- .../dispatcher/all/AllDispatcher.java | 4 +- .../ConnectionOrderedChannelHandler.java | 64 +- .../ConnectionOrderedDispatcher.java | 2 +- .../dispatcher/direct/DirectDispatcher.java | 4 +- .../execution/ExecutionChannelHandler.java | 10 +- .../execution/ExecutionDispatcher.java | 4 +- .../message/MessageOnlyChannelHandler.java | 8 +- .../message/MessageOnlyDispatcher.java | 2 +- .../dubbo/remoting/ChanelHandlerTest.java | 131 +- .../alibaba/dubbo/remoting/DemoService.java | 21 +- .../dubbo/remoting/DemoServiceImpl.java | 47 +- .../java/com/alibaba/dubbo/remoting/Main.java | 247 +- .../alibaba/dubbo/remoting/MockResult.java | 53 +- .../remoting/PerformanceClientCloseTest.java | 23 +- .../remoting/PerformanceClientFixedTest.java | 31 +- .../dubbo/remoting/PerformanceClientTest.java | 91 +- .../dubbo/remoting/PerformanceServerMain.java | 26 +- .../dubbo/remoting/PerformanceServerTest.java | 144 +- .../dubbo/remoting/PerformanceUtils.java | 29 +- .../alibaba/dubbo/remoting/RpcMessage.java | 55 +- .../dubbo/remoting/RpcMessageHandler.java | 97 +- .../alibaba/dubbo/remoting/TelnetServer.java | 3 +- .../buffer/AbstractChannelBufferTest.java | 99 +- .../buffer/DirectChannelBufferTest.java | 2 +- .../remoting/codec/AbstractMockChannel.java | 68 +- .../remoting/codec/ExchangeCodecTest.java | 274 +- .../dubbo/remoting/codec/TelnetCodecTest.java | 335 +- .../support/header/HeartBeatTaskTest.java | 15 +- .../exchange/support/header/MockChannel.java | 6 +- .../handler/ConnectChannelHandlerTest.java | 85 +- .../handler/HeaderExchangeHandlerTest.java | 88 +- .../dubbo/remoting/handler/MockedChannel.java | 61 +- .../handler/MockedChannelHandler.java | 44 +- .../handler/WrappedChannelHandlerTest.java | 145 +- .../remoting/transport/AbstractCodecTest.java | 12 +- .../transport/codec/CodecAdapterTest.java | 14 +- .../codec/DeprecatedExchangeCodec.java | 21 +- .../codec/DeprecatedTelnetCodec.java | 197 +- .../src/test/resources/log4j.xml | 22 +- dubbo-remoting/dubbo-remoting-grizzly/pom.xml | 52 +- .../transport/grizzly/GrizzlyChannel.java | 34 +- .../transport/grizzly/GrizzlyClient.java | 31 +- .../grizzly/GrizzlyCodecAdapter.java | 36 +- .../transport/grizzly/GrizzlyHandler.java | 28 +- .../transport/grizzly/GrizzlyServer.java | 42 +- .../transport/grizzly/GrizzlyTransporter.java | 2 +- dubbo-remoting/dubbo-remoting-http/pom.xml | 52 +- .../dubbo/remoting/http/HttpBinder.java | 8 +- .../dubbo/remoting/http/HttpHandler.java | 53 +- .../dubbo/remoting/http/HttpServer.java | 30 +- .../remoting/http/jetty/JettyHttpBinder.java | 2 +- .../remoting/http/jetty/JettyHttpServer.java | 28 +- .../http/servlet/DispatcherServlet.java | 83 +- .../http/servlet/ServletHttpBinder.java | 4 +- .../http/servlet/ServletHttpServer.java | 6 +- .../http/support/AbstractHttpServer.java | 16 +- dubbo-remoting/dubbo-remoting-mina/pom.xml | 60 +- .../remoting/transport/mina/MinaChannel.java | 54 +- .../remoting/transport/mina/MinaClient.java | 116 +- .../transport/mina/MinaCodecAdapter.java | 32 +- .../remoting/transport/mina/MinaHandler.java | 42 +- .../remoting/transport/mina/MinaServer.java | 36 +- .../transport/mina/MinaTransporter.java | 36 +- .../transport/mina/ClientToServerTest.java | 57 +- .../remoting/transport/mina/ClientsTest.java | 12 +- .../remoting/transport/mina/Hello.java | 36 +- .../mina/MinaClientToServerTest.java | 32 +- .../remoting/transport/mina/World.java | 36 +- .../remoting/transport/mina/WorldHandler.java | 32 +- dubbo-remoting/dubbo-remoting-netty/pom.xml | 52 +- .../netty/NettyBackedChannelBuffer.java | 138 +- .../NettyBackedChannelBufferFactory.java | 12 +- .../transport/netty/NettyChannel.java | 68 +- .../remoting/transport/netty/NettyClient.java | 52 +- .../transport/netty/NettyCodecAdapter.java | 38 +- .../transport/netty/NettyHandler.java | 58 +- .../remoting/transport/netty/NettyHelper.java | 6 +- .../remoting/transport/netty/NettyServer.java | 46 +- .../transport/netty/NettyTransporter.java | 36 +- .../support/header/HeartbeatHandlerTest.java | 7 +- .../dispatcher/FakeChannelHandlers.java | 12 +- .../transport/netty/ClientReconnectTest.java | 201 +- .../transport/netty/ClientToServerTest.java | 57 +- .../remoting/transport/netty/ClientsTest.java | 10 +- .../dubbo/remoting/transport/netty/Hello.java | 36 +- .../transport/netty/NettyClientTest.java | 73 +- .../netty/NettyClientToServerTest.java | 32 +- .../transport/netty/NettyStringTest.java | 26 +- .../transport/netty/TelnetServerHandler.java | 32 +- .../transport/netty/ThreadNameTest.java | 20 +- .../dubbo/remoting/transport/netty/World.java | 36 +- .../transport/netty/WorldHandler.java | 32 +- .../src/test/resources/log4j.xml | 38 +- dubbo-remoting/dubbo-remoting-p2p/pom.xml | 44 +- .../com/alibaba/dubbo/remoting/p2p/Group.java | 14 +- .../alibaba/dubbo/remoting/p2p/Networker.java | 6 +- .../dubbo/remoting/p2p/Networkers.java | 10 +- .../com/alibaba/dubbo/remoting/p2p/Peer.java | 8 +- .../remoting/p2p/exchange/ExchangeGroup.java | 4 +- .../p2p/exchange/ExchangeNetworker.java | 4 +- .../p2p/exchange/ExchangeNetworkers.java | 8 +- .../remoting/p2p/exchange/ExchangePeer.java | 2 +- .../support/AbstractExchangeGroup.java | 24 +- .../exchange/support/ExchangeServerPeer.java | 22 +- .../exchange/support/FileExchangeGroup.java | 37 +- .../support/FileExchangeNetworker.java | 2 +- .../support/MulticastExchangeGroup.java | 28 +- .../support/MulticastExchangeNetworker.java | 2 +- .../remoting/p2p/support/AbstractGroup.java | 22 +- .../dubbo/remoting/p2p/support/FileGroup.java | 35 +- .../remoting/p2p/support/FileNetworker.java | 2 +- .../remoting/p2p/support/MulticastGroup.java | 28 +- .../p2p/support/MulticastNetworker.java | 2 +- .../remoting/p2p/support/ServerPeer.java | 20 +- .../alibaba/dubbo/remoting/p2p/PeerMain.java | 18 +- .../dubbo-remoting-zookeeper/pom.xml | 68 +- .../remoting/zookeeper/ChildListener.java | 2 +- .../remoting/zookeeper/StateListener.java | 8 +- .../remoting/zookeeper/ZookeeperClient.java | 26 +- .../zookeeper/ZookeeperTransporter.java | 4 +- .../curator/CuratorZookeeperClient.java | 240 +- .../curator/CuratorZookeeperTransporter.java | 6 +- .../support/AbstractZookeeperClient.java | 202 +- .../zkclient/ZkclientZookeeperClient.java | 155 +- .../ZkclientZookeeperTransporter.java | 6 +- dubbo-remoting/pom.xml | 46 +- dubbo-rpc/dubbo-rpc-api/pom.xml | 44 +- .../java/com/alibaba/dubbo/rpc/Exporter.java | 14 +- .../alibaba/dubbo/rpc/ExporterListener.java | 10 +- .../java/com/alibaba/dubbo/rpc/Filter.java | 26 +- .../com/alibaba/dubbo/rpc/Invocation.java | 86 +- .../java/com/alibaba/dubbo/rpc/Invoker.java | 8 +- .../alibaba/dubbo/rpc/InvokerListener.java | 10 +- .../java/com/alibaba/dubbo/rpc/Protocol.java | 16 +- .../com/alibaba/dubbo/rpc/ProxyFactory.java | 6 +- .../java/com/alibaba/dubbo/rpc/Result.java | 42 +- .../com/alibaba/dubbo/rpc/RpcConstants.java | 7 +- .../com/alibaba/dubbo/rpc/RpcContext.java | 484 +- .../com/alibaba/dubbo/rpc/RpcException.java | 31 +- .../com/alibaba/dubbo/rpc/RpcInvocation.java | 80 +- .../java/com/alibaba/dubbo/rpc/RpcResult.java | 34 +- .../java/com/alibaba/dubbo/rpc/RpcStatus.java | 86 +- .../com/alibaba/dubbo/rpc/StaticContext.java | 78 +- .../dubbo/rpc/filter/AccessLogFilter.java | 142 +- .../dubbo/rpc/filter/ActiveLimitFilter.java | 14 +- .../dubbo/rpc/filter/ClassLoaderFilter.java | 2 +- .../dubbo/rpc/filter/CompatibleFilter.java | 24 +- .../rpc/filter/ConsumerContextFilter.java | 8 +- .../dubbo/rpc/filter/ContextFilter.java | 14 +- .../dubbo/rpc/filter/DeprecatedFilter.java | 10 +- .../alibaba/dubbo/rpc/filter/EchoFilter.java | 12 +- .../dubbo/rpc/filter/ExceptionFilter.java | 20 +- .../dubbo/rpc/filter/ExecuteLimitFilter.java | 10 +- .../dubbo/rpc/filter/GenericFilter.java | 58 +- .../dubbo/rpc/filter/GenericImplFilter.java | 74 +- .../dubbo/rpc/filter/TimeoutFilter.java | 22 +- .../alibaba/dubbo/rpc/filter/TokenFilter.java | 32 +- .../rpc/filter/tps/DefaultTPSLimiter.java | 14 +- .../dubbo/rpc/filter/tps/StatItem.java | 16 +- .../dubbo/rpc/filter/tps/TPSLimiter.java | 2 +- .../listener/DeprecatedInvokerListener.java | 2 +- .../rpc/listener/ExporterListenerAdapter.java | 2 +- .../rpc/listener/InvokerListenerAdapter.java | 2 +- .../rpc/listener/ListenerExporterWrapper.java | 10 +- .../rpc/listener/ListenerInvokerWrapper.java | 18 +- .../dubbo/rpc/protocol/AbstractExporter.java | 6 +- .../dubbo/rpc/protocol/AbstractInvoker.java | 114 +- .../dubbo/rpc/protocol/AbstractProtocol.java | 89 +- .../rpc/protocol/AbstractProxyProtocol.java | 23 +- .../dubbo/rpc/protocol/InvokerWrapper.java | 6 +- .../rpc/protocol/ProtocolFilterWrapper.java | 56 +- .../rpc/protocol/ProtocolListenerWrapper.java | 14 +- .../dubbo/rpc/proxy/AbstractProxyFactory.java | 8 +- .../dubbo/rpc/proxy/AbstractProxyInvoker.java | 56 +- .../rpc/proxy/InvokerInvocationHandler.java | 42 +- .../javassist/JavassistProxyFactory.java | 52 +- .../dubbo/rpc/proxy/jdk/JdkProxyFactory.java | 52 +- .../wrapper/StubProxyFactoryWrapper.java | 36 +- .../dubbo/rpc/service/EchoService.java | 4 +- .../dubbo/rpc/service/GenericException.java | 48 +- .../dubbo/rpc/service/GenericService.java | 8 +- .../dubbo/rpc/support/DelegateExporter.java | 15 +- .../dubbo/rpc/support/DelegateInvoker.java | 2 +- .../dubbo/rpc/support/MockInvoker.java | 265 +- .../dubbo/rpc/support/MockProtocol.java | 20 +- .../dubbo/rpc/support/ProtocolUtils.java | 14 +- .../alibaba/dubbo/rpc/support/RpcUtils.java | 140 +- .../com/alibaba/dubbo/rpc/CustomArgument.java | 52 +- .../com/alibaba/dubbo/rpc/DemoRequest.java | 87 +- .../com/alibaba/dubbo/rpc/ProtocolUtils.java | 10 +- .../dubbo/rpc/filter/AccessLogFilterTest.java | 10 +- .../rpc/filter/ActiveLimitFilterTest.java | 14 +- .../filter/CompatibleFilterFilterTest.java | 48 +- .../rpc/filter/ConsumerContextFilterTest.java | 24 +- .../dubbo/rpc/filter/ContextFilterTest.java | 19 +- .../rpc/filter/DeprecatedFilterTest.java | 12 +- .../dubbo/rpc/filter/EchoFilterTest.java | 20 +- .../dubbo/rpc/filter/ExceptionFilterTest.java | 20 +- .../dubbo/rpc/filter/TpsLimitFilterTest.java | 7 +- .../dubbo/rpc/filter/tps/StatItemTest.java | 9 +- .../alibaba/dubbo/rpc/proxy/DemoRequest.java | 87 +- .../alibaba/dubbo/rpc/proxy/DemoService.java | 51 +- .../dubbo/rpc/proxy/DemoServiceImpl.java | 115 +- .../dubbo/rpc/proxy/RemoteService.java | 19 +- .../dubbo/rpc/proxy/RemoteServiceImpl.java | 53 +- .../com/alibaba/dubbo/rpc/proxy/Type.java | 9 +- .../dubbo/rpc/support/DemoService.java | 67 +- .../dubbo/rpc/support/DemoServiceImpl.java | 159 +- .../dubbo/rpc/support/MockInvocation.java | 12 +- .../alibaba/dubbo/rpc/support/MyInvoker.java | 10 +- .../com/alibaba/dubbo/rpc/support/Person.java | 6 +- .../dubbo/rpc/support/RpcUtilsTest.java | 145 +- .../com/alibaba/dubbo/rpc/support/Type.java | 9 +- .../src/test/resources/log4j.xml | 66 +- dubbo-rpc/dubbo-rpc-default/pom.xml | 98 +- .../protocol/dubbo/CallbackServiceCodec.java | 297 +- .../protocol/dubbo/ChannelWrappedInvoker.java | 68 +- .../dubbo/DecodeableRpcInvocation.java | 20 +- .../protocol/dubbo/DecodeableRpcResult.java | 24 +- .../dubbo/rpc/protocol/dubbo/DubboCodec.java | 39 +- .../rpc/protocol/dubbo/DubboCountCodec.java | 12 +- .../rpc/protocol/dubbo/DubboExporter.java | 10 +- .../rpc/protocol/dubbo/DubboInvoker.java | 64 +- .../rpc/protocol/dubbo/DubboProtocol.java | 168 +- .../rpc/protocol/dubbo/FutureAdapter.java | 16 +- .../dubbo/LazyConnectExchangeClient.java | 188 +- .../dubbo/ReferenceCountExchangeClient.java | 64 +- .../protocol/dubbo/filter/FutureFilter.java | 114 +- .../protocol/dubbo/filter/TraceFilter.java | 42 +- .../dubbo/page/ClientsPageHandler.java | 10 +- .../dubbo/page/ServersPageHandler.java | 12 +- .../dubbo/status/ServerStatusChecker.java | 8 +- .../dubbo/status/ThreadPoolStatusChecker.java | 16 +- .../dubbo/telnet/ChangeTelnetHandler.java | 4 +- .../dubbo/telnet/CountTelnetHandler.java | 16 +- .../dubbo/telnet/CurrentTelnetHandler.java | 4 +- .../dubbo/telnet/InvokeTelnetHandler.java | 104 +- .../dubbo/telnet/ListTelnetHandler.java | 6 +- .../dubbo/telnet/LogTelnetHandler.java | 94 +- .../dubbo/telnet/PortTelnetHandler.java | 8 +- .../dubbo/telnet/TraceTelnetHandler.java | 10 +- .../dubbo/DubboInvokerAvilableTest.java | 98 +- .../protocol/dubbo/DubboLazyConnectTest.java | 83 +- .../rpc/protocol/dubbo/DubboProtocolTest.java | 146 +- .../protocol/dubbo/ExplicitCallbackTest.java | 409 +- .../rpc/protocol/dubbo/FutureFilterTest.java | 24 +- .../protocol/dubbo/ImplicitCallBackTest.java | 393 +- .../rpc/protocol/dubbo/MultiThreadTest.java | 121 +- .../ReferenceCountExchangeClientTest.java | 181 +- .../rpc/protocol/dubbo/RpcFilterTest.java | 70 +- .../dubbo/support/CustomArgument.java | 50 +- .../protocol/dubbo/support/DemoRequest.java | 87 +- .../protocol/dubbo/support/DemoService.java | 48 +- .../dubbo/support/DemoServiceImpl.java | 131 +- .../rpc/protocol/dubbo/support/EnumBak.java | 193 +- .../protocol/dubbo/support/NonSerialized.java | 2 +- .../rpc/protocol/dubbo/support/Person.java | 6 +- .../protocol/dubbo/support/ProtocolUtils.java | 14 +- .../protocol/dubbo/support/RemoteService.java | 19 +- .../dubbo/support/RemoteServiceImpl.java | 53 +- .../rpc/protocol/dubbo/support/Type.java | 9 +- .../dubbo/telnet/ChangeTelnetHandlerTest.java | 32 +- .../telnet/CurrentTelnetHandlerTest.java | 14 +- .../telnet/InvokerTelnetHandlerTest.java | 22 +- .../dubbo/telnet/ListTelnetHandlerTest.java | 36 +- .../dubbo/telnet/LogTelnetHandlerTest.java | 12 +- .../dubbo/telnet/PortTelnetHandlerTest.java | 21 +- .../src/test/resources/log4j.xml | 56 +- dubbo-rpc/dubbo-rpc-hessian/pom.xml | 74 +- .../rpc/protocol/hessian/HessianProtocol.java | 160 +- .../hessian/HttpClientConnection.java | 23 +- .../hessian/HttpClientConnectionFactory.java | 17 +- .../protocol/hessian/HessianProtocolTest.java | 22 +- .../rpc/protocol/hessian/HessianService.java | 12 +- .../protocol/hessian/HessianServiceImpl.java | 12 +- dubbo-rpc/dubbo-rpc-http/pom.xml | 70 +- .../dubbo/rpc/protocol/http/HttpProtocol.java | 103 +- dubbo-rpc/dubbo-rpc-injvm/pom.xml | 44 +- .../rpc/protocol/injvm/InjvmExporter.java | 10 +- .../rpc/protocol/injvm/InjvmInvoker.java | 27 +- .../rpc/protocol/injvm/InjvmProtocol.java | 83 +- .../dubbo/rpc/protocol/injvm/DemoRequest.java | 57 +- .../dubbo/rpc/protocol/injvm/DemoService.java | 21 +- .../rpc/protocol/injvm/DemoServiceImpl.java | 85 +- .../rpc/protocol/injvm/InjvmProtocolTest.java | 44 +- .../rpc/protocol/injvm/ProtocolTest.java | 34 +- .../dubbo/rpc/protocol/injvm/Type.java | 5 +- dubbo-rpc/dubbo-rpc-memcached/pom.xml | 52 +- .../protocol/memcached/MemcachedProtocol.java | 25 +- dubbo-rpc/dubbo-rpc-redis/pom.xml | 54 +- .../rpc/protocol/redis/RedisProtocol.java | 46 +- dubbo-rpc/dubbo-rpc-rmi/pom.xml | 52 +- .../dubbo/rpc/protocol/rmi/RmiProtocol.java | 16 +- .../dubbo/rpc/protocol/rmi/DemoService.java | 25 +- .../rpc/protocol/rmi/DemoServiceImpl.java | 85 +- .../dubbo/rpc/protocol/rmi/RemoteService.java | 7 +- .../rpc/protocol/rmi/RemoteServiceImpl.java | 23 +- .../rpc/protocol/rmi/RmiProtocolTest.java | 108 +- .../alibaba/dubbo/rpc/protocol/rmi/Type.java | 5 +- dubbo-rpc/dubbo-rpc-thrift/pom.xml | 90 +- .../protocol/thrift/ClassNameGenerator.java | 10 +- .../thrift/DubboClassNameGenerator.java | 12 +- .../thrift/ThriftClassNameGenerator.java | 12 +- .../rpc/protocol/thrift/ThriftCodec.java | 594 +- .../rpc/protocol/thrift/ThriftConstants.java | 7 +- .../rpc/protocol/thrift/ThriftInvoker.java | 44 +- .../protocol/thrift/ThriftNativeCodec.java | 60 +- .../rpc/protocol/thrift/ThriftProtocol.java | 92 +- .../dubbo/rpc/protocol/thrift/ThriftType.java | 29 +- .../rpc/protocol/thrift/ThriftUtils.java | 116 +- .../thrift/ext/MultiServiceProcessor.java | 82 +- .../io/RandomAccessByteArrayOutputStream.java | 51 +- .../test/java/$__ClassNameTestDubboStub.java | 1082 +-- .../src/test/java/ClassNameTest.java | 29 +- .../src/test/java/ClassNameTestDubbo.java | 20 +- .../src/test/java/ClassNameTestThrift.java | 1253 +-- .../dubbo/rpc/gen/dubbo/$__DemoStub.java | 7240 ++++++++------- .../com/alibaba/dubbo/rpc/gen/dubbo/Demo.java | 33 +- .../alibaba/dubbo/rpc/gen/thrift/Demo.java | 7981 ++++++++--------- .../rpc/protocol/thrift/AbstractTest.java | 41 +- .../dubbo/rpc/protocol/thrift/DemoImpl.java | 20 +- .../rpc/protocol/thrift/DubboDemoImpl.java | 7 +- .../thrift/FramedTransportFactory.java | 8 +- .../rpc/protocol/thrift/MockedChannel.java | 20 +- .../protocol/thrift/ServerExceptionTest.java | 37 +- .../thrift/ServiceMethodNotFoundTest.java | 50 +- .../rpc/protocol/thrift/ThriftCodecTest.java | 372 +- .../rpc/protocol/thrift/ThriftDemoImpl.java | 8 +- .../protocol/thrift/ThriftProtocolTest.java | 14 +- .../rpc/protocol/thrift/ThriftUtilsTest.java | 65 +- .../thrift/examples/DubboDemoConsumer.java | 4 +- .../test/resources/dubbo-demo-consumer.xml | 8 +- .../test/resources/dubbo-demo-provider.xml | 6 +- dubbo-rpc/dubbo-rpc-webservice/pom.xml | 78 +- .../webservice/WebServiceProtocol.java | 127 +- dubbo-rpc/pom.xml | 54 +- dubbo-simple/dubbo-monitor-simple/pom.xml | 318 +- .../src/main/assembly/assembly.xml | 44 +- .../dubbo/monitor/simple/CountUtils.java | 22 +- .../monitor/simple/RegistryContainer.java | 58 +- .../monitor/simple/SimpleMonitorService.java | 295 +- .../simple/pages/ApplicationsPageHandler.java | 26 +- .../simple/pages/ChartsPageHandler.java | 20 +- .../simple/pages/ConsumersPageHandler.java | 24 +- .../simple/pages/DependenciesPageHandler.java | 26 +- .../simple/pages/HostsPageHandler.java | 26 +- .../simple/pages/ProvidersPageHandler.java | 24 +- .../simple/pages/ServicesPageHandler.java | 16 +- .../simple/pages/StatisticsPageHandler.java | 30 +- .../simple/pages/UnregisterPageHandler.java | 2 +- .../simple/pages/UnsubscribePageHandler.java | 20 +- .../META-INF/spring/dubbo-monitor-simple.xml | 48 +- .../dubbo/monitor/simple/SimpleMonitor.java | 4 +- .../simple/SimpleMonitorServiceTest.java | 8 +- .../src/test/resources/log4j.xml | 18 +- dubbo-simple/dubbo-registry-simple/pom.xml | 126 +- .../src/main/assembly/assembly.xml | 44 +- .../simple/SimpleRegistryService.java | 96 +- .../META-INF/spring/dubbo-registry-simple.xml | 39 +- .../dubbo/registry/simple/SimpleRegistry.java | 4 +- .../simple/SimpleRegistryServiceTest.java | 4 +- .../src/test/resources/log4j.xml | 18 +- dubbo-simple/pom.xml | 38 +- dubbo-test/dubbo-test-benchmark/pom.xml | 108 +- .../dubbo-test-benchmark/src/assembly/dev.xml | 34 +- .../src/assembly/release.xml | 34 +- .../benchmark/AbstractBenchmarkClient.java | 62 +- .../benchmark/AbstractBenchmarkServer.java | 13 +- .../rpc/benchmark/AbstractClientRunnable.java | 41 +- .../dubbo/rpc/benchmark/BenchmarkClient.java | 10 +- .../dubbo/rpc/benchmark/ClientRunnable.java | 12 +- .../dubbo/rpc/benchmark/DemoService.java | 2 +- .../dubbo/rpc/benchmark/DemoServiceImpl.java | 4 +- .../rpc/benchmark/ExchangeClientFactory.java | 43 +- .../dubbo/rpc/benchmark/RequestObject.java | 22 +- .../dubbo/rpc/benchmark/ResponseObject.java | 32 +- .../rpc/benchmark/RpcBenchmarkClient.java | 18 +- .../dubbo/rpc/benchmark/RpcClient.java | 15 +- .../dubbo/rpc/benchmark/ServiceFactory.java | 28 +- ...impleProcessorBenchmarkClientRunnable.java | 51 +- .../src/main/resources/ProviderSample.xml | 50 +- .../src/test/backup/BenchmarkRunner.java | 1923 ++-- .../src/test/backup/Dubbo.java | 51 +- .../client/DemoBenchmarkClientRunnable.java | 13 +- dubbo-test/dubbo-test-compatibility/pom.xml | 44 +- dubbo-test/dubbo-test-examples/pom.xml | 250 +- .../annotation/AnnotationConsumer.java | 8 +- .../annotation/AnnotationProvider.java | 6 +- .../annotation/action/AnnotationAction.java | 10 +- .../annotation/annotation-consumer.xml | 18 +- .../annotation/annotation-provider.xml | 24 +- .../annotation/api/AnnotationService.java | 4 +- .../impl/AnnotationServiceImpl.java | 2 +- .../dubbo/examples/async/AsyncConsumer.java | 22 +- .../dubbo/examples/async/AsyncProvider.java | 6 +- .../examples/async/api/AsyncService.java | 4 +- .../dubbo/examples/async/async-consumer.xml | 18 +- .../dubbo/examples/async/async-provider.xml | 28 +- .../examples/async/impl/AsyncServiceImpl.java | 2 +- .../dubbo/examples/cache/CacheConsumer.java | 26 +- .../dubbo/examples/cache/CacheProvider.java | 4 +- .../examples/cache/api/CacheService.java | 2 +- .../dubbo/examples/cache/cache-consumer.xml | 18 +- .../dubbo/examples/cache/cache-provider.xml | 28 +- .../examples/cache/impl/CacheServiceImpl.java | 8 +- .../examples/callback/CallbackConsumer.java | 6 +- .../examples/callback/CallbackProvider.java | 6 +- .../callback/api/CallbackListener.java | 4 +- .../callback/api/CallbackService.java | 4 +- .../examples/callback/callback-consumer.xml | 18 +- .../examples/callback/callback-provider.xml | 39 +- .../callback/impl/CallbackServiceImpl.java | 76 +- .../examples/generic/GenericConsumer.java | 6 +- .../examples/generic/GenericProvider.java | 6 +- .../dubbo/examples/generic/api/IService.java | 2 +- .../examples/generic/api/IUserService.java | 24 +- .../examples/generic/generic-consumer.xml | 18 +- .../examples/generic/generic-provider.xml | 30 +- .../generic/impl/UserServiceImpl.java | 6 +- .../heartbeat/HeartBeatExchangeHandler.java | 32 +- .../examples/heartbeat/HeartbeatClient.java | 64 +- .../examples/heartbeat/HeartbeatProvider.java | 4 +- .../examples/heartbeat/HeartbeatServer.java | 48 +- .../examples/heartbeat/api/HelloService.java | 2 +- .../examples/heartbeat/heartbeat-consumer.xml | 9 +- .../examples/heartbeat/heartbeat-provider.xml | 11 +- .../examples/memcached/MemcachedConsumer.java | 8 +- .../examples/memcached/memcached-consumer.xml | 14 +- .../dubbo/examples/merge/MergeConsumer.java | 14 +- .../dubbo/examples/merge/MergeConsumer2.java | 14 +- .../dubbo/examples/merge/MergeProvider.java | 6 +- .../dubbo/examples/merge/MergeProvider2.java | 6 +- .../examples/merge/api/MergeService.java | 4 +- .../examples/merge/impl/MergeServiceImpl.java | 8 +- .../merge/impl/MergeServiceImpl2.java | 8 +- .../merge/impl/MergeServiceImpl3.java | 8 +- .../dubbo/examples/merge/merge-consumer.xml | 18 +- .../dubbo/examples/merge/merge-consumer2.xml | 19 +- .../dubbo/examples/merge/merge-provider.xml | 36 +- .../dubbo/examples/merge/merge-provider2.xml | 28 +- .../dubbo/examples/redis/RedisConsumer.java | 8 +- .../dubbo/examples/redis/redis-consumer.xml | 14 +- .../validation/ValidationConsumer.java | 35 +- .../validation/ValidationProvider.java | 4 +- .../validation/api/ValidationParameter.java | 9 +- .../validation/api/ValidationService.java | 12 +- .../impl/ValidationServiceImpl.java | 2 +- .../validation/validation-consumer.xml | 19 +- .../validation/validation-provider.xml | 29 +- .../examples/version/VersionConsumer.java | 8 +- .../examples/version/VersionProvider.java | 6 +- .../examples/version/VersionProvider2.java | 6 +- .../examples/version/api/VersionService.java | 8 +- .../version/impl/VersionServiceImpl.java | 6 +- .../version/impl/VersionServiceImpl2.java | 6 +- .../examples/version/version-consumer.xml | 18 +- .../examples/version/version-provider.xml | 29 +- .../examples/version/version-provider2.xml | 29 +- .../examples/annotation/AnnotationTest.java | 6 +- .../examples/validation/ValidationTest.java | 42 +- dubbo-test/dubbo-test-integration/pom.xml | 200 +- dubbo-test/pom.xml | 42 +- dubbo/pom.xml | 935 +- hessian-lite/pom.xml | 4 +- .../com/caucho/hessian/HessianException.java | 52 +- .../hessian/io/AbstractDeserializer.java | 102 +- .../hessian/io/AbstractHessianInput.java | 739 +- .../hessian/io/AbstractHessianOutput.java | 912 +- .../hessian/io/AbstractHessianResolver.java | 15 +- .../hessian/io/AbstractListDeserializer.java | 17 +- .../hessian/io/AbstractMapDeserializer.java | 28 +- .../caucho/hessian/io/AbstractSerializer.java | 14 +- .../hessian/io/AbstractSerializerFactory.java | 34 +- .../caucho/hessian/io/ArrayDeserializer.java | 176 +- .../caucho/hessian/io/ArraySerializer.java | 58 +- .../caucho/hessian/io/BasicDeserializer.java | 1031 ++- .../caucho/hessian/io/BasicSerializer.java | 418 +- .../caucho/hessian/io/BeanDeserializer.java | 423 +- .../com/caucho/hessian/io/BeanSerializer.java | 449 +- .../hessian/io/BeanSerializerFactory.java | 50 +- .../com/caucho/hessian/io/CalendarHandle.java | 57 +- .../caucho/hessian/io/CalendarSerializer.java | 30 +- .../caucho/hessian/io/ClassDeserializer.java | 179 +- .../caucho/hessian/io/ClassSerializer.java | 48 +- .../hessian/io/CollectionDeserializer.java | 140 +- .../hessian/io/CollectionSerializer.java | 78 +- .../com/caucho/hessian/io/Deflation.java | 259 +- .../com/caucho/hessian/io/Deserializer.java | 32 +- .../caucho/hessian/io/EnumDeserializer.java | 135 +- .../com/caucho/hessian/io/EnumSerializer.java | 79 +- .../hessian/io/EnumerationDeserializer.java | 34 +- .../hessian/io/EnumerationSerializer.java | 38 +- .../caucho/hessian/io/EnvelopeFactory.java | 9 +- .../hessian/io/ExtSerializerFactory.java | 90 +- .../caucho/hessian/io/Hessian2Constants.java | 189 +- .../com/caucho/hessian/io/Hessian2Input.java | 6011 +++++++------ .../com/caucho/hessian/io/Hessian2Output.java | 2694 +++--- .../hessian/io/Hessian2StreamingInput.java | 183 +- .../hessian/io/Hessian2StreamingOutput.java | 90 +- .../hessian/io/HessianDebugInputStream.java | 193 +- .../hessian/io/HessianDebugOutputStream.java | 181 +- .../caucho/hessian/io/HessianDebugState.java | 3915 ++++---- .../caucho/hessian/io/HessianEnvelope.java | 40 +- .../hessian/io/HessianFieldException.java | 58 +- .../com/caucho/hessian/io/HessianInput.java | 2706 +++--- .../hessian/io/HessianInputFactory.java | 74 +- .../com/caucho/hessian/io/HessianOutput.java | 1699 ++-- .../hessian/io/HessianProtocolException.java | 90 +- .../com/caucho/hessian/io/HessianRemote.java | 120 +- .../hessian/io/HessianRemoteObject.java | 5 +- .../hessian/io/HessianRemoteResolver.java | 10 +- .../hessian/io/HessianSerializerInput.java | 187 +- .../hessian/io/HessianSerializerOutput.java | 111 +- .../hessian/io/HessianServiceException.java | 58 +- .../caucho/hessian/io/IOExceptionWrapper.java | 31 +- .../hessian/io/InputStreamDeserializer.java | 17 +- .../hessian/io/InputStreamSerializer.java | 36 +- .../caucho/hessian/io/IteratorSerializer.java | 38 +- .../caucho/hessian/io/JavaDeserializer.java | 1067 ++- .../com/caucho/hessian/io/JavaSerializer.java | 647 +- .../com/caucho/hessian/io/LocaleHandle.java | 114 +- .../caucho/hessian/io/LocaleSerializer.java | 28 +- .../caucho/hessian/io/MapDeserializer.java | 172 +- .../com/caucho/hessian/io/MapSerializer.java | 71 +- .../caucho/hessian/io/ObjectDeserializer.java | 71 +- .../caucho/hessian/io/RemoteSerializer.java | 11 +- .../com/caucho/hessian/io/Serializer.java | 6 +- .../caucho/hessian/io/SerializerFactory.java | 1040 ++- .../hessian/io/SqlDateDeserializer.java | 117 +- .../caucho/hessian/io/SqlDateSerializer.java | 51 +- .../io/StackTraceElementDeserializer.java | 21 +- .../hessian/io/StringValueDeserializer.java | 113 +- .../hessian/io/StringValueSerializer.java | 48 +- .../hessian/io/ThrowableSerializer.java | 22 +- .../caucho/hessian/io/ValueDeserializer.java | 56 +- .../hessian/security/X509Encryption.java | 606 +- .../hessian/security/X509Signature.java | 610 +- .../caucho/hessian/util/IdentityIntMap.java | 307 +- .../com/caucho/hessian/util/IntMap.java | 307 +- pom.xml | 19 +- 1404 files changed, 78332 insertions(+), 78157 deletions(-) diff --git a/dubbo-admin/pom.xml b/dubbo-admin/pom.xml index 7720a7b155b..21fa9b717b1 100644 --- a/dubbo-admin/pom.xml +++ b/dubbo-admin/pom.xml @@ -13,141 +13,141 @@ - See the License for the specific language governing permissions and - limitations under the License. --> - - 4.0.0 - - com.alibaba - dubbo-parent - 2.5.4-SNAPSHOT - - dubbo-admin - war - ${project.artifactId} - The admin module of dubbo project - - 1.5 - / - false - false - - - - com.alibaba - dubbo - ${project.parent.version} - - - com.alibaba.citrus - citrus-webx-all - - - org.javassist - javassist - - - org.jboss.netty - netty - - - org.apache.mina - mina-core - - - org.glassfish.grizzly - grizzly-core - - - org.apache.httpcomponents - httpclient - - - com.alibaba - fastjson - - - com.thoughtworks.xstream - xstream - - - org.apache.bsf - bsf-api - - - org.apache.zookeeper - zookeeper - - - com.github.sgroschupf - zkclient - - - com.netflix.curator - curator-framework - - - com.googlecode.xmemcached - xmemcached - - - org.apache.thrift - libthrift - - - com.caucho - hessian - - - javax.servlet - servlet-api - provided - - - log4j - log4j - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - - - redis.clients - jedis - - - javax.validation - validation-api - - - org.hibernate - hibernate-validator - - - javax.cache - cache-api - - - - - - org.mortbay.jetty - maven-jetty-plugin - ${jetty_version} - - / - 10 - - - 8080 - 60000 - - - - - - + + 4.0.0 + + com.alibaba + dubbo-parent + 2.5.4-SNAPSHOT + + dubbo-admin + war + ${project.artifactId} + The admin module of dubbo project + + 1.5 + / + false + false + + + + com.alibaba + dubbo + ${project.parent.version} + + + com.alibaba.citrus + citrus-webx-all + + + org.javassist + javassist + + + org.jboss.netty + netty + + + org.apache.mina + mina-core + + + org.glassfish.grizzly + grizzly-core + + + org.apache.httpcomponents + httpclient + + + com.alibaba + fastjson + + + com.thoughtworks.xstream + xstream + + + org.apache.bsf + bsf-api + + + org.apache.zookeeper + zookeeper + + + com.github.sgroschupf + zkclient + + + com.netflix.curator + curator-framework + + + com.googlecode.xmemcached + xmemcached + + + org.apache.thrift + libthrift + + + com.caucho + hessian + + + javax.servlet + servlet-api + provided + + + log4j + log4j + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + redis.clients + jedis + + + javax.validation + validation-api + + + org.hibernate + hibernate-validator + + + javax.cache + cache-api + + + + + + org.mortbay.jetty + maven-jetty-plugin + ${jetty_version} + + / + 10 + + + 8080 + 60000 + + + + + + diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/PageContext.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/PageContext.java index 8f293a14a3d..6327e86698d 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/PageContext.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/PageContext.java @@ -1,11 +1,11 @@ /** * Project: dubbo.registry-1.1.0-SNAPSHOT - * + *

* File Created at 2010-5-26 - * + *

* Copyright 1999-2010 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -14,25 +14,25 @@ */ package com.alibaba.dubbo.governance; -import java.util.Map; - import com.alibaba.dubbo.registry.common.domain.User; +import java.util.Map; + /** * Context - * + * * @author william.liangf */ public interface PageContext { public String get(String key); - + public String[] gets(String key); public Map getAll(); public void put(String key, Object value); - + public String getMessage(String key, Object... args); public String getClientAddress(); @@ -40,11 +40,11 @@ public interface PageContext { public String getOperateAddress(); public String getRegistryAddress(); - + public String getURI(); - + public String getURL(); - + public String getReferer(); public User getLoginUser(); diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/biz/common/i18n/impl/MessageResourceServiceImpl.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/biz/common/i18n/impl/MessageResourceServiceImpl.java index d10d92a8add..1355baf9ad6 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/biz/common/i18n/impl/MessageResourceServiceImpl.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/biz/common/i18n/impl/MessageResourceServiceImpl.java @@ -1,12 +1,12 @@ package com.alibaba.dubbo.governance.biz.common.i18n.impl; +import com.alibaba.dubbo.governance.biz.common.i18n.MessageResourceService; +import com.alibaba.dubbo.governance.web.common.i18n.LocaleUtil; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.context.NoSuchMessageException; -import com.alibaba.dubbo.governance.biz.common.i18n.MessageResourceService; -import com.alibaba.dubbo.governance.web.common.i18n.LocaleUtil; - public class MessageResourceServiceImpl implements MessageResourceService { @Autowired diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/ConfigService.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/ConfigService.java index 0d6d0f634e8..aace66ff533 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/ConfigService.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/ConfigService.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.server-1.1.0-SNAPSHOT - * + *

* File Created at 2010-6-30 * $Id: ConfigService.java 181723 2012-06-26 01:56:06Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,21 +15,21 @@ */ package com.alibaba.dubbo.governance.service; +import com.alibaba.dubbo.registry.common.domain.Config; + import java.util.List; import java.util.Map; -import com.alibaba.dubbo.registry.common.domain.Config; - /** * TODO Comment of ConfigDAO - * + * * @author rain.chenjr - * + * */ public interface ConfigService { - void update(List configs); + void update(List configs); - Map findAllConfigsMap(); + Map findAllConfigsMap(); } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/ConsumerService.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/ConsumerService.java index 61ffacf35ce..ba7ad09f483 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/ConsumerService.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/ConsumerService.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry-1.1.0-SNAPSHOT - * + *

* File Created at 2010-4-15 * $Id: ConsumerService.java 182013 2012-06-26 10:32:43Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,13 +15,13 @@ */ package com.alibaba.dubbo.governance.service; -import java.util.List; - import com.alibaba.dubbo.registry.common.domain.Consumer; +import java.util.List; + /** * 消费者数据访问对象 - * + * * @author william.liangf */ public interface ConsumerService { @@ -29,30 +29,30 @@ public interface ConsumerService { List findByService(String serviceName); Consumer findConsumer(Long id); - + List findAll(); /** * 查询所有的消费者地址 */ List findAddresses(); - + List findAddressesByApplication(String application); - + List findAddressesByService(String serviceName); List findByAddress(String consumerAddress); - + List findServicesByAddress(String consumerAddress); List findApplications(); - + List findApplicationsByServiceName(String serviceName); - + List findByApplication(String application); - + List findServicesByApplication(String application); List findServices(); - + } \ No newline at end of file diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/OverrideService.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/OverrideService.java index 68ef58cdb11..e823b967a93 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/OverrideService.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/OverrideService.java @@ -15,37 +15,37 @@ */ package com.alibaba.dubbo.governance.service; -import java.util.List; - import com.alibaba.dubbo.registry.common.domain.Override; +import java.util.List; + /** * @author tony.chenl */ public interface OverrideService { - + void saveOverride(Override override); - + void updateOverride(Override override); void deleteOverride(Long id); - + void enableOverride(Long id); - + void disableOverride(Long id); List findByService(String service); - + List findByAddress(String address); - + List findByServiceAndAddress(String service, String address); - + List findByApplication(String application); List findByServiceAndApplication(String service, String application); - + List findAll(); Override findById(Long id); - + } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/OwnerService.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/OwnerService.java index 6034ae09cf4..a645b15b26f 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/OwnerService.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/OwnerService.java @@ -1,25 +1,25 @@ package com.alibaba.dubbo.governance.service; -import java.util.List; - import com.alibaba.dubbo.registry.common.domain.Owner; +import java.util.List; + public interface OwnerService { - - List findAllServiceNames(); - - List findServiceNamesByUsername(String username); - - List findUsernamesByServiceName(String serviceName); - - List findByService(String serviceName); - - List findAll(); - - Owner findById(Long id); - - void saveOwner(Owner owner); - - void deleteOwner(Owner owner); - + + List findAllServiceNames(); + + List findServiceNamesByUsername(String username); + + List findUsernamesByServiceName(String serviceName); + + List findByService(String serviceName); + + List findAll(); + + Owner findById(Long id); + + void saveOwner(Owner owner); + + void deleteOwner(Owner owner); + } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/ProviderService.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/ProviderService.java index 2b169b3de4d..f5e77ba1745 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/ProviderService.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/ProviderService.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry-1.1.0-SNAPSHOT - * + *

* File Created at 2010-4-15 * $Id: ProviderService.java 182143 2012-06-27 03:25:50Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,41 +15,41 @@ */ package com.alibaba.dubbo.governance.service; -import java.util.List; - import com.alibaba.dubbo.registry.common.domain.Provider; +import java.util.List; + /** * ProviderService - * + * * @author william.liangf */ public interface ProviderService { - + void create(Provider provider); void enableProvider(Long id); - + void disableProvider(Long id); void doublingProvider(Long id); - + void halvingProvider(Long id); - + void deleteStaticProvider(Long id); - + void updateProvider(Provider provider); Provider findProvider(Long id); - + List findServices(); - + List findAddresses(); - + List findAddressesByApplication(String application); - + List findAddressesByService(String serviceName); - + List findApplicationsByServiceName(String serviceName); List findByService(String serviceName); @@ -61,13 +61,13 @@ public interface ProviderService { List findServicesByAddress(String providerAddress); List findApplications(); - + List findByApplication(String application); - + List findServicesByApplication(String application); - + List findMethodsByService(String serviceName); - - Provider findByServiceAndAddress(String service, String address); - + + Provider findByServiceAndAddress(String service, String address); + } \ No newline at end of file diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/RouteService.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/RouteService.java index 464f662ca6e..bd5a292206e 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/RouteService.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/RouteService.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry-1.1.0-SNAPSHOT - * + *

* File Created at 2010-4-15 * $Id: RouteService.java 182337 2012-06-27 09:04:15Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,43 +15,43 @@ */ package com.alibaba.dubbo.governance.service; -import java.util.List; - import com.alibaba.dubbo.registry.common.domain.Route; +import java.util.List; + /** * RouteService - * + * * @author william.liangf */ public interface RouteService { void createRoute(Route route); - + void updateRoute(Route route); void deleteRoute(Long id); - + void enableRoute(Long id); void disableRoute(Long id); Route findRoute(Long id); - + List findAll(); List findByService(String serviceName); - + List findByAddress(String address); - + List findByServiceAndAddress(String service, String address); List findForceRouteByService(String service); - + List findForceRouteByAddress(String address); List findForceRouteByServiceAndAddress(String service, String address); - + List findAllForceRoute(); } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/UserService.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/UserService.java index 9dcffe38d62..77d7383f95e 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/UserService.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/UserService.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry-1.1.0-SNAPSHOT - * + *

* File Created at 2010-4-15 * $Id: UserService.java 182013 2012-06-26 10:32:43Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,35 +15,35 @@ */ package com.alibaba.dubbo.governance.service; -import java.util.List; - import com.alibaba.dubbo.registry.common.domain.User; +import java.util.List; + /** * UserService - * + * * @author william.liangf */ public interface UserService { List findAllUsers(); - + User findUser(String username); - + User findById(Long id); void createUser(User user); - + void updateUser(User user); - + void modifyUser(User user); - + boolean updatePassword(User user, String oldPassword); - + void resetPassword(User user); void enableUser(User user); - + void disableUser(User user); void deleteUser(User user); diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/AbstractService.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/AbstractService.java index 284a3c4d00a..61ebf20cf28 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/AbstractService.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/AbstractService.java @@ -1,11 +1,11 @@ /** * Project: dubbo.registry.server-1.1.0-SNAPSHOT - * + *

* File Created at 2010-6-28 - * + *

* Copyright 1999-2010 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -14,35 +14,33 @@ */ package com.alibaba.dubbo.governance.service.impl; -import java.util.Map; -import java.util.concurrent.ConcurrentMap; - -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.governance.sync.RegistryServerSync; import com.alibaba.dubbo.registry.RegistryService; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.Map; +import java.util.concurrent.ConcurrentMap; + /** * IbatisDAO - * + * * @author william.liangf */ public class AbstractService { protected static final Logger logger = LoggerFactory.getLogger(AbstractService.class); - - @Autowired - private RegistryServerSync sync; - @Autowired protected RegistryService registryService; - - public ConcurrentMap>> getRegistryCache(){ + @Autowired + private RegistryServerSync sync; + + public ConcurrentMap>> getRegistryCache() { return sync.getRegistryCache(); } - - + + } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/ConfigServiceImpl.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/ConfigServiceImpl.java index 1941afd27f0..561e646a16d 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/ConfigServiceImpl.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/ConfigServiceImpl.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.server-1.1.0-SNAPSHOT - * + *

* File Created at 2010-6-30 * $Id: ConfigServiceImpl.java 181735 2012-06-26 02:31:34Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,25 +15,25 @@ */ package com.alibaba.dubbo.governance.service.impl; -import java.util.List; -import java.util.Map; - import com.alibaba.dubbo.governance.service.ConfigService; import com.alibaba.dubbo.registry.common.domain.Config; +import java.util.List; +import java.util.Map; + /** * TODO Comment of IbatisConfigDAO * @author rain.chenjr * */ -public class ConfigServiceImpl extends AbstractService implements ConfigService{ +public class ConfigServiceImpl extends AbstractService implements ConfigService { /* (non-Javadoc) * @see com.alibaba.dubbo.governance.service.ConfigService#update(java.util.List) */ public void update(List configs) { // TODO Auto-generated method stub - + } /* (non-Javadoc) diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/ConsumerServiceImpl.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/ConsumerServiceImpl.java index bd236c29329..bf5b0d19f82 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/ConsumerServiceImpl.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/ConsumerServiceImpl.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry-1.1.0-SNAPSHOT - * + *

* File Created at 2010-4-15 * $Id: ConsumerServiceImpl.java 184666 2012-07-05 11:13:17Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,12 +15,6 @@ */ package com.alibaba.dubbo.governance.service.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentMap; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.governance.service.ConsumerService; @@ -28,8 +22,14 @@ import com.alibaba.dubbo.governance.sync.util.SyncUtils; import com.alibaba.dubbo.registry.common.domain.Consumer; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentMap; + /** - * + * * @author william.liangf */ public class ConsumerServiceImpl extends AbstractService implements ConsumerService { @@ -41,7 +41,7 @@ public List findByService(String service) { public Consumer findConsumer(Long id) { return SyncUtils.url2Consumer(findConsumerUrl(id)); } - + private Pair findConsumerUrl(Long id) { return SyncUtils.filterFromCategory(getRegistryCache(), Constants.CONSUMERS_CATEGORY, id); } @@ -49,7 +49,7 @@ private Pair findConsumerUrl(Long id) { public List findAll() { return SyncUtils.url2ConsumerList(findAllConsumerUrl()); } - + private Map findAllConsumerUrl() { Map filter = new HashMap(); filter.put(Constants.CATEGORY_KEY, Constants.CONSUMERS_CATEGORY); @@ -59,51 +59,51 @@ private Map findAllConsumerUrl() { public List findAddresses() { List ret = new ArrayList(); ConcurrentMap> consumerUrls = getRegistryCache().get(Constants.CONSUMERS_CATEGORY); - if(null == consumerUrls) return ret; - - for(Map.Entry> e1 : consumerUrls.entrySet()) { + if (null == consumerUrls) return ret; + + for (Map.Entry> e1 : consumerUrls.entrySet()) { Map value = e1.getValue(); - for(Map.Entry e2 : value.entrySet()) { + for (Map.Entry e2 : value.entrySet()) { URL u = e2.getValue(); String app = u.getAddress(); - if(app != null) ret.add(app); + if (app != null) ret.add(app); } } - + return ret; } public List findAddressesByApplication(String application) { List ret = new ArrayList(); ConcurrentMap> consumerUrls = getRegistryCache().get(Constants.CONSUMERS_CATEGORY); - for(Map.Entry> e1 : consumerUrls.entrySet()) { + for (Map.Entry> e1 : consumerUrls.entrySet()) { Map value = e1.getValue(); - for(Map.Entry e2 : value.entrySet()) { + for (Map.Entry e2 : value.entrySet()) { URL u = e2.getValue(); - if(application.equals(u.getParameter(Constants.APPLICATION_KEY))) { + if (application.equals(u.getParameter(Constants.APPLICATION_KEY))) { String addr = u.getAddress(); - if(addr != null) ret.add(addr); + if (addr != null) ret.add(addr); } } } - + return ret; } public List findAddressesByService(String service) { List ret = new ArrayList(); ConcurrentMap> consumerUrls = getRegistryCache().get(Constants.CONSUMERS_CATEGORY); - if(null == consumerUrls) return ret; - - for(Map.Entry e2 : consumerUrls.get(service).entrySet()) { + if (null == consumerUrls) return ret; + + for (Map.Entry e2 : consumerUrls.get(service).entrySet()) { URL u = e2.getValue(); String app = u.getAddress(); - if(app != null) ret.add(app); + if (app != null) ret.add(app); } - + return ret; } - + public List findByAddress(String consumerAddress) { return SyncUtils.url2ConsumerList(findConsumerUrlByAddress(consumerAddress)); } @@ -111,19 +111,19 @@ public List findByAddress(String consumerAddress) { public List findServicesByAddress(String address) { List ret = new ArrayList(); ConcurrentMap> consumerUrls = getRegistryCache().get(Constants.CONSUMERS_CATEGORY); - if(consumerUrls == null || address == null || address.length() == 0) return ret; - - for(Map.Entry> e1 : consumerUrls.entrySet()) { + if (consumerUrls == null || address == null || address.length() == 0) return ret; + + for (Map.Entry> e1 : consumerUrls.entrySet()) { Map value = e1.getValue(); - for(Map.Entry e2 : value.entrySet()) { + for (Map.Entry e2 : value.entrySet()) { URL u = e2.getValue(); - if(address.equals(u.getAddress())) { + if (address.equals(u.getAddress())) { ret.add(e1.getKey()); break; } } } - + return ret; } @@ -131,89 +131,89 @@ private Map findConsumerUrlByAddress(String address) { Map filter = new HashMap(); filter.put(Constants.CATEGORY_KEY, Constants.CONSUMERS_CATEGORY); filter.put(SyncUtils.ADDRESS_FILTER_KEY, address); - + return SyncUtils.filterFromCategory(getRegistryCache(), filter); } - + public List findApplications() { List ret = new ArrayList(); ConcurrentMap> consumerUrls = getRegistryCache().get(Constants.CONSUMERS_CATEGORY); - if(consumerUrls == null) return ret; - - for(Map.Entry> e1 : consumerUrls.entrySet()) { + if (consumerUrls == null) return ret; + + for (Map.Entry> e1 : consumerUrls.entrySet()) { Map value = e1.getValue(); - for(Map.Entry e2 : value.entrySet()) { + for (Map.Entry e2 : value.entrySet()) { URL u = e2.getValue(); String app = u.getParameter(Constants.APPLICATION_KEY); - if(app != null) ret.add(app); + if (app != null) ret.add(app); } } - + return ret; } public List findApplicationsByServiceName(String service) { List ret = new ArrayList(); ConcurrentMap> consumerUrls = getRegistryCache().get(Constants.CONSUMERS_CATEGORY); - if(consumerUrls == null) return ret; - + if (consumerUrls == null) return ret; + Map value = consumerUrls.get(service); - if(value == null){ - return ret; + if (value == null) { + return ret; } - for(Map.Entry e2 : value.entrySet()) { + for (Map.Entry e2 : value.entrySet()) { URL u = e2.getValue(); String app = u.getParameter(Constants.APPLICATION_KEY); - if(app != null) ret.add(app); + if (app != null) ret.add(app); } - + return ret; } public List findByApplication(String application) { return SyncUtils.url2ConsumerList(findConsumerUrlByApplication(application)); } - + private Map findConsumerUrlByApplication(String application) { Map filter = new HashMap(); filter.put(Constants.CATEGORY_KEY, Constants.CONSUMERS_CATEGORY); filter.put(Constants.APPLICATION_KEY, application); - + return SyncUtils.filterFromCategory(getRegistryCache(), filter); } public List findServicesByApplication(String application) { List ret = new ArrayList(); ConcurrentMap> consumerUrls = getRegistryCache().get(Constants.CONSUMERS_CATEGORY); - if(consumerUrls == null || application == null || application.length() == 0) return ret; - - for(Map.Entry> e1 : consumerUrls.entrySet()) { + if (consumerUrls == null || application == null || application.length() == 0) return ret; + + for (Map.Entry> e1 : consumerUrls.entrySet()) { Map value = e1.getValue(); - for(Map.Entry e2 : value.entrySet()) { + for (Map.Entry e2 : value.entrySet()) { URL u = e2.getValue(); - if(application.equals(u.getParameter(Constants.APPLICATION_KEY))) { + if (application.equals(u.getParameter(Constants.APPLICATION_KEY))) { ret.add(e1.getKey()); break; } } } - + return ret; } public List findServices() { List ret = new ArrayList(); ConcurrentMap> consumerUrls = getRegistryCache().get(Constants.CONSUMERS_CATEGORY); - if(consumerUrls != null) ret.addAll(consumerUrls.keySet()); + if (consumerUrls != null) ret.addAll(consumerUrls.keySet()); return ret; } - + public Map findConsumerUrlByService(String service) { Map filter = new HashMap(); filter.put(Constants.CATEGORY_KEY, Constants.CONSUMERS_CATEGORY); filter.put(SyncUtils.SERVICE_FILTER_KEY, service); - + return SyncUtils.filterFromCategory(getRegistryCache(), filter); } - + } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/OverrideServiceImpl.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/OverrideServiceImpl.java index 1b6dfbe8c7d..386aa8d956d 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/OverrideServiceImpl.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/OverrideServiceImpl.java @@ -15,10 +15,6 @@ */ package com.alibaba.dubbo.governance.service.impl; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.governance.service.OverrideService; @@ -26,11 +22,16 @@ import com.alibaba.dubbo.governance.sync.util.SyncUtils; import com.alibaba.dubbo.registry.common.domain.Override; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + /** * IbatisOverrideDAO.java + * * @author tony.chenl */ -public class OverrideServiceImpl extends AbstractService implements OverrideService{ +public class OverrideServiceImpl extends AbstractService implements OverrideService { public void saveOverride(Override override) { URL url = getUrlFromOverride(override); @@ -39,105 +40,105 @@ public void saveOverride(Override override) { public void updateOverride(Override override) { Long id = override.getId(); - if(id == null) { + if (id == null) { throw new IllegalStateException("no override id"); } URL oldOverride = findOverrideUrl(id); - if(oldOverride == null) { + if (oldOverride == null) { throw new IllegalStateException("Route was changed!"); } URL newOverride = getUrlFromOverride(override); - + registryService.unregister(oldOverride); registryService.register(newOverride); - + } public void deleteOverride(Long id) { URL oldOverride = findOverrideUrl(id); - if(oldOverride == null) { + if (oldOverride == null) { throw new IllegalStateException("Route was changed!"); } registryService.unregister(oldOverride); } public void enableOverride(Long id) { - if(id == null) { + if (id == null) { throw new IllegalStateException("no override id"); } - + URL oldOverride = findOverrideUrl(id); - if(oldOverride == null) { + if (oldOverride == null) { throw new IllegalStateException("Override was changed!"); } - if(oldOverride.getParameter("enabled", true)) { + if (oldOverride.getParameter("enabled", true)) { return; } URL newOverride = oldOverride.removeParameter("enabled"); registryService.unregister(oldOverride); registryService.register(newOverride); - + } public void disableOverride(Long id) { - if(id == null) { + if (id == null) { throw new IllegalStateException("no override id"); } - + URL oldProvider = findOverrideUrl(id); - if(oldProvider == null) { + if (oldProvider == null) { throw new IllegalStateException("Override was changed!"); } - if(!oldProvider.getParameter("enabled", true)) { + if (!oldProvider.getParameter("enabled", true)) { return; } URL newProvider = oldProvider.addParameter("enabled", false); registryService.unregister(oldProvider); registryService.register(newProvider); - + } private Map findOverrideUrl(String service, String address, String application) { Map filter = new HashMap(); filter.put(Constants.CATEGORY_KEY, Constants.CONFIGURATORS_CATEGORY); if (service != null && service.length() > 0) { - filter.put(SyncUtils.SERVICE_FILTER_KEY, service); + filter.put(SyncUtils.SERVICE_FILTER_KEY, service); } if (address != null && address.length() > 0) { - filter.put(SyncUtils.ADDRESS_FILTER_KEY, address); + filter.put(SyncUtils.ADDRESS_FILTER_KEY, address); } if (application != null && application.length() > 0) { - filter.put(Constants.APPLICATION_KEY, application); + filter.put(Constants.APPLICATION_KEY, application); } return SyncUtils.filterFromCategory(getRegistryCache(), filter); } public List findByAddress(String address) { - return SyncUtils.url2OverrideList(findOverrideUrl(null, address, null)); + return SyncUtils.url2OverrideList(findOverrideUrl(null, address, null)); } public List findByServiceAndAddress(String service, String address) { - return SyncUtils.url2OverrideList(findOverrideUrl(service, address, null)); + return SyncUtils.url2OverrideList(findOverrideUrl(service, address, null)); } - + public List findByApplication(String application) { return SyncUtils.url2OverrideList(findOverrideUrl(null, null, application)); } public List findByService(String service) { - return SyncUtils.url2OverrideList(findOverrideUrl(service, null, null)); + return SyncUtils.url2OverrideList(findOverrideUrl(service, null, null)); } public List findByServiceAndApplication(String service, String application) { - return SyncUtils.url2OverrideList(findOverrideUrl(service, null, application)); + return SyncUtils.url2OverrideList(findOverrideUrl(service, null, application)); } - + public List findAll() { return SyncUtils.url2OverrideList(findOverrideUrl(null, null, null)); } - + private Pair findOverrideUrlPair(Long id) { return SyncUtils.filterFromCategory(getRegistryCache(), Constants.CONFIGURATORS_CATEGORY, id); } @@ -145,9 +146,9 @@ private Pair findOverrideUrlPair(Long id) { public Override findById(Long id) { return SyncUtils.url2Override(findOverrideUrlPair(id)); } - + private URL getUrlFromOverride(Override override) { - return override.toUrl(); + return override.toUrl(); /*Map params = ConvertUtil.serviceName2Map(override.getService()); if(!params.containsKey(Constants.INTERFACE_KEY)) { throw new IllegalArgumentException("No interface info"); @@ -179,8 +180,8 @@ private URL getUrlFromOverride(Override override) { url = url.addParameterString(override.getParams()); return url;*/ } - - URL findOverrideUrl(Long id){ + + URL findOverrideUrl(Long id) { return getUrlFromOverride(findById(id)); } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/OwnerServiceImpl.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/OwnerServiceImpl.java index 8f98851ef24..d49f8033cea 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/OwnerServiceImpl.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/OwnerServiceImpl.java @@ -1,12 +1,5 @@ package com.alibaba.dubbo.governance.service.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.governance.service.OverrideService; @@ -16,11 +9,18 @@ import com.alibaba.dubbo.registry.common.domain.Owner; import com.alibaba.dubbo.registry.common.domain.Provider; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + public class OwnerServiceImpl extends AbstractService implements OwnerService { - + @Autowired ProviderService providerService; - + @Autowired OverrideService overrideService; @@ -42,101 +42,101 @@ public List findUsernamesByServiceName(String serviceName) { public List findByService(String serviceName) { List pList = providerService.findByService(serviceName); List cList = overrideService.findByServiceAndAddress(serviceName, Constants.ANYHOST_VALUE); - return toOverrideLiset(pList,cList); + return toOverrideLiset(pList, cList); } public List findAll() { List pList = providerService.findAll(); List cList = overrideService.findAll(); - return toOverrideLiset(pList,cList); + return toOverrideLiset(pList, cList); } public Owner findById(Long id) { - + return null; } - - private List toOverrideLiset(List pList, List cList){ + + private List toOverrideLiset(List pList, List cList) { Map oList = new HashMap(); - for(Provider p : pList){ - if(p.getUsername() != null){ - for (String username : Constants.COMMA_SPLIT_PATTERN.split(p.getUsername())) { - Owner o = new Owner(); - o.setService(p.getService()); - o.setUsername(username); - oList.put(o.getService() + "/" + o.getUsername(), o); - } + for (Provider p : pList) { + if (p.getUsername() != null) { + for (String username : Constants.COMMA_SPLIT_PATTERN.split(p.getUsername())) { + Owner o = new Owner(); + o.setService(p.getService()); + o.setUsername(username); + oList.put(o.getService() + "/" + o.getUsername(), o); + } } } - for(Override c : cList){ - Map params = StringUtils.parseQueryString(c.getParams()); - String usernames = params.get("owner"); - if(usernames != null && usernames.length() > 0){ - for (String username : Constants.COMMA_SPLIT_PATTERN.split(usernames)) { - Owner o = new Owner(); + for (Override c : cList) { + Map params = StringUtils.parseQueryString(c.getParams()); + String usernames = params.get("owner"); + if (usernames != null && usernames.length() > 0) { + for (String username : Constants.COMMA_SPLIT_PATTERN.split(usernames)) { + Owner o = new Owner(); o.setService(c.getService()); o.setUsername(username); oList.put(o.getService() + "/" + o.getUsername(), o); - } + } } } return new ArrayList(oList.values()); } - public void saveOwner(Owner owner) { - List overrides = overrideService.findByServiceAndAddress(owner.getService(), Constants.ANYHOST_VALUE); + public void saveOwner(Owner owner) { + List overrides = overrideService.findByServiceAndAddress(owner.getService(), Constants.ANYHOST_VALUE); if (overrides == null || overrides.size() == 0) { - Override override = new Override(); - override.setAddress(Constants.ANYHOST_VALUE); - override.setService(owner.getService()); - override.setEnabled(true); - override.setParams("owner=" + owner.getUsername()); - overrideService.saveOverride(override); + Override override = new Override(); + override.setAddress(Constants.ANYHOST_VALUE); + override.setService(owner.getService()); + override.setEnabled(true); + override.setParams("owner=" + owner.getUsername()); + overrideService.saveOverride(override); } else { - for(Override override : overrides){ - Map params = StringUtils.parseQueryString(override.getParams()); - String usernames = params.get("owner"); - if (usernames == null || usernames.length() == 0) { - usernames = owner.getUsername(); - } else { - usernames = usernames + "," + owner.getUsername(); - } - params.put("owner", usernames); - override.setParams(StringUtils.toQueryString(params)); - overrideService.updateOverride(override); - } + for (Override override : overrides) { + Map params = StringUtils.parseQueryString(override.getParams()); + String usernames = params.get("owner"); + if (usernames == null || usernames.length() == 0) { + usernames = owner.getUsername(); + } else { + usernames = usernames + "," + owner.getUsername(); + } + params.put("owner", usernames); + override.setParams(StringUtils.toQueryString(params)); + overrideService.updateOverride(override); + } } - } + } - public void deleteOwner(Owner owner) { - List overrides = overrideService.findByServiceAndAddress(owner.getService(), Constants.ANYHOST_VALUE); + public void deleteOwner(Owner owner) { + List overrides = overrideService.findByServiceAndAddress(owner.getService(), Constants.ANYHOST_VALUE); if (overrides == null || overrides.size() == 0) { - Override override = new Override(); - override.setAddress(Constants.ANYHOST_VALUE); - override.setService(owner.getService()); - override.setEnabled(true); - override.setParams("owner=" + owner.getUsername()); - overrideService.saveOverride(override); + Override override = new Override(); + override.setAddress(Constants.ANYHOST_VALUE); + override.setService(owner.getService()); + override.setEnabled(true); + override.setParams("owner=" + owner.getUsername()); + overrideService.saveOverride(override); } else { - for(Override override : overrides){ - Map params = StringUtils.parseQueryString(override.getParams()); - String usernames = params.get("owner"); - if (usernames != null && usernames.length() > 0) { - if (usernames.equals(owner.getUsername())) { - params.remove("owner"); - } else { - usernames = usernames.replace(owner.getUsername() + ",", "").replace("," + owner.getUsername(), ""); - params.put("owner", usernames); - } - if (params.size() > 0) { - override.setParams(StringUtils.toQueryString(params)); - overrideService.updateOverride(override); - } else { - overrideService.deleteOverride(override.getId()); - } - } - } + for (Override override : overrides) { + Map params = StringUtils.parseQueryString(override.getParams()); + String usernames = params.get("owner"); + if (usernames != null && usernames.length() > 0) { + if (usernames.equals(owner.getUsername())) { + params.remove("owner"); + } else { + usernames = usernames.replace(owner.getUsername() + ",", "").replace("," + owner.getUsername(), ""); + params.put("owner", usernames); + } + if (params.size() > 0) { + override.setParams(StringUtils.toQueryString(params)); + overrideService.updateOverride(override); + } else { + overrideService.deleteOverride(override.getId()); + } + } + } } - } + } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/ProviderServiceImpl.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/ProviderServiceImpl.java index 8f0cd3168de..5db1f79b15a 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/ProviderServiceImpl.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/ProviderServiceImpl.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry-1.1.0-SNAPSHOT - * + *

* File Created at 2010-4-15 * $Id: ProviderServiceImpl.java 185206 2012-07-09 03:06:37Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,15 +15,6 @@ */ package com.alibaba.dubbo.governance.service.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.ConcurrentMap; - -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.utils.StringUtils; @@ -35,15 +26,24 @@ import com.alibaba.dubbo.registry.common.domain.Provider; import com.alibaba.dubbo.registry.common.route.ParseUtils; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.ConcurrentMap; + /** * IbatisProviderService - * + * * @author tony.chenl */ public class ProviderServiceImpl extends AbstractService implements ProviderService { - - @Autowired - OverrideService overrideService; + + @Autowired + OverrideService overrideService; public void create(Provider provider) { URL url = provider.toUrl(); @@ -51,159 +51,159 @@ public void create(Provider provider) { } public void enableProvider(Long id) { - if(id == null) { + if (id == null) { throw new IllegalStateException("no provider id"); } - + Provider oldProvider = findProvider(id); - - if(oldProvider == null) { + + if (oldProvider == null) { throw new IllegalStateException("Provider was changed!"); - } + } if (oldProvider.isDynamic()) { - //保证disable的override唯一 - if(!oldProvider.isEnabled()){ - Override override = new Override(); - override.setAddress(oldProvider.getAddress()); - override.setService(oldProvider.getService()); - override.setEnabled(true); - override.setParams(Constants.DISABLED_KEY+"=false"); - overrideService.saveOverride(override); - return; - } - List oList = overrideService.findByServiceAndAddress(oldProvider.getService(), oldProvider.getAddress()); - - for(Override o : oList){ - Map params = StringUtils.parseQueryString(o.getParams()); - if(params.containsKey(Constants.DISABLED_KEY)){ - if(params.get(Constants.DISABLED_KEY) .equals("true")){ - overrideService.deleteOverride(o.getId()); - } - } - } + //保证disable的override唯一 + if (!oldProvider.isEnabled()) { + Override override = new Override(); + override.setAddress(oldProvider.getAddress()); + override.setService(oldProvider.getService()); + override.setEnabled(true); + override.setParams(Constants.DISABLED_KEY + "=false"); + overrideService.saveOverride(override); + return; + } + List oList = overrideService.findByServiceAndAddress(oldProvider.getService(), oldProvider.getAddress()); + + for (Override o : oList) { + Map params = StringUtils.parseQueryString(o.getParams()); + if (params.containsKey(Constants.DISABLED_KEY)) { + if (params.get(Constants.DISABLED_KEY).equals("true")) { + overrideService.deleteOverride(o.getId()); + } + } + } } else { - oldProvider.setEnabled(true); - updateProvider(oldProvider); + oldProvider.setEnabled(true); + updateProvider(oldProvider); } } public void disableProvider(Long id) { - if(id == null) { + if (id == null) { throw new IllegalStateException("no provider id"); } - + Provider oldProvider = findProvider(id); - if(oldProvider == null) { + if (oldProvider == null) { throw new IllegalStateException("Provider was changed!"); } - + if (oldProvider.isDynamic()) { - //保证disable的override唯一 - if(oldProvider.isEnabled()){ - Override override = new Override(); - override.setAddress(oldProvider.getAddress()); - override.setService(oldProvider.getService()); - override.setEnabled(true); - override.setParams(Constants.DISABLED_KEY+"=true"); - overrideService.saveOverride(override); - return; - } - List oList = overrideService.findByServiceAndAddress(oldProvider.getService(), oldProvider.getAddress()); - - for(Override o : oList){ - Map params = StringUtils.parseQueryString(o.getParams()); - if(params.containsKey(Constants.DISABLED_KEY)){ - if(params.get(Constants.DISABLED_KEY) .equals("false")){ - overrideService.deleteOverride(o.getId()); - } - } - } + //保证disable的override唯一 + if (oldProvider.isEnabled()) { + Override override = new Override(); + override.setAddress(oldProvider.getAddress()); + override.setService(oldProvider.getService()); + override.setEnabled(true); + override.setParams(Constants.DISABLED_KEY + "=true"); + overrideService.saveOverride(override); + return; + } + List oList = overrideService.findByServiceAndAddress(oldProvider.getService(), oldProvider.getAddress()); + + for (Override o : oList) { + Map params = StringUtils.parseQueryString(o.getParams()); + if (params.containsKey(Constants.DISABLED_KEY)) { + if (params.get(Constants.DISABLED_KEY).equals("false")) { + overrideService.deleteOverride(o.getId()); + } + } + } } else { - oldProvider.setEnabled(false); - updateProvider(oldProvider); + oldProvider.setEnabled(false); + updateProvider(oldProvider); } - + } - + public void doublingProvider(Long id) { - setWeight(id, 2F); + setWeight(id, 2F); } - + public void halvingProvider(Long id) { - setWeight(id, 0.5F); + setWeight(id, 0.5F); } public void setWeight(Long id, float factor) { - if(id == null) { + if (id == null) { throw new IllegalStateException("no provider id"); } Provider oldProvider = findProvider(id); - if(oldProvider == null) { + if (oldProvider == null) { throw new IllegalStateException("Provider was changed!"); } Map map = StringUtils.parseQueryString(oldProvider.getParameters()); - String weight = map.get(Constants.WEIGHT_KEY); + String weight = map.get(Constants.WEIGHT_KEY); if (oldProvider.isDynamic()) { - //保证disable的override唯一 - List overrides = overrideService.findByServiceAndAddress(oldProvider.getService(), oldProvider.getAddress()); - if (overrides == null || overrides.size() == 0) { - int value = getWeight(weight, factor); - if (value != Constants.DEFAULT_WEIGHT) { - Override override = new Override(); - override.setAddress(oldProvider.getAddress()); - override.setService(oldProvider.getService()); - override.setEnabled(true); - override.setParams(Constants.WEIGHT_KEY + "=" + String.valueOf(value)); - overrideService.saveOverride(override); - } - } else { - for(Override override : overrides){ - Map params = StringUtils.parseQueryString(override.getParams()); - String overrideWeight = params.get(Constants.WEIGHT_KEY); - if (overrideWeight == null || overrideWeight.length() == 0) { - overrideWeight = weight; - } - int value = getWeight(overrideWeight, factor); - if (value == getWeight(weight, 1)) { - params.remove(Constants.WEIGHT_KEY); - } else { - params.put(Constants.WEIGHT_KEY, String.valueOf(value)); - } - if (params.size() > 0) { - override.setParams(StringUtils.toQueryString(params)); - overrideService.updateOverride(override); - } else { - overrideService.deleteOverride(override.getId()); - } - } - } + //保证disable的override唯一 + List overrides = overrideService.findByServiceAndAddress(oldProvider.getService(), oldProvider.getAddress()); + if (overrides == null || overrides.size() == 0) { + int value = getWeight(weight, factor); + if (value != Constants.DEFAULT_WEIGHT) { + Override override = new Override(); + override.setAddress(oldProvider.getAddress()); + override.setService(oldProvider.getService()); + override.setEnabled(true); + override.setParams(Constants.WEIGHT_KEY + "=" + String.valueOf(value)); + overrideService.saveOverride(override); + } + } else { + for (Override override : overrides) { + Map params = StringUtils.parseQueryString(override.getParams()); + String overrideWeight = params.get(Constants.WEIGHT_KEY); + if (overrideWeight == null || overrideWeight.length() == 0) { + overrideWeight = weight; + } + int value = getWeight(overrideWeight, factor); + if (value == getWeight(weight, 1)) { + params.remove(Constants.WEIGHT_KEY); + } else { + params.put(Constants.WEIGHT_KEY, String.valueOf(value)); + } + if (params.size() > 0) { + override.setParams(StringUtils.toQueryString(params)); + overrideService.updateOverride(override); + } else { + overrideService.deleteOverride(override.getId()); + } + } + } } else { - int value = getWeight(weight, factor); - if (value == Constants.DEFAULT_WEIGHT) { - map.remove(Constants.WEIGHT_KEY); - } else { - map.put(Constants.WEIGHT_KEY, String.valueOf(value)); - } - oldProvider.setParameters(StringUtils.toQueryString(map)); - updateProvider(oldProvider); + int value = getWeight(weight, factor); + if (value == Constants.DEFAULT_WEIGHT) { + map.remove(Constants.WEIGHT_KEY); + } else { + map.put(Constants.WEIGHT_KEY, String.valueOf(value)); + } + oldProvider.setParameters(StringUtils.toQueryString(map)); + updateProvider(oldProvider); } } - + private int getWeight(String value, float factor) { - int weight = 100; - if (value != null && value.length() > 0) { - weight = Integer.parseInt(value); - } - weight = (int) (weight * factor); - if (weight < 1) weight = 1; - if (weight == 2) weight = 3; - if (weight == 24) weight = 25; - return weight; + int weight = 100; + if (value != null && value.length() > 0) { + weight = Integer.parseInt(value); + } + weight = (int) (weight * factor); + if (weight < 1) weight = 1; + if (weight == 2) weight = 3; + if (weight == 24) weight = 25; + return weight; } public void deleteStaticProvider(Long id) { URL oldProvider = findProviderUrl(id); - if(oldProvider == null) { + if (oldProvider == null) { throw new IllegalStateException("Provider was changed!"); } registryService.unregister(oldProvider); @@ -211,16 +211,16 @@ public void deleteStaticProvider(Long id) { public void updateProvider(Provider provider) { Long id = provider.getId(); - if(id == null) { + if (id == null) { throw new IllegalStateException("no provider id"); } - + URL oldProvider = findProviderUrl(id); - if(oldProvider == null) { + if (oldProvider == null) { throw new IllegalStateException("Provider was changed!"); } URL newProvider = provider.toUrl(); - + registryService.unregister(oldProvider); registryService.register(newProvider); } @@ -228,7 +228,7 @@ public void updateProvider(Provider provider) { public Provider findProvider(Long id) { return SyncUtils.url2Provider(findProviderUrlPair(id)); } - + public Pair findProviderUrlPair(Long id) { return SyncUtils.filterFromCategory(getRegistryCache(), Constants.PROVIDERS_CATEGORY, id); } @@ -236,152 +236,152 @@ public Pair findProviderUrlPair(Long id) { public List findServices() { List ret = new ArrayList(); ConcurrentMap> providerUrls = getRegistryCache().get(Constants.PROVIDERS_CATEGORY); - if(providerUrls != null) ret.addAll(providerUrls.keySet()); + if (providerUrls != null) ret.addAll(providerUrls.keySet()); return ret; } public List findAddresses() { List ret = new ArrayList(); - + ConcurrentMap> providerUrls = getRegistryCache().get(Constants.PROVIDERS_CATEGORY); - if(null == providerUrls) return ret; - - for(Map.Entry> e1 : providerUrls.entrySet()) { + if (null == providerUrls) return ret; + + for (Map.Entry> e1 : providerUrls.entrySet()) { Map value = e1.getValue(); - for(Map.Entry e2 : value.entrySet()) { + for (Map.Entry e2 : value.entrySet()) { URL u = e2.getValue(); String app = u.getAddress(); - if(app != null) ret.add(app); + if (app != null) ret.add(app); } } - + return ret; } public List findAddressesByApplication(String application) { List ret = new ArrayList(); ConcurrentMap> providerUrls = getRegistryCache().get(Constants.PROVIDERS_CATEGORY); - for(Map.Entry> e1 : providerUrls.entrySet()) { + for (Map.Entry> e1 : providerUrls.entrySet()) { Map value = e1.getValue(); - for(Map.Entry e2 : value.entrySet()) { + for (Map.Entry e2 : value.entrySet()) { URL u = e2.getValue(); - if(application.equals(u.getParameter(Constants.APPLICATION_KEY))) { + if (application.equals(u.getParameter(Constants.APPLICATION_KEY))) { String addr = u.getAddress(); - if(addr != null) ret.add(addr); + if (addr != null) ret.add(addr); } } } - + return ret; } public List findAddressesByService(String service) { List ret = new ArrayList(); ConcurrentMap> providerUrls = getRegistryCache().get(Constants.PROVIDERS_CATEGORY); - if(null == providerUrls) return ret; - - for(Map.Entry e2 : providerUrls.get(service).entrySet()) { + if (null == providerUrls) return ret; + + for (Map.Entry e2 : providerUrls.get(service).entrySet()) { URL u = e2.getValue(); String app = u.getAddress(); - if(app != null) ret.add(app); + if (app != null) ret.add(app); } - + return ret; } public List findApplicationsByServiceName(String service) { List ret = new ArrayList(); ConcurrentMap> providerUrls = getRegistryCache().get(Constants.PROVIDERS_CATEGORY); - if(null == providerUrls) return ret; - + if (null == providerUrls) return ret; + Map value = providerUrls.get(service); - if(value == null){ - return ret; + if (value == null) { + return ret; } - for(Map.Entry e2 : value.entrySet()) { + for (Map.Entry e2 : value.entrySet()) { URL u = e2.getValue(); String app = u.getParameter(Constants.APPLICATION_KEY); - if(app != null) ret.add(app); + if (app != null) ret.add(app); } - + return ret; } public List findByService(String serviceName) { return SyncUtils.url2ProviderList(findProviderUrlByService(serviceName)); } - + private Map findProviderUrlByService(String service) { Map filter = new HashMap(); filter.put(Constants.CATEGORY_KEY, Constants.PROVIDERS_CATEGORY); filter.put(SyncUtils.SERVICE_FILTER_KEY, service); - + return SyncUtils.filterFromCategory(getRegistryCache(), filter); } public List findAll() { return SyncUtils.url2ProviderList(findAllProviderUrl()); } - + private Map findAllProviderUrl() { Map filter = new HashMap(); filter.put(Constants.CATEGORY_KEY, Constants.PROVIDERS_CATEGORY); return SyncUtils.filterFromCategory(getRegistryCache(), filter); } - + public List findByAddress(String providerAddress) { return SyncUtils.url2ProviderList(findProviderUrlByAddress(providerAddress)); } - + public Map findProviderUrlByAddress(String address) { Map filter = new HashMap(); filter.put(Constants.CATEGORY_KEY, Constants.PROVIDERS_CATEGORY); filter.put(SyncUtils.ADDRESS_FILTER_KEY, address); - + return SyncUtils.filterFromCategory(getRegistryCache(), filter); } public List findServicesByAddress(String address) { List ret = new ArrayList(); - + ConcurrentMap> providerUrls = getRegistryCache().get(Constants.PROVIDERS_CATEGORY); - if(providerUrls == null || address == null || address.length() == 0) return ret; - - for(Map.Entry> e1 : providerUrls.entrySet()) { + if (providerUrls == null || address == null || address.length() == 0) return ret; + + for (Map.Entry> e1 : providerUrls.entrySet()) { Map value = e1.getValue(); - for(Map.Entry e2 : value.entrySet()) { + for (Map.Entry e2 : value.entrySet()) { URL u = e2.getValue(); - if(address.equals(u.getAddress())) { + if (address.equals(u.getAddress())) { ret.add(e1.getKey()); break; } } } - + return ret; } public List findApplications() { List ret = new ArrayList(); ConcurrentMap> providerUrls = getRegistryCache().get(Constants.PROVIDERS_CATEGORY); - if(providerUrls == null) return ret; - - for(Map.Entry> e1 : providerUrls.entrySet()) { + if (providerUrls == null) return ret; + + for (Map.Entry> e1 : providerUrls.entrySet()) { Map value = e1.getValue(); - for(Map.Entry e2 : value.entrySet()) { + for (Map.Entry e2 : value.entrySet()) { URL u = e2.getValue(); String app = u.getParameter(Constants.APPLICATION_KEY); - if(app != null) ret.add(app); + if (app != null) ret.add(app); } } - + return ret; } public List findByApplication(String application) { return SyncUtils.url2ProviderList(findProviderUrlByApplication(application)); } - + private Map findProviderUrlByApplication(String application) { Map filter = new HashMap(); filter.put(Constants.CATEGORY_KEY, Constants.PROVIDERS_CATEGORY); @@ -391,21 +391,21 @@ private Map findProviderUrlByApplication(String application) { public List findServicesByApplication(String application) { List ret = new ArrayList(); - + ConcurrentMap> providerUrls = getRegistryCache().get(Constants.PROVIDERS_CATEGORY); - if(providerUrls == null || application == null || application.length() == 0) return ret; - - for(Map.Entry> e1 : providerUrls.entrySet()) { + if (providerUrls == null || application == null || application.length() == 0) return ret; + + for (Map.Entry> e1 : providerUrls.entrySet()) { Map value = e1.getValue(); - for(Map.Entry e2 : value.entrySet()) { + for (Map.Entry e2 : value.entrySet()) { URL u = e2.getValue(); - if(application.equals(u.getParameter(Constants.APPLICATION_KEY))) { + if (application.equals(u.getParameter(Constants.APPLICATION_KEY))) { ret.add(e1.getKey()); break; } } } - + return ret; } @@ -413,11 +413,11 @@ public List findMethodsByService(String service) { List ret = new ArrayList(); ConcurrentMap> providerUrls = getRegistryCache().get(Constants.PROVIDERS_CATEGORY); - if(providerUrls == null || service == null || service.length() == 0) return ret; - + if (providerUrls == null || service == null || service.length() == 0) return ret; + Map providers = providerUrls.get(service); - if(null == providers || providers.isEmpty()) return ret; - + if (null == providers || providers.isEmpty()) return ret; + Entry p = providers.entrySet().iterator().next(); String value = p.getValue().getParameter("methods"); if (value == null || value.length() == 0) { @@ -427,8 +427,8 @@ public List findMethodsByService(String service) { if (methods == null || methods.length == 0) { return ret; } - - for(String m : methods) { + + for (String m : methods) { ret.add(m); } return ret; @@ -441,20 +441,19 @@ private URL findProviderUrl(Long id) { public Provider findByServiceAndAddress(String service, String address) { return SyncUtils.url2Provider(findProviderUrl(service, address)); } - - private Pair findProviderUrl(String service, String address) { + + private Pair findProviderUrl(String service, String address) { Map filter = new HashMap(); filter.put(Constants.CATEGORY_KEY, Constants.PROVIDERS_CATEGORY); filter.put(SyncUtils.ADDRESS_FILTER_KEY, address); - + Map ret = SyncUtils.filterFromCategory(getRegistryCache(), filter); - if(ret.isEmpty()) { + if (ret.isEmpty()) { return null; - } - else { + } else { Long key = ret.entrySet().iterator().next().getKey(); return new Pair(key, ret.get(key)); } } - + } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/RouteServiceImpl.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/RouteServiceImpl.java index 152b3d56957..3ed1f54f9f0 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/RouteServiceImpl.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/RouteServiceImpl.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry-1.1.0-SNAPSHOT - * + *

* File Created at 2010-4-15 * $Id: RouteServiceImpl.java 182851 2012-06-28 09:39:16Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,10 +15,6 @@ */ package com.alibaba.dubbo.governance.service.impl; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.governance.service.RouteService; @@ -26,9 +22,13 @@ import com.alibaba.dubbo.governance.sync.util.SyncUtils; import com.alibaba.dubbo.registry.common.domain.Route; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + /** * IbatisRouteService - * + * * @author william.liangf */ public class RouteServiceImpl extends AbstractService implements RouteService { @@ -39,84 +39,84 @@ public void createRoute(Route route) { public void updateRoute(Route route) { Long id = route.getId(); - if(id == null) { + if (id == null) { throw new IllegalStateException("no route id"); } URL oldRoute = findRouteUrl(id); - if(oldRoute == null) { + if (oldRoute == null) { throw new IllegalStateException("Route was changed!"); } - + registryService.unregister(oldRoute); registryService.register(route.toUrl()); } public void deleteRoute(Long id) { URL oldRoute = findRouteUrl(id); - if(oldRoute == null) { + if (oldRoute == null) { throw new IllegalStateException("Route was changed!"); } registryService.unregister(oldRoute); } public void enableRoute(Long id) { - if(id == null) { + if (id == null) { throw new IllegalStateException("no route id"); } - + URL oldRoute = findRouteUrl(id); - if(oldRoute == null) { + if (oldRoute == null) { throw new IllegalStateException("Route was changed!"); } - if(oldRoute.getParameter("enabled", true)) { + if (oldRoute.getParameter("enabled", true)) { return; } - registryService.unregister(oldRoute); - URL newRoute= oldRoute.addParameter("enabled", true); + registryService.unregister(oldRoute); + URL newRoute = oldRoute.addParameter("enabled", true); registryService.register(newRoute); - + } public void disableRoute(Long id) { - if(id == null) { + if (id == null) { throw new IllegalStateException("no route id"); } - + URL oldRoute = findRouteUrl(id); - if(oldRoute == null) { + if (oldRoute == null) { throw new IllegalStateException("Route was changed!"); } - if(!oldRoute.getParameter("enabled", true)) { + if (!oldRoute.getParameter("enabled", true)) { return; } URL newRoute = oldRoute.addParameter("enabled", false); registryService.unregister(oldRoute); registryService.register(newRoute); - + } public List findAll() { return SyncUtils.url2RouteList(findAllUrl()); } - + private Map findAllUrl() { Map filter = new HashMap(); filter.put(Constants.CATEGORY_KEY, Constants.ROUTERS_CATEGORY); - + return SyncUtils.filterFromCategory(getRegistryCache(), filter); } public Route findRoute(Long id) { return SyncUtils.url2Route(findRouteUrlPair(id)); } - + public Pair findRouteUrlPair(Long id) { return SyncUtils.filterFromCategory(getRegistryCache(), Constants.ROUTERS_CATEGORY, id); } - - private URL findRouteUrl(Long id){ + + private URL findRouteUrl(Long id) { return findRoute(id).toUrl(); } @@ -124,13 +124,13 @@ private Map findRouteUrl(String service, String address, boolean forc Map filter = new HashMap(); filter.put(Constants.CATEGORY_KEY, Constants.ROUTERS_CATEGORY); if (service != null && service.length() > 0) { - filter.put(SyncUtils.SERVICE_FILTER_KEY, service); + filter.put(SyncUtils.SERVICE_FILTER_KEY, service); } if (address != null && address.length() > 0) { - filter.put(SyncUtils.ADDRESS_FILTER_KEY, address); + filter.put(SyncUtils.ADDRESS_FILTER_KEY, address); } if (force) { - filter.put("force", "true"); + filter.put("force", "true"); } return SyncUtils.filterFromCategory(getRegistryCache(), filter); } @@ -150,7 +150,7 @@ public List findByServiceAndAddress(String service, String address) { public List findForceRouteByService(String service) { return SyncUtils.url2RouteList(findRouteUrl(service, null, true)); } - + public List findForceRouteByAddress(String address) { return SyncUtils.url2RouteList(findRouteUrl(null, address, true)); } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/UserServiceImpl.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/UserServiceImpl.java index 5bc11308531..d597e48ee2a 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/UserServiceImpl.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/UserServiceImpl.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry-1.1.0-SNAPSHOT - * + *

* File Created at 2010-4-15 * $Id: UserServiceImpl.java 182013 2012-06-26 10:32:43Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,35 +15,34 @@ */ package com.alibaba.dubbo.governance.service.impl; -import java.util.List; -import java.util.Map; - import com.alibaba.dubbo.governance.service.UserService; import com.alibaba.dubbo.registry.common.domain.User; import com.alibaba.dubbo.registry.common.util.Coder; +import java.util.List; +import java.util.Map; + /** * IBatisUserService - * + * * @author william.liangf */ public class UserServiceImpl extends AbstractService implements UserService { - private String rootPassword; + private String rootPassword; + private String guestPassword; - public void setRootPassword(String password) { - this.rootPassword = (password == null ? "" : password); - } - - private String guestPassword; + public void setRootPassword(String password) { + this.rootPassword = (password == null ? "" : password); + } - public void setGuestPassword(String password) { - this.guestPassword = (password == null ? "" : password); - } + public void setGuestPassword(String password) { + this.guestPassword = (password == null ? "" : password); + } public User findUser(String username) { - if ("guest".equals(username)) { - User user = new User(); + if ("guest".equals(username)) { + User user = new User(); user.setUsername(username); user.setPassword(Coder.encodeMd5(username + ":" + User.REALM + ":" + guestPassword)); user.setName(username); @@ -52,8 +51,8 @@ public User findUser(String username) { user.setLocale("zh"); user.setServicePrivilege(""); return user; - } else if ("root".equals(username)) { - User user = new User(); + } else if ("root".equals(username)) { + User user = new User(); user.setUsername(username); user.setPassword(Coder.encodeMd5(username + ":" + User.REALM + ":" + rootPassword)); user.setName(username); @@ -62,8 +61,8 @@ public User findUser(String username) { user.setLocale("zh"); user.setServicePrivilege("*"); return user; - } - return null; + } + return null; } public List findAllUsers() { @@ -83,17 +82,17 @@ public User findById(Long id) { public void createUser(User user) { // TODO Auto-generated method stub - + } public void updateUser(User user) { // TODO Auto-generated method stub - + } public void modifyUser(User user) { // TODO Auto-generated method stub - + } public boolean updatePassword(User user, String oldPassword) { @@ -103,22 +102,22 @@ public boolean updatePassword(User user, String oldPassword) { public void resetPassword(User user) { // TODO Auto-generated method stub - + } public void enableUser(User user) { // TODO Auto-generated method stub - + } public void disableUser(User user) { // TODO Auto-generated method stub - + } public void deleteUser(User user) { // TODO Auto-generated method stub - + } public List findUsersByServiceName(String serviceName) { diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/status/DatabaseStatusChecker.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/status/DatabaseStatusChecker.java index c88c4b94db7..78446225038 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/status/DatabaseStatusChecker.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/status/DatabaseStatusChecker.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.server-1.1.0-SNAPSHOT - * + *

* File Created at 2009-12-27 * $Id: DatabaseStatusChecker.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,32 +15,31 @@ */ package com.alibaba.dubbo.governance.status; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.ResultSet; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.status.Status; import com.alibaba.dubbo.common.status.StatusChecker; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; + /** * DatabaseStatus - * + * * @author william.liangf */ public class DatabaseStatusChecker implements StatusChecker { private static final Logger logger = LoggerFactory.getLogger(DatabaseStatusChecker.class); - + private int version; - + private String message; - + @Autowired private DataSource dataSource; @@ -63,9 +62,9 @@ public Status check() { } if (message == null) { message = metaData.getURL() - + " (" + metaData.getDatabaseProductName() - + " " + metaData.getDatabaseProductVersion() - + ", " + getIsolation(metaData.getDefaultTransactionIsolation()) + ")"; + + " (" + metaData.getDatabaseProductName() + + " " + metaData.getDatabaseProductVersion() + + ", " + getIsolation(metaData.getDefaultTransactionIsolation()) + ")"; } if (version == 0) { version = metaData.getDatabaseMajorVersion(); @@ -77,9 +76,9 @@ public Status check() { logger.error(e.getMessage(), e); ok = false; } - return new Status(! ok ? Status.Level.ERROR : (version < 5 ? Status.Level.WARN : Status.Level.OK), message); + return new Status(!ok ? Status.Level.ERROR : (version < 5 ? Status.Level.WARN : Status.Level.OK), message); } - + private String getIsolation(int i) { if (i == Connection.TRANSACTION_READ_COMMITTED) { return "READ_COMMITTED"; diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/status/LoadStatusChecker.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/status/LoadStatusChecker.java index 5011b96839b..284d4de6627 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/status/LoadStatusChecker.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/status/LoadStatusChecker.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.server-1.1.0-SNAPSHOT - * + *

* File Created at 2009-12-27 * $Id: LoadStatusChecker.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,30 +15,30 @@ */ package com.alibaba.dubbo.governance.status; +import com.alibaba.dubbo.common.status.Status; +import com.alibaba.dubbo.common.status.StatusChecker; + import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; import java.lang.reflect.Method; -import com.alibaba.dubbo.common.status.Status; -import com.alibaba.dubbo.common.status.StatusChecker; - /** * Load Status - * + * * @author william.liangf */ public class LoadStatusChecker implements StatusChecker { public Status check() { - OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean(); - double load; - try { - Method method = OperatingSystemMXBean.class.getMethod("getSystemLoadAverage", new Class[0]); - load = (Double)method.invoke(operatingSystemMXBean, new Object[0]); - } catch (Throwable e) { - load = -1; - } - int cpu = operatingSystemMXBean.getAvailableProcessors(); + OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean(); + double load; + try { + Method method = OperatingSystemMXBean.class.getMethod("getSystemLoadAverage", new Class[0]); + load = (Double) method.invoke(operatingSystemMXBean, new Object[0]); + } catch (Throwable e) { + load = -1; + } + int cpu = operatingSystemMXBean.getAvailableProcessors(); return new Status(load < 0 ? Status.Level.UNKNOWN : (load < cpu ? Status.Level.OK : Status.Level.WARN), "Load: " + load + " / CPU: " + cpu); } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/status/MemoryStatusChecker.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/status/MemoryStatusChecker.java index 34a202168e9..3007bce5c78 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/status/MemoryStatusChecker.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/status/MemoryStatusChecker.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.server-1.1.0-SNAPSHOT - * + *

* File Created at 2009-12-27 * $Id: MemoryStatusChecker.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -20,7 +20,7 @@ /** * MemoryStatus - * + * * @author william.liangf */ public class MemoryStatusChecker implements StatusChecker { @@ -31,9 +31,9 @@ public Status check() { long totalMemory = runtime.totalMemory(); long maxMemory = runtime.maxMemory(); boolean ok = (maxMemory - (totalMemory - freeMemory) > 2048); // 剩余空间小于2M报警 - String msg = "Max:" + (maxMemory / 1024 / 1024) + "M, Total:" - + (totalMemory / 1024 / 1024) + "M, Free:" + (freeMemory / 1024 / 1024) - + "M, Use:" + ((totalMemory / 1024 / 1024) - (freeMemory / 1024 / 1024)) + "M"; + String msg = "Max:" + (maxMemory / 1024 / 1024) + "M, Total:" + + (totalMemory / 1024 / 1024) + "M, Free:" + (freeMemory / 1024 / 1024) + + "M, Use:" + ((totalMemory / 1024 / 1024) - (freeMemory / 1024 / 1024)) + "M"; return new Status(ok ? Status.Level.OK : Status.Level.WARN, msg); } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/sync/RegistryServerSync.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/sync/RegistryServerSync.java index 6fb1911c2e8..104e3d62a2f 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/sync/RegistryServerSync.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/sync/RegistryServerSync.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.console-2.2.0-SNAPSHOT - * + *

* File Created at Mar 21, 2012 * $Id: RegistryServerSync.java 182143 2012-06-27 03:25:50Z tony.chenl $ - * + *

* Copyright 1999-2100 Alibaba.com Corporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,17 +15,6 @@ */ package com.alibaba.dubbo.governance.sync; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicLong; - -import org.springframework.beans.factory.DisposableBean; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.logger.Logger; @@ -36,6 +25,17 @@ import com.alibaba.dubbo.registry.NotifyListener; import com.alibaba.dubbo.registry.RegistryService; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.atomic.AtomicLong; + /** * @author ding.lid */ @@ -44,29 +44,27 @@ public class RegistryServerSync implements InitializingBean, DisposableBean, Not private static final Logger logger = LoggerFactory.getLogger(RegistryServerSync.class); private static final URL SUBSCRIBE = new URL(Constants.ADMIN_PROTOCOL, NetUtils.getLocalHost(), 0, "", - Constants.INTERFACE_KEY, Constants.ANY_VALUE, - Constants.GROUP_KEY, Constants.ANY_VALUE, - Constants.VERSION_KEY, Constants.ANY_VALUE, - Constants.CLASSIFIER_KEY, Constants.ANY_VALUE, - Constants.CATEGORY_KEY, Constants.PROVIDERS_CATEGORY + "," - + Constants.CONSUMERS_CATEGORY + "," - + Constants.ROUTERS_CATEGORY + "," - + Constants.CONFIGURATORS_CATEGORY, - Constants.ENABLED_KEY, Constants.ANY_VALUE, - Constants.CHECK_KEY, String.valueOf(false)); + Constants.INTERFACE_KEY, Constants.ANY_VALUE, + Constants.GROUP_KEY, Constants.ANY_VALUE, + Constants.VERSION_KEY, Constants.ANY_VALUE, + Constants.CLASSIFIER_KEY, Constants.ANY_VALUE, + Constants.CATEGORY_KEY, Constants.PROVIDERS_CATEGORY + "," + + Constants.CONSUMERS_CATEGORY + "," + + Constants.ROUTERS_CATEGORY + "," + + Constants.CONFIGURATORS_CATEGORY, + Constants.ENABLED_KEY, Constants.ANY_VALUE, + Constants.CHECK_KEY, String.valueOf(false)); private static final AtomicLong ID = new AtomicLong(); - - @Autowired - private RegistryService registryService; - // ConcurrentMap>> private final ConcurrentMap>> registryCache = new ConcurrentHashMap>>(); + @Autowired + private RegistryService registryService; - public ConcurrentMap>> getRegistryCache(){ + public ConcurrentMap>> getRegistryCache() { return registryCache; } - + public void afterPropertiesSet() throws Exception { logger.info("Init Dubbo Admin Sync Cache..."); registryService.subscribe(SUBSCRIBE, this); @@ -75,55 +73,55 @@ public void afterPropertiesSet() throws Exception { public void destroy() throws Exception { registryService.unsubscribe(SUBSCRIBE, this); } - + // 收到的通知对于 ,同一种类型数据(override、subcribe、route、其它是Provider),同一个服务的数据是全量的 public void notify(List urls) { - if(urls == null || urls.isEmpty()) { - return; + if (urls == null || urls.isEmpty()) { + return; } // Map>> final Map>> categories = new HashMap>>(); - for(URL url : urls) { - String category = url.getParameter(Constants.CATEGORY_KEY, Constants.PROVIDERS_CATEGORY); - if(Constants.EMPTY_PROTOCOL.equalsIgnoreCase(url.getProtocol())) { // 注意:empty协议的group和version为* - ConcurrentMap> services = registryCache.get(category); - if(services != null) { - String group = url.getParameter(Constants.GROUP_KEY); - String version = url.getParameter(Constants.VERSION_KEY); - // 注意:empty协议的group和version为* - if (! Constants.ANY_VALUE.equals(group) && ! Constants.ANY_VALUE.equals(version)) { - services.remove(url.getServiceKey()); - } else { - for (Map.Entry> serviceEntry : services.entrySet()) { - String service = serviceEntry.getKey(); - if (Tool.getInterface(service).equals(url.getServiceInterface()) - && (Constants.ANY_VALUE.equals(group) || StringUtils.isEquals(group, Tool.getGroup(service))) - && (Constants.ANY_VALUE.equals(version) || StringUtils.isEquals(version, Tool.getVersion(service)))) { - services.remove(service); - } - } - } + for (URL url : urls) { + String category = url.getParameter(Constants.CATEGORY_KEY, Constants.PROVIDERS_CATEGORY); + if (Constants.EMPTY_PROTOCOL.equalsIgnoreCase(url.getProtocol())) { // 注意:empty协议的group和version为* + ConcurrentMap> services = registryCache.get(category); + if (services != null) { + String group = url.getParameter(Constants.GROUP_KEY); + String version = url.getParameter(Constants.VERSION_KEY); + // 注意:empty协议的group和version为* + if (!Constants.ANY_VALUE.equals(group) && !Constants.ANY_VALUE.equals(version)) { + services.remove(url.getServiceKey()); + } else { + for (Map.Entry> serviceEntry : services.entrySet()) { + String service = serviceEntry.getKey(); + if (Tool.getInterface(service).equals(url.getServiceInterface()) + && (Constants.ANY_VALUE.equals(group) || StringUtils.isEquals(group, Tool.getGroup(service))) + && (Constants.ANY_VALUE.equals(version) || StringUtils.isEquals(version, Tool.getVersion(service)))) { + services.remove(service); + } + } + } } } else { - Map> services = categories.get(category); - if(services == null) { - services = new HashMap>(); + Map> services = categories.get(category); + if (services == null) { + services = new HashMap>(); categories.put(category, services); } String service = url.getServiceKey(); Map ids = services.get(service); - if(ids == null) { + if (ids == null) { ids = new HashMap(); services.put(service, ids); } ids.put(ID.incrementAndGet(), url); } } - for(Map.Entry>> categoryEntry : categories.entrySet()) { + for (Map.Entry>> categoryEntry : categories.entrySet()) { String category = categoryEntry.getKey(); ConcurrentMap> services = registryCache.get(category); - if(services == null) { - services = new ConcurrentHashMap>(); + if (services == null) { + services = new ConcurrentHashMap>(); registryCache.put(category, services); } services.putAll(categoryEntry.getValue()); diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/sync/util/Pair.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/sync/util/Pair.java index 37cc3a146c1..467aaebbed7 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/sync/util/Pair.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/sync/util/Pair.java @@ -19,65 +19,65 @@ public class Pair implements Map.Entry { - private K key; + private K key; + + private V value; + + public Pair() { + } - private V value; - - public Pair() { - } - public Pair(K key, V value) { this.key = key; this.value = value; } public K getKey() { - return key; - } + return key; + } - public void setKey(K key) { - this.key = key; - } + public void setKey(K key) { + this.key = key; + } - public V getValue() { - return value; - } + public V getValue() { + return value; + } - public V setValue(V value) { - V old = this.value; - this.value = value; - return old; - } + public V setValue(V value) { + V old = this.value; + this.value = value; + return old; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((key == null) ? 0 : key.hashCode()); - result = prime * result + ((value == null) ? 0 : value.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((key == null) ? 0 : key.hashCode()); + result = prime * result + ((value == null) ? 0 : value.hashCode()); + return result; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Pair other = (Pair) obj; - if (key == null) { - if (other.key != null) - return false; - } else if (!key.equals(other.key)) - return false; - if (value == null) { - if (other.value != null) - return false; - } else if (!value.equals(other.value)) - return false; - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Pair other = (Pair) obj; + if (key == null) { + if (other.key != null) + return false; + } else if (!key.equals(other.key)) + return false; + if (value == null) { + if (other.value != null) + return false; + } else if (!value.equals(other.value)) + return false; + return true; + } } \ No newline at end of file diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/sync/util/SyncUtils.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/sync/util/SyncUtils.java index 341ea9e95ff..b113332c7f2 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/sync/util/SyncUtils.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/sync/util/SyncUtils.java @@ -1,12 +1,12 @@ /** * Project: dubbo.governance-2.2.0-SNAPSHOT - * + *

* File Created at Mar 31, 2012 * $Id: SyncUtils.java 184666 2012-07-05 11:13:17Z tony.chenl $ - * + *

* Copyright 1999-2100 Alibaba.com Corporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,11 +15,6 @@ */ package com.alibaba.dubbo.governance.sync.util; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.utils.StringUtils; @@ -27,22 +22,27 @@ import com.alibaba.dubbo.registry.common.domain.Provider; import com.alibaba.dubbo.registry.common.domain.Route; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + /** * @author ding.lid */ public class SyncUtils { - + public static final String SERVICE_FILTER_KEY = ".service"; public static final String ADDRESS_FILTER_KEY = ".address"; - + public static final String ID_FILTER_KEY = ".id"; public static Provider url2Provider(Pair pair) { - if (pair == null) { - return null; - } - + if (pair == null) { + return null; + } + Long id = pair.getKey(); URL url = pair.getValue(); @@ -64,20 +64,20 @@ public static Provider url2Provider(Pair pair) { return p; } - + public static List url2ProviderList(Map ps) { List ret = new ArrayList(); - for(Map.Entry entry : ps.entrySet()) { + for (Map.Entry entry : ps.entrySet()) { ret.add(url2Provider(new Pair(entry.getKey(), entry.getValue()))); } return ret; } public static Consumer url2Consumer(Pair pair) { - if (pair == null) { - return null; - } - + if (pair == null) { + return null; + } + Long id = pair.getKey(); URL url = pair.getValue(); @@ -93,21 +93,21 @@ public static Consumer url2Consumer(Pair pair) { return c; } - + public static List url2ConsumerList(Map cs) { List list = new ArrayList(); - if(cs == null) return list; - for(Map.Entry entry : cs.entrySet()) { + if (cs == null) return list; + for (Map.Entry entry : cs.entrySet()) { list.add(url2Consumer(new Pair(entry.getKey(), entry.getValue()))); } return list; } public static Route url2Route(Pair pair) { - if (pair == null) { - return null; - } - + if (pair == null) { + return null; + } + Long id = pair.getKey(); URL url = pair.getValue(); @@ -124,21 +124,21 @@ public static Route url2Route(Pair pair) { r.setRule(url.getParameterAndDecoded(Constants.RULE_KEY)); return r; } - + public static List url2RouteList(Map cs) { List list = new ArrayList(); - if(cs == null) return list; - for(Map.Entry entry : cs.entrySet()) { + if (cs == null) return list; + for (Map.Entry entry : cs.entrySet()) { list.add(url2Route(new Pair(entry.getKey(), entry.getValue()))); } return list; } public static com.alibaba.dubbo.registry.common.domain.Override url2Override(Pair pair) { - if (pair == null) { - return null; - } - + if (pair == null) { + return null; + } + Long id = pair.getKey(); URL url = pair.getValue(); @@ -163,7 +163,7 @@ public static com.alibaba.dubbo.registry.common.domain.Override url2Override(Pai String host = url.getHost(); boolean anyhost = url.getParameter(Constants.ANYHOST_VALUE, false); - if(!anyhost || !"0.0.0.0".equals(host)) { + if (!anyhost || !"0.0.0.0".equals(host)) { o.setAddress(url.getAddress()); } @@ -174,84 +174,82 @@ public static com.alibaba.dubbo.registry.common.domain.Override url2Override(Pai return o; } - + // Map>> public static >> Map filterFromCategory(Map urls, Map filter) { String c = (String) filter.get(Constants.CATEGORY_KEY); - if(c==null) throw new IllegalArgumentException("no category"); - + if (c == null) throw new IllegalArgumentException("no category"); + filter.remove(Constants.CATEGORY_KEY); return filterFromService(urls.get(c), filter); } - + public static List url2OverrideList(Map cs) { List list = new ArrayList(); - if(cs == null) return list; - for(Map.Entry entry : cs.entrySet()) { + if (cs == null) return list; + for (Map.Entry entry : cs.entrySet()) { list.add(url2Override(new Pair(entry.getKey(), entry.getValue()))); } return list; } - - + + // Map> public static Map filterFromService(Map> urls, Map filter) { Map ret = new HashMap(); - if(urls == null) return ret; - + if (urls == null) return ret; + String s = (String) filter.remove(SERVICE_FILTER_KEY); - if(s == null) { - for(Map.Entry> entry : urls.entrySet()) { + if (s == null) { + for (Map.Entry> entry : urls.entrySet()) { filterFromUrls(entry.getValue(), ret, filter); } - } - else { + } else { Map map = urls.get(s); filterFromUrls(map, ret, filter); } - + return ret; } // Map static void filterFromUrls(Map from, Map to, Map filter) { - if(from == null || from.isEmpty()) return; - - for(Map.Entry entry : from.entrySet()) { + if (from == null || from.isEmpty()) return; + + for (Map.Entry entry : from.entrySet()) { URL url = entry.getValue(); - + boolean match = true; - for(Map.Entry e : filter.entrySet()) { + for (Map.Entry e : filter.entrySet()) { String key = e.getKey(); String value = e.getValue(); - - if(ADDRESS_FILTER_KEY.equals(key)) { - if(!value.equals(url.getAddress())) { + + if (ADDRESS_FILTER_KEY.equals(key)) { + if (!value.equals(url.getAddress())) { match = false; break; } - } - else { - if(!value.equals(url.getParameter(key))) { + } else { + if (!value.equals(url.getParameter(key))) { match = false; break; } } } - - if(match) { + + if (match) { to.put(entry.getKey(), url); } } } - + public static >> Pair filterFromCategory(Map urls, String category, Long id) { SM services = urls.get(category); - if(services == null) return null; - - for(Map.Entry> e1 : services.entrySet()) { + if (services == null) return null; + + for (Map.Entry> e1 : services.entrySet()) { Map u = e1.getValue(); - if(u.containsKey(id)) return new Pair(id, u.get(id)); + if (u.containsKey(id)) return new Pair(id, u.get(id)); } return null; } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/auth/DubboUser.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/auth/DubboUser.java index f20813bbc13..12710fe6cea 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/auth/DubboUser.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/auth/DubboUser.java @@ -1,30 +1,30 @@ /** * Function: dubbo用户类 - * + *

* File Created at 2011-08-17 - * + *

* Copyright 2011 Alibaba.com Croporation Limited. * All rights reserved. */ package com.alibaba.dubbo.governance.web.common.auth; -import java.io.Serializable; - import com.alibaba.dubbo.registry.common.domain.User; +import java.io.Serializable; + /** * MinasUser: DubboUser - * + * * @author guanghui.shigh */ public class DubboUser implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private static final ThreadLocal userHolder = new ThreadLocal(); + private static final ThreadLocal userHolder = new ThreadLocal(); - private DubboUser() { - } + private DubboUser() { + } public static final User getCurrentUser() { return (User) userHolder.get(); diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/i18n/LocaleUtil.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/i18n/LocaleUtil.java index bb56e2a19eb..fb3c45cfdf8 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/i18n/LocaleUtil.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/i18n/LocaleUtil.java @@ -5,10 +5,6 @@ public class LocaleUtil { private static ThreadLocal userLocale = new ThreadLocal(); - public static void setLocale(Locale locale) { - userLocale.set(locale); - } - public static void cleanLocale() { userLocale.remove(); } @@ -17,4 +13,8 @@ public static Locale getLocale() { return userLocale.get(); } + public static void setLocale(Locale locale) { + userLocale.set(locale); + } + } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/interceptor/AuthorizationValve.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/interceptor/AuthorizationValve.java index 4201148fbb8..583156c1f38 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/interceptor/AuthorizationValve.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/interceptor/AuthorizationValve.java @@ -1,27 +1,13 @@ /** * Function: 拦截器 - * + *

* File Created at 2011-08-11 - * + *

* Copyright 2011 Alibaba.com Croporation Limited. * All rights reserved. */ package com.alibaba.dubbo.governance.web.common.interceptor; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.citrus.service.pipeline.PipelineContext; import com.alibaba.citrus.service.pipeline.support.AbstractValve; import com.alibaba.dubbo.common.logger.Logger; @@ -32,6 +18,19 @@ import com.alibaba.dubbo.registry.common.domain.User; import com.alibaba.dubbo.registry.common.util.Coder; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + /** * @author william.liangf * @author guanghui.shigh @@ -41,15 +40,36 @@ public class AuthorizationValve extends AbstractValve { private static final Logger logger = LoggerFactory.getLogger(AuthorizationValve.class); - + private static final String BASIC_CHALLENGE = "Basic"; + private static final String DIGEST_CHALLENGE = "Digest"; + private static final String CHALLENGE = BASIC_CHALLENGE; + private static final String REALM = User.REALM; + private static Pattern PARAMETER_PATTERN = Pattern.compile("(\\w+)=[\"]?([^,\"]+)[\"]?[,]?\\s*"); @Autowired - private HttpServletRequest request; - + private HttpServletRequest request; @Autowired private HttpServletResponse response; - @Autowired private UserService userService; + private String logout = "/logout"; + private String logoutCookie = "logout"; + + static Map parseParameters(String query) { + Matcher matcher = PARAMETER_PATTERN.matcher(query); + Map map = new HashMap(); + while (matcher.find()) { + String key = matcher.group(1); + String value = matcher.group(2); + map.put(key, value); + } + return map; + } + + static byte[] readToBytes(InputStream in) throws IOException { + byte[] buf = new byte[in.available()]; + in.read(buf); + return buf; + } @Override protected void init() throws Exception { @@ -60,23 +80,23 @@ public void invoke(PipelineContext pipelineContext) throws Exception { logger.info("AuthorizationValve of uri: " + request.getRequestURI()); } String uri = request.getRequestURI(); - String contextPath = request.getContextPath(); - if (contextPath != null && contextPath.length() > 0 && ! "/".equals(contextPath)) { - uri = uri.substring(contextPath.length()); - } + String contextPath = request.getContextPath(); + if (contextPath != null && contextPath.length() > 0 && !"/".equals(contextPath)) { + uri = uri.substring(contextPath.length()); + } if (uri.equals(logout)) { - if (! isLogout()) { - setLogout(true); - showLoginForm(); - } else { - setLogout(false); - response.sendRedirect(contextPath == null || contextPath.length() == 0 ? "/" : contextPath); - } + if (!isLogout()) { + setLogout(true); + showLoginForm(); + } else { + setLogout(false); + response.sendRedirect(contextPath == null || contextPath.length() == 0 ? "/" : contextPath); + } return; - } + } //FIXME - if(! uri.startsWith("/status/")){ - User user = null; + if (!uri.startsWith("/status/")) { + User user = null; String authType = null; String authorization = request.getHeader("Authorization"); if (authorization != null && authorization.length() > 0) { @@ -99,32 +119,20 @@ public void invoke(PipelineContext pipelineContext) throws Exception { request.getSession().setAttribute(WebConstants.CURRENT_USER_KEY, user); pipelineContext.invokeNext(); } - }else{ + } else { pipelineContext.invokeNext(); } } private User getUser(String username) { - return userService.findUser(username); + return userService.findUser(username); } - private static final String BASIC_CHALLENGE = "Basic"; - - private static final String DIGEST_CHALLENGE = "Digest"; - - private static final String CHALLENGE = BASIC_CHALLENGE; - - private static final String REALM = User.REALM; - - private String logout = "/logout"; - - private String logoutCookie = "logout"; - private void showLoginForm() throws IOException { if (DIGEST_CHALLENGE.equals(CHALLENGE)) { response.setHeader("WWW-Authenticate", CHALLENGE + " realm=\"" + REALM + "\", qop=\"auth\", nonce=\"" - + UUID.randomUUID().toString().replace("-", "") + "\", opaque=\"" - + Coder.encodeMd5(REALM) + "\""); + + UUID.randomUUID().toString().replace("-", "") + "\", opaque=\"" + + Coder.encodeMd5(REALM) + "\""); } else { response.setHeader("WWW-Authenticate", CHALLENGE + " realm=\"" + REALM + "\""); } @@ -132,7 +140,7 @@ private void showLoginForm() throws IOException { response.setHeader("Content-Type", "text/html; charset=iso-8859-1"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } - + private User loginByBase(String authorization) { authorization = Coder.decodeBase64(authorization); int i = authorization.indexOf(':'); @@ -175,11 +183,11 @@ private User loginByDigest(String value) throws IOException { String a1 = pwd; String a2 = "auth-int".equals(qop) - ? Coder.encodeMd5(method + ":" + uri + ":" + Coder.encodeMd5(readToBytes(request.getInputStream()))) - : Coder.encodeMd5(method + ":" + uri); + ? Coder.encodeMd5(method + ":" + uri + ":" + Coder.encodeMd5(readToBytes(request.getInputStream()))) + : Coder.encodeMd5(method + ":" + uri); String digest = "auth".equals(qop) || "auth-int".equals(qop) - ? Coder.encodeMd5(a1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + a2) - : Coder.encodeMd5(a1 + ":" + nonce + ":" + a2); + ? Coder.encodeMd5(a1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + a2) + : Coder.encodeMd5(a1 + ":" + nonce + ":" + a2); if (digest.equals(passwordDigest)) { return user; } @@ -189,7 +197,7 @@ private User loginByDigest(String value) throws IOException { } return null; } - + private boolean isLogout() { Cookie[] cookies = request.getCookies(); if (cookies != null && cookies.length > 0) { @@ -201,27 +209,8 @@ private boolean isLogout() { } return false; } - + private void setLogout(boolean logoutValue) { response.addCookie(new Cookie(logoutCookie, String.valueOf(logoutValue))); } - - private static Pattern PARAMETER_PATTERN = Pattern.compile("(\\w+)=[\"]?([^,\"]+)[\"]?[,]?\\s*"); - - static Map parseParameters(String query) { - Matcher matcher = PARAMETER_PATTERN.matcher(query); - Map map = new HashMap(); - while (matcher.find()) { - String key = matcher.group(1); - String value = matcher.group(2); - map.put(key, value); - } - return map; - } - - static byte[] readToBytes(InputStream in) throws IOException { - byte[] buf = new byte[in.available()]; - in.read(buf); - return buf; - } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/interceptor/LocaleValve.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/interceptor/LocaleValve.java index c562ffce879..082d1b4ffa3 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/interceptor/LocaleValve.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/interceptor/LocaleValve.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.console-2.1.0-SNAPSHOT - * + *

* File Created at Sep 13, 2011 * $Id: LocaleValve.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 1999-2100 Alibaba.com Corporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,31 +15,28 @@ */ package com.alibaba.dubbo.governance.web.common.interceptor; -import static com.alibaba.citrus.turbine.util.TurbineUtil.getTurbineRunData; +import com.alibaba.citrus.service.pipeline.PipelineContext; +import com.alibaba.citrus.service.pipeline.support.AbstractValve; +import com.alibaba.citrus.turbine.TurbineRunData; +import com.alibaba.dubbo.governance.web.common.i18n.LocaleUtil; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.servlet.http.HttpServletRequest; import java.util.HashSet; import java.util.Locale; import java.util.Set; -import javax.servlet.http.HttpServletRequest; - -import org.springframework.beans.factory.annotation.Autowired; - -import com.alibaba.citrus.service.pipeline.PipelineContext; -import com.alibaba.citrus.service.pipeline.support.AbstractValve; -import com.alibaba.citrus.turbine.TurbineRunData; -import com.alibaba.dubbo.governance.web.common.i18n.LocaleUtil; +import static com.alibaba.citrus.turbine.util.TurbineUtil.getTurbineRunData; /** * @author guanghui.shigh */ public class LocaleValve extends AbstractValve { - - @Autowired - private HttpServletRequest request; //添加拦截器例外设置 private final static Set TARGET_WITHOUT_CHECK = new HashSet(); + static { TARGET_WITHOUT_CHECK.add("/ok"); TARGET_WITHOUT_CHECK.add("/error"); @@ -47,6 +44,9 @@ public class LocaleValve extends AbstractValve { TARGET_WITHOUT_CHECK.add("/logout"); } + @Autowired + private HttpServletRequest request; + private boolean ignoreTarget(String target) { return TARGET_WITHOUT_CHECK.contains(target); } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/interceptor/RestfuleUrlRewriter.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/interceptor/RestfuleUrlRewriter.java index cf7fbe21c91..39acdade200 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/interceptor/RestfuleUrlRewriter.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/interceptor/RestfuleUrlRewriter.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.console-2.1.0-SNAPSHOT - * + *

* File Created at Sep 5, 2011 * $Id: RestfuleUrlRewriter.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 1999-2100 Alibaba.com Corporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,6 +15,11 @@ */ package com.alibaba.dubbo.governance.web.common.interceptor; +import com.alibaba.citrus.service.requestcontext.rewrite.RewriteSubstitutionContext; +import com.alibaba.citrus.service.requestcontext.rewrite.RewriteSubstitutionHandler; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -25,22 +30,28 @@ import java.util.Set; import java.util.regex.Pattern; -import com.alibaba.citrus.service.requestcontext.rewrite.RewriteSubstitutionContext; -import com.alibaba.citrus.service.requestcontext.rewrite.RewriteSubstitutionHandler; -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; - /** * Restful URL Rewrite成 WebX的URL。 - * + * * @author ding.lid */ public class RestfuleUrlRewriter implements RewriteSubstitutionHandler { - private static final Logger logger = LoggerFactory.getLogger(RestfuleUrlRewriter.class); + private static final Logger logger = LoggerFactory.getLogger(RestfuleUrlRewriter.class); private static final Map pl2single; - private static final Set appParameter; + private static final Set appParameter; + private final static String METHOD_KEY = "_method"; // show, + private final static String TYPE_KEY = "_type"; + private final static String ID_KEY = "id"; + private final static String PAGES_KEY = "currentPage"; + private final static String PATH_KEY = "_path"; + private final static Pattern SLASH_PATTERN = Pattern.compile("/+"); + private final static Pattern NUM_PATTERN = Pattern.compile("\\d+"); + private final static Pattern MULTI_NUM_PATTERN = Pattern.compile("[+\\d]+"); + private final static Pattern PAGES_SPLIT_PATTERN = Pattern.compile("/+pages/+"); + private final static Pattern PAGES_PATTERN = Pattern.compile(".*/+pages/+\\d+$"); + static { Map map = new HashMap(); @@ -64,18 +75,6 @@ public class RestfuleUrlRewriter implements RewriteSubstitutionHandler { appParameter = Collections.unmodifiableSet(set); } - private final static String METHOD_KEY = "_method"; // show, - private final static String TYPE_KEY = "_type"; - private final static String ID_KEY = "id"; - private final static String PAGES_KEY = "currentPage"; - private final static String PATH_KEY = "_path"; - - private final static Pattern SLASH_PATTERN = Pattern.compile("/+"); - private final static Pattern NUM_PATTERN = Pattern.compile("\\d+"); - private final static Pattern MULTI_NUM_PATTERN = Pattern.compile("[+\\d]+"); - private final static Pattern PAGES_SPLIT_PATTERN = Pattern.compile("/+pages/+"); - private final static Pattern PAGES_PATTERN = Pattern.compile(".*/+pages/+\\d+$"); - public void postSubstitution(RewriteSubstitutionContext context) { final String oldPath = context.getPath(); String path = oldPath; @@ -96,28 +95,28 @@ public void postSubstitution(RewriteSubstitutionContext context) { } List temp = Arrays.asList(SLASH_PATTERN.split(path)); //兼容2.0.x注册中心的shell风格url 如:http://root:hello1234@127.0.0.1:8080/status/dubbo.test.api.HelloService:1.1 - if("status".equals(temp.get(0))&&temp.size()>1){ + if ("status".equals(temp.get(0)) && temp.size() > 1) { context.setPath("servicestatus"); return; } //兼容包含group的path String[] split = temp.toArray(new String[temp.size()]); - - if(temp.size()>2&&temp.contains("services")){ + + if (temp.size() > 2 && temp.contains("services")) { List parts = new ArrayList(); parts.addAll(temp); - for(int i = 0;i * File Created at 2011-08-11 - * + *

* Copyright 2011 Alibaba.com Croporation Limited. * All rights reserved. */ package com.alibaba.dubbo.governance.web.common.interceptor; -import static com.alibaba.citrus.turbine.util.TurbineUtil.getTurbineRunData; - -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; - -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.citrus.service.pipeline.PipelineContext; import com.alibaba.citrus.service.pipeline.support.AbstractValve; import com.alibaba.citrus.turbine.TurbineRunData; @@ -25,14 +16,22 @@ import com.alibaba.dubbo.governance.web.util.WebConstants; import com.alibaba.dubbo.registry.common.domain.User; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import java.util.Map; + +import static com.alibaba.citrus.turbine.util.TurbineUtil.getTurbineRunData; + /** * @author guanghui.shigh */ public class ServicePrivilegeCheckValve extends AbstractValve { - private static final Logger logger = LoggerFactory.getLogger(ServicePrivilegeCheckValve.class); + private static final Logger logger = LoggerFactory.getLogger(ServicePrivilegeCheckValve.class); @Autowired - private HttpServletRequest request; + private HttpServletRequest request; @Override protected void init() throws Exception { @@ -43,56 +42,56 @@ public void invoke(PipelineContext pipelineContext) throws Exception { invokeCheckServicePrivilege(user); pipelineContext.invokeNext(); } - - + + private void invokeCheckServicePrivilege(User user) { - TurbineRunData rundata = getTurbineRunData(request); - HttpSession session = request.getSession(); - - @SuppressWarnings("unchecked") - Map requestMapping = request.getParameterMap(); - - //记录上次操作到请求中 - String returnURL = ""; - if(session.getAttribute("returnURL")==null){ - returnURL = request.getContextPath(); - }else{ - returnURL = (String)session.getAttribute("returnURL"); - } - - if(requestMapping.get("service").length>0){ - String service = ((String[]) requestMapping.get("service"))[0]; - String method = "index"; - if(requestMapping.get("_method").length>0){ - method = requestMapping.get("_method")[0]; - } - - boolean exclude = "index".equals(method) || "show".equals(method); - if(!exclude){ - if (user != null && !user.hasServicePrivilege(service)) { - request.setAttribute("returnURL",returnURL); - redirectToNoRight(rundata); + TurbineRunData rundata = getTurbineRunData(request); + HttpSession session = request.getSession(); + + @SuppressWarnings("unchecked") + Map requestMapping = request.getParameterMap(); + + //记录上次操作到请求中 + String returnURL = ""; + if (session.getAttribute("returnURL") == null) { + returnURL = request.getContextPath(); + } else { + returnURL = (String) session.getAttribute("returnURL"); + } + + if (requestMapping.get("service").length > 0) { + String service = ((String[]) requestMapping.get("service"))[0]; + String method = "index"; + if (requestMapping.get("_method").length > 0) { + method = requestMapping.get("_method")[0]; + } + + boolean exclude = "index".equals(method) || "show".equals(method); + if (!exclude) { + if (user != null && !user.hasServicePrivilege(service)) { + request.setAttribute("returnURL", returnURL); + redirectToNoRight(rundata); } - } - } - String type = requestMapping.get("_type").length == 0 ? null : requestMapping.get("_type")[0]; - if(!"noServicePrivilege".equals(type)){ - session.setAttribute("returnURL", request.getRequestURI()); - } - return; - } - - /** + } + } + String type = requestMapping.get("_type").length == 0 ? null : requestMapping.get("_type")[0]; + if (!"noServicePrivilege".equals(type)) { + session.setAttribute("returnURL", request.getRequestURI()); + } + return; + } + + /** * 无权限跳转 * @param rundata */ private void redirectToNoRight(TurbineRunData rundata) { - if(logger.isInfoEnabled()) { + if (logger.isInfoEnabled()) { logger.info("No right to access: " + request.getRequestURI()); } - - rundata.getParameters().setString("returnURL1", (String)rundata.getRequest().getAttribute("returnURL")); - rundata.setRedirectLocation("http://localhost:8080/governance/noServicePrivilege?returnURL="+rundata.getRequest().getAttribute("returnURL")); - return; - } + + rundata.getParameters().setString("returnURL1", (String) rundata.getRequest().getAttribute("returnURL")); + rundata.setRedirectLocation("http://localhost:8080/governance/noServicePrivilege?returnURL=" + rundata.getRequest().getAttribute("returnURL")); + return; + } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/module/screen/Error_404.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/module/screen/Error_404.java index 664fc400cb2..b0fffa89df0 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/module/screen/Error_404.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/module/screen/Error_404.java @@ -15,15 +15,15 @@ */ package com.alibaba.dubbo.governance.web.common.module.screen; -import java.util.Map; - import com.alibaba.dubbo.governance.web.common.pulltool.RootContextPath; +import java.util.Map; + public class Error_404 { - - public void execute(Map context) throws Throwable { - String contextPath = (String) context.get("request.contextPath"); + + public void execute(Map context) throws Throwable { + String contextPath = (String) context.get("request.contextPath"); context.put("rootContextPath", new RootContextPath(contextPath)); - } + } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/module/screen/Error_other.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/module/screen/Error_other.java index af75b860752..54d091a5f50 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/module/screen/Error_other.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/module/screen/Error_other.java @@ -15,15 +15,15 @@ */ package com.alibaba.dubbo.governance.web.common.module.screen; -import java.util.Map; - import com.alibaba.dubbo.governance.web.common.pulltool.RootContextPath; +import java.util.Map; + public class Error_other { - - public void execute(Map context) throws Throwable { - String contextPath = (String) context.get("request.contextPath"); + + public void execute(Map context) throws Throwable { + String contextPath = (String) context.get("request.contextPath"); context.put("rootContextPath", new RootContextPath(contextPath)); - } + } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/module/screen/Restful.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/module/screen/Restful.java index f5d385dbaf0..5e986675edf 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/module/screen/Restful.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/module/screen/Restful.java @@ -7,6 +7,15 @@ */ package com.alibaba.dubbo.governance.web.common.module.screen; +import com.alibaba.dubbo.common.utils.CompatibleTypeUtils; +import com.alibaba.dubbo.governance.biz.common.i18n.MessageResourceService; +import com.alibaba.dubbo.governance.web.common.pulltool.RootContextPath; +import com.alibaba.dubbo.governance.web.util.WebConstants; +import com.alibaba.dubbo.registry.common.domain.User; + +import org.apache.log4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; + import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -14,89 +23,105 @@ import java.util.Map; import java.util.regex.Pattern; -import org.apache.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; - -import com.alibaba.dubbo.common.utils.CompatibleTypeUtils; -import com.alibaba.dubbo.governance.biz.common.i18n.MessageResourceService; -import com.alibaba.dubbo.governance.web.common.pulltool.RootContextPath; -import com.alibaba.dubbo.governance.web.util.WebConstants; -import com.alibaba.dubbo.registry.common.domain.User; - /** * BaseScreen - * + * * @author william.liangf */ public abstract class Restful { - - protected static final Logger logger = Logger.getLogger(Restful.class); - - protected static final Pattern SPACE_SPLIT_PATTERN = Pattern.compile("\\s+"); - - @Autowired - private MessageResourceService messageResourceService; - - public String getMessage(String key, Object... args) { - return messageResourceService.getMessage(key, args); - } - - //FIXME 把这些辅助方法提取出去 - protected String role = null; - protected String operator = null; - protected User currentUser = null; - protected String operatorAddress = null; - protected String currentRegistry = null; - + + protected static final Logger logger = Logger.getLogger(Restful.class); + + protected static final Pattern SPACE_SPLIT_PATTERN = Pattern.compile("\\s+"); + //FIXME 把这些辅助方法提取出去 + protected String role = null; + protected String operator = null; + protected User currentUser = null; + protected String operatorAddress = null; + protected String currentRegistry = null; + @Autowired + private MessageResourceService messageResourceService; + + private static boolean isPrimitive(Class cls) { + return cls.isPrimitive() || cls == Boolean.class || cls == Byte.class + || cls == Character.class || cls == Short.class || cls == Integer.class + || cls == Long.class || cls == Float.class || cls == Double.class + || cls == String.class; + } + + private static Object convertPrimitive(Class cls, String value) { + if (cls == boolean.class || cls == Boolean.class) { + return value == null || value.length() == 0 ? false : Boolean.valueOf(value); + } else if (cls == byte.class || cls == Byte.class) { + return value == null || value.length() == 0 ? 0 : Byte.valueOf(value); + } else if (cls == char.class || cls == Character.class) { + return value == null || value.length() == 0 ? '\0' : value.charAt(0); + } else if (cls == short.class || cls == Short.class) { + return value == null || value.length() == 0 ? 0 : Short.valueOf(value); + } else if (cls == int.class || cls == Integer.class) { + return value == null || value.length() == 0 ? 0 : Integer.valueOf(value); + } else if (cls == long.class || cls == Long.class) { + return value == null || value.length() == 0 ? 0 : Long.valueOf(value); + } else if (cls == float.class || cls == Float.class) { + return value == null || value.length() == 0 ? 0 : Float.valueOf(value); + } else if (cls == double.class || cls == Double.class) { + return value == null || value.length() == 0 ? 0 : Double.valueOf(value); + } + return value; + } + + public String getMessage(String key, Object... args) { + return messageResourceService.getMessage(key, args); + } + public void execute(Map context) throws Throwable { - if(context.get(WebConstants.CURRENT_USER_KEY)!=null){ - User user = (User) context.get(WebConstants.CURRENT_USER_KEY); - currentUser = user; - operator = user.getUsername(); - role = user.getRole(); - context.put(WebConstants.CURRENT_USER_KEY, user); + if (context.get(WebConstants.CURRENT_USER_KEY) != null) { + User user = (User) context.get(WebConstants.CURRENT_USER_KEY); + currentUser = user; + operator = user.getUsername(); + role = user.getRole(); + context.put(WebConstants.CURRENT_USER_KEY, user); } - operatorAddress = (String)context.get("request.remoteHost"); + operatorAddress = (String) context.get("request.remoteHost"); context.put("operator", operator); - context.put("operatorAddress", operatorAddress); - + context.put("operatorAddress", operatorAddress); + context.put("currentRegistry", currentRegistry); - + String httpMethod = (String) context.get("request.method"); String method = (String) context.get("_method"); String contextPath = (String) context.get("request.contextPath"); context.put("rootContextPath", new RootContextPath(contextPath)); - + // 分析Method if (method == null || method.length() == 0) { String id = (String) context.get("id"); - if(id == null || id.length() == 0) { + if (id == null || id.length() == 0) { method = "index"; - } - else { + } else { method = "show"; } } if ("index".equals(method)) { - if("post".equalsIgnoreCase(httpMethod)) { + if ("post".equalsIgnoreCase(httpMethod)) { method = "create"; } } else if ("show".equals(method)) { - if("put".equalsIgnoreCase(httpMethod) || "post".equalsIgnoreCase(httpMethod)) { // 因表单不能提交PUT请求,用POST代替 + if ("put".equalsIgnoreCase(httpMethod) || "post".equalsIgnoreCase(httpMethod)) { // 因表单不能提交PUT请求,用POST代替 method = "update"; } else if ("delete".equalsIgnoreCase(httpMethod)) { // 因表单不能提交DELETE请求,用参数代替 method = "delete"; } } context.put("_method", method); - + try { Method m = null; try { m = getClass().getMethod(method, new Class[]{Map.class}); } catch (NoSuchMethodException e) { for (Method mtd : getClass().getMethods()) { - if (Modifier.isPublic(mtd.getModifiers()) + if (Modifier.isPublic(mtd.getModifiers()) && mtd.getName().equals(method)) { m = mtd; break; @@ -109,8 +134,8 @@ public void execute(Map context) throws Throwable { if (m.getParameterTypes().length > 2) { throw new IllegalStateException("Unsupport restful method " + m); } else if (m.getParameterTypes().length == 2 - && (m.getParameterTypes()[0].equals(Map.class) - || ! m.getParameterTypes()[1].equals(Map.class))) { + && (m.getParameterTypes()[0].equals(Map.class) + || !m.getParameterTypes()[1].equals(Map.class))) { throw new IllegalStateException("Unsupport restful method " + m); } Object r; @@ -128,13 +153,13 @@ public void execute(Map context) throws Throwable { String id = (String) context.get("id"); String[] ids = id == null ? new String[0] : id.split("[.+]+"); value = Array.newInstance(t.getComponentType(), ids.length); - for (int i = 0; i < ids.length; i ++) { + for (int i = 0; i < ids.length; i++) { Array.set(value, i, convertPrimitive(t.getComponentType(), ids[i])); } } else { value = t.newInstance(); for (Method mtd : t.getMethods()) { - if (Modifier.isPublic(mtd.getModifiers()) + if (Modifier.isPublic(mtd.getModifiers()) && mtd.getName().startsWith("set") && mtd.getParameterTypes().length == 1) { String p = mtd.getName().substring(3, 4).toLowerCase() + mtd.getName().substring(4); @@ -147,39 +172,39 @@ public void execute(Map context) throws Throwable { } } if (v != null) { - try { - mtd.invoke(value, new Object[] { CompatibleTypeUtils.compatibleTypeConvert(v, mtd.getParameterTypes()[0]) }); - } catch (Throwable e) { - logger.warn(e.getMessage(), e); - } + try { + mtd.invoke(value, new Object[]{CompatibleTypeUtils.compatibleTypeConvert(v, mtd.getParameterTypes()[0])}); + } catch (Throwable e) { + logger.warn(e.getMessage(), e); + } } } } } if (m.getParameterTypes().length == 1) { - r = m.invoke(this, new Object[] {value}); + r = m.invoke(this, new Object[]{value}); } else { - r = m.invoke(this, new Object[] {value, context}); + r = m.invoke(this, new Object[]{value, context}); } } if (m.getReturnType() == boolean.class || m.getReturnType() == Boolean.class) { context.put("rundata.layout", "redirect"); context.put("rundata.target", "redirect"); context.put("success", r == null || ((Boolean) r).booleanValue()); - if(context.get("redirect")==null){ - context.put("redirect", getDefaultRedirect(context, method)); + if (context.get("redirect") == null) { + context.put("redirect", getDefaultRedirect(context, method)); } } else if (m.getReturnType() == String.class) { String redirect = (String) r; if (redirect == null) { redirect = getDefaultRedirect(context, method); } - - if(context.get("chain")!=null){ - context.put("rundata.layout", "home"); + + if (context.get("chain") != null) { + context.put("rundata.layout", "home"); context.put("rundata.target", "home"); - }else{ - context.put("rundata.redirect", redirect); + } else { + context.put("rundata.redirect", redirect); } } else { context.put("rundata.layout", method); @@ -200,38 +225,10 @@ public void execute(Map context) throws Throwable { // context.put("redirect", getDefaultRedirect(context, method)); } } - - private static boolean isPrimitive(Class cls) { - return cls.isPrimitive()|| cls == Boolean.class || cls == Byte.class - || cls == Character.class || cls == Short.class || cls == Integer.class - || cls == Long.class || cls == Float.class || cls == Double.class - || cls == String.class; - } - - private static Object convertPrimitive(Class cls, String value) { - if (cls == boolean.class || cls == Boolean.class) { - return value == null || value.length() == 0 ? false : Boolean.valueOf(value); - } else if (cls == byte.class || cls == Byte.class) { - return value == null || value.length() == 0 ? 0 : Byte.valueOf(value); - } else if (cls == char.class || cls == Character.class) { - return value == null || value.length() == 0 ? '\0' : value.charAt(0); - } else if (cls == short.class || cls == Short.class) { - return value == null || value.length() == 0 ? 0 : Short.valueOf(value); - } else if (cls == int.class || cls == Integer.class) { - return value == null || value.length() == 0 ? 0 : Integer.valueOf(value); - } else if (cls == long.class || cls == Long.class) { - return value == null || value.length() == 0 ? 0 : Long.valueOf(value); - } else if (cls == float.class || cls == Float.class) { - return value == null || value.length() == 0 ? 0 : Float.valueOf(value); - } else if (cls == double.class || cls == Double.class) { - return value == null || value.length() == 0 ? 0 : Double.valueOf(value); - } - return value; - } - + private String getDefaultRedirect(Map context, String operate) { String defaultRedirect = (String) context.get("defaultRedirect"); - return defaultRedirect; + return defaultRedirect; } - + } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/pulltool/DateFormatUtil.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/pulltool/DateFormatUtil.java index b63e292a28c..6fea58270a1 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/pulltool/DateFormatUtil.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/pulltool/DateFormatUtil.java @@ -1,26 +1,26 @@ package com.alibaba.dubbo.governance.web.common.pulltool; +import org.apache.commons.lang.StringUtils; + import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Map; -import org.apache.commons.lang.StringUtils; - /** * DateFormat Utility - * + * * @author guanghui.shigh */ public class DateFormatUtil { - private static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss"; + private static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss"; - private static final ThreadLocal> tl = new ThreadLocal>(); + private static final ThreadLocal> tl = new ThreadLocal>(); /** * According to the specified format, Get a DateFormat - * + * * @param format * @return */ @@ -48,7 +48,7 @@ public static DateFormat getDateFormat(String format) { /** * Get Default DateFormat - * + * * @return */ public static DateFormat getDateFormat() { diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/pulltool/I18nMessageTool.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/pulltool/I18nMessageTool.java index 2ec3d6be236..bdfaf55ce65 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/pulltool/I18nMessageTool.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/pulltool/I18nMessageTool.java @@ -1,12 +1,12 @@ /** * Project: iris-web-1.0-SNAPSHOT - * + *

* File Created at Jul 9, 2010 * $Id: I18nMessageTool.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,33 +15,32 @@ */ package com.alibaba.dubbo.governance.web.common.pulltool; -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.citrus.service.pull.ToolFactory; import com.alibaba.dubbo.governance.biz.common.i18n.MessageResourceService; +import org.springframework.beans.factory.annotation.Autowired; + /** * PullTool for accessing message bundle. - * + * * @author gerry */ public class I18nMessageTool implements ToolFactory { @Autowired private MessageResourceService messageResourceService; + private boolean singleton = true; //应该是global范围的对象!! public Object createTool() throws Exception { return messageResourceService; } - private boolean singleton = true; //应该是global范围的对象!! + public boolean isSingleton() { + return this.singleton; + } public void setSingleton(boolean singleton) { this.singleton = singleton; } - - public boolean isSingleton() { - return this.singleton; - } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/pulltool/RootContextPath.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/pulltool/RootContextPath.java index 3d796194920..288398000a9 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/pulltool/RootContextPath.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/pulltool/RootContextPath.java @@ -16,25 +16,25 @@ package com.alibaba.dubbo.governance.web.common.pulltool; public class RootContextPath { - - private String contextPath; - - public RootContextPath(String contextPath) { - this.contextPath = contextPath; - } - public String getURI(String uri) { - String prefix; - if (contextPath != null && contextPath.length() > 0 && ! "/".equals(contextPath)) { - prefix = contextPath; - } else { - prefix = ""; - } - if (uri.startsWith("/")) { - return prefix + uri; - } else { - return prefix + "/" + uri; - } - } + private String contextPath; + + public RootContextPath(String contextPath) { + this.contextPath = contextPath; + } + + public String getURI(String uri) { + String prefix; + if (contextPath != null && contextPath.length() > 0 && !"/".equals(contextPath)) { + prefix = contextPath; + } else { + prefix = ""; + } + if (uri.startsWith("/")) { + return prefix + uri; + } else { + return prefix + "/" + uri; + } + } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/pulltool/Tool.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/pulltool/Tool.java index 435767664e2..dd32a1f6a72 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/pulltool/Tool.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/pulltool/Tool.java @@ -1,11 +1,11 @@ /** * Project: dubbo.registry.server-1.1.0-SNAPSHOT - * + *

* File Created at 2010-7-27 - * + *

* Copyright 1999-2010 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -14,21 +14,6 @@ */ package com.alibaba.dubbo.governance.web.common.pulltool; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Array; -import java.net.InetAddress; -import java.net.URLEncoder; -import java.net.UnknownHostException; -import java.text.ParseException; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.List; -import java.util.Map; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.utils.NetUtils; @@ -45,24 +30,46 @@ import com.alibaba.dubbo.registry.common.route.RouteRule.MatchPair; import com.alibaba.dubbo.registry.common.util.StringEscapeUtils; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Array; +import java.net.InetAddress; +import java.net.URLEncoder; +import java.net.UnknownHostException; +import java.text.ParseException; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.List; +import java.util.Map; + /** * Tool - * + * * @author william.liangf */ public class Tool { - private OverrideService overrideService; - - private RouteService routeService; - - public void setOverrideService(OverrideService overrideService) { - this.overrideService = overrideService; - } - - public void setRouteService(RouteService routeService) { - this.routeService = routeService; - } + private static final Comparator SIMPLE_NAME_COMPARATOR = new Comparator() { + public int compare(String s1, String s2) { + if (s1 == null && s2 == null) { + return 0; + } + if (s1 == null) { + return -1; + } + if (s2 == null) { + return 1; + } + s1 = getSimpleName(s1); + s2 = getSimpleName(s2); + return s1.compareToIgnoreCase(s2); + } + }; + private OverrideService overrideService; + private RouteService routeService; public static String toStackTraceString(Throwable t) { StringWriter writer = new StringWriter(); @@ -74,15 +81,15 @@ public static String toStackTraceString(Throwable t) { public static boolean isContains(String[] values, String value) { return StringUtils.isContains(values, value); } - + public static boolean startWith(String value, String prefix) { return value.startsWith(prefix); } - + public static String getHostPrefix(String address) { if (address != null && address.length() > 0) { String hostname = getHostName(address); - if (! address.startsWith(hostname)) { + if (!address.startsWith(hostname)) { return "(" + hostname + ")"; } } @@ -92,19 +99,19 @@ public static String getHostPrefix(String address) { public static String getHostName(String address) { return NetUtils.getHostName(address); } - + public static String getHostAddress(String address) { if (address != null && address.length() > 0) { int i = address.indexOf(':'); - String port = address.substring(i+1); + String port = address.substring(i + 1); String hostname = NetUtils.getHostName(address); - if (! address.equals(hostname)) { + if (!address.equals(hostname)) { return hostname + ":" + port; } } return ""; } - + public static String getPath(String url) { try { return URL.valueOf(url).getPath(); @@ -112,7 +119,7 @@ public static String getPath(String url) { return url; } } - + public static String getAddress(String url) { try { return URL.valueOf(url).getAddress(); @@ -122,46 +129,46 @@ public static String getAddress(String url) { } public static String getInterface(String service) { - if (service != null && service.length() > 0) { - int i = service.indexOf('/'); - if (i >= 0) { - service = service.substring(i + 1); - } - i = service.lastIndexOf(':'); - if (i >= 0) { - service = service.substring(0, i); - } - } + if (service != null && service.length() > 0) { + int i = service.indexOf('/'); + if (i >= 0) { + service = service.substring(i + 1); + } + i = service.lastIndexOf(':'); + if (i >= 0) { + service = service.substring(0, i); + } + } return service; } public static String getGroup(String service) { - if (service != null && service.length() > 0) { - int i = service.indexOf('/'); - if (i >= 0) { - return service.substring(0, i); - } - } + if (service != null && service.length() > 0) { + int i = service.indexOf('/'); + if (i >= 0) { + return service.substring(0, i); + } + } return null; } - + public static String getVersion(String service) { - if (service != null && service.length() > 0) { - int i = service.lastIndexOf(':'); - if (i >= 0) { - return service.substring(i + 1); - } - } + if (service != null && service.length() > 0) { + int i = service.lastIndexOf(':'); + if (i >= 0) { + return service.substring(i + 1); + } + } return null; } - + public static String getIP(String address) { - if (address != null && address.length() > 0) { - int i = address.indexOf("://"); - if (i >= 0) { - address = address.substring(i + 3); - } - i = address.indexOf('/'); + if (address != null && address.length() > 0) { + int i = address.indexOf("://"); + if (i >= 0) { + address = address.substring(i + 3); + } + i = address.indexOf('/'); if (i >= 0) { address = address.substring(0, i); } @@ -179,10 +186,10 @@ public static String getIP(String address) { } catch (UnknownHostException e) { } } - } - return address; + } + return address; } - + public static String encode(String url) { try { return URLEncoder.encode(url, "UTF-8"); @@ -190,7 +197,7 @@ public static String encode(String url) { return url; } } - + public static String escape(String html) { return StringEscapeUtils.escapeHtml(html); } @@ -198,70 +205,53 @@ public static String escape(String html) { public static String unescape(String html) { return StringEscapeUtils.unescapeHtml(html); } - + public static String encodeUrl(String url) { - return URL.encode(url); + return URL.encode(url); } public static String decodeUrl(String url) { return URL.decode(url); } - + public static String encodeHtml(String html) { - return StringEscapeUtils.escapeHtml(html); + return StringEscapeUtils.escapeHtml(html); } - + public static int countMapValues(Map map) { - int total = 0; - if (map != null && map.size() > 0) { - for (Object value : map.values()) { - if (value != null) { - if (value instanceof Number) { - total += ((Number)value).intValue(); - } else if (value.getClass().isArray()) { - total += Array.getLength(value); - } else if (value instanceof Collection) { - total += ((Collection)value).size(); - } else if (value instanceof Map) { - total += ((Map)value).size(); - } else { - total += 1; - } - } - } - } - return total; - } - - private static final Comparator SIMPLE_NAME_COMPARATOR = new Comparator() { - public int compare(String s1, String s2) { - if (s1 == null && s2 == null) { - return 0; - } - if (s1 == null) { - return -1; - } - if (s2 == null) { - return 1; - } - s1 = getSimpleName(s1); - s2 = getSimpleName(s2); - return s1.compareToIgnoreCase(s2); - } - }; - - public static List sortSimpleName(List list) { - if (list != null && list.size() > 0) { - Collections.sort(list, SIMPLE_NAME_COMPARATOR); - } - return list; - } - - public static String getSimpleName(String name) { + int total = 0; + if (map != null && map.size() > 0) { + for (Object value : map.values()) { + if (value != null) { + if (value instanceof Number) { + total += ((Number) value).intValue(); + } else if (value.getClass().isArray()) { + total += Array.getLength(value); + } else if (value instanceof Collection) { + total += ((Collection) value).size(); + } else if (value instanceof Map) { + total += ((Map) value).size(); + } else { + total += 1; + } + } + } + } + return total; + } + + public static List sortSimpleName(List list) { + if (list != null && list.size() > 0) { + Collections.sort(list, SIMPLE_NAME_COMPARATOR); + } + return list; + } + + public static String getSimpleName(String name) { if (name != null && name.length() > 0) { final int ip = name.indexOf('/'); String v = ip != -1 ? name.substring(0, ip + 1) : ""; - + int i = name.lastIndexOf(':'); int j = (i >= 0 ? name.lastIndexOf('.', i) : name.lastIndexOf('.')); if (j >= 0) { @@ -271,14 +261,14 @@ public static String getSimpleName(String name) { } return name; } - - public static String getParameter(String parameters, String key){ + + public static String getParameter(String parameters, String key) { String value = ""; if (parameters != null && parameters.length() > 0) { String[] pairs = parameters.split("&"); - for(String pair : pairs){ + for (String pair : pairs) { String[] kv = pair.split("="); - if(key.equals(kv[0])){ + if (key.equals(kv[0])) { value = kv[1]; break; } @@ -286,168 +276,176 @@ public static String getParameter(String parameters, String key){ } return value; } - - public static Map toParameterMap(String parameters){ - return StringUtils.parseQueryString(parameters); - } - - - /** - * 从provider的paramters参数中获取版本值 - * @param parameters - * @return - */ - public static String getVersionFromPara(String parameters){ - String version = ""; - if (parameters != null && parameters.length() > 0) { - String[] params = parameters.split("&"); - for(String o : params){ - String[] kv = o.split("="); - if("version".equals(kv[0])){ - version = kv[1]; - break; - } - } - } - return version; - } - - public String formatTimestamp(String timestamp){ - if (timestamp == null || timestamp.length() == 0) { - return ""; - } - return formatDate(new Date(Long.valueOf(timestamp))); - } - - //时间格式化 - public String formatDate(Date date){ - if(date==null){ - return ""; - } - return DateFormatUtil.getDateFormat().format(date); - } - - public String formatDate(Date date, String template){ - if(date==null || template==null){ - return ""; - } - return DateFormatUtil.getDateFormat(template).format(date); - } - - public boolean beforeNow(Date date){ + + public static Map toParameterMap(String parameters) { + return StringUtils.parseQueryString(parameters); + } + + /** + * 从provider的paramters参数中获取版本值 + * + * @param parameters + * @return + */ + public static String getVersionFromPara(String parameters) { + String version = ""; + if (parameters != null && parameters.length() > 0) { + String[] params = parameters.split("&"); + for (String o : params) { + String[] kv = o.split("="); + if ("version".equals(kv[0])) { + version = kv[1]; + break; + } + } + } + return version; + } + + public static boolean isProviderEnabled(Provider provider, List oList) { + for (Override o : oList) { + if (o.isMatch(provider)) { + Map params = StringUtils.parseQueryString(o.getParams()); + String disbaled = params.get(Constants.DISABLED_KEY); + if (disbaled != null && disbaled.length() > 0) { + return !"true".equals(disbaled); + } + } + } + return provider.isEnabled(); + } + + public static int getProviderWeight(Provider provider, List oList) { + for (Override o : oList) { + if (o.isMatch(provider)) { + Map params = StringUtils.parseQueryString(o.getParams()); + String weight = params.get(Constants.WEIGHT_KEY); + if (weight != null && weight.length() > 0) { + return Integer.parseInt(weight); + } + } + } + return provider.getWeight(); + } + + public void setOverrideService(OverrideService overrideService) { + this.overrideService = overrideService; + } + + public void setRouteService(RouteService routeService) { + this.routeService = routeService; + } + + public String formatTimestamp(String timestamp) { + if (timestamp == null || timestamp.length() == 0) { + return ""; + } + return formatDate(new Date(Long.valueOf(timestamp))); + } + + //时间格式化 + public String formatDate(Date date) { + if (date == null) { + return ""; + } + return DateFormatUtil.getDateFormat().format(date); + } + + public String formatDate(Date date, String template) { + if (date == null || template == null) { + return ""; + } + return DateFormatUtil.getDateFormat(template).format(date); + } + + public boolean beforeNow(Date date) { Date now = new Date(); - if(now.after(date)){ - return true; + if (now.after(date)) { + return true; } return false; } - + //时间相减 - public long dateMinus(Date date1, Date date2){ - return (date1.getTime() - date1.getTime())/ 1000; - } - - public boolean isProviderEnabled(Provider provider){ - List oList = overrideService.findByServiceAndAddress(provider.getService(), provider.getAddress()); - return isProviderEnabled(provider, oList); - } - - public static boolean isProviderEnabled(Provider provider, List oList){ - for(Override o : oList){ - if (o.isMatch(provider)) { - Map params = StringUtils.parseQueryString(o.getParams()); - String disbaled = params.get(Constants.DISABLED_KEY); - if(disbaled != null && disbaled.length() > 0){ - return ! "true".equals(disbaled); - } - } - } - return provider.isEnabled(); - } - - public int getProviderWeight(Provider provider){ - List oList = overrideService.findByServiceAndAddress(provider.getService(), provider.getAddress()); - return getProviderWeight(provider, oList); - } - - public static int getProviderWeight(Provider provider, List oList) { - for(Override o : oList){ - if (o.isMatch(provider)) { - Map params = StringUtils.parseQueryString(o.getParams()); - String weight = params.get(Constants.WEIGHT_KEY); - if(weight != null && weight.length() > 0){ - return Integer.parseInt(weight); - } - } - } - return provider.getWeight(); - } - - public boolean isInBlackList(Consumer consumer){ - String service = consumer.getService(); - List routes = routeService.findForceRouteByService(service); - if(routes == null || routes.size() == 0){ - return false; - } - String ip = getIP(consumer.getAddress()); - for(Route route : routes){ - try { - if (! route.isEnabled()) { - continue; - } - String filterRule = route.getFilterRule(); - if (filterRule == null || filterRule.length() == 0 || "false".equals(filterRule)) { - Map rule = RouteRule.parseRule(route.getMatchRule()); - MatchPair pair = rule.get("consumer.host"); - if (pair == null) { - pair = rule.get("host"); - } - if(pair != null){ - if (pair.getMatches() != null && pair.getMatches().size() > 0) { - for(String host : pair.getMatches()){ - if (ParseUtils.isMatchGlobPattern(host, ip)) { - return true; - } - } - } - if (pair.getUnmatches() != null && pair.getUnmatches().size() > 0) { - boolean forbid = true; - for(String host : pair.getUnmatches()){ - if (ParseUtils.isMatchGlobPattern(host, ip)) { - forbid = false; - } - } - if (forbid) { - return true; - } - } - } - } - } catch (ParseException e) { - throw new RuntimeException(e.getMessage(), e); - } + public long dateMinus(Date date1, Date date2) { + return (date1.getTime() - date1.getTime()) / 1000; + } + + public boolean isProviderEnabled(Provider provider) { + List oList = overrideService.findByServiceAndAddress(provider.getService(), provider.getAddress()); + return isProviderEnabled(provider, oList); + } + + public int getProviderWeight(Provider provider) { + List oList = overrideService.findByServiceAndAddress(provider.getService(), provider.getAddress()); + return getProviderWeight(provider, oList); + } + + public boolean isInBlackList(Consumer consumer) { + String service = consumer.getService(); + List routes = routeService.findForceRouteByService(service); + if (routes == null || routes.size() == 0) { + return false; + } + String ip = getIP(consumer.getAddress()); + for (Route route : routes) { + try { + if (!route.isEnabled()) { + continue; + } + String filterRule = route.getFilterRule(); + if (filterRule == null || filterRule.length() == 0 || "false".equals(filterRule)) { + Map rule = RouteRule.parseRule(route.getMatchRule()); + MatchPair pair = rule.get("consumer.host"); + if (pair == null) { + pair = rule.get("host"); + } + if (pair != null) { + if (pair.getMatches() != null && pair.getMatches().size() > 0) { + for (String host : pair.getMatches()) { + if (ParseUtils.isMatchGlobPattern(host, ip)) { + return true; + } + } + } + if (pair.getUnmatches() != null && pair.getUnmatches().size() > 0) { + boolean forbid = true; + for (String host : pair.getUnmatches()) { + if (ParseUtils.isMatchGlobPattern(host, ip)) { + forbid = false; + } + } + if (forbid) { + return true; + } + } + } + } + } catch (ParseException e) { + throw new RuntimeException(e.getMessage(), e); + } } - return false; - } - - public String getConsumerMock(Consumer consumer){ - return getOverridesMock(consumer.getOverrides()); - } - - public String getOverridesMock(List overrides){ - if(overrides != null && overrides.size() > 0) { - for(Override override : overrides) { - Map params = StringUtils.parseQueryString(override.getParams()); - String mock = params.get("mock"); - if (mock != null && mock.length() > 0) { - return mock; - } - } - } - return ""; - } - - public boolean checkUrl(User user,String uri){ + return false; + } + + public String getConsumerMock(Consumer consumer) { + return getOverridesMock(consumer.getOverrides()); + } + + public String getOverridesMock(List overrides) { + if (overrides != null && overrides.size() > 0) { + for (Override override : overrides) { + Map params = StringUtils.parseQueryString(override.getParams()); + String mock = params.get("mock"); + if (mock != null && mock.length() > 0) { + return mock; + } + } + } + return ""; + } + + public boolean checkUrl(User user, String uri) { return true; /*if(!User.ROOT.equals(user.getRole())){ List disabledSysinfo = new ArrayList(); diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/pulltool/ToolUtil.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/pulltool/ToolUtil.java index db90b5e5e4d..e0107f67c7b 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/pulltool/ToolUtil.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/pulltool/ToolUtil.java @@ -1,38 +1,37 @@ package com.alibaba.dubbo.governance.web.common.pulltool; -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.citrus.service.pull.ToolFactory; import com.alibaba.dubbo.governance.service.OverrideService; import com.alibaba.dubbo.governance.service.RouteService; +import org.springframework.beans.factory.annotation.Autowired; + /** * PullTool for accessing message bundle. - * + * * @author gerry */ public class ToolUtil implements ToolFactory { - @Autowired - OverrideService overrideService; - - @Autowired - RouteService routeService; + @Autowired + OverrideService overrideService; + + @Autowired + RouteService routeService; + private boolean singleton = false; //应该是global范围的对象!! public Object createTool() throws Exception { - Tool tool = new Tool(); - tool.setOverrideService(overrideService); - tool.setRouteService(routeService); + Tool tool = new Tool(); + tool.setOverrideService(overrideService); + tool.setRouteService(routeService); return tool; } - private boolean singleton = false; //应该是global范围的对象!! - public boolean isSingleton() { return this.singleton; } - + public void setSingleton(boolean singleton) { this.singleton = singleton; } - + } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/resolver/MapDataResolverFactory.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/resolver/MapDataResolverFactory.java index 9a89eb545ba..2af8de15b5c 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/resolver/MapDataResolverFactory.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/resolver/MapDataResolverFactory.java @@ -7,21 +7,20 @@ */ package com.alibaba.dubbo.governance.web.common.resolver; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.citrus.service.dataresolver.DataResolver; import com.alibaba.citrus.service.dataresolver.DataResolverContext; import com.alibaba.citrus.service.dataresolver.DataResolverFactory; import com.alibaba.citrus.turbine.TurbineRunDataInternal; import com.alibaba.citrus.turbine.util.TurbineUtil; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.servlet.http.HttpServletRequest; +import java.util.Map; + /** * MapDataResolverFactory - * + * * @author william.liangf */ public class MapDataResolverFactory implements DataResolverFactory { @@ -35,12 +34,12 @@ public DataResolver getDataResolver(DataResolverContext context) { } return null; } - + public class MapDataResolver implements DataResolver { - + public final DataResolverContext context; - public MapDataResolver(DataResolverContext context){ + public MapDataResolver(DataResolverContext context) { this.context = context; } @@ -50,5 +49,5 @@ public Object resolve() { } } - + } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/resolver/ParameterMap.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/resolver/ParameterMap.java index dbb066ba736..373adb93d40 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/resolver/ParameterMap.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/resolver/ParameterMap.java @@ -7,37 +7,36 @@ */ package com.alibaba.dubbo.governance.web.common.resolver; +import com.alibaba.citrus.turbine.Context; +import com.alibaba.citrus.turbine.TurbineRunDataInternal; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; import java.util.Collection; import java.util.Enumeration; import java.util.HashSet; import java.util.Map; import java.util.Set; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; - -import com.alibaba.citrus.turbine.Context; -import com.alibaba.citrus.turbine.TurbineRunDataInternal; - /** * ParameterMap - * + * * @author william.liangf */ public class ParameterMap implements Map { - + private static final String CONTEXT_PREFIX = "context."; private static final String PARAMETER_PREFIX = "parameter."; private static final String HEADER_PREFIX = "header."; - + private static final String REQUEST_PREFIX = "request."; - + private static final String SESSION_PREFIX = "session."; - + private static final String COOKIE_PREFIX = "cookie."; - + private static final String APPLICATION_PREFIX = "application."; private static final String RUNDATA_PREFIX = "rundata."; @@ -47,7 +46,7 @@ public class ParameterMap implements Map { private static final String REMOTE_HOST_KEY = REQUEST_PREFIX + "remoteHost"; private static final String CONTEXT_PATH_KEY = REQUEST_PREFIX + "contextPath"; - + private static final String USER_PRINCIPAL_KEY = REQUEST_PREFIX + "userPrincipal"; private static final String TARGET_KEY = RUNDATA_PREFIX + "target"; @@ -65,13 +64,13 @@ public class ParameterMap implements Map { private static final String LAYOUT_ENABLED_KEY = RUNDATA_PREFIX + "layoutEnabled"; private final HttpServletRequest request; - + private final Context context; - + private final TurbineRunDataInternal rundata; @SuppressWarnings("unchecked") - public ParameterMap(HttpServletRequest request, Context context, TurbineRunDataInternal navigator){ + public ParameterMap(HttpServletRequest request, Context context, TurbineRunDataInternal navigator) { super(); this.request = request; this.context = context; @@ -174,18 +173,18 @@ public Object get(Object key) { return value; } } - + private Object getParameterValue(String key) { String[] values = request.getParameterValues(key); if (values == null || values.length == 0) { return null; } else if (values.length == 1) { return values[0]; - } else { + } else { return values; } } - + private Object getCookieValue(String key) { Cookie[] cookies = request.getCookies(); if (cookies != null && cookies.length > 0) { @@ -327,14 +326,14 @@ public Set> entrySet() { } return entries; } - + private class ParameterEntry implements Entry { private final String key; - + private volatile Object value; - public ParameterEntry(String key){ + public ParameterEntry(String key) { this.key = key; this.value = ParameterMap.this.get(key); } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/utils/RelateUserUtils.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/utils/RelateUserUtils.java index 86ab30e871d..88510093630 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/utils/RelateUserUtils.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/utils/RelateUserUtils.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.server-2.0.0-SNAPSHOT - * + *

* File Created at Jan 24, 2011 * $Id: RelateUserUtils.java 181723 2012-06-26 01:56:06Z tony.chenl $ - * + *

* Copyright 1999-2100 Alibaba.com Corporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,19 +15,19 @@ */ package com.alibaba.dubbo.governance.web.common.utils; -import java.util.List; -import java.util.Set; - import com.alibaba.dubbo.governance.service.OwnerService; import com.alibaba.dubbo.registry.common.route.ParseUtils; +import java.util.List; +import java.util.Set; + /** * @author ding.lid */ public class RelateUserUtils { /** * 添加与服务相关的Owner - * + * * @param usernames 用于添加的用户名 * @param serviceName 不含通配符 */ @@ -44,12 +44,12 @@ public static void addOwnersOfService(Set usernames, String serviceName, /** * 添加与服务模式相关的Owner - * + * * @param usernames 用于添加的用户名 * @param serviceNamePattern 服务模式,Glob模式 */ public static void addOwnersOfServicePattern(Set usernames, String serviceNamePattern, - OwnerService ownerDAO) { + OwnerService ownerDAO) { List serviceNamePatterns = ownerDAO.findAllServiceNames(); for (String p : serviceNamePatterns) { if (ParseUtils.hasIntersection(p, serviceNamePattern)) { diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Accesses.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Accesses.java index 09de89fe0e9..24e364d809e 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Accesses.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Accesses.java @@ -7,6 +7,17 @@ */ package com.alibaba.dubbo.governance.web.governance.module.screen; +import com.alibaba.dubbo.governance.service.ProviderService; +import com.alibaba.dubbo.governance.service.RouteService; +import com.alibaba.dubbo.governance.web.common.module.screen.Restful; +import com.alibaba.dubbo.registry.common.domain.Access; +import com.alibaba.dubbo.registry.common.domain.Route; +import com.alibaba.dubbo.registry.common.route.RouteRule; +import com.alibaba.dubbo.registry.common.route.RouteRule.MatchPair; +import com.alibaba.dubbo.registry.common.util.Tool; + +import org.springframework.beans.factory.annotation.Autowired; + import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; @@ -20,31 +31,22 @@ import java.util.Set; import java.util.regex.Pattern; -import org.springframework.beans.factory.annotation.Autowired; - -import com.alibaba.dubbo.governance.service.ProviderService; -import com.alibaba.dubbo.governance.service.RouteService; -import com.alibaba.dubbo.governance.web.common.module.screen.Restful; -import com.alibaba.dubbo.registry.common.domain.Access; -import com.alibaba.dubbo.registry.common.domain.Route; -import com.alibaba.dubbo.registry.common.route.RouteRule; -import com.alibaba.dubbo.registry.common.route.RouteRule.MatchPair; -import com.alibaba.dubbo.registry.common.util.Tool; - /** * Providers. URI: /services/$service/accesses - * + * * @author william.liangf * @author ding.lid * @author tony.chenl */ public class Accesses extends Restful { + private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3}$"); + private static final Pattern LOCAL_IP_PATTERN = Pattern.compile("127(\\.\\d{1,3}){3}$"); + private static final Pattern ALL_IP_PATTERN = Pattern.compile("0{1,3}(\\.0{1,3}){3}$"); @Autowired - private RouteService routeService; - + private RouteService routeService; @Autowired - private ProviderService providerService; + private ProviderService providerService; public void index(Map context) throws Exception { String service = (String) context.get("service"); @@ -59,28 +61,28 @@ public void index(Map context) throws Exception { routes = routeService.findAllForceRoute(); } List accesses = new ArrayList(); - if(routes == null){ + if (routes == null) { context.put("accesses", accesses); return; } - for(Route route :routes){ + for (Route route : routes) { Map rule = RouteRule.parseRule(route.getMatchRule()); MatchPair pair = rule.get("consumer.host"); - if(pair != null){ - for(String host : pair.getMatches()){ + if (pair != null) { + for (String host : pair.getMatches()) { Access access = new Access(); access.setAddress(host); access.setService(route.getService()); access.setAllow(false); accesses.add(access); } - for(String host : pair.getUnmatches()){ + for (String host : pair.getUnmatches()) { Access access = new Access(); access.setAddress(host); access.setService(route.getService()); access.setAllow(true); accesses.add(access); - } + } } } context.put("accesses", accesses); @@ -91,71 +93,66 @@ public void add(Map context) { context.put("serviceList", serviceList); } - private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3}$"); - - private static final Pattern LOCAL_IP_PATTERN = Pattern.compile("127(\\.\\d{1,3}){3}$"); - private static final Pattern ALL_IP_PATTERN = Pattern.compile("0{1,3}(\\.0{1,3}){3}$"); - public boolean create(Map context) throws Exception { String addr = (String) context.get("consumerAddress"); - String services = (String) context.get("service"); + String services = (String) context.get("service"); Set consumerAddresses = toAddr(addr); Set aimServices = toService(services); - for(String aimService : aimServices) { + for (String aimService : aimServices) { boolean isFirst = false; List routes = routeService.findForceRouteByService(aimService); Route route = null; - if(routes==null||routes.size()==0){ + if (routes == null || routes.size() == 0) { isFirst = true; - route = new Route(); + route = new Route(); route.setService(aimService); route.setForce(true); - route.setName(aimService+" blackwhitelist"); + route.setName(aimService + " blackwhitelist"); route.setFilterRule("false"); route.setEnabled(true); - }else{ + } else { route = routes.get(0); } Map when = null; MatchPair matchPair = null; - if(isFirst){ + if (isFirst) { when = new HashMap(); - matchPair = new MatchPair(new HashSet(),new HashSet()); + matchPair = new MatchPair(new HashSet(), new HashSet()); when.put("consumer.host", matchPair); - }else{ + } else { when = RouteRule.parseRule(route.getMatchRule()); matchPair = when.get("consumer.host"); } for (String consumerAddress : consumerAddresses) { - if(Boolean.valueOf((String) context.get("allow"))){ + if (Boolean.valueOf((String) context.get("allow"))) { matchPair.getUnmatches().add(Tool.getIP(consumerAddress)); - - }else{ + + } else { matchPair.getMatches().add(Tool.getIP(consumerAddress)); } } StringBuilder sb = new StringBuilder(); - RouteRule.contidionToString(sb,when); + RouteRule.contidionToString(sb, when); route.setMatchRule(sb.toString()); route.setUsername(operator); - if(isFirst){ + if (isFirst) { routeService.createRoute(route); - }else{ + } else { routeService.updateRoute(route); } - + } return true; } - - private Set toAddr(String addr) throws IOException{ + + private Set toAddr(String addr) throws IOException { Set consumerAddresses = new HashSet(); BufferedReader reader = new BufferedReader(new StringReader(addr)); while (true) { String line = reader.readLine(); if (null == line) break; - + String[] split = line.split("[\\s,;]+"); for (String s : split) { if (s.length() == 0) @@ -172,15 +169,15 @@ private Set toAddr(String addr) throws IOException{ } return consumerAddresses; } - - private Set toService(String services) throws IOException{ - Set aimServices = new HashSet(); + + private Set toService(String services) throws IOException { + Set aimServices = new HashSet(); BufferedReader reader = new BufferedReader(new StringReader(services)); while (true) { String line = reader.readLine(); if (null == line) break; - + String[] split = line.split("[\\s,;]+"); for (String s : split) { if (s.length() == 0) @@ -193,63 +190,64 @@ private Set toService(String services) throws IOException{ /** * 删除动作 - * @throws ParseException + * + * @throws ParseException */ public boolean delete(Map context) throws ParseException { String accesses = (String) context.get("accesses"); String[] temp = accesses.split(" "); - Map> prepareToDeleate = new HashMap>(); - for(String s : temp){ - String service = s.split("=")[0]; + Map> prepareToDeleate = new HashMap>(); + for (String s : temp) { + String service = s.split("=")[0]; String address = s.split("=")[1]; Set addresses = prepareToDeleate.get(service); - if(addresses == null){ - prepareToDeleate.put(service, new HashSet()); - addresses = prepareToDeleate.get(service); + if (addresses == null) { + prepareToDeleate.put(service, new HashSet()); + addresses = prepareToDeleate.get(service); } addresses.add(address); } - for(Entry> entry : prepareToDeleate.entrySet()){ - + for (Entry> entry : prepareToDeleate.entrySet()) { + String service = entry.getKey(); List routes = routeService.findForceRouteByService(service); - if(routes == null || routes.size() == 0){ + if (routes == null || routes.size() == 0) { continue; } - for(Route blackwhitelist : routes){ + for (Route blackwhitelist : routes) { MatchPair pairs = RouteRule.parseRule(blackwhitelist.getMatchRule()).get("consumer.host"); Set matches = new HashSet(); matches.addAll(pairs.getMatches()); Set unmatches = new HashSet(); unmatches.addAll(pairs.getUnmatches()); - for(String pair : pairs.getMatches()){ - for(String address : entry.getValue()){ - if(pair.equals(address)){ + for (String pair : pairs.getMatches()) { + for (String address : entry.getValue()) { + if (pair.equals(address)) { matches.remove(pair); break; } - } + } } - for(String pair : pairs.getUnmatches()){ - for(String address : entry.getValue()){ - if(pair.equals(address)){ - unmatches.remove(pair); - break; - } - } + for (String pair : pairs.getUnmatches()) { + for (String address : entry.getValue()) { + if (pair.equals(address)) { + unmatches.remove(pair); + break; + } + } } - if(matches.size()==0 && unmatches.size()==0){ + if (matches.size() == 0 && unmatches.size() == 0) { routeService.deleteRoute(blackwhitelist.getId()); - }else{ + } else { Map condition = new HashMap(); - condition.put("consumer.host", new MatchPair(matches,unmatches)); + condition.put("consumer.host", new MatchPair(matches, unmatches)); StringBuilder sb = new StringBuilder(); - RouteRule.contidionToString(sb,condition); + RouteRule.contidionToString(sb, condition); blackwhitelist.setMatchRule(sb.toString()); routeService.updateRoute(blackwhitelist); } } - + } return true; } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Addresses.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Addresses.java index 224be5995b2..a482bcfd4e6 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Addresses.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Addresses.java @@ -7,30 +7,30 @@ */ package com.alibaba.dubbo.governance.web.governance.module.screen; +import com.alibaba.dubbo.common.utils.StringUtils; +import com.alibaba.dubbo.governance.service.ConsumerService; +import com.alibaba.dubbo.governance.service.ProviderService; +import com.alibaba.dubbo.governance.web.common.module.screen.Restful; + +import org.springframework.beans.factory.annotation.Autowired; + import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; -import org.springframework.beans.factory.annotation.Autowired; - -import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.governance.service.ConsumerService; -import com.alibaba.dubbo.governance.service.ProviderService; -import com.alibaba.dubbo.governance.web.common.module.screen.Restful; - /** * Providers. * URI: /services/$service/providers - * + * * @author william.liangf */ public class Addresses extends Restful { - + @Autowired private ProviderService providerService; - + @Autowired private ConsumerService consumerService; @@ -39,19 +39,18 @@ public void index(Map context) { String service = (String) context.get("service"); List providerAddresses = null; List consumerAddresses = null; - + if (application != null && application.length() > 0) { providerAddresses = providerService.findAddressesByApplication(application); consumerAddresses = consumerService.findAddressesByApplication(application); } else if (service != null && service.length() > 0) { providerAddresses = providerService.findAddressesByService(service); consumerAddresses = consumerService.findAddressesByService(service); - } - else { + } else { providerAddresses = providerService.findAddresses(); consumerAddresses = consumerService.findAddresses(); } - + Set addresses = new TreeSet(); if (providerAddresses != null) { addresses.addAll(providerAddresses); @@ -62,17 +61,17 @@ public void index(Map context) { context.put("providerAddresses", providerAddresses); context.put("consumerAddresses", consumerAddresses); context.put("addresses", addresses); - + if (context.get("service") == null && context.get("application") == null && context.get("address") == null) { context.put("address", "*"); } - + String keyword = (String) context.get("keyword"); if (StringUtils.isNotEmpty(keyword)) { - if("*".equals(keyword)) return; - + if ("*".equals(keyword)) return; + keyword = keyword.toLowerCase(); Set newList = new HashSet(); Set newProviders = new HashSet(); @@ -101,15 +100,15 @@ public void index(Map context) { public void search(Map context) { index(context); - + Set newList = new HashSet(); @SuppressWarnings("unchecked") - Set list = (Set)context.get("addresses"); + Set list = (Set) context.get("addresses"); String keyword = (String) context.get("keyword"); - if(StringUtils.isNotEmpty(keyword)){ + if (StringUtils.isNotEmpty(keyword)) { keyword = keyword.toLowerCase(); - for(String o : list){ - if(o.toLowerCase().indexOf(keyword)!=-1){ + for (String o : list) { + if (o.toLowerCase().indexOf(keyword) != -1) { newList.add(o); } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Applications.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Applications.java index 9cf219c8212..93094e41337 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Applications.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Applications.java @@ -7,17 +7,6 @@ */ package com.alibaba.dubbo.governance.web.governance.module.screen; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; - -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.governance.service.ConsumerService; @@ -27,27 +16,38 @@ import com.alibaba.dubbo.registry.common.domain.Override; import com.alibaba.dubbo.registry.common.route.OverrideUtils; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + /** * Providers. * URI: /applications - * + * * @author william.liangf */ public class Applications extends Restful { - + @Autowired private ProviderService providerService; - + @Autowired private ConsumerService consumerService; @Autowired private OverrideService overrideService; - + public void index(Map context) { - String service = (String) context.get("service"); - if (context.get("service") != null) { - Set applications = new TreeSet(); + String service = (String) context.get("service"); + if (context.get("service") != null) { + Set applications = new TreeSet(); List providerApplications = providerService.findApplicationsByServiceName(service); if (providerApplications != null && providerApplications.size() > 0) { applications.addAll(providerApplications); @@ -57,19 +57,19 @@ public void index(Map context) { applications.addAll(consumerApplications); } context.put("applications", applications); - context.put("providerApplications", providerApplications); + context.put("providerApplications", providerApplications); context.put("consumerApplications", consumerApplications); if (service != null && service.length() > 0) { - List overrides = overrideService.findByService(service); - Map> application2Overrides = new HashMap>(); - if (overrides != null && overrides.size() > 0 + List overrides = overrideService.findByService(service); + Map> application2Overrides = new HashMap>(); + if (overrides != null && overrides.size() > 0 && applications != null && applications.size() > 0) { for (String a : applications) { if (overrides != null && overrides.size() > 0) { - List appOverrides = new ArrayList(); + List appOverrides = new ArrayList(); for (Override override : overrides) { if (override.isMatch(service, null, a)) { - appOverrides.add(override); + appOverrides.add(override); } } Collections.sort(appOverrides, OverrideUtils.OVERRIDE_COMPARATOR); @@ -77,10 +77,10 @@ public void index(Map context) { } } } - context.put("overrides", application2Overrides); + context.put("overrides", application2Overrides); } - return; - } + return; + } if (context.get("service") == null && context.get("application") == null && context.get("address") == null) { @@ -95,17 +95,17 @@ public void index(Map context) { if (consumerApplications != null && consumerApplications.size() > 0) { applications.addAll(consumerApplications); } - + Set newList = new HashSet(); Set newProviders = new HashSet(); Set newConsumers = new HashSet(); context.put("applications", applications); context.put("providerApplications", providerApplications); context.put("consumerApplications", consumerApplications); - + String keyword = (String) context.get("keyword"); - if (StringUtils.isNotEmpty(keyword) && ! "*".equals(keyword)) { - keyword = keyword.toLowerCase(); + if (StringUtils.isNotEmpty(keyword) && !"*".equals(keyword)) { + keyword = keyword.toLowerCase(); for (String o : applications) { if (o.toLowerCase().indexOf(keyword) != -1) { newList.add(o); @@ -126,18 +126,18 @@ public void index(Map context) { context.put("consumerApplications", newConsumers); } } - + public void search(Map context) { index(context); - + Set newList = new HashSet(); @SuppressWarnings("unchecked") - Set apps = (Set)context.get("applications"); + Set apps = (Set) context.get("applications"); String keyword = (String) context.get("keyword"); - if(StringUtils.isNotEmpty(keyword)){ + if (StringUtils.isNotEmpty(keyword)) { keyword = keyword.toLowerCase(); - for(String o : apps){ - if(o.toLowerCase().indexOf(keyword)!=-1){ + for (String o : apps) { + if (o.toLowerCase().indexOf(keyword) != -1) { newList.add(o); } } @@ -146,110 +146,110 @@ public void search(Map context) { } public boolean shield(Map context) throws Exception { - return mock(context, "force:return null"); + return mock(context, "force:return null"); } public boolean tolerant(Map context) throws Exception { - return mock(context, "fail:return null"); + return mock(context, "fail:return null"); } public boolean recover(Map context) throws Exception { - return mock(context, ""); + return mock(context, ""); } private boolean mock(Map context, String mock) throws Exception { - String service = (String) context.get("service"); - String applications = (String) context.get("application"); + String service = (String) context.get("service"); + String applications = (String) context.get("application"); if (service == null || service.length() == 0 - || applications == null || applications.length() == 0){ + || applications == null || applications.length() == 0) { context.put("message", getMessage("NoSuchOperationData")); return false; } - if (! super.currentUser.hasServicePrivilege(service)) { + if (!super.currentUser.hasServicePrivilege(service)) { context.put("message", getMessage("HaveNoServicePrivilege", service)); return false; } for (String application : SPACE_SPLIT_PATTERN.split(applications)) { - List overrides = overrideService.findByServiceAndApplication(service, application); - if (overrides != null && overrides.size() > 0) { - for (Override override: overrides) { - Map map = StringUtils.parseQueryString(override.getParams()); - if (mock == null || mock.length() == 0) { - map.remove("mock"); - } else { - map.put("mock", URL.encode(mock)); - } - if (map.size() > 0) { - override.setParams(StringUtils.toQueryString(map)); - override.setEnabled(true); - override.setOperator(operator); - override.setOperatorAddress(operatorAddress); - overrideService.updateOverride(override); - } else { - overrideService.deleteOverride(override.getId()); - } - } - } else if (mock != null && mock.length() > 0) { - Override override = new Override(); - override.setService(service); - override.setApplication(application); - override.setParams("mock=" + URL.encode(mock)); - override.setEnabled(true); - override.setOperator(operator); - override.setOperatorAddress(operatorAddress); - overrideService.saveOverride(override); - } + List overrides = overrideService.findByServiceAndApplication(service, application); + if (overrides != null && overrides.size() > 0) { + for (Override override : overrides) { + Map map = StringUtils.parseQueryString(override.getParams()); + if (mock == null || mock.length() == 0) { + map.remove("mock"); + } else { + map.put("mock", URL.encode(mock)); + } + if (map.size() > 0) { + override.setParams(StringUtils.toQueryString(map)); + override.setEnabled(true); + override.setOperator(operator); + override.setOperatorAddress(operatorAddress); + overrideService.updateOverride(override); + } else { + overrideService.deleteOverride(override.getId()); + } + } + } else if (mock != null && mock.length() > 0) { + Override override = new Override(); + override.setService(service); + override.setApplication(application); + override.setParams("mock=" + URL.encode(mock)); + override.setEnabled(true); + override.setOperator(operator); + override.setOperatorAddress(operatorAddress); + overrideService.saveOverride(override); + } } return true; } public boolean allshield(Map context) throws Exception { - return allmock(context, "force:return null"); + return allmock(context, "force:return null"); } public boolean alltolerant(Map context) throws Exception { - return allmock(context, "fail:return null"); + return allmock(context, "fail:return null"); } public boolean allrecover(Map context) throws Exception { - return allmock(context, ""); + return allmock(context, ""); } - + private boolean allmock(Map context, String mock) throws Exception { - String service = (String) context.get("service"); + String service = (String) context.get("service"); if (service == null || service.length() == 0) { context.put("message", getMessage("NoSuchOperationData")); return false; } - if (! super.currentUser.hasServicePrivilege(service)) { + if (!super.currentUser.hasServicePrivilege(service)) { context.put("message", getMessage("HaveNoServicePrivilege", service)); return false; } List overrides = overrideService.findByService(service); Override allOverride = null; if (overrides != null && overrides.size() > 0) { - for (Override override: overrides) { - if (override.isDefault()) { - allOverride = override; - break; - } + for (Override override : overrides) { + if (override.isDefault()) { + allOverride = override; + break; + } } } if (allOverride != null) { - Map map = StringUtils.parseQueryString(allOverride.getParams()); + Map map = StringUtils.parseQueryString(allOverride.getParams()); if (mock == null || mock.length() == 0) { map.remove("mock"); } else { map.put("mock", URL.encode(mock)); } if (map.size() > 0) { - allOverride.setParams(StringUtils.toQueryString(map)); - allOverride.setEnabled(true); - allOverride.setOperator(operator); - allOverride.setOperatorAddress(operatorAddress); + allOverride.setParams(StringUtils.toQueryString(map)); + allOverride.setEnabled(true); + allOverride.setOperator(operator); + allOverride.setOperatorAddress(operatorAddress); overrideService.updateOverride(allOverride); } else { - overrideService.deleteOverride(allOverride.getId()); + overrideService.deleteOverride(allOverride.getId()); } } else if (mock != null && mock.length() > 0) { Override override = new Override(); diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Consumers.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Consumers.java index f892e58fce8..c60e42dca5a 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Consumers.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Consumers.java @@ -7,15 +7,6 @@ */ package com.alibaba.dubbo.governance.web.governance.module.screen; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.governance.service.ConsumerService; @@ -33,25 +24,34 @@ import com.alibaba.dubbo.registry.common.route.RouteUtils; import com.alibaba.dubbo.registry.common.util.Tool; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + /** * Consumers. URI: /services/$service/consumers - * + * * @author william.liangf */ public class Consumers extends Restful { @Autowired private ProviderService providerService; - + @Autowired private ConsumerService consumerService; - + @Autowired private OverrideService overrideService; - + @Autowired private RouteService routeService; - + public void index(Map context) throws Exception { String service = (String) context.get("service"); String application = (String) context.get("application"); @@ -59,13 +59,13 @@ public void index(Map context) throws Exception { List consumers; List overrides; List providers = null; - List routes = null; + List routes = null; // service if (service != null && service.length() > 0) { consumers = consumerService.findByService(service); overrides = overrideService.findByService(service); providers = providerService.findByService(service); - routes = routeService.findByService(service); + routes = routeService.findByService(service); } // address else if (address != null && address.length() > 0) { @@ -84,46 +84,46 @@ else if (application != null && application.length() > 0) { } if (consumers != null && consumers.size() > 0) { for (Consumer consumer : consumers) { - if (service == null || service.length() == 0) { - providers = providerService.findByService(consumer.getService()); - routes = routeService.findByService(consumer.getService()); - } + if (service == null || service.length() == 0) { + providers = providerService.findByService(consumer.getService()); + routes = routeService.findByService(consumer.getService()); + } List routed = new ArrayList(); consumer.setProviders(RouteUtils.route(consumer.getService(), consumer.getAddress(), consumer.getParameters(), providers, overrides, routes, null, routed)); - consumer.setRoutes(routed); - OverrideUtils.setConsumerOverrides(consumer, overrides); + consumer.setRoutes(routed); + OverrideUtils.setConsumerOverrides(consumer, overrides); } } context.put("consumers", consumers); } - + public void show(Long id, Map context) { - Consumer consumer = consumerService.findConsumer(id); - List providers = providerService.findByService(consumer.getService()); - List routes = routeService.findByService(consumer.getService()); - List overrides = overrideService.findByService(consumer.getService()); - List routed = new ArrayList(); + Consumer consumer = consumerService.findConsumer(id); + List providers = providerService.findByService(consumer.getService()); + List routes = routeService.findByService(consumer.getService()); + List overrides = overrideService.findByService(consumer.getService()); + List routed = new ArrayList(); consumer.setProviders(RouteUtils.route(consumer.getService(), consumer.getAddress(), consumer.getParameters(), providers, overrides, routes, null, routed)); - consumer.setRoutes(routed); - OverrideUtils.setConsumerOverrides(consumer, overrides); - context.put("consumer", consumer); - context.put("providers", consumer.getProviders()); - context.put("routes", consumer.getRoutes()); - context.put("overrides", consumer.getOverrides()); + consumer.setRoutes(routed); + OverrideUtils.setConsumerOverrides(consumer, overrides); + context.put("consumer", consumer); + context.put("providers", consumer.getProviders()); + context.put("routes", consumer.getRoutes()); + context.put("overrides", consumer.getOverrides()); } - + public void edit(Long id, Map context) { - show(id, context); + show(id, context); } - + public boolean update(Consumer newConsumer, Map context) { - Long id = newConsumer.getId(); - String parameters = newConsumer.getParameters(); - Consumer consumer = consumerService.findConsumer(id); - if (consumer == null) { - context.put("message", getMessage("NoSuchOperationData", id)); - return false; - } + Long id = newConsumer.getId(); + String parameters = newConsumer.getParameters(); + Consumer consumer = consumerService.findConsumer(id); + if (consumer == null) { + context.put("message", getMessage("NoSuchOperationData", id)); + return false; + } String service = consumer.getService(); if (!super.currentUser.hasServicePrivilege(service)) { context.put("message", getMessage("HaveNoServicePrivilege", service)); @@ -132,9 +132,9 @@ public boolean update(Consumer newConsumer, Map context) { Map oldMap = StringUtils.parseQueryString(consumer.getParameters()); Map newMap = StringUtils.parseQueryString(parameters); for (Map.Entry entry : oldMap.entrySet()) { - if (entry.getValue().equals(newMap.get(entry.getKey()))) { - newMap.remove(entry.getKey()); - } + if (entry.getValue().equals(newMap.get(entry.getKey()))) { + newMap.remove(entry.getKey()); + } } String address = consumer.getAddress(); List overrides = overrideService.findByServiceAndAddress(consumer.getService(), consumer.getAddress()); @@ -142,13 +142,13 @@ public boolean update(Consumer newConsumer, Map context) { Override override = consumer.getOverride(); if (override != null) { if (newMap.size() > 0) { - override.setParams(StringUtils.toQueryString(newMap)); + override.setParams(StringUtils.toQueryString(newMap)); override.setEnabled(true); override.setOperator(operator); override.setOperatorAddress(operatorAddress); overrideService.updateOverride(override); } else { - overrideService.deleteOverride(override.getId()); + overrideService.deleteOverride(override.getId()); } } else { override = new Override(); @@ -162,40 +162,40 @@ public boolean update(Consumer newConsumer, Map context) { } return true; } - + public void routed(Long id, Map context) { - show(id, context); + show(id, context); } public void notified(Long id, Map context) { - show(id, context); + show(id, context); } public void overrided(Long id, Map context) { - show(id, context); + show(id, context); } - + public boolean shield(Long[] ids, Map context) throws Exception { - return mock(ids, context, "force:return null"); + return mock(ids, context, "force:return null"); } public boolean tolerant(Long[] ids, Map context) throws Exception { - return mock(ids, context, "fail:return null"); + return mock(ids, context, "fail:return null"); } public boolean recover(Long[] ids, Map context) throws Exception { - return mock(ids, context, ""); + return mock(ids, context, ""); } private boolean mock(Long[] ids, Map context, String mock) throws Exception { - if (ids == null || ids.length == 0){ + if (ids == null || ids.length == 0) { context.put("message", getMessage("NoSuchOperationData")); return false; } List consumers = new ArrayList(); for (Long id : ids) { Consumer c = consumerService.findConsumer(id); - if(c != null){ + if (c != null) { consumers.add(c); if (!super.currentUser.hasServicePrivilege(c.getService())) { context.put("message", getMessage("HaveNoServicePrivilege", c.getService())); @@ -203,12 +203,12 @@ private boolean mock(Long[] ids, Map context, String mock) throw } } } - for(Consumer consumer : consumers) { + for (Consumer consumer : consumers) { String service = consumer.getService(); String address = Tool.getIP(consumer.getAddress()); List overrides = overrideService.findByServiceAndAddress(service, address); if (overrides != null && overrides.size() > 0) { - for (Override override: overrides) { + for (Override override : overrides) { Map map = StringUtils.parseQueryString(override.getParams()); if (mock == null || mock.length() == 0) { map.remove("mock"); @@ -216,13 +216,13 @@ private boolean mock(Long[] ids, Map context, String mock) throw map.put("mock", URL.encode(mock)); } if (map.size() > 0) { - override.setParams(StringUtils.toQueryString(map)); + override.setParams(StringUtils.toQueryString(map)); override.setEnabled(true); override.setOperator(operator); override.setOperatorAddress(operatorAddress); overrideService.updateOverride(override); } else { - overrideService.deleteOverride(override.getId()); + overrideService.deleteOverride(override.getId()); } } } else if (mock != null && mock.length() > 0) { @@ -240,52 +240,52 @@ private boolean mock(Long[] ids, Map context, String mock) throw } public boolean allshield(Map context) throws Exception { - return allmock(context, "force:return null"); + return allmock(context, "force:return null"); } public boolean alltolerant(Map context) throws Exception { - return allmock(context, "fail:return null"); + return allmock(context, "fail:return null"); } public boolean allrecover(Map context) throws Exception { - return allmock(context, ""); + return allmock(context, ""); } - + private boolean allmock(Map context, String mock) throws Exception { - String service = (String) context.get("service"); + String service = (String) context.get("service"); if (service == null || service.length() == 0) { context.put("message", getMessage("NoSuchOperationData")); return false; } - if (! super.currentUser.hasServicePrivilege(service)) { + if (!super.currentUser.hasServicePrivilege(service)) { context.put("message", getMessage("HaveNoServicePrivilege", service)); return false; } List overrides = overrideService.findByService(service); Override allOverride = null; if (overrides != null && overrides.size() > 0) { - for (Override override: overrides) { - if (override.isDefault()) { - allOverride = override; - break; - } + for (Override override : overrides) { + if (override.isDefault()) { + allOverride = override; + break; + } } } if (allOverride != null) { - Map map = StringUtils.parseQueryString(allOverride.getParams()); + Map map = StringUtils.parseQueryString(allOverride.getParams()); if (mock == null || mock.length() == 0) { map.remove("mock"); } else { map.put("mock", URL.encode(mock)); } if (map.size() > 0) { - allOverride.setParams(StringUtils.toQueryString(map)); - allOverride.setEnabled(true); - allOverride.setOperator(operator); - allOverride.setOperatorAddress(operatorAddress); + allOverride.setParams(StringUtils.toQueryString(map)); + allOverride.setEnabled(true); + allOverride.setOperator(operator); + allOverride.setOperatorAddress(operatorAddress); overrideService.updateOverride(allOverride); } else { - overrideService.deleteOverride(allOverride.getId()); + overrideService.deleteOverride(allOverride.getId()); } } else if (mock != null && mock.length() > 0) { Override override = new Override(); @@ -300,30 +300,30 @@ private boolean allmock(Map context, String mock) throws Excepti } public boolean allow(Long[] ids, Map context) throws Exception { - return access(ids, context, true, false); + return access(ids, context, true, false); } - + public boolean forbid(Long[] ids, Map context) throws Exception { - return access(ids, context, false, false); + return access(ids, context, false, false); } public boolean onlyallow(Long[] ids, Map context) throws Exception { - return access(ids, context, true, true); + return access(ids, context, true, true); } public boolean onlyforbid(Long[] ids, Map context) throws Exception { - return access(ids, context, false, true); + return access(ids, context, false, true); } private boolean access(Long[] ids, Map context, boolean allow, boolean only) throws Exception { - if (ids == null || ids.length == 0){ + if (ids == null || ids.length == 0) { context.put("message", getMessage("NoSuchOperationData")); return false; } List consumers = new ArrayList(); for (Long id : ids) { Consumer c = consumerService.findConsumer(id); - if(c != null){ + if (c != null) { consumers.add(c); if (!super.currentUser.hasServicePrivilege(c.getService())) { context.put("message", getMessage("HaveNoServicePrivilege", c.getService())); @@ -332,27 +332,27 @@ private boolean access(Long[] ids, Map context, boolean allow, b } } Map> serviceAddresses = new HashMap>(); - for(Consumer consumer : consumers) { - String service = consumer.getService(); - String address = Tool.getIP(consumer.getAddress()); - Set addresses = serviceAddresses.get(service); - if (addresses == null) { - addresses = new HashSet(); - serviceAddresses.put(service, addresses); - } - addresses.add(address); + for (Consumer consumer : consumers) { + String service = consumer.getService(); + String address = Tool.getIP(consumer.getAddress()); + Set addresses = serviceAddresses.get(service); + if (addresses == null) { + addresses = new HashSet(); + serviceAddresses.put(service, addresses); + } + addresses.add(address); } - for(Map.Entry> entry : serviceAddresses.entrySet()) { + for (Map.Entry> entry : serviceAddresses.entrySet()) { String service = entry.getKey(); boolean isFirst = false; List routes = routeService.findForceRouteByService(service); Route route = null; - if(routes == null || routes.size() == 0){ + if (routes == null || routes.size() == 0) { isFirst = true; - route = new Route(); + route = new Route(); route.setService(service); route.setForce(true); - route.setName(service+" blackwhitelist"); + route.setName(service + " blackwhitelist"); route.setFilterRule("false"); route.setEnabled(true); } else { @@ -360,53 +360,53 @@ private boolean access(Long[] ids, Map context, boolean allow, b } Map when = null; MatchPair matchPair = null; - if(isFirst){ + if (isFirst) { when = new HashMap(); - matchPair = new MatchPair(new HashSet(),new HashSet()); + matchPair = new MatchPair(new HashSet(), new HashSet()); when.put("consumer.host", matchPair); - }else{ + } else { when = RouteRule.parseRule(route.getMatchRule()); matchPair = when.get("consumer.host"); } if (only) { - matchPair.getUnmatches().clear(); - matchPair.getMatches().clear(); - if (allow) { - matchPair.getUnmatches().addAll(entry.getValue()); - } else { - matchPair.getMatches().addAll(entry.getValue()); - } + matchPair.getUnmatches().clear(); + matchPair.getMatches().clear(); + if (allow) { + matchPair.getUnmatches().addAll(entry.getValue()); + } else { + matchPair.getMatches().addAll(entry.getValue()); + } } else { - for (String consumerAddress : entry.getValue()) { - if(matchPair.getUnmatches().size() > 0) { // 白名单优先 - matchPair.getMatches().remove(consumerAddress); // 去掉黑名单中相同数据 - if (allow) { // 如果允许访问 - matchPair.getUnmatches().add(consumerAddress); // 加入白名单 - } else { // 如果禁止访问 - matchPair.getUnmatches().remove(consumerAddress); // 从白名单中去除 - } + for (String consumerAddress : entry.getValue()) { + if (matchPair.getUnmatches().size() > 0) { // 白名单优先 + matchPair.getMatches().remove(consumerAddress); // 去掉黑名单中相同数据 + if (allow) { // 如果允许访问 + matchPair.getUnmatches().add(consumerAddress); // 加入白名单 + } else { // 如果禁止访问 + matchPair.getUnmatches().remove(consumerAddress); // 从白名单中去除 + } } else { // 黑名单生效 - if (allow) { // 如果允许访问 - matchPair.getMatches().remove(consumerAddress); // 从黑名单中去除 - } else { // 如果禁止访问 - matchPair.getMatches().add(consumerAddress); // 加入黑名单 - } + if (allow) { // 如果允许访问 + matchPair.getMatches().remove(consumerAddress); // 从黑名单中去除 + } else { // 如果禁止访问 + matchPair.getMatches().add(consumerAddress); // 加入黑名单 + } } } } StringBuilder sb = new StringBuilder(); - RouteRule.contidionToString(sb,when); + RouteRule.contidionToString(sb, when); route.setMatchRule(sb.toString()); route.setUsername(operator); if (matchPair.getMatches().size() > 0 || matchPair.getUnmatches().size() > 0) { - if(isFirst) { - routeService.createRoute(route); + if (isFirst) { + routeService.createRoute(route); } else { - routeService.updateRoute(route); + routeService.updateRoute(route); } - } else if (! isFirst) { - routeService.deleteRoute(route.getId()); - } + } else if (!isFirst) { + routeService.deleteRoute(route.getId()); + } } return true; } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Loadbalances.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Loadbalances.java index eb339da399f..5fc57ac8dc7 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Loadbalances.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Loadbalances.java @@ -7,13 +7,6 @@ */ package com.alibaba.dubbo.governance.web.governance.module.screen; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.dubbo.common.utils.CollectionUtils; import com.alibaba.dubbo.governance.service.OverrideService; import com.alibaba.dubbo.governance.service.ProviderService; @@ -23,27 +16,34 @@ import com.alibaba.dubbo.registry.common.util.OverrideUtils; import com.alibaba.dubbo.registry.common.util.Tool; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + /** * Providers. * URI: /services/$service/loadbalances - * + * * @author william.liangf */ public class Loadbalances extends Restful { - + @Autowired private OverrideService overrideService; - + @Autowired private ProviderService providerService; public void index(Map context) { final String service = StringUtils.trimToNull((String) context.get("service")); - + List loadbalances; if (service != null && service.length() > 0) { loadbalances = OverrideUtils.overridesToLoadBalances(overrideService.findByService(service)); - + loadbalances = OverrideUtils.overridesToLoadBalances(overrideService.findByService(service)); } else { loadbalances = OverrideUtils.overridesToLoadBalances(overrideService.findAll()); @@ -52,16 +52,16 @@ public void index(Map context) { } public void show(Long id, Map context) { - LoadBalance loadbalance = OverrideUtils.overrideToLoadBalance(overrideService.findById(id)); + LoadBalance loadbalance = OverrideUtils.overrideToLoadBalance(overrideService.findById(id)); context.put("loadbalance", loadbalance); } - + public void add(Map context) { - String service = (String)context.get("service"); + String service = (String) context.get("service"); if (service != null && service.length() > 0 && !service.contains("*")) { List providerList = providerService.findByService(service); List addressList = new ArrayList(); - for(Provider provider : providerList){ + for (Provider provider : providerList) { addressList.add(provider.getUrl().split("://")[1].split("/")[0]); } context.put("addressList", addressList); @@ -71,37 +71,38 @@ public void add(Map context) { List serviceList = Tool.sortSimpleName(providerService.findServices()); context.put("serviceList", serviceList); } - if(context.get("input") != null) context.put("input", context.get("input")); + if (context.get("input") != null) context.put("input", context.get("input")); } public void edit(Long id, Map context) { - add(context); - show(id, context); + add(context); + show(id, context); } - + public boolean create(LoadBalance loadBalance, Map context) { if (!super.currentUser.hasServicePrivilege(loadBalance.getService())) { context.put("message", getMessage("HaveNoServicePrivilege", loadBalance.getService())); return false; } - - loadBalance.setUsername((String)context.get("operator")); - overrideService.saveOverride(OverrideUtils.loadBalanceToOverride(loadBalance)); + + loadBalance.setUsername((String) context.get("operator")); + overrideService.saveOverride(OverrideUtils.loadBalanceToOverride(loadBalance)); return true; } - + public boolean update(LoadBalance loadBalance, Map context) { if (!super.currentUser.hasServicePrivilege(loadBalance.getService())) { context.put("message", getMessage("HaveNoServicePrivilege", loadBalance.getService())); return false; } - overrideService.updateOverride(OverrideUtils.loadBalanceToOverride(loadBalance)); + overrideService.updateOverride(OverrideUtils.loadBalanceToOverride(loadBalance)); return true; } /** * 删除动作 + * * @param ids * @return */ @@ -113,9 +114,9 @@ public boolean delete(Long[] ids, Map context) { return false; } } - + for (Long id : ids) { - overrideService.deleteOverride(id); + overrideService.deleteOverride(id); } return true; } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/NoServicePrivilege.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/NoServicePrivilege.java index 355ed34fa12..103578baa21 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/NoServicePrivilege.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/NoServicePrivilege.java @@ -1,31 +1,31 @@ /** - * Function: - * + * Function: + *

* File Created at 2010-11-17 * $Id: NoServicePrivilege.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 2009 Alibaba.com Croporation Limited. * All rights reserved. */ package com.alibaba.dubbo.governance.web.governance.module.screen; -import javax.servlet.http.HttpServletRequest; +import com.alibaba.citrus.turbine.Context; import org.springframework.beans.factory.annotation.Autowired; -import com.alibaba.citrus.turbine.Context; +import javax.servlet.http.HttpServletRequest; /** * TODO Comment of NoServicePrivilege - * + * * @author guanghui.shigh */ public class NoServicePrivilege { @Autowired private HttpServletRequest request; - + public void execute(Context context) { - context.put("returnUrl", request.getParameter("returnUrl")); + context.put("returnUrl", request.getParameter("returnUrl")); } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Overrides.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Overrides.java index 491037257a6..d4465c622dd 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Overrides.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Overrides.java @@ -15,17 +15,6 @@ */ package com.alibaba.dubbo.governance.web.governance.module.screen; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.utils.CollectionUtils; import com.alibaba.dubbo.common.utils.StringUtils; @@ -35,19 +24,59 @@ import com.alibaba.dubbo.governance.web.common.module.screen.Restful; import com.alibaba.dubbo.registry.common.domain.Override; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + /** * @author ding.lid */ -public class Overrides extends Restful { +public class Overrides extends Restful { + static final Pattern AND = Pattern.compile("\\&"); + static final Pattern EQUAL = Pattern.compile("([^=\\s]*)\\s*=\\s*(\\S*)"); + static final String DEFAULT_MOCK_JSON_KEY = "mock"; + static final String MOCK_JSON_KEY_POSTFIX = ".mock"; + static final String FORM_OVERRIDE_KEY = "overrideKey"; + static final String FORM_OVERRIDE_VALUE = "overrideValue"; + static final String FORM_DEFAULT_MOCK_METHOD_FORCE = "mockDefaultMethodForce"; + static final String FORM_DEFAULT_MOCK_METHOD_JSON = "mockDefaultMethodJson"; + static final String FORM_ORIGINAL_METHOD_FORCE_PREFIX = "mockMethodForce."; + static final String FORM_ORIGINAL_METHOD_PREFIX = "mockMethod."; + static final String FORM_DYNAMIC_METHOD_NAME_PREFIX = "mockMethodName"; + static final String FORM_DYNAMIC_METHOD_FORCE_PREFIX = "mockMethodForce"; + static final String FORM_DYNAMIC_METHOD_JSON_PREFIX = "mockMethodJson"; @Autowired private OverrideService overrideService; - + + // FORM KEY @Autowired private ProviderService providerService; - @Autowired private ConsumerService consumerService; - + + static Map parseQueryString(String query) { + HashMap ret = new HashMap(); + if (query == null || (query = query.trim()).length() == 0) return ret; + + String[] kvs = AND.split(query); + for (String kv : kvs) { + Matcher matcher = EQUAL.matcher(kv); + if (!matcher.matches()) continue; + String key = matcher.group(1); + String value = matcher.group(2); + ret.put(key, value); + } + + return ret; + } + public void index(Map context) { String service = (String) context.get("service"); String application = (String) context.get("application"); @@ -55,12 +84,11 @@ public void index(Map context) { List overrides; if (StringUtils.isNotEmpty(service)) { overrides = overrideService.findByService(service); - } else if(StringUtils.isNotEmpty(application)){ + } else if (StringUtils.isNotEmpty(application)) { overrides = overrideService.findByApplication(application); - }else if(StringUtils.isNotEmpty(address)){ + } else if (StringUtils.isNotEmpty(address)) { overrides = overrideService.findByAddress(address); - } - else{ + } else { overrides = overrideService.findAll(); } context.put("overrides", overrides); @@ -68,129 +96,110 @@ public void index(Map context) { public void show(Long id, Map context) { Override override = overrideService.findById(id); - + Map parameters = parseQueryString(override.getParams()); - if(parameters.get(DEFAULT_MOCK_JSON_KEY) != null) { + if (parameters.get(DEFAULT_MOCK_JSON_KEY) != null) { String mock = URL.decode(parameters.get(DEFAULT_MOCK_JSON_KEY)); String[] tokens = parseMock(mock); context.put(FORM_DEFAULT_MOCK_METHOD_FORCE, tokens[0]); context.put(FORM_DEFAULT_MOCK_METHOD_JSON, tokens[1]); parameters.remove(DEFAULT_MOCK_JSON_KEY); } - + Map method2Force = new LinkedHashMap(); Map method2Json = new LinkedHashMap(); - - for (Iterator> iterator = parameters.entrySet().iterator(); iterator.hasNext();) { - Map.Entry e = iterator.next(); + + for (Iterator> iterator = parameters.entrySet().iterator(); iterator.hasNext(); ) { + Map.Entry e = iterator.next(); String key = e.getKey(); - - if(key.endsWith(MOCK_JSON_KEY_POSTFIX)) { + + if (key.endsWith(MOCK_JSON_KEY_POSTFIX)) { String m = key.substring(0, key.length() - MOCK_JSON_KEY_POSTFIX.length()); parseMock(m, e.getValue(), method2Force, method2Json); iterator.remove(); } } - + context.put("methodForces", method2Force); context.put("methodJsons", method2Json); context.put("parameters", parameters); context.put("override", override); } - - public void add(Map context){ + + public void add(Map context) { List serviceList = new ArrayList(); List applicationList = new ArrayList(); String service = (String) context.get("service"); String application = (String) context.get("application"); - if(StringUtils.isNotEmpty(application)){ + if (StringUtils.isNotEmpty(application)) { serviceList.addAll(providerService.findServicesByApplication(application)); serviceList.addAll(consumerService.findServicesByApplication(application)); context.put("serviceList", serviceList); - }else if(StringUtils.isNotEmpty(service)){ + } else if (StringUtils.isNotEmpty(service)) { applicationList.addAll(providerService.findApplicationsByServiceName(service)); applicationList.addAll(consumerService.findApplicationsByServiceName(service)); context.put("applicationList", applicationList); - }else{ + } else { serviceList.addAll(providerService.findServices()); serviceList.addAll(consumerService.findServices()); providerService.findServicesByApplication(application); consumerService.findServicesByApplication(application); } context.put("serviceList", serviceList); - + if (StringUtils.isNotEmpty(service) && !service.contains("*")) { context.put("methods", CollectionUtils.sort(new ArrayList(providerService.findMethodsByService(service)))); } } - static final Pattern AND = Pattern.compile("\\&"); - static final Pattern EQUAL = Pattern.compile("([^=\\s]*)\\s*=\\s*(\\S*)"); - - static Map parseQueryString(String query) { - HashMap ret = new HashMap(); - if(query == null || (query = query.trim()).length() == 0) return ret; - - String[] kvs = AND.split(query); - for(String kv : kvs) { - Matcher matcher = EQUAL.matcher(kv); - if(!matcher.matches()) continue; - String key = matcher.group(1); - String value = matcher.group(2); - ret.put(key, value); - } - - return ret; - } - - public void edit(Long id, Map context) { + public void edit(Long id, Map context) { Override override = overrideService.findById(id); - + Map parameters = parseQueryString(override.getParams()); - - if(parameters.get(DEFAULT_MOCK_JSON_KEY)!=null){ + + if (parameters.get(DEFAULT_MOCK_JSON_KEY) != null) { String mock = URL.decode(parameters.get(DEFAULT_MOCK_JSON_KEY)); String[] tokens = parseMock(mock); context.put(FORM_DEFAULT_MOCK_METHOD_FORCE, tokens[0]); context.put(FORM_DEFAULT_MOCK_METHOD_JSON, tokens[1]); parameters.remove(DEFAULT_MOCK_JSON_KEY); } - + Map method2Force = new LinkedHashMap(); Map method2Json = new LinkedHashMap(); - + List methods = CollectionUtils.sort(new ArrayList(providerService.findMethodsByService(override.getService()))); - if(methods != null && methods.isEmpty()) { - for(String m : methods) { + if (methods != null && methods.isEmpty()) { + for (String m : methods) { parseMock(m, parameters.get(m + MOCK_JSON_KEY_POSTFIX), method2Force, method2Json); parameters.remove(m + MOCK_JSON_KEY_POSTFIX); } } - for (Iterator> iterator = parameters.entrySet().iterator(); iterator.hasNext();) { - Map.Entry e = iterator.next(); + for (Iterator> iterator = parameters.entrySet().iterator(); iterator.hasNext(); ) { + Map.Entry e = iterator.next(); String key = e.getKey(); - - if(key.endsWith(MOCK_JSON_KEY_POSTFIX)) { + + if (key.endsWith(MOCK_JSON_KEY_POSTFIX)) { String m = key.substring(0, key.length() - MOCK_JSON_KEY_POSTFIX.length()); parseMock(m, e.getValue(), method2Force, method2Json); iterator.remove(); } } - + context.put("methods", methods); context.put("methodForces", method2Force); context.put("methodJsons", method2Json); context.put("parameters", parameters); context.put("override", override); } - + private void parseMock(String m, String mock, Map method2Force, Map method2Json) { String[] tokens = parseMock(mock); method2Force.put(m, tokens[0]); method2Json.put(m, tokens[1]); } - + private String[] parseMock(String mock) { mock = URL.decode(mock); String force; @@ -208,28 +217,10 @@ private String[] parseMock(String mock) { tokens[1] = mock; return tokens; } - - static final String DEFAULT_MOCK_JSON_KEY = "mock"; - static final String MOCK_JSON_KEY_POSTFIX = ".mock"; - - // FORM KEY - - static final String FORM_OVERRIDE_KEY = "overrideKey"; - static final String FORM_OVERRIDE_VALUE = "overrideValue"; - - static final String FORM_DEFAULT_MOCK_METHOD_FORCE = "mockDefaultMethodForce"; - static final String FORM_DEFAULT_MOCK_METHOD_JSON = "mockDefaultMethodJson"; - - static final String FORM_ORIGINAL_METHOD_FORCE_PREFIX = "mockMethodForce."; - static final String FORM_ORIGINAL_METHOD_PREFIX = "mockMethod."; - - static final String FORM_DYNAMIC_METHOD_NAME_PREFIX = "mockMethodName"; - static final String FORM_DYNAMIC_METHOD_FORCE_PREFIX = "mockMethodForce"; - static final String FORM_DYNAMIC_METHOD_JSON_PREFIX = "mockMethodJson"; - + boolean catchParams(Override override, Map context) { String service = (String) context.get("service"); - if(service == null || service.trim().length() == 0) { + if (service == null || service.trim().length() == 0) { context.put("message", getMessage("service is blank!")); return false; } @@ -237,90 +228,90 @@ boolean catchParams(Override override, Map context) { context.put("message", getMessage("HaveNoServicePrivilege", service)); return false; } - + String defaultMockMethodForce = (String) context.get(FORM_DEFAULT_MOCK_METHOD_FORCE); String defaultMockMethodJson = (String) context.get(FORM_DEFAULT_MOCK_METHOD_JSON); - + Map override2Value = new HashMap(); Map method2Json = new HashMap(); - - for(Map.Entry param : context.entrySet()) { + + for (Map.Entry param : context.entrySet()) { String key = param.getKey().trim(); - if(! (param.getValue() instanceof String) ) continue; - + if (!(param.getValue() instanceof String)) continue; + String value = (String) param.getValue(); - - if(key.startsWith(FORM_OVERRIDE_KEY) && value != null && value.trim().length() > 0) { + + if (key.startsWith(FORM_OVERRIDE_KEY) && value != null && value.trim().length() > 0) { String index = key.substring(FORM_OVERRIDE_KEY.length()); String overrideValue = (String) context.get(FORM_OVERRIDE_VALUE + index); - if(overrideValue != null && overrideValue.trim().length() > 0) { + if (overrideValue != null && overrideValue.trim().length() > 0) { override2Value.put(value.trim(), overrideValue.trim()); } } - - if(key.startsWith(FORM_ORIGINAL_METHOD_PREFIX) && value != null && value.trim().length() > 0) { + + if (key.startsWith(FORM_ORIGINAL_METHOD_PREFIX) && value != null && value.trim().length() > 0) { String method = key.substring(FORM_ORIGINAL_METHOD_PREFIX.length()); String force = (String) context.get(FORM_ORIGINAL_METHOD_FORCE_PREFIX + method); method2Json.put(method, force + ":" + value.trim()); } - - if(key.startsWith(FORM_DYNAMIC_METHOD_NAME_PREFIX) && value != null && value.trim().length() > 0) { + + if (key.startsWith(FORM_DYNAMIC_METHOD_NAME_PREFIX) && value != null && value.trim().length() > 0) { String index = key.substring(FORM_DYNAMIC_METHOD_NAME_PREFIX.length()); String force = (String) context.get(FORM_DYNAMIC_METHOD_FORCE_PREFIX + index); String json = (String) context.get(FORM_DYNAMIC_METHOD_JSON_PREFIX + index); - - if(json != null && json.trim().length() > 0) { + + if (json != null && json.trim().length() > 0) { method2Json.put(value.trim(), force + ":" + json.trim()); } } } - + StringBuilder paramters = new StringBuilder(); boolean isFirst = true; - if(defaultMockMethodJson != null && defaultMockMethodJson.trim().length() > 0) { + if (defaultMockMethodJson != null && defaultMockMethodJson.trim().length() > 0) { paramters.append("mock=").append(URL.encode(defaultMockMethodForce + ":" + defaultMockMethodJson.trim())); isFirst = false; } - for(Map.Entry e : method2Json.entrySet()) { - if(isFirst) isFirst = false; + for (Map.Entry e : method2Json.entrySet()) { + if (isFirst) isFirst = false; else paramters.append("&"); - + paramters.append(e.getKey()).append(MOCK_JSON_KEY_POSTFIX).append("=").append(URL.encode(e.getValue())); } - for(Map.Entry e : override2Value.entrySet()) { - if(isFirst) isFirst = false; + for (Map.Entry e : override2Value.entrySet()) { + if (isFirst) isFirst = false; else paramters.append("&"); - + paramters.append(e.getKey()).append("=").append(URL.encode(e.getValue())); } - + String p = paramters.toString(); - if(p.trim().length() == 0) { + if (p.trim().length() == 0) { context.put("message", getMessage("Please enter Parameters!")); return false; } - + override.setParams(p); return true; } - + public boolean create(Override override, Map context) { - if(!catchParams(override, context)) return false; - + if (!catchParams(override, context)) return false; + overrideService.saveOverride(override); return true; } - - public boolean update(Override override,Map context) { + + public boolean update(Override override, Map context) { Override o = overrideService.findById(override.getId()); override.setService(o.getService()); override.setAddress(o.getAddress()); override.setApplication(o.getApplication()); - - if(!catchParams(override, context)) return false; - + + if (!catchParams(override, context)) return false; + overrideService.updateOverride(override); - + return true; } @@ -328,51 +319,49 @@ public boolean delete(Long[] ids, Map context) { for (Long id : ids) { overrideService.deleteOverride(id); } - + return true; } public boolean enable(Long[] ids, Map context) { - for(Long id : ids){ + for (Long id : ids) { Override override = overrideService.findById(id); - if(override == null){ + if (override == null) { context.put("message", getMessage("NoSuchOperationData", id)); return false; - } - else{ + } else { if (!super.currentUser.hasServicePrivilege(override.getService())) { - context.put("message", getMessage("HaveNoServicePrivilege", override.getService())); - return false; - } + context.put("message", getMessage("HaveNoServicePrivilege", override.getService())); + return false; + } } - } - + } + for (Long id : ids) { overrideService.enableOverride(id); } - + return true; } - + public boolean disable(Long[] ids, Map context) { - for(Long id : ids){ + for (Long id : ids) { Override override = overrideService.findById(id); - if(override == null){ + if (override == null) { context.put("message", getMessage("NoSuchOperationData", id)); return false; - } - else{ + } else { if (!super.currentUser.hasServicePrivilege(override.getService())) { - context.put("message", getMessage("HaveNoServicePrivilege", override.getService())); - return false; - } + context.put("message", getMessage("HaveNoServicePrivilege", override.getService())); + return false; + } } - } - + } + for (Long id : ids) { overrideService.disableOverride(id); } - + return true; } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Owners.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Owners.java index cedad8fea82..d62bb0d4e9e 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Owners.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Owners.java @@ -7,83 +7,83 @@ */ package com.alibaba.dubbo.governance.web.governance.module.screen; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.dubbo.governance.service.OwnerService; import com.alibaba.dubbo.governance.service.ProviderService; import com.alibaba.dubbo.governance.web.common.module.screen.Restful; import com.alibaba.dubbo.registry.common.domain.Owner; import com.alibaba.dubbo.registry.common.util.Tool; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + /** * Providers. URI: /services/$service/owners - * + * * @author william.liangf */ public class Owners extends Restful { - @Autowired - private OwnerService ownerService; + @Autowired + private OwnerService ownerService; + + @Autowired + private ProviderService providerService; + + public void index(Map context) { + String service = (String) context.get("service"); + List owners; + if (service != null && service.length() > 0) { + owners = ownerService.findByService(service); + } else { + owners = ownerService.findAll(); + } + context.put("owners", owners); + } - @Autowired - private ProviderService providerService; - - public void index(Map context) { - String service = (String) context.get("service"); - List owners; - if (service != null && service.length() > 0) { - owners = ownerService.findByService(service); - } else { - owners = ownerService.findAll(); - } - context.put("owners", owners); - } - - public void add(Map context) { - String service = (String) context.get("service"); - if (service == null || service.length() == 0) { + public void add(Map context) { + String service = (String) context.get("service"); + if (service == null || service.length() == 0) { List serviceList = Tool.sortSimpleName(new ArrayList(providerService.findServices())); context.put("serviceList", serviceList); } - } + } - public boolean create(Owner owner, Map context) { - String service = owner.getService(); - String username = owner.getUsername(); - if (service == null || service.length() == 0 - || username == null || username.length() == 0){ + public boolean create(Owner owner, Map context) { + String service = owner.getService(); + String username = owner.getUsername(); + if (service == null || service.length() == 0 + || username == null || username.length() == 0) { context.put("message", getMessage("NoSuchOperationData")); return false; } - if (! super.currentUser.hasServicePrivilege(service)) { + if (!super.currentUser.hasServicePrivilege(service)) { context.put("message", getMessage("HaveNoServicePrivilege", service)); return false; } - ownerService.saveOwner(owner); - return true; - } + ownerService.saveOwner(owner); + return true; + } - public boolean delete(Long[] ids, Map context) { - String service = (String) context.get("service"); - String username = (String) context.get("username"); - Owner owner = new Owner(); - owner.setService(service); - owner.setUsername(username); - if (service == null || service.length() == 0 - || username == null || username.length() == 0){ + public boolean delete(Long[] ids, Map context) { + String service = (String) context.get("service"); + String username = (String) context.get("username"); + Owner owner = new Owner(); + owner.setService(service); + owner.setUsername(username); + if (service == null || service.length() == 0 + || username == null || username.length() == 0) { context.put("message", getMessage("NoSuchOperationData")); return false; } - if (! super.currentUser.hasServicePrivilege(service)) { + if (!super.currentUser.hasServicePrivilege(service)) { context.put("message", getMessage("HaveNoServicePrivilege", service)); return false; } - ownerService.deleteOwner(owner); - return true; - } + ownerService.deleteOwner(owner); + return true; + } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Providers.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Providers.java index 74afeb424d8..e368ecc2197 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Providers.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Providers.java @@ -7,17 +7,6 @@ */ package com.alibaba.dubbo.governance.web.governance.module.screen; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.governance.service.OverrideService; import com.alibaba.dubbo.governance.service.ProviderService; @@ -27,6 +16,16 @@ import com.alibaba.dubbo.registry.common.route.OverrideUtils; import com.alibaba.dubbo.registry.common.util.Tool; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + /** *

Providers.

* URI:
@@ -57,7 +56,7 @@ * GET /services/$service/providers/$id/disable 禁用
* GET /services/$service/providers/$id/reconnect 重连
* GET /services/$service/providers/$id/recover 恢复
- * + * * @author william.liangf */ public class Providers extends Restful { @@ -67,121 +66,123 @@ public class Providers extends Restful { @Autowired private OverrideService overrideService; - + @Autowired private HttpServletResponse response; - + @Autowired private HttpServletRequest request; - + public void index(Provider provider, Map context) { String service = (String) context.get("service"); String application = (String) context.get("application"); - String address = (String)context.get("address"); - + String address = (String) context.get("address"); + String value = ""; String separators = "...."; - + List providers = null; - + // service if (service != null && service.length() > 0) { providers = providerService.findByService(service); - + value = service + separators + request.getRequestURI(); } // address else if (address != null && address.length() > 0) { providers = providerService.findByAddress(address); - + value = address + separators + request.getRequestURI(); - } + } // application else if (application != null && application.length() > 0) { providers = providerService.findByApplication(application); - + value = application + separators + request.getRequestURI(); } // all else { providers = providerService.findAll(); } - + context.put("providers", providers); - + // 设置搜索结果到cookie中 setSearchHistroy(context, value); } - + /** * 设置search记录到cookie中,操作步骤: * 检查加入的记录是否已经存在cookie中,如果存在,则更新列表次序;如果不存在,则插入到最前面 + * * @param context * @param value */ private void setSearchHistroy(Map context, String value) { - //分析已有的cookie - String separatorsB = "\\.\\.\\.\\.\\.\\."; + //分析已有的cookie + String separatorsB = "\\.\\.\\.\\.\\.\\."; String newCookiev = value; Cookie[] cookies = request.getCookies(); - for(Cookie c:cookies){ - if(c.getName().equals("HISTORY")){ - String cookiev = c.getValue(); - String[] values = cookiev.split(separatorsB); - int count = 1; - for(String v : values){ - if(count<=10){ - if(!value.equals(v)){ - newCookiev = newCookiev + separatorsB + v; - } - } - count ++; - } - break; - } - } - - Cookie _cookie=new Cookie("HISTORY", newCookiev); - _cookie.setMaxAge(60*60*24*7); // 设置Cookie的存活时间为30分钟 - _cookie.setPath("/"); + for (Cookie c : cookies) { + if (c.getName().equals("HISTORY")) { + String cookiev = c.getValue(); + String[] values = cookiev.split(separatorsB); + int count = 1; + for (String v : values) { + if (count <= 10) { + if (!value.equals(v)) { + newCookiev = newCookiev + separatorsB + v; + } + } + count++; + } + break; + } + } + + Cookie _cookie = new Cookie("HISTORY", newCookiev); + _cookie.setMaxAge(60 * 60 * 24 * 7); // 设置Cookie的存活时间为30分钟 + _cookie.setPath("/"); response.addCookie(_cookie); // 写入客户端硬盘 - } + } - public void show(Long id, Map context) { + public void show(Long id, Map context) { Provider provider = providerService.findProvider(id); if (provider != null && provider.isDynamic()) { - List overrides = overrideService.findByServiceAndAddress(provider.getService(), provider.getAddress()); - OverrideUtils.setProviderOverrides(provider, overrides); + List overrides = overrideService.findByServiceAndAddress(provider.getService(), provider.getAddress()); + OverrideUtils.setProviderOverrides(provider, overrides); } context.put("provider", provider); } - + /** * 装载新增服务页面,获取所有的服务名称 + * * @param context */ public void add(Long id, Map context) { - if (context.get("service") == null) { - List serviceList = Tool.sortSimpleName(new ArrayList(providerService.findServices())); - context.put("serviceList", serviceList); - } - if (id != null) { - Provider p = providerService.findProvider(id); - if (p != null) { - context.put("provider", p); - String parameters = p.getParameters(); - if (parameters != null && parameters.length() > 0) { - Map map = StringUtils.parseQueryString(parameters); - map.put("timestamp", String.valueOf(System.currentTimeMillis())); - map.remove("pid"); - p.setParameters(StringUtils.toQueryString(map)); - } - } - } + if (context.get("service") == null) { + List serviceList = Tool.sortSimpleName(new ArrayList(providerService.findServices())); + context.put("serviceList", serviceList); + } + if (id != null) { + Provider p = providerService.findProvider(id); + if (p != null) { + context.put("provider", p); + String parameters = p.getParameters(); + if (parameters != null && parameters.length() > 0) { + Map map = StringUtils.parseQueryString(parameters); + map.put("timestamp", String.valueOf(System.currentTimeMillis())); + map.remove("pid"); + p.setParameters(StringUtils.toQueryString(map)); + } + } + } } public void edit(Long id, Map context) { - show(id, context); + show(id, context); } public boolean create(Provider provider, Map context) { @@ -191,14 +192,14 @@ public boolean create(Provider provider, Map context) { return false; } if (provider.getParameters() == null) { - String url = provider.getUrl(); - if (url != null) { - int i = url.indexOf('?'); - if (i > 0) { - provider.setUrl(url.substring(0, i)); - provider.setParameters(url.substring(i + 1)); - } - } + String url = provider.getUrl(); + if (url != null) { + int i = url.indexOf('?'); + if (i > 0) { + provider.setUrl(url.substring(0, i)); + provider.setParameters(url.substring(i + 1)); + } + } } provider.setDynamic(false); // 页面上添加的一定是静态的Provider providerService.create(provider); @@ -206,13 +207,13 @@ public boolean create(Provider provider, Map context) { } public boolean update(Provider newProvider, Map context) { - Long id = newProvider.getId(); - String parameters = newProvider.getParameters(); - Provider provider = providerService.findProvider(id); - if (provider == null) { - context.put("message", getMessage("NoSuchOperationData", id)); - return false; - } + Long id = newProvider.getId(); + String parameters = newProvider.getParameters(); + Provider provider = providerService.findProvider(id); + if (provider == null) { + context.put("message", getMessage("NoSuchOperationData", id)); + return false; + } String service = provider.getService(); if (!super.currentUser.hasServicePrivilege(service)) { context.put("message", getMessage("HaveNoServicePrivilege", service)); @@ -221,24 +222,24 @@ public boolean update(Provider newProvider, Map context) { Map oldMap = StringUtils.parseQueryString(provider.getParameters()); Map newMap = StringUtils.parseQueryString(parameters); for (Map.Entry entry : oldMap.entrySet()) { - if (entry.getValue().equals(newMap.get(entry.getKey()))) { - newMap.remove(entry.getKey()); - } + if (entry.getValue().equals(newMap.get(entry.getKey()))) { + newMap.remove(entry.getKey()); + } } - if (provider.isDynamic()) { + if (provider.isDynamic()) { String address = provider.getAddress(); List overrides = overrideService.findByServiceAndAddress(provider.getService(), provider.getAddress()); - OverrideUtils.setProviderOverrides(provider, overrides); - Override override = provider.getOverride(); + OverrideUtils.setProviderOverrides(provider, overrides); + Override override = provider.getOverride(); if (override != null) { if (newMap.size() > 0) { - override.setParams(StringUtils.toQueryString(newMap)); + override.setParams(StringUtils.toQueryString(newMap)); override.setEnabled(true); override.setOperator(operator); override.setOperatorAddress(operatorAddress); overrideService.updateOverride(override); } else { - overrideService.deleteOverride(override.getId()); + overrideService.deleteOverride(override.getId()); } } else { override = new Override(); @@ -250,101 +251,101 @@ public boolean update(Provider newProvider, Map context) { override.setOperatorAddress(operatorAddress); overrideService.saveOverride(override); } - } else { - provider.setParameters(parameters); - providerService.updateProvider(provider); - } + } else { + provider.setParameters(parameters); + providerService.updateProvider(provider); + } return true; } public boolean delete(Long[] ids, Map context) { - for (Long id : ids) { - Provider provider = providerService.findProvider(id); - if (provider == null) { - context.put("message", getMessage("NoSuchOperationData", id)); - return false; - } else if (provider.isDynamic()) { - context.put("message", getMessage("CanNotDeleteDynamicData", id)); - return false; - } else if (! super.currentUser.hasServicePrivilege(provider.getService())) { - context.put( "message", getMessage("HaveNoServicePrivilege", provider.getService())); - return false; - } - } - for (Long id : ids) { - providerService.deleteStaticProvider(id); - } - return true; + for (Long id : ids) { + Provider provider = providerService.findProvider(id); + if (provider == null) { + context.put("message", getMessage("NoSuchOperationData", id)); + return false; + } else if (provider.isDynamic()) { + context.put("message", getMessage("CanNotDeleteDynamicData", id)); + return false; + } else if (!super.currentUser.hasServicePrivilege(provider.getService())) { + context.put("message", getMessage("HaveNoServicePrivilege", provider.getService())); + return false; + } + } + for (Long id : ids) { + providerService.deleteStaticProvider(id); + } + return true; } - + public boolean enable(Long[] ids, Map context) { - Map id2Provider = new HashMap(); - for (Long id : ids) { - Provider provider = providerService.findProvider(id); - if (provider == null) { - context.put("message", getMessage("NoSuchOperationData", id)); - return false; - } else if (! super.currentUser.hasServicePrivilege(provider.getService())) { - context.put("message", getMessage("HaveNoServicePrivilege", provider.getService())); - return false; - } - id2Provider.put(id, provider); - } - for (Long id : ids) { - providerService.enableProvider(id); - } - return true; + Map id2Provider = new HashMap(); + for (Long id : ids) { + Provider provider = providerService.findProvider(id); + if (provider == null) { + context.put("message", getMessage("NoSuchOperationData", id)); + return false; + } else if (!super.currentUser.hasServicePrivilege(provider.getService())) { + context.put("message", getMessage("HaveNoServicePrivilege", provider.getService())); + return false; + } + id2Provider.put(id, provider); + } + for (Long id : ids) { + providerService.enableProvider(id); + } + return true; } - + public boolean disable(Long[] ids, Map context) { - for (Long id : ids) { - Provider provider = providerService.findProvider(id); - if (provider == null) { - context.put("message", getMessage("NoSuchOperationData", id)); - return false; - } else if (! super.currentUser.hasServicePrivilege(provider.getService())) { - context.put("message", getMessage("HaveNoServicePrivilege", provider.getService())); - return false; - } - } - for (Long id : ids) { - providerService.disableProvider(id); - } - return true; + for (Long id : ids) { + Provider provider = providerService.findProvider(id); + if (provider == null) { + context.put("message", getMessage("NoSuchOperationData", id)); + return false; + } else if (!super.currentUser.hasServicePrivilege(provider.getService())) { + context.put("message", getMessage("HaveNoServicePrivilege", provider.getService())); + return false; + } + } + for (Long id : ids) { + providerService.disableProvider(id); + } + return true; } - + public boolean doubling(Long[] ids, Map context) { - for (Long id : ids) { - Provider provider = providerService.findProvider(id); - if (provider == null) { - context.put("message", getMessage("NoSuchOperationData", id)); - return false; - } else if (! super.currentUser.hasServicePrivilege(provider.getService())) { - context.put("message", getMessage("HaveNoServicePrivilege", provider.getService())); - return false; - } - } - for (Long id : ids) { - providerService.doublingProvider(id); - } - return true; + for (Long id : ids) { + Provider provider = providerService.findProvider(id); + if (provider == null) { + context.put("message", getMessage("NoSuchOperationData", id)); + return false; + } else if (!super.currentUser.hasServicePrivilege(provider.getService())) { + context.put("message", getMessage("HaveNoServicePrivilege", provider.getService())); + return false; + } + } + for (Long id : ids) { + providerService.doublingProvider(id); + } + return true; } - + public boolean halving(Long[] ids, Map context) { - for (Long id : ids) { - Provider provider = providerService.findProvider(id); - if (provider == null) { - context.put("message", getMessage("NoSuchOperationData", id)); - return false; - } else if (! super.currentUser.hasServicePrivilege(provider.getService())) { - context.put("message", getMessage("HaveNoServicePrivilege", provider.getService())); - return false; - } - } - for (Long id : ids) { - providerService.halvingProvider(id); - } - return true; + for (Long id : ids) { + Provider provider = providerService.findProvider(id); + if (provider == null) { + context.put("message", getMessage("NoSuchOperationData", id)); + return false; + } else if (!super.currentUser.hasServicePrivilege(provider.getService())) { + context.put("message", getMessage("HaveNoServicePrivilege", provider.getService())); + return false; + } + } + for (Long id : ids) { + providerService.halvingProvider(id); + } + return true; } - + } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Routes.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Routes.java index 79bb4c6d620..76b1c738dc5 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Routes.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Routes.java @@ -7,16 +7,6 @@ */ package com.alibaba.dubbo.governance.web.governance.module.screen; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.dubbo.common.utils.CollectionUtils; import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.governance.service.ConsumerService; @@ -32,48 +22,102 @@ import com.alibaba.dubbo.registry.common.route.RouteUtils; import com.alibaba.dubbo.registry.common.util.Tool; +import org.springframework.beans.factory.annotation.Autowired; + +import java.text.ParseException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + /** * Providers. * URI: /services/$service/routes - * + * * @author ding.lid * @author william.liangf * @author tony.chenl */ public class Routes extends Restful { - - private static final int MAX_RULE_LENGTH = 1000; - + + private static final int MAX_RULE_LENGTH = 1000; + static String[][] when_names = { + {"method", "method", "unmethod"}, + {"consumer.application", "consumerApplication", "unconsumerApplication"}, + {"consumer.cluster", "consumerCluster", "unconsumerCluster"}, + {"consumer.host", "consumerHost", "unconsumerHost"}, + {"consumer.version", "consumerVersion", "unconsumerVersion"}, + {"consumer.group", "consumerGroup", "unconsumerGroup"}, + }; + static String[][] then_names = { + {"provider.application", "providerApplication", "unproviderApplication"}, + {"provider.cluster", "providerCluster", "unproviderCluster"}, // 要校验Cluster是否存在 + {"provider.host", "providerHost", "unproviderHost"}, + {"provider.protocol", "providerProtocol", "unproviderProtocol"}, + {"provider.port", "providerPort", "unproviderPort"}, + {"provider.version", "providerVersion", "unproviderVersion"}, + {"provider.group", "providerGroup", "unproviderGroup"} + }; @Autowired private RouteService routeService; - @Autowired private ProviderService providerService; - @Autowired private ConsumerService consumerService; - - static String[][] when_names = { - {"method", "method", "unmethod"}, - {"consumer.application", "consumerApplication", "unconsumerApplication"}, - {"consumer.cluster", "consumerCluster", "unconsumerCluster"}, - {"consumer.host", "consumerHost", "unconsumerHost"}, - {"consumer.version", "consumerVersion", "unconsumerVersion"}, - {"consumer.group", "consumerGroup", "unconsumerGroup"}, - }; - static String[][] then_names = { - {"provider.application", "providerApplication", "unproviderApplication"}, - {"provider.cluster", "providerCluster", "unproviderCluster"}, // 要校验Cluster是否存在 - {"provider.host", "providerHost", "unproviderHost"}, - {"provider.protocol", "providerProtocol", "unproviderProtocol"}, - {"provider.port", "providerPort", "unproviderPort"}, - {"provider.version", "providerVersion", "unproviderVersion"}, - {"provider.group", "providerGroup", "unproviderGroup"} - }; + static void checkService(String service) { + if (service.contains(",")) throw new IllegalStateException("service(" + service + ") contain illegale ','"); + + String interfaceName = service; + int gi = interfaceName.indexOf("/"); + if (gi != -1) interfaceName = interfaceName.substring(gi + 1); + int vi = interfaceName.indexOf(':'); + if (vi != -1) interfaceName = interfaceName.substring(0, vi); + + if (interfaceName.indexOf('*') != -1 && interfaceName.indexOf('*') != interfaceName.length() - 1) { + throw new IllegalStateException("service(" + service + ") only allow 1 *, and must be last char!"); + } + } + + /** + * 添加与服务相关的Owner + * + * @param usernames 用于添加的用户名 + * @param serviceName 不含通配符 + */ + public static void addOwnersOfService(Set usernames, String serviceName, + OwnerService ownerDAO) { + List serviceNamePatterns = ownerDAO.findAllServiceNames(); + for (String p : serviceNamePatterns) { + if (ParseUtils.isMatchGlobPattern(p, serviceName)) { + List list = ownerDAO.findUsernamesByServiceName(p); + usernames.addAll(list); + } + } + } + + /** + * 添加与服务模式相关的Owner + * + * @param usernames 用于添加的用户名 + * @param serviceNamePattern 服务模式,Glob模式 + */ + public static void addOwnersOfServicePattern(Set usernames, String serviceNamePattern, + OwnerService ownerDAO) { + List serviceNamePatterns = ownerDAO.findAllServiceNames(); + for (String p : serviceNamePatterns) { + if (ParseUtils.hasIntersection(p, serviceNamePattern)) { + List list = ownerDAO.findUsernamesByServiceName(p); + usernames.addAll(list); + } + } + } /** * 路由模块首页 + * * @param context */ public void index(Map context) { @@ -82,7 +126,7 @@ public void index(Map context) { address = Tool.getIP(address); List routes; if (service != null && service.length() > 0 - && address != null && address.length() > 0) { + && address != null && address.length() > 0) { routes = routeService.findByServiceAndAddress(service, address); } else if (service != null && service.length() > 0) { routes = routeService.findByService(service); @@ -96,58 +140,60 @@ public void index(Map context) { /** * 显示路由详细信息 + * * @param context */ public void show(Map context) { - try { - Route route = routeService.findRoute(Long.parseLong((String)context.get("id"))); - - if (route == null) { - throw new IllegalArgumentException("The route is not existed."); - } - if(route.getService()!=null && !route.getService().isEmpty()){ - context.put("service", route.getService()); - } - - RouteRule routeRule= RouteRule.parse(route); - - @SuppressWarnings("unchecked") - Map[] paramArray = new Map[] { - routeRule.getWhenCondition(), routeRule.getThenCondition()}; - String[][][] namesArray = new String[][][] {when_names, then_names }; - - for(int i=0; i param = paramArray[i]; - String[][] names = namesArray[i]; - for(String[] name : names) { - RouteRule.MatchPair matchPair = param.get(name[0]); - if(matchPair == null) { - continue; - } - - if(!matchPair.getMatches().isEmpty()) { - String m = RouteRule.join(matchPair.getMatches()); - context.put(name[1], m); - } - if(!matchPair.getUnmatches().isEmpty()) { - String u = RouteRule.join(matchPair.getUnmatches()); - context.put(name[2], u); - } - } - } - context.put("route", route); - context.put("methods", CollectionUtils.sort(new ArrayList(providerService.findMethodsByService(route.getService())))); - } catch (ParseException e) { - e.printStackTrace(); - } + try { + Route route = routeService.findRoute(Long.parseLong((String) context.get("id"))); + + if (route == null) { + throw new IllegalArgumentException("The route is not existed."); + } + if (route.getService() != null && !route.getService().isEmpty()) { + context.put("service", route.getService()); + } + + RouteRule routeRule = RouteRule.parse(route); + + @SuppressWarnings("unchecked") + Map[] paramArray = new Map[]{ + routeRule.getWhenCondition(), routeRule.getThenCondition()}; + String[][][] namesArray = new String[][][]{when_names, then_names}; + + for (int i = 0; i < paramArray.length; ++i) { + Map param = paramArray[i]; + String[][] names = namesArray[i]; + for (String[] name : names) { + RouteRule.MatchPair matchPair = param.get(name[0]); + if (matchPair == null) { + continue; + } + + if (!matchPair.getMatches().isEmpty()) { + String m = RouteRule.join(matchPair.getMatches()); + context.put(name[1], m); + } + if (!matchPair.getUnmatches().isEmpty()) { + String u = RouteRule.join(matchPair.getUnmatches()); + context.put(name[2], u); + } + } + } + context.put("route", route); + context.put("methods", CollectionUtils.sort(new ArrayList(providerService.findMethodsByService(route.getService())))); + } catch (ParseException e) { + e.printStackTrace(); + } } - + /** * 载入新增路由页面 + * * @param context */ public void add(Map context) { - String service = (String)context.get("service"); + String service = (String) context.get("service"); if (service != null && service.length() > 0 && !service.contains("*")) { context.put("service", service); context.put("methods", CollectionUtils.sort(new ArrayList(providerService.findMethodsByService(service)))); @@ -155,64 +201,52 @@ public void add(Map context) { List serviceList = Tool.sortSimpleName(new ArrayList(providerService.findServices())); context.put("serviceList", serviceList); } - - if(context.get("input") != null) context.put("input", context.get("input")); - + + if (context.get("input") != null) context.put("input", context.get("input")); + } /** * 载入修改路由页面 + * * @param context */ public void edit(Map context) { - add(context); - show(context); - } - - static void checkService(String service) { - if(service.contains(",")) throw new IllegalStateException("service(" + service + ") contain illegale ','"); - - String interfaceName = service; - int gi = interfaceName.indexOf("/"); - if(gi != -1) interfaceName = interfaceName.substring(gi + 1); - int vi = interfaceName.indexOf(':'); - if(vi != -1) interfaceName = interfaceName.substring(0, vi); - - if(interfaceName.indexOf('*') != -1 && interfaceName.indexOf('*') != interfaceName.length() -1) { - throw new IllegalStateException("service(" + service + ") only allow 1 *, and must be last char!"); - } + add(context); + show(context); } - + /** * 保存路由信息到数据库中 + * * @param context * @return */ public boolean create(Map context) { - String name = (String)context.get("name"); - String service = (String)context.get("service"); + String name = (String) context.get("name"); + String service = (String) context.get("service"); if (StringUtils.isNotEmpty(service) && StringUtils.isNotEmpty(name)) { checkService(service); - + Map when_name2valueList = new HashMap(); Map notWhen_name2valueList = new HashMap(); - for(String[] names : when_names) { - when_name2valueList.put(names[0], (String)context.get(names[1])); - notWhen_name2valueList.put(names[0], (String)context.get(names[2])); // value不为null的情况,这里处理,后面会保证 + for (String[] names : when_names) { + when_name2valueList.put(names[0], (String) context.get(names[1])); + notWhen_name2valueList.put(names[0], (String) context.get(names[2])); // value不为null的情况,这里处理,后面会保证 } - + Map then_name2valueList = new HashMap(); Map notThen_name2valueList = new HashMap(); - for(String[] names : then_names) { - then_name2valueList.put(names[0], (String)context.get(names[1])); - notThen_name2valueList.put(names[0], (String)context.get(names[2])); + for (String[] names : then_names) { + then_name2valueList.put(names[0], (String) context.get(names[1])); + notThen_name2valueList.put(names[0], (String) context.get(names[2])); } RouteRule routeRule = RouteRule.createFromNameAndValueListString( when_name2valueList, notWhen_name2valueList, then_name2valueList, notThen_name2valueList); - + if (routeRule.getThenCondition().isEmpty()) { context.put("message", getMessage("Add route error! then is empty.")); return false; @@ -220,7 +254,7 @@ public boolean create(Map context) { String matchRule = routeRule.getWhenConditionString(); String filterRule = routeRule.getThenConditionString(); - + //限制表达式的长度 if (matchRule.length() > MAX_RULE_LENGTH) { context.put("message", getMessage("When rule is too long!")); @@ -230,95 +264,96 @@ public boolean create(Map context) { context.put("message", getMessage("Then rule is too long!")); return false; } - + Route route = new Route(); route.setService(service); route.setName(name); - route.setUsername((String)context.get("operator")); - route.setOperator((String)context.get("operatorAddress")); + route.setUsername((String) context.get("operator")); + route.setOperator((String) context.get("operatorAddress")); route.setRule(routeRule.toString()); - if (StringUtils.isNotEmpty((String)context.get("priority"))) { - route.setPriority(Integer.parseInt((String)context.get("priority"))); + if (StringUtils.isNotEmpty((String) context.get("priority"))) { + route.setPriority(Integer.parseInt((String) context.get("priority"))); } routeService.createRoute(route); - + } - + return true; } /** * 保存更新数据到数据库中 + * * @param context * @return */ public boolean update(Map context) { - String idStr = (String)context.get("id"); - if (idStr != null && idStr.length() > 0 ) { - String[] blacks = (String[])context.get("black"); + String idStr = (String) context.get("id"); + if (idStr != null && idStr.length() > 0) { + String[] blacks = (String[]) context.get("black"); boolean black = false; - if(blacks != null && blacks.length > 0){ + if (blacks != null && blacks.length > 0) { black = true; } Route oldRoute = routeService.findRoute(Long.valueOf(idStr)); - if(null == oldRoute) { + if (null == oldRoute) { context.put("message", getMessage("NoSuchRecord")); return false; } //判断参数,拼凑rule - if (StringUtils.isNotEmpty((String)context.get("name"))) { - String service = oldRoute.getService(); + if (StringUtils.isNotEmpty((String) context.get("name"))) { + String service = oldRoute.getService(); if (context.get("operator") == null) { context.put("message", getMessage("HaveNoServicePrivilege", service)); return false; } - + Map when_name2valueList = new HashMap(); Map notWhen_name2valueList = new HashMap(); - for(String[] names : when_names) { - when_name2valueList.put(names[0], (String)context.get(names[1])); - notWhen_name2valueList.put(names[0], (String)context.get(names[2])); // value不为null的情况,这里处理,后面会保证 + for (String[] names : when_names) { + when_name2valueList.put(names[0], (String) context.get(names[1])); + notWhen_name2valueList.put(names[0], (String) context.get(names[2])); // value不为null的情况,这里处理,后面会保证 } Map then_name2valueList = new HashMap(); Map notThen_name2valueList = new HashMap(); - for(String[] names : then_names) { - then_name2valueList.put(names[0], (String)context.get(names[1])); - notThen_name2valueList.put(names[0], (String)context.get(names[2])); + for (String[] names : then_names) { + then_name2valueList.put(names[0], (String) context.get(names[1])); + notThen_name2valueList.put(names[0], (String) context.get(names[2])); } RouteRule routeRule = RouteRule.createFromNameAndValueListString( when_name2valueList, notWhen_name2valueList, then_name2valueList, notThen_name2valueList); - + RouteRule result = null; - if(black){ + if (black) { RouteRule.MatchPair matchPair = routeRule.getThenCondition().get("black"); Map then = null; - if(null == matchPair) { + if (null == matchPair) { matchPair = new RouteRule.MatchPair(); then = new HashMap(); then.put("black", matchPair); - }else{ + } else { matchPair.getMatches().clear(); } matchPair.getMatches().add(String.valueOf(black)); - result = RouteRule.copyWithReplace(routeRule, null, then); + result = RouteRule.copyWithReplace(routeRule, null, then); } - - if(result == null){ + + if (result == null) { result = routeRule; } - + if (result.getThenCondition().isEmpty()) { context.put("message", getMessage("Update route error! then is empty.")); return false; } - + String matchRule = result.getWhenConditionString(); String filterRule = result.getThenConditionString(); - + //限制表达式的长度 if (matchRule.length() > MAX_RULE_LENGTH) { context.put("message", getMessage("When rule is too long!")); @@ -328,120 +363,123 @@ public boolean update(Map context) { context.put("message", getMessage("Then rule is too long!")); return false; } - + int priority = 0; - if (StringUtils.isNotEmpty((String)context.get("priority"))) { - priority = Integer.parseInt((String)context.get("priority")); + if (StringUtils.isNotEmpty((String) context.get("priority"))) { + priority = Integer.parseInt((String) context.get("priority")); } - + Route route = new Route(); route.setRule(result.toString()); route.setService(service); route.setPriority(priority); - route.setName((String)context.get("name")); - route.setUsername((String)context.get("operator")); - route.setOperator((String)context.get("operatorAddress")); + route.setName((String) context.get("name")); + route.setUsername((String) context.get("operator")); + route.setOperator((String) context.get("operatorAddress")); route.setId(Long.valueOf(idStr)); - route.setPriority(Integer.parseInt((String)context.get("priority"))); + route.setPriority(Integer.parseInt((String) context.get("priority"))); route.setEnabled(oldRoute.isEnabled()); routeService.updateRoute(route); - + Set usernames = new HashSet(); - usernames.add((String)context.get("operator")); + usernames.add((String) context.get("operator")); usernames.add(route.getUsername()); //RelateUserUtils.addOwnersOfService(usernames, route.getService(), ownerDAO); - + Map params = new HashMap(); params.put("action", "update"); params.put("route", route); - + } else { context.put("message", getMessage("MissRequestParameters", "name")); } } else { context.put("message", getMessage("MissRequestParameters", "id")); } - + return true; } /** * 删除指定ID的route规则 + * * @param ids * @return */ public boolean delete(Long[] ids, Map context) { - for (Long id : ids) { - routeService.deleteRoute(id); - } - - return true; + for (Long id : ids) { + routeService.deleteRoute(id); + } + + return true; } - + /** * 启用指定ID的route规则(可以批量处理) + * * @param ids * @return */ public boolean enable(Long[] ids, Map context) { - for(Long id : ids){ + for (Long id : ids) { routeService.enableRoute(id); } - + return true; } - + /** * 禁用指定ID的route规则(可以批量处理) + * * @param ids * @return */ public boolean disable(Long[] ids, Map context) { - for(Long id : ids){ + for (Long id : ids) { routeService.disableRoute(id); } - + return true; } - + /** * 选择消费者 + * * @param context */ - public void routeselect(Map context){ - long rid = Long.valueOf((String)context.get("id")); + public void routeselect(Map context) { + long rid = Long.valueOf((String) context.get("id")); context.put("id", rid); - + Route route = routeService.findRoute(rid); if (route == null) { throw new IllegalStateException("Route(id=" + rid + ") is not existed!"); } - + context.put("route", route); // 获取数据 List consumers = consumerService.findByService(route.getService()); context.put("consumers", consumers); - + Map matchRoute = new HashMap(); - for(Consumer c : consumers) { + for (Consumer c : consumers) { matchRoute.put(c.getAddress(), RouteUtils.matchRoute(c.getAddress(), null, route, null)); } context.put("matchRoute", matchRoute); } - - + public void preview(Map context) throws Exception { - String rid = (String)context.get("id"); - String consumerid = (String)context.get("cid"); - - - if(StringUtils.isEmpty(rid)) { + String rid = (String) context.get("id"); + String consumerid = (String) context.get("cid"); + + + if (StringUtils.isEmpty(rid)) { context.put("message", getMessage("MissRequestParameters", "id")); } - + Map serviceUrls = new HashMap(); Route route = routeService.findRoute(Long.valueOf(rid)); - if(null == route) { + if (null == route) { context.put("message", getMessage("NoSuchRecord")); } List providers = providerService.findByService(route.getService()); @@ -450,9 +488,9 @@ public void preview(Map context) throws Exception { serviceUrls.put(p.getUrl(), p.getParameters()); } } - if(StringUtils.isNotEmpty(consumerid)) { + if (StringUtils.isNotEmpty(consumerid)) { Consumer consumer = consumerService.findConsumer(Long.valueOf(consumerid)); - if(null == consumer) { + if (null == consumer) { context.put("message", getMessage("NoSuchRecord")); } Map result = RouteUtils.previewRoute(consumer.getService(), consumer.getAddress(), consumer.getParameters(), serviceUrls, @@ -460,55 +498,20 @@ public void preview(Map context) throws Exception { context.put("route", route); context.put("consumer", consumer); context.put("result", result); - } - else { - String address = (String)context.get("address"); - String service = (String)context.get("service"); - + } else { + String address = (String) context.get("address"); + String service = (String) context.get("service"); + Map result = RouteUtils.previewRoute(service, address, null, serviceUrls, route, null, null); context.put("route", route); - + Consumer consumer = new Consumer(); consumer.setService(service); consumer.setAddress(address); context.put("consumer", consumer); context.put("result", result); } - - } - - /** - * 添加与服务相关的Owner - * - * @param usernames 用于添加的用户名 - * @param serviceName 不含通配符 - */ - public static void addOwnersOfService(Set usernames, String serviceName, - OwnerService ownerDAO) { - List serviceNamePatterns = ownerDAO.findAllServiceNames(); - for (String p : serviceNamePatterns) { - if (ParseUtils.isMatchGlobPattern(p, serviceName)) { - List list = ownerDAO.findUsernamesByServiceName(p); - usernames.addAll(list); - } - } - } - /** - * 添加与服务模式相关的Owner - * - * @param usernames 用于添加的用户名 - * @param serviceNamePattern 服务模式,Glob模式 - */ - public static void addOwnersOfServicePattern(Set usernames, String serviceNamePattern, - OwnerService ownerDAO) { - List serviceNamePatterns = ownerDAO.findAllServiceNames(); - for (String p : serviceNamePatterns) { - if (ParseUtils.hasIntersection(p, serviceNamePattern)) { - List list = ownerDAO.findUsernamesByServiceName(p); - usernames.addAll(list); - } - } } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Services.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Services.java index 6ae56d205af..33198986e32 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Services.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Services.java @@ -7,17 +7,6 @@ */ package com.alibaba.dubbo.governance.web.governance.module.screen; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; - -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.governance.service.ConsumerService; @@ -28,32 +17,43 @@ import com.alibaba.dubbo.registry.common.route.OverrideUtils; import com.alibaba.dubbo.registry.common.util.Tool; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + /** * Providers. URI: /services/$service/providers /addresses/$address/services /application/$application/services - * + * * @author ding.lid */ public class Services extends Restful { @Autowired private ProviderService providerService; - + @Autowired private ConsumerService consumerService; - + @Autowired private OverrideService overrideService; - + public void index(Map context) { String application = (String) context.get("application"); String address = (String) context.get("address"); - + if (context.get("service") == null && context.get("application") == null && context.get("address") == null) { context.put("service", "*"); } - + List providerServices = null; List consumerServices = null; List overrides = null; @@ -70,7 +70,7 @@ public void index(Map context) { consumerServices = consumerService.findServices(); overrides = overrideService.findAll(); } - + Set services = new TreeSet(); if (providerServices != null) { services.addAll(providerServices); @@ -78,16 +78,16 @@ public void index(Map context) { if (consumerServices != null) { services.addAll(consumerServices); } - + Map> service2Overrides = new HashMap>(); - if (overrides != null && overrides.size() > 0 + if (overrides != null && overrides.size() > 0 && services != null && services.size() > 0) { for (String s : services) { if (overrides != null && overrides.size() > 0) { for (Override override : overrides) { - List serOverrides = new ArrayList(); - if (override.isMatch(s, address, application)) { - serOverrides.add(override); + List serOverrides = new ArrayList(); + if (override.isMatch(s, address, application)) { + serOverrides.add(override); } Collections.sort(serOverrides, OverrideUtils.OVERRIDE_COMPARATOR); service2Overrides.put(s, serOverrides); @@ -95,19 +95,19 @@ public void index(Map context) { } } } - + context.put("providerServices", providerServices); context.put("consumerServices", consumerServices); context.put("services", services); context.put("overrides", service2Overrides); - + String keyword = (String) context.get("keyword"); - if (StringUtils.isNotEmpty(keyword) && ! "*".equals(keyword)) { + if (StringUtils.isNotEmpty(keyword) && !"*".equals(keyword)) { keyword = keyword.toLowerCase(); Set newList = new HashSet(); Set newProviders = new HashSet(); Set newConsumers = new HashSet(); - + for (String o : services) { if (o.toLowerCase().toLowerCase().indexOf(keyword) != -1) { newList.add(o); @@ -130,61 +130,61 @@ public void index(Map context) { } public boolean shield(Map context) throws Exception { - return mock(context, "force:return null"); + return mock(context, "force:return null"); } public boolean tolerant(Map context) throws Exception { - return mock(context, "fail:return null"); + return mock(context, "fail:return null"); } public boolean recover(Map context) throws Exception { - return mock(context, ""); + return mock(context, ""); } - + private boolean mock(Map context, String mock) throws Exception { - String services = (String) context.get("service"); - String application = (String) context.get("application"); + String services = (String) context.get("service"); + String application = (String) context.get("application"); if (services == null || services.length() == 0 - || application == null || application.length() == 0){ + || application == null || application.length() == 0) { context.put("message", getMessage("NoSuchOperationData")); return false; } for (String service : SPACE_SPLIT_PATTERN.split(services)) { - if (! super.currentUser.hasServicePrivilege(service)) { - context.put("message", getMessage("HaveNoServicePrivilege", service)); - return false; - } + if (!super.currentUser.hasServicePrivilege(service)) { + context.put("message", getMessage("HaveNoServicePrivilege", service)); + return false; + } } for (String service : SPACE_SPLIT_PATTERN.split(services)) { - List overrides = overrideService.findByServiceAndApplication(service, application); - if (overrides != null && overrides.size() > 0) { - for (Override override: overrides) { - Map map = StringUtils.parseQueryString(override.getParams()); - if (mock == null || mock.length() == 0) { - map.remove("mock"); - } else { - map.put("mock", URL.encode(mock)); - } - if (map.size() > 0) { - override.setParams(StringUtils.toQueryString(map)); - override.setEnabled(true); - override.setOperator(operator); - override.setOperatorAddress(operatorAddress); - overrideService.updateOverride(override); - } else { - overrideService.deleteOverride(override.getId()); - } - } - } else if (mock != null && mock.length() > 0) { - Override override = new Override(); - override.setService(service); - override.setApplication(application); - override.setParams("mock=" + URL.encode(mock)); - override.setEnabled(true); - override.setOperator(operator); - override.setOperatorAddress(operatorAddress); - overrideService.saveOverride(override); - } + List overrides = overrideService.findByServiceAndApplication(service, application); + if (overrides != null && overrides.size() > 0) { + for (Override override : overrides) { + Map map = StringUtils.parseQueryString(override.getParams()); + if (mock == null || mock.length() == 0) { + map.remove("mock"); + } else { + map.put("mock", URL.encode(mock)); + } + if (map.size() > 0) { + override.setParams(StringUtils.toQueryString(map)); + override.setEnabled(true); + override.setOperator(operator); + override.setOperatorAddress(operatorAddress); + overrideService.updateOverride(override); + } else { + overrideService.deleteOverride(override.getId()); + } + } + } else if (mock != null && mock.length() > 0) { + Override override = new Override(); + override.setService(service); + override.setApplication(application); + override.setParams("mock=" + URL.encode(mock)); + override.setEnabled(true); + override.setOperator(operator); + override.setOperatorAddress(operatorAddress); + overrideService.saveOverride(override); + } } return true; } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Weights.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Weights.java index f5d1df47e78..ba0a0a75854 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Weights.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/governance/module/screen/Weights.java @@ -7,19 +7,6 @@ */ package com.alibaba.dubbo.governance.web.governance.module.screen; -import java.io.BufferedReader; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.math.NumberUtils; -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.dubbo.common.utils.CollectionUtils; import com.alibaba.dubbo.governance.service.OverrideService; import com.alibaba.dubbo.governance.service.ProviderService; @@ -29,20 +16,35 @@ import com.alibaba.dubbo.registry.common.util.OverrideUtils; import com.alibaba.dubbo.registry.common.util.Tool; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.math.NumberUtils; +import org.springframework.beans.factory.annotation.Autowired; + +import java.io.BufferedReader; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + /** * Providers. * URI: /services/$service/weights - * + * * @author william.liangf */ public class Weights extends Restful { - + + private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3}$"); + private static final Pattern LOCAL_IP_PATTERN = Pattern.compile("127(\\.\\d{1,3}){3}$"); + private static final Pattern ALL_IP_PATTERN = Pattern.compile("0{1,3}(\\.0{1,3}){3}$"); @Autowired private OverrideService overrideService; - @Autowired private ProviderService providerService; - + public void index(Map context) { final String service = StringUtils.trimToNull((String) context.get("service")); String address = (String) context.get("address"); @@ -57,19 +59,18 @@ public void index(Map context) { } context.put("weights", weights); } - - - + /** * load页面供新增操作 + * * @param context */ public void add(Map context) { - String service = (String)context.get("service"); + String service = (String) context.get("service"); if (service != null && service.length() > 0 && !service.contains("*")) { List providerList = providerService.findByService(service); List addressList = new ArrayList(); - for(Provider provider : providerList){ + for (Provider provider : providerList) { addressList.add(provider.getUrl().split("://")[1].split("/")[0]); } context.put("addressList", addressList); @@ -79,51 +80,47 @@ public void add(Map context) { List serviceList = Tool.sortSimpleName(providerService.findServices()); context.put("serviceList", serviceList); } - if(context.get("input") != null) context.put("input", context.get("input")); + if (context.get("input") != null) context.put("input", context.get("input")); } - + /** * load页面供新增操作 + * * @param context */ public void multiadd(Map context) { List serviceList = Tool.sortSimpleName(providerService.findServices()); context.put("serviceList", serviceList); } - - private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3}$"); - private static final Pattern LOCAL_IP_PATTERN = Pattern.compile("127(\\.\\d{1,3}){3}$"); - private static final Pattern ALL_IP_PATTERN = Pattern.compile("0{1,3}(\\.0{1,3}){3}$"); - public boolean create(Map context) throws Exception { String addr = (String) context.get("address"); - String services = (String) context.get("multiservice"); - if(services == null || services.trim().length() == 0) { - services = (String) context.get("service"); + String services = (String) context.get("multiservice"); + if (services == null || services.trim().length() == 0) { + services = (String) context.get("service"); } - String weight = (String) context.get("weight"); - + String weight = (String) context.get("weight"); + int w = Integer.parseInt(weight); - + Set addresses = new HashSet(); BufferedReader reader = new BufferedReader(new StringReader(addr)); while (true) { String line = reader.readLine(); if (null == line) break; - + String[] split = line.split("[\\s,;]+"); for (String s : split) { if (s.length() == 0) continue; - + String ip = s; String port = null; - if(s.indexOf(":") != -1) { + if (s.indexOf(":") != -1) { ip = s.substring(0, s.indexOf(":")); port = s.substring(s.indexOf(":") + 1, s.length()); - if(port.trim().length() == 0) port = null; + if (port.trim().length() == 0) port = null; } if (!IP_PATTERN.matcher(ip).matches()) { context.put("message", "illegal IP: " + s); @@ -133,8 +130,8 @@ public boolean create(Map context) throws Exception { context.put("message", "local IP or any host ip is illegal: " + s); return false; } - if(port != null) { - if(!NumberUtils.isDigits(port)) { + if (port != null) { + if (!NumberUtils.isDigits(port)) { context.put("message", "illegal port: " + s); return false; } @@ -142,14 +139,14 @@ public boolean create(Map context) throws Exception { addresses.add(s); } } - - Set aimServices = new HashSet(); + + Set aimServices = new HashSet(); reader = new BufferedReader(new StringReader(services)); while (true) { String line = reader.readLine(); if (null == line) break; - + String[] split = line.split("[\\s,;]+"); for (String s : split) { if (s.length() == 0) @@ -161,11 +158,11 @@ public boolean create(Map context) throws Exception { aimServices.add(s); } } - - for(String aimService : aimServices) { + + for (String aimService : aimServices) { for (String a : addresses) { Weight wt = new Weight(); - wt.setUsername((String)context.get("operator")); + wt.setUsername((String) context.get("operator")); wt.setAddress(Tool.getIP(a)); wt.setService(aimService); wt.setWeight(w); @@ -180,34 +177,36 @@ public void edit(Long id, Map context) { show(id, context); context.put("service", overrideService.findById(id).getService()); } - + public void sameSeviceEdit(Long id, Map context) { add(context); show(id, context); } - + /** * load weight对象供编辑操作 + * * @param id * @param context */ public void show(Long id, Map context) { - Weight weight = OverrideUtils.overrideToWeight(overrideService.findById(id)); + Weight weight = OverrideUtils.overrideToWeight(overrideService.findById(id)); context.put("weight", weight); } - + public boolean update(Weight weight, Map context) { if (!super.currentUser.hasServicePrivilege(weight.getService())) { context.put("message", getMessage("HaveNoServicePrivilege", weight.getService())); return false; } weight.setAddress(Tool.getIP(weight.getAddress())); - overrideService.updateOverride(OverrideUtils.weightToOverride(weight)); + overrideService.updateOverride(OverrideUtils.weightToOverride(weight)); return true; } /** * 删除动作 + * * @param ids * @return */ @@ -219,9 +218,9 @@ public boolean delete(Long[] ids, Map context) { return false; } } - + for (Long id : ids) { - overrideService.deleteOverride(id); + overrideService.deleteOverride(id); } return true; } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/control/Menu.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/control/Menu.java index 9961e0e2701..919a795f8ce 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/control/Menu.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/control/Menu.java @@ -1,20 +1,14 @@ /** - * Function: - * + * Function: + *

* File Created at 2010-11-17 * $Id: Menu.java 185206 2012-07-09 03:06:37Z tony.chenl $ - * + *

* Copyright 2009 Alibaba.com Croporation Limited. * All rights reserved. */ package com.alibaba.dubbo.governance.web.home.module.control; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; - -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.citrus.service.requestcontext.parser.CookieParser; import com.alibaba.citrus.turbine.Context; import com.alibaba.dubbo.governance.sync.RegistryServerSync; @@ -22,6 +16,12 @@ import com.alibaba.dubbo.governance.web.util.WebConstants; import com.alibaba.dubbo.registry.common.domain.User; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + /** * @author guanghui.shigh * @author ding.lid @@ -29,27 +29,25 @@ */ public class Menu { - @Autowired - private HttpServletRequest request; - @Autowired ServletContext servletcontext; - @Autowired RegistryServerSync registryServerSync; + @Autowired + private HttpServletRequest request; public void execute(HttpSession session, Context context, CookieParser parser) { - + User user = (User) session.getAttribute(WebConstants.CURRENT_USER_KEY); if (user != null) context.put("operator", user.getUsername()); - + RootContextPath rootContextPath = new RootContextPath(request.getContextPath()); context.put("rootContextPath", rootContextPath); - if (! context.containsKey("bucLogoutAddress")) { - context.put("bucLogoutAddress", rootContextPath.getURI("logout")); + if (!context.containsKey("bucLogoutAddress")) { + context.put("bucLogoutAddress", rootContextPath.getURI("logout")); } - if (! context.containsKey("helpUrl")) { - context.put("helpUrl", "http://code.alibabatech.com/wiki/display/dubbo"); + if (!context.containsKey("helpUrl")) { + context.put("helpUrl", "http://code.alibabatech.com/wiki/display/dubbo"); } context.put(WebConstants.CURRENT_USER_KEY, user); context.put("language", parser.getString("locale")); diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Disable.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Disable.java index c159deefee0..599a1e96507 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Disable.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Disable.java @@ -7,15 +7,14 @@ */ package com.alibaba.dubbo.governance.web.home.module.screen; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; +import com.alibaba.dubbo.governance.service.ProviderService; +import com.alibaba.dubbo.registry.common.domain.Provider; import org.springframework.beans.factory.annotation.Autowired; -import com.alibaba.dubbo.governance.service.ProviderService; -import com.alibaba.dubbo.registry.common.domain.Provider; +import javax.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.Map; /** * @author tony.chenl @@ -23,8 +22,8 @@ public class Disable extends Shell { @Autowired - private ProviderService providerService; - + private ProviderService providerService; + @Autowired private HttpServletRequest request; @@ -32,28 +31,28 @@ public void setProviderDAO(ProviderService providerDAO) { this.providerService = providerDAO; } - protected String doExecute(Map context) throws Exception { - String address = request.getParameter("provider"); - if (address == null || address.length() == 0) { - address = request.getParameter("client"); - } - if (address == null || address.length() == 0) { - throw new IllegalArgumentException("The url provider parameter is null! Usage: " + request.getRequestURL().toString() + "?provider=" + operatorAddress); - } - List providers = providerService.findByAddress(address); - if (providers != null && providers.size() > 0) { - for (Provider provider : providers) { - if (! currentUser.hasServicePrivilege(provider.getService())) { - throw new IllegalStateException("The user " + currentUser.getUsername() + " have no privilege of service " + provider.getService()); - } - } - for (Provider provider : providers) { - provider.setUsername(operator); - provider.setOperatorAddress(operatorAddress); - providerService.disableProvider(provider.getId()); - } - } - return "Disable " + (providers == null ? 0 : providers.size()) + " services."; + protected String doExecute(Map context) throws Exception { + String address = request.getParameter("provider"); + if (address == null || address.length() == 0) { + address = request.getParameter("client"); + } + if (address == null || address.length() == 0) { + throw new IllegalArgumentException("The url provider parameter is null! Usage: " + request.getRequestURL().toString() + "?provider=" + operatorAddress); + } + List providers = providerService.findByAddress(address); + if (providers != null && providers.size() > 0) { + for (Provider provider : providers) { + if (!currentUser.hasServicePrivilege(provider.getService())) { + throw new IllegalStateException("The user " + currentUser.getUsername() + " have no privilege of service " + provider.getService()); + } + } + for (Provider provider : providers) { + provider.setUsername(operator); + provider.setOperatorAddress(operatorAddress); + providerService.disableProvider(provider.getId()); + } + } + return "Disable " + (providers == null ? 0 : providers.size()) + " services."; } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Index.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Index.java index 4e3c062ca1d..5bc73c4c7bb 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Index.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Index.java @@ -15,15 +15,6 @@ */ package com.alibaba.dubbo.governance.web.home.module.screen; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.servlet.http.HttpServletRequest; - -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.citrus.turbine.Context; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; @@ -33,9 +24,17 @@ import com.alibaba.dubbo.registry.common.domain.Consumer; import com.alibaba.dubbo.registry.common.domain.Provider; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.servlet.http.HttpServletRequest; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + /** * Index - * + * * @author william.liangf */ public class Index { @@ -44,16 +43,16 @@ public class Index { @Autowired private HttpServletRequest request; - + @Autowired private ProviderService providerService; - + @Autowired private ConsumerService consumerService; - + public void execute(Context context) { Set applications = new HashSet(); - Set services = new HashSet(); + Set services = new HashSet(); List pList = new ArrayList(); try { pList = providerService.findAll(); @@ -64,7 +63,7 @@ public void execute(Context context) { applications.add(p.getApplication()); services.add(p.getService()); } - List cList = new ArrayList(); + List cList = new ArrayList(); try { cList = consumerService.findAll(); } catch (Exception e) { diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Lookup.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Lookup.java index 4781c8b6a7b..888297e8ae1 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Lookup.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Lookup.java @@ -15,68 +15,68 @@ */ package com.alibaba.dubbo.governance.web.home.module.screen; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.governance.service.ConsumerService; import com.alibaba.dubbo.registry.RegistryService; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + /** * @author tony.chenl */ -public class Lookup extends Restful{ - +public class Lookup extends Restful { + @Autowired ConsumerService consumerDAO; - + @Autowired private RegistryService registryService; public Result doExecute(Map context) throws Exception { String inf = request.getParameter("interface"); - if(inf==null || inf.isEmpty()){ + if (inf == null || inf.isEmpty()) { throw new IllegalArgumentException("please give me the interface"); } String group = null; - if(inf.contains("/")) { + if (inf.contains("/")) { int idx = inf.indexOf('/'); group = inf.substring(idx); inf = inf.substring(idx + 1, inf.length()); } String version = null; - if(inf.contains(":")) { + if (inf.contains(":")) { int idx = inf.lastIndexOf(':'); version = inf.substring(idx + 1, inf.length()); inf = inf.substring(idx); } - + String parameters = request.getParameter("parameters"); - String url = "subscribe://" + operatorAddress + "/" + request.getParameter("interface") ; - if(parameters != null && parameters.trim().length() > 0) { + String url = "subscribe://" + operatorAddress + "/" + request.getParameter("interface"); + if (parameters != null && parameters.trim().length() > 0) { url += parameters.trim(); } - + URL u = URL.valueOf(url); - if(group != null) { + if (group != null) { u.addParameter("group", group); } - - if(version != null) u.addParameter("version", version); - + + if (version != null) u.addParameter("version", version); + List lookup = registryService.lookup(u); - - Map> serviceUrl = new HashMap>(); + + Map> serviceUrl = new HashMap>(); Map urls = new HashMap(); serviceUrl.put(request.getParameter("interface").trim(), urls); - - for(URL u2 : lookup) { + + for (URL u2 : lookup) { urls.put(u2.toIdentityString(), u2.toParameterString()); } - + Result result = new Result(); result.setMessage(serviceUrl); return result; diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Reg.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Reg.java index db8adc707d7..90d98d265a5 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Reg.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Reg.java @@ -24,15 +24,15 @@ public class Reg extends Restful { public Result doExecute(Map context) throws Exception { - if(url==null){ + if (url == null) { throw new IllegalArgumentException("please give me the url"); } - if(url.getPath().isEmpty()){ + if (url.getPath().isEmpty()) { throw new IllegalArgumentException("please use interface as your url path"); } - Map tmp = new HashMap(); - tmp.put(url.toIdentityString(),url.toParameterString()); - Map> register = new HashMap>(); + Map tmp = new HashMap(); + tmp.put(url.toIdentityString(), url.toParameterString()); + Map> register = new HashMap>(); register.put(url.getPath(), tmp); // Map> newRegister = RegistryUtils.convertRegister(register); // registryService.register(operatorAddress, newRegister, false); diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Register.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Register.java index 8b9bdd27fe2..48a2303e5ac 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Register.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Register.java @@ -7,18 +7,17 @@ */ package com.alibaba.dubbo.governance.web.home.module.screen; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.dubbo.common.utils.CollectionUtils; import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.governance.service.ProviderService; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.servlet.http.HttpServletRequest; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + /** * @author tony.chenl */ @@ -29,35 +28,35 @@ public class Register extends Shell { @Autowired private HttpServletRequest request; - + // @Autowired // private RegistryCache registryCache; - + @SuppressWarnings("unchecked") - protected String doExecute(Map context) throws Exception { - Map params = request.getParameterMap(); + protected String doExecute(Map context) throws Exception { + Map params = request.getParameterMap(); if (params == null || params.size() == 0) { - throw new IllegalArgumentException("The url parameters is null! Usage: " + request.getRequestURL().toString() + "?com.xxx.XxxService=http://" + request.getRemoteAddr() + "/xxxService?application=xxx&foo1=123"); + throw new IllegalArgumentException("The url parameters is null! Usage: " + request.getRequestURL().toString() + "?com.xxx.XxxService=http://" + request.getRemoteAddr() + "/xxxService?application=xxx&foo1=123"); } Map> map = new HashMap>(); for (Map.Entry entry : params.entrySet()) { if (entry.getKey() != null && entry.getKey().length() > 0 && entry.getValue() != null && entry.getValue().length > 0 && entry.getValue()[0] != null && entry.getValue()[0].length() > 0) { - if (! currentUser.hasServicePrivilege(entry.getKey())) { - throw new IllegalStateException("The user " + currentUser.getUsername() + " have no privilege of service " + entry.getKey()); - } - String serviceName = entry.getKey(); - Map url2query = CollectionUtils.split(Arrays.asList(entry.getValue()), "?"); - // check whether url contain application info - for(Map.Entry e : url2query.entrySet()) { - Map query = StringUtils.parseQueryString(e.getValue()); - String app = query.get("application"); - if(StringUtils.isBlank(app)) { - throw new IllegalStateException("No application for service(" + serviceName + "): " - + e.getKey() + "?" + e.getValue()); - } - } + if (!currentUser.hasServicePrivilege(entry.getKey())) { + throw new IllegalStateException("The user " + currentUser.getUsername() + " have no privilege of service " + entry.getKey()); + } + String serviceName = entry.getKey(); + Map url2query = CollectionUtils.split(Arrays.asList(entry.getValue()), "?"); + // check whether url contain application info + for (Map.Entry e : url2query.entrySet()) { + Map query = StringUtils.parseQueryString(e.getValue()); + String app = query.get("application"); + if (StringUtils.isBlank(app)) { + throw new IllegalStateException("No application for service(" + serviceName + "): " + + e.getKey() + "?" + e.getValue()); + } + } map.put(serviceName, url2query); } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Restful.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Restful.java index 402686951fc..7922379c0d0 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Restful.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Restful.java @@ -7,39 +7,36 @@ */ package com.alibaba.dubbo.governance.web.home.module.screen; -import java.util.Map; - -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.governance.web.util.WebConstants; import com.alibaba.dubbo.registry.common.domain.User; import com.alibaba.fastjson.JSON; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.Map; + public abstract class Restful { - @Autowired - private HttpServletResponse response; - + protected String role = null; + protected String operator = null; + + // @Autowired +// RegistryValidator registryService; + protected User currentUser = null; + protected String operatorAddress = null; + protected URL url = null; @Autowired HttpServletRequest request; - -// @Autowired -// RegistryValidator registryService; - - protected String role = null; - protected String operator = null; - protected User currentUser = null; - protected String operatorAddress = null; - protected URL url = null; + @Autowired + private HttpServletResponse response; public void execute(Map context) throws Exception { Result result = new Result(); - if(request.getParameter("url")!=null){ + if (request.getParameter("url") != null) { url = URL.valueOf(URL.decode(request.getParameter("url"))); } if (context.get(WebConstants.CURRENT_USER_KEY) != null) { @@ -50,7 +47,7 @@ public void execute(Map context) throws Exception { context.put(WebConstants.CURRENT_USER_KEY, user); } operatorAddress = (String) context.get("clientid"); - if(operatorAddress==null || operatorAddress.isEmpty()){ + if (operatorAddress == null || operatorAddress.isEmpty()) { operatorAddress = (String) context.get("request.remoteHost"); } context.put("operator", operator); @@ -69,7 +66,7 @@ public void execute(Map context) throws Exception { // result.setCode(2); // result.setMessage(t.getMessage()); // } - catch (Throwable t){ + catch (Throwable t) { result.setStatus("ERROR"); result.setCode(1); result.setMessage(t.getMessage()); @@ -82,7 +79,7 @@ public void execute(Map context) throws Exception { } catch (Exception e) { response.setStatus(500); os.print(e.getMessage()); - }finally{ + } finally { os.flush(); } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Result.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Result.java index 8512ed1991d..87171f195ac 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Result.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Result.java @@ -23,9 +23,9 @@ public class Result implements Serializable { private static final long serialVersionUID = 4922467873471920132L; - private String status; - private Object message; - private int code; + private String status; + private Object message; + private int code; public String getStatus() { return status; @@ -42,12 +42,12 @@ public Object getMessage() { public void setMessage(Object message) { this.message = message; } - + public int getCode() { return code; } - + public void setCode(int code) { this.code = code; } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Servicestatus.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Servicestatus.java index bc1fb7d9eeb..83fbcc6658b 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Servicestatus.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Servicestatus.java @@ -1,11 +1,11 @@ /** * Project: dubbo.registry-1.1.0-SNAPSHOT - * + *

* File Created at 2010-5-14 - * + *

* Copyright 1999-2010 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -21,36 +21,36 @@ * use it only in accordance with the terms of the license agreement you entered * into with Alibaba.com. */ -import java.io.PrintWriter; -import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import com.alibaba.dubbo.governance.service.ProviderService; import org.springframework.beans.factory.annotation.Autowired; -import com.alibaba.dubbo.governance.service.ProviderService; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.PrintWriter; +import java.util.Map; /** * @author tony.chenl */ -public class Servicestatus{ +public class Servicestatus { // @Autowired // private RegistryCache registryCache; - + @Autowired private HttpServletRequest request; - + @Autowired private ProviderService providerDAO; - + @Autowired private HttpServletResponse response; - public void execute(Map context) throws Exception { + public void execute(Map context) throws Exception { String uri = request.getRequestURI(); String contextPath = request.getContextPath(); - if (contextPath != null && ! "/".equals(contextPath)) { + if (contextPath != null && !"/".equals(contextPath)) { uri = uri.substring(contextPath.length()); } if (uri.startsWith("/status/")) { diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Shell.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Shell.java index f2948ab99f6..3e3b53fc195 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Shell.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Shell.java @@ -7,66 +7,62 @@ */ package com.alibaba.dubbo.governance.web.home.module.screen; -import java.io.PrintWriter; -import java.util.Map; -import java.util.regex.Pattern; - -import javax.servlet.http.HttpServletResponse; +import com.alibaba.dubbo.governance.web.util.WebConstants; +import com.alibaba.dubbo.registry.common.domain.User; import org.springframework.beans.factory.annotation.Autowired; -import com.alibaba.dubbo.governance.web.util.WebConstants; -import com.alibaba.dubbo.registry.common.domain.User; +import javax.servlet.http.HttpServletResponse; +import java.io.PrintWriter; +import java.util.Map; +import java.util.regex.Pattern; public abstract class Shell { - @Autowired - private HttpServletResponse response; - + private static final Pattern OK_PATTERN = Pattern.compile("ok", Pattern.CASE_INSENSITIVE); + private static final Pattern ERROR_PATTERN = Pattern.compile("error", Pattern.CASE_INSENSITIVE); protected String role = null; protected String operator = null; protected User currentUser = null; protected String operatorAddress = null; + @Autowired + private HttpServletResponse response; + + private static String filterOK(String value) { + if (value == null || value.length() == 0) { + return value; + } + return OK_PATTERN.matcher(value).replaceAll("0k"); + } + + private static String filterERROR(String value) { + if (value == null || value.length() == 0) { + return value; + } + return ERROR_PATTERN.matcher(value).replaceAll("err0r"); + } - public void execute(Map context) throws Exception { - if(context.get(WebConstants.CURRENT_USER_KEY)!=null){ + public void execute(Map context) throws Exception { + if (context.get(WebConstants.CURRENT_USER_KEY) != null) { User user = (User) context.get(WebConstants.CURRENT_USER_KEY); currentUser = user; operator = user.getUsername(); role = user.getRole(); context.put(WebConstants.CURRENT_USER_KEY, user); } - operatorAddress = (String)context.get("request.remoteHost"); + operatorAddress = (String) context.get("request.remoteHost"); context.put("operator", operator); context.put("operatorAddress", operatorAddress); - try { - String message = doExecute(context); - context.put("message", "OK: " + filterERROR(message)); - } catch (Throwable t) { - context.put("message", "ERROR: " + filterOK(t.getMessage())); + try { + String message = doExecute(context); + context.put("message", "OK: " + filterERROR(message)); + } catch (Throwable t) { + context.put("message", "ERROR: " + filterOK(t.getMessage())); } - PrintWriter writer = response.getWriter(); - writer.print(context.get("message")); - writer.flush(); - } - - protected abstract String doExecute(Map context) throws Exception; - - private static final Pattern OK_PATTERN = Pattern.compile("ok", Pattern.CASE_INSENSITIVE); - - private static final Pattern ERROR_PATTERN = Pattern.compile("error", Pattern.CASE_INSENSITIVE); - - private static String filterOK(String value) { - if (value == null || value.length() == 0) { - return value; - } - return OK_PATTERN.matcher(value).replaceAll("0k"); - } + PrintWriter writer = response.getWriter(); + writer.print(context.get("message")); + writer.flush(); + } - private static String filterERROR(String value) { - if (value == null || value.length() == 0) { - return value; - } - return ERROR_PATTERN.matcher(value).replaceAll("err0r"); - } + protected abstract String doExecute(Map context) throws Exception; } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Status.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Status.java index a697993baa1..ca282bb8fdf 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Status.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Status.java @@ -7,6 +7,13 @@ */ package com.alibaba.dubbo.governance.web.home.module.screen; +import com.alibaba.dubbo.common.status.Status.Level; +import com.alibaba.dubbo.common.status.StatusChecker; +import com.alibaba.dubbo.registry.common.StatusManager; + +import org.springframework.beans.factory.annotation.Autowired; + +import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Collection; @@ -14,22 +21,22 @@ import java.util.Map; import java.util.regex.Pattern; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.beans.factory.annotation.Autowired; - -import com.alibaba.dubbo.common.status.Status.Level; -import com.alibaba.dubbo.common.status.StatusChecker; -import com.alibaba.dubbo.registry.common.StatusManager; - /** * @author tony.chenl */ -public class Status{ +public class Status { + private static final Pattern OK_PATTERN = Pattern.compile("o(k)", Pattern.CASE_INSENSITIVE); @Autowired private HttpServletResponse response; - public void execute(Map context) throws Exception { + public static String filterOK(String message) { + if (message == null) + return ""; + // 避免ok关键字,用数字0代替字母o + return OK_PATTERN.matcher(message).replaceAll("0$1"); + } + + public void execute(Map context) throws Exception { //FIXME cache监控存在性能问题 汇总页面去掉 Map statuses = StatusManager.getInstance().getStatusList(new String[]{"cache"}); com.alibaba.dubbo.common.status.Status status = StatusManager.getInstance().getStatusSummary(statuses); @@ -45,15 +52,6 @@ public void execute(Map context) throws Exception { writer.print(context.get("message").toString()); writer.flush(); } - - private static final Pattern OK_PATTERN = Pattern.compile("o(k)", Pattern.CASE_INSENSITIVE); - - public static String filterOK(String message) { - if (message == null) - return ""; - // 避免ok关键字,用数字0代替字母o - return OK_PATTERN.matcher(message).replaceAll("0$1"); - } public void setStatusHandlers(Collection statusHandlers) { StatusManager.getInstance().addStatusHandlers(statusHandlers); diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Unreg.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Unreg.java index dfa15077aa2..7625d199755 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Unreg.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Unreg.java @@ -22,30 +22,31 @@ /** * UnReg.java + * * @author tony.chenl */ -public class Unreg extends Restful{ - +public class Unreg extends Restful { + public Result doExecute(Map context) throws Exception { - if(url==null){ + if (url == null) { throw new IllegalArgumentException("please give me the url"); } - if(url.getPath().isEmpty()){ + if (url.getPath().isEmpty()) { throw new IllegalArgumentException("please use interface as your url path"); } HashMap> services = new HashMap>(); - Set serviceUrl = new HashSet(); + Set serviceUrl = new HashSet(); serviceUrl.add(url.toIdentityString()); String name = url.getPath(); - String version =url.getParameter("version"); - if(version != null){ + String version = url.getParameter("version"); + if (version != null) { name = name + ":" + version; } - String group =url.getParameter("group"); - if(group != null){ + String group = url.getParameter("group"); + if (group != null) { name = group + "/" + name; } - services.put(name,serviceUrl); + services.put(name, serviceUrl); // registryService.unregister(operatorAddress,services); Result result = new Result(); result.setMessage("Unregister Successfully!"); diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Unregister.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Unregister.java index 256699830af..115659eb76f 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Unregister.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Unregister.java @@ -7,51 +7,50 @@ */ package com.alibaba.dubbo.governance.web.home.module.screen; -import java.util.Arrays; -import java.util.Map; -import java.util.Map.Entry; - -import javax.servlet.http.HttpServletRequest; - -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.dubbo.common.utils.CollectionUtils; import com.alibaba.dubbo.governance.service.ProviderService; import com.alibaba.dubbo.registry.common.domain.Provider; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.servlet.http.HttpServletRequest; +import java.util.Arrays; +import java.util.Map; +import java.util.Map.Entry; + /** * @author tony.chenl */ public class Unregister extends Shell { @Autowired - private ProviderService providervice; - + private ProviderService providervice; + @Autowired private HttpServletRequest request; @SuppressWarnings("unchecked") - protected String doExecute(Map context) throws Exception { - Map params = request.getParameterMap(); + protected String doExecute(Map context) throws Exception { + Map params = request.getParameterMap(); if (params == null || params.size() == 0) { - throw new IllegalArgumentException("The url parameters is null! Usage: " + request.getRequestURL().toString() + "?com.xxx.XxxService=http://" + operatorAddress + "/xxxService"); + throw new IllegalArgumentException("The url parameters is null! Usage: " + request.getRequestURL().toString() + "?com.xxx.XxxService=http://" + operatorAddress + "/xxxService"); } for (Map.Entry entry : params.entrySet()) { if (entry.getKey() != null && entry.getKey().length() > 0 && entry.getValue() != null && entry.getValue().length > 0 && entry.getValue()[0] != null && entry.getValue()[0].length() > 0) { - if (! currentUser.hasServicePrivilege(entry.getKey())) { + if (!currentUser.hasServicePrivilege(entry.getKey())) { throw new IllegalStateException("The user " + operator + " have no privilege of service " + entry.getKey()); } - for(Entry e : CollectionUtils.split(Arrays.asList(entry.getValue()), "?").entrySet()){ - Provider provider = providervice.findByServiceAndAddress(entry.getKey(), e.getKey()); + for (Entry e : CollectionUtils.split(Arrays.asList(entry.getValue()), "?").entrySet()) { + Provider provider = providervice.findByServiceAndAddress(entry.getKey(), e.getKey()); if (provider != null) { providervice.deleteStaticProvider(provider.getId()); } } } } - + return "Unregister " + params.size() + " services."; } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Unregisterall.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Unregisterall.java index cb2a2cc4332..ecc8dbca931 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Unregisterall.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/screen/Unregisterall.java @@ -7,15 +7,14 @@ */ package com.alibaba.dubbo.governance.web.home.module.screen; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; +import com.alibaba.dubbo.governance.service.ProviderService; +import com.alibaba.dubbo.registry.common.domain.Provider; import org.springframework.beans.factory.annotation.Autowired; -import com.alibaba.dubbo.governance.service.ProviderService; -import com.alibaba.dubbo.registry.common.domain.Provider; +import javax.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.Map; /** * @author tony.chenl @@ -23,33 +22,33 @@ public class Unregisterall extends Shell { @Autowired - private ProviderService providerService; - + private ProviderService providerService; + @Autowired private HttpServletRequest request; - protected String doExecute(Map context) throws Exception { - String address = request.getParameter("provider"); - if (address == null || address.length() == 0) { - address = request.getParameter("client"); - } - if (address == null || address.length() == 0) { - throw new IllegalArgumentException("The url provider parameter is null! Usage: " + request.getRequestURL().toString() + "?provider=" + operatorAddress); - } - List providers = providerService.findByAddress(address); - if (providers != null && providers.size() > 0) { - for (Provider provider : providers) { - if (! currentUser.hasServicePrivilege(provider.getService())) { - throw new IllegalStateException("The user " + currentUser + " have no privilege of service " + provider.getService()); - } - } - for (Provider provider : providers) { - provider.setUsername(operator); - provider.setOperatorAddress(operatorAddress); - providerService.deleteStaticProvider(provider.getId()); - } - } - return "Unregister " + (providers == null ? 0 : providers.size()) + " services."; + protected String doExecute(Map context) throws Exception { + String address = request.getParameter("provider"); + if (address == null || address.length() == 0) { + address = request.getParameter("client"); + } + if (address == null || address.length() == 0) { + throw new IllegalArgumentException("The url provider parameter is null! Usage: " + request.getRequestURL().toString() + "?provider=" + operatorAddress); + } + List providers = providerService.findByAddress(address); + if (providers != null && providers.size() > 0) { + for (Provider provider : providers) { + if (!currentUser.hasServicePrivilege(provider.getService())) { + throw new IllegalStateException("The user " + currentUser + " have no privilege of service " + provider.getService()); + } + } + for (Provider provider : providers) { + provider.setUsername(operator); + provider.setOperatorAddress(operatorAddress); + providerService.deleteStaticProvider(provider.getId()); + } + } + return "Unregister " + (providers == null ? 0 : providers.size()) + " services."; } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/personal/module/screen/Infos.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/personal/module/screen/Infos.java index e1b9ac1972d..c1ac5f12ee4 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/personal/module/screen/Infos.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/personal/module/screen/Infos.java @@ -1,13 +1,13 @@ package com.alibaba.dubbo.governance.web.personal.module.screen; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.dubbo.governance.service.UserService; import com.alibaba.dubbo.governance.web.common.module.screen.Restful; import com.alibaba.dubbo.registry.common.domain.User; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.Map; + public class Infos extends Restful { @Autowired private UserService userDAO; @@ -16,7 +16,7 @@ public void index(Map context) { User user = userDAO.findById(currentUser.getId()); context.put("user", user); } - + public boolean update(Map context) { User user = new User(); user.setId(currentUser.getId()); diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/personal/module/screen/Passwds.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/personal/module/screen/Passwds.java index 46953769582..065674797b1 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/personal/module/screen/Passwds.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/personal/module/screen/Passwds.java @@ -1,13 +1,13 @@ package com.alibaba.dubbo.governance.web.personal.module.screen; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.dubbo.governance.service.UserService; import com.alibaba.dubbo.governance.web.common.module.screen.Restful; import com.alibaba.dubbo.registry.common.domain.User; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.Map; + public class Passwds extends Restful { @Autowired diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Dump.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Dump.java index bb320b6918b..f6ffc047d84 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Dump.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Dump.java @@ -15,6 +15,16 @@ */ package com.alibaba.dubbo.governance.web.sysinfo.module.screen; +import com.alibaba.dubbo.common.utils.StringUtils; +import com.alibaba.dubbo.governance.service.ConsumerService; +import com.alibaba.dubbo.governance.service.ProviderService; +import com.alibaba.dubbo.governance.web.common.module.screen.Restful; +import com.alibaba.dubbo.registry.common.domain.Consumer; +import com.alibaba.dubbo.registry.common.domain.Provider; + +import org.springframework.beans.factory.annotation.Autowired; + +import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; @@ -26,27 +36,16 @@ import java.util.Map; import java.util.Set; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.beans.factory.annotation.Autowired; - -import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.governance.service.ConsumerService; -import com.alibaba.dubbo.governance.service.ProviderService; -import com.alibaba.dubbo.governance.web.common.module.screen.Restful; -import com.alibaba.dubbo.registry.common.domain.Consumer; -import com.alibaba.dubbo.registry.common.domain.Provider; - /** * @author tony.chenl */ public class Dump extends Restful { - + @Autowired - ProviderService providerDAO; + ProviderService providerDAO; @Autowired - ConsumerService consumerDAO; + ConsumerService consumerDAO; @Autowired HttpServletResponse response; @@ -106,7 +105,7 @@ public void consumers(Map context) throws IOException { writer.flush(); response.setContentType("text/plain"); } - + public void versions(Map context) throws IOException { PrintWriter writer = response.getWriter(); List providers = providerDAO.findAll(); @@ -141,7 +140,7 @@ public void versions(Map context) throws IOException { writer.flush(); response.setContentType("text/plain"); } - + private List getNoProviders() { List providerServices = providerDAO.findServices(); List consumerServices = consumerDAO.findServices(); diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Dumps.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Dumps.java index 30b085ffb7f..6b03528cff1 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Dumps.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Dumps.java @@ -15,28 +15,27 @@ */ package com.alibaba.dubbo.governance.web.sysinfo.module.screen; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletResponse; - -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.dubbo.governance.service.ConsumerService; import com.alibaba.dubbo.governance.service.ProviderService; import com.alibaba.dubbo.governance.web.common.module.screen.Restful; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.servlet.http.HttpServletResponse; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + /** * @author tony.chenl */ public class Dumps extends Restful { @Autowired - ProviderService providerDAO; + ProviderService providerDAO; @Autowired - ConsumerService consumerDAO; + ConsumerService consumerDAO; @Autowired HttpServletResponse response; diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Envs.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Envs.java index 5eff9c99235..be9765b5bfe 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Envs.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Envs.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.console-2.1.0-SNAPSHOT - * + *

* File Created at Sep 13, 2011 * $Id: Envs.java 185206 2012-07-09 03:06:37Z tony.chenl $ - * + *

* Copyright 1999-2100 Alibaba.com Corporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,6 +15,10 @@ */ package com.alibaba.dubbo.governance.web.sysinfo.module.screen; +import com.alibaba.dubbo.common.Version; +import com.alibaba.dubbo.common.utils.NetUtils; +import com.alibaba.dubbo.governance.web.common.module.screen.Restful; + import java.lang.management.ManagementFactory; import java.text.SimpleDateFormat; import java.util.Date; @@ -22,15 +26,16 @@ import java.util.Map; import java.util.TreeMap; -import com.alibaba.dubbo.common.Version; -import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.governance.web.common.module.screen.Restful; - /** * @author ding.lid */ public class Envs extends Restful { - + + private static final long SECOND = 1000; + private static final long MINUTE = 60 * SECOND; + private static final long HOUR = 60 * MINUTE; + private static final long DAY = 24 * HOUR; + public void index(Map context) throws Exception { Map properties = new TreeMap(); StringBuilder msg = new StringBuilder(); @@ -46,20 +51,12 @@ public void index(Map context) throws Exception { + String.valueOf(Runtime.getRuntime().availableProcessors()) + " cores"); properties.put("Locale", Locale.getDefault().toString() + "/" + System.getProperty("file.encoding")); - properties.put("Uptime", formatUptime(ManagementFactory.getRuntimeMXBean().getUptime()) - + " From " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS Z").format(new Date(ManagementFactory.getRuntimeMXBean().getStartTime())) + properties.put("Uptime", formatUptime(ManagementFactory.getRuntimeMXBean().getUptime()) + + " From " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS Z").format(new Date(ManagementFactory.getRuntimeMXBean().getStartTime())) + " To " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS Z").format(new Date())); context.put("properties", properties); } - - private static final long SECOND = 1000; - - private static final long MINUTE = 60 * SECOND; - - private static final long HOUR = 60 * MINUTE; - - private static final long DAY = 24 * HOUR; - + private String formatUptime(long uptime) { StringBuilder buf = new StringBuilder(); if (uptime > DAY) { diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Logs.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Logs.java index 502be6ef7b5..d1b4b2c6b34 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Logs.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Logs.java @@ -15,6 +15,11 @@ */ package com.alibaba.dubbo.governance.web.sysinfo.module.screen; +import com.alibaba.dubbo.common.logger.Level; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.governance.web.common.module.screen.Restful; +import com.alibaba.dubbo.registry.common.domain.User; + import java.io.File; import java.io.FileInputStream; import java.nio.ByteBuffer; @@ -23,11 +28,6 @@ import java.util.Date; import java.util.Map; -import com.alibaba.dubbo.common.logger.Level; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.governance.web.common.module.screen.Restful; -import com.alibaba.dubbo.registry.common.domain.User; - /** * @author tony.chenl */ @@ -68,15 +68,15 @@ public void index(Map context) throws Exception { context.put("modified", modified); context.put("content", content); } - + public boolean change(Map context) throws Exception { - String contextLevel = (String)context.get("level"); + String contextLevel = (String) context.get("level"); if (contextLevel == null || contextLevel.length() == 0) { context.put("message", getMessage("MissRequestParameters", "level")); return false; } - if (! User.ROOT.equals(role)) { - context.put("message", getMessage("HaveNoRootPrivilege")); + if (!User.ROOT.equals(role)) { + context.put("message", getMessage("HaveNoRootPrivilege")); return false; } Level level = Level.valueOf(contextLevel); diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Statuses.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Statuses.java index 72d4b930315..c26f64e1bf3 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Statuses.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Statuses.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.console-2.1.0-SNAPSHOT - * + *

* File Created at Sep 13, 2011 * $Id: Status.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 1999-2100 Alibaba.com Corporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,27 +15,27 @@ */ package com.alibaba.dubbo.governance.web.sysinfo.module.screen; -import java.util.LinkedHashMap; -import java.util.Map; - import com.alibaba.dubbo.common.extension.ExtensionLoader; import com.alibaba.dubbo.common.status.StatusChecker; import com.alibaba.dubbo.governance.web.common.module.screen.Restful; import com.alibaba.dubbo.registry.common.StatusManager; +import java.util.LinkedHashMap; +import java.util.Map; + /** * @author ding.lid */ public class Statuses extends Restful { public void index(Map context) throws Exception { - ExtensionLoader loader= ExtensionLoader.getExtensionLoader(StatusChecker.class); - Map statusList = new LinkedHashMap(); + ExtensionLoader loader = ExtensionLoader.getExtensionLoader(StatusChecker.class); + Map statusList = new LinkedHashMap(); for (String name : loader.getSupportedExtensions()) { - com.alibaba.dubbo.common.status.Status status = loader.getExtension(name).check(); - if (status.getLevel() != null && status.getLevel() != com.alibaba.dubbo.common.status.Status.Level.UNKNOWN) { - statusList.put(name, status); - } - } + com.alibaba.dubbo.common.status.Status status = loader.getExtension(name).check(); + if (status.getLevel() != null && status.getLevel() != com.alibaba.dubbo.common.status.Status.Level.UNKNOWN) { + statusList.put(name, status); + } + } statusList.put("summary", StatusManager.getStatusSummary(statusList)); context.put("statusList", statusList); } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Versions.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Versions.java index 1d100f66896..703ea96aa2d 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Versions.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Versions.java @@ -15,15 +15,6 @@ */ package com.alibaba.dubbo.governance.web.sysinfo.module.screen; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.governance.service.ConsumerService; import com.alibaba.dubbo.governance.service.ProviderService; @@ -31,16 +22,25 @@ import com.alibaba.dubbo.registry.common.domain.Consumer; import com.alibaba.dubbo.registry.common.domain.Provider; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + /** * @author tony.chenl */ public class Versions extends Restful { @Autowired private ProviderService providerService; - + @Autowired private ConsumerService consumerService; - + public void index(Map context) { List providers = providerService.findAll(); List consumers = consumerService.findAll(); @@ -57,7 +57,7 @@ public void index(Map context) { Map parameter = StringUtils.parseQueryString(temp.next()); if (parameter != null) { String dubbo = parameter.get("dubbo"); - if(dubbo == null) dubbo = "0.0.0"; + if (dubbo == null) dubbo = "0.0.0"; String application = parameter.get("application"); if (versions.get(dubbo) == null) { Set apps = new HashSet(); @@ -70,7 +70,7 @@ public void index(Map context) { } public void show(Long[] ids, Map context) { - String version =(String)context.get("version"); + String version = (String) context.get("version"); if (version != null && version.length() > 0) { List providers = providerService.findAll(); List consumers = consumerService.findAll(); @@ -87,7 +87,7 @@ public void show(Long[] ids, Map context) { Map parameter = StringUtils.parseQueryString(temp.next()); if (parameter != null) { String dubbo = parameter.get("dubbo"); - if(dubbo == null) dubbo = "0.0.0"; + if (dubbo == null) dubbo = "0.0.0"; String application = parameter.get("application"); if (version.equals(dubbo)) { applications.add(application); diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysmanage/module/screen/Configs.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysmanage/module/screen/Configs.java index a26c928452a..daf903e8859 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysmanage/module/screen/Configs.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysmanage/module/screen/Configs.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.console-2.1.0-SNAPSHOT - * + *

* File Created at Sep 13, 2011 * $Id: Configs.java 181723 2012-06-26 01:56:06Z tony.chenl $ - * + *

* Copyright 1999-2100 Alibaba.com Corporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,6 +15,14 @@ */ package com.alibaba.dubbo.governance.web.sysmanage.module.screen; +import com.alibaba.dubbo.governance.service.ConfigService; +import com.alibaba.dubbo.governance.web.common.module.screen.Restful; +import com.alibaba.dubbo.registry.common.domain.Config; +import com.alibaba.dubbo.registry.common.domain.User; + +import org.springframework.beans.factory.annotation.Autowired; + +import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -22,35 +30,27 @@ import java.util.Map; import java.util.Set; -import javax.servlet.http.HttpServletRequest; - -import org.springframework.beans.factory.annotation.Autowired; - -import com.alibaba.dubbo.governance.service.ConfigService; -import com.alibaba.dubbo.governance.web.common.module.screen.Restful; -import com.alibaba.dubbo.registry.common.domain.Config; -import com.alibaba.dubbo.registry.common.domain.User; - /** * @author ding.lid */ public class Configs extends Restful { - + @Autowired private ConfigService configDAO; - + @Autowired private HttpServletRequest request; public void index(Map context) { context.put("configs", configDAO.findAllConfigsMap()); } - + public boolean update(Map context) { @SuppressWarnings("unchecked") - Map all = request.getParameterMap();; + Map all = request.getParameterMap(); + ; if (all != null && all.size() > 0) { - if (! User.ROOT.equals(currentUser.getRole())) { + if (!User.ROOT.equals(currentUser.getRole())) { context.put("message", getMessage("HaveNoRootPrivilege")); return false; } @@ -58,7 +58,7 @@ public boolean update(Map context) { for (Map.Entry entry : all.entrySet()) { String key = entry.getKey(); String[] values = entry.getValue(); - if (key != null && key.length() > 0 && ! key.startsWith("_")) { + if (key != null && key.length() > 0 && !key.startsWith("_")) { String value = ""; if (values != null && values.length > 0 && values[0] != null && values[0].length() > 0) { @@ -74,10 +74,10 @@ public boolean update(Map context) { } if (configs.size() > 0) { configDAO.update(configs); - + Set usernames = new HashSet(); usernames.add(currentUser.getName()); - + Map params = new HashMap(); params.put("configs", configs); } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysmanage/module/screen/Privileges.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysmanage/module/screen/Privileges.java index 1adb87b4d76..cd08c4a1d32 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysmanage/module/screen/Privileges.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysmanage/module/screen/Privileges.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.console-2.1.0-SNAPSHOT - * + *

* File Created at Sep 13, 2011 * $Id: Privileges.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 1999-2100 Alibaba.com Corporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -22,5 +22,5 @@ * */ public class Privileges extends Restful { - + } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysmanage/module/screen/Userown.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysmanage/module/screen/Userown.java index e9bfceac259..45de9aa8b78 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysmanage/module/screen/Userown.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysmanage/module/screen/Userown.java @@ -7,29 +7,29 @@ */ package com.alibaba.dubbo.governance.web.sysmanage.module.screen; -import java.util.List; -import java.util.Map; +import com.alibaba.dubbo.governance.service.OwnerService; +import com.alibaba.dubbo.governance.web.common.module.screen.Restful; import org.springframework.beans.factory.annotation.Autowired; -import com.alibaba.dubbo.governance.service.OwnerService; -import com.alibaba.dubbo.governance.web.common.module.screen.Restful; +import java.util.List; +import java.util.Map; /** * Providers. URI: /services/$service/owners - * + * * @author william.liangf */ public class Userown extends Restful { - @Autowired - private OwnerService ownerDAO; + @Autowired + private OwnerService ownerDAO; - public void index(Map context) { - String user = (String) context.get("user"); - List services; - services = ownerDAO.findServiceNamesByUsername(user); - context.put("user", user); - context.put("services", services); - } + public void index(Map context) { + String user = (String) context.get("user"); + List services; + services = ownerDAO.findServiceNamesByUsername(user); + context.put("user", user); + context.put("services", services); + } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/util/ContextUtil.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/util/ContextUtil.java index b1edc0e8e73..046a4eb6b25 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/util/ContextUtil.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/util/ContextUtil.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.console-2.1.0-SNAPSHOT - * + *

* File Created at Oct 31, 2011 * $Id: ContextUtil.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 1999-2100 Alibaba.com Corporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -23,13 +23,13 @@ * */ public class ContextUtil { - - private ContextUtil(Map c){ + + private ContextUtil(Map c) { } - - public static Object get(Map context, Object key, Object defaultv){ + + public static Object get(Map context, Object key, Object defaultv) { Object res = context.get(key); - if(res == null){ + if (res == null) { res = defaultv; } return res; diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/util/GovernanceWarmup.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/util/GovernanceWarmup.java index 254a542c585..8bcba351e6a 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/util/GovernanceWarmup.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/util/GovernanceWarmup.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.console-2.1.0-SNAPSHOT - * + *

* File Created at Nov 1, 2011 * $Id: GovernanceWarmup.java 182013 2012-06-26 10:32:43Z tony.chenl $ - * + *

* Copyright 1999-2100 Alibaba.com Corporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,13 +15,13 @@ */ package com.alibaba.dubbo.governance.web.util; -import org.springframework.beans.factory.InitializingBean; - import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.status.StatusChecker; import com.alibaba.dubbo.registry.common.StatusManager; +import org.springframework.beans.factory.InitializingBean; + /** * @author ding.lid */ @@ -52,8 +52,8 @@ public void afterPropertiesSet() throws Exception { StatusManager statusManager = StatusManager.getInstance(); - statusManager.addStatusHandler("memory",memoryStatusChecker); - statusManager.addStatusHandler("load",loadStatusChecker); + statusManager.addStatusHandler("memory", memoryStatusChecker); + statusManager.addStatusHandler("load", loadStatusChecker); // statusManager.addStatusHandler("database",databaseStatusChecker); // statusManager.addStatusHandler("cache",cacheStatusChecker); // statusManager.addStatusHandler("threadpool",threadPoolStatusChecker); @@ -63,42 +63,42 @@ public void afterPropertiesSet() throws Exception { // statusManager.addStatusHandler("timer",timerStatusChecker); // statusManager.addStatusHandler("warmup",warmupStatusChecker); } - + public void setMemoryStatusChecker(StatusChecker memoryStatusChecker) { this.memoryStatusChecker = memoryStatusChecker; } - + public void setThreadPoolStatusChecker(StatusChecker threadPoolStatusChecker) { this.threadPoolStatusChecker = threadPoolStatusChecker; } - + public void setCacheStatusChecker(StatusChecker cacheStatusChecker) { this.cacheStatusChecker = cacheStatusChecker; } - + public void setDatabaseStatusChecker(StatusChecker databaseStatusChecker) { this.databaseStatusChecker = databaseStatusChecker; } - + public void setFailureStatusChecker(StatusChecker failureStatusChecker) { this.failureStatusChecker = failureStatusChecker; } - + public void setLoadStatusChecker(StatusChecker loadStatusChecker) { this.loadStatusChecker = loadStatusChecker; } - + public void setSocketStatusChecker(StatusChecker socketStatusChecker) { SocketStatusChecker = socketStatusChecker; } - + public void setTimerStatusChecker(StatusChecker timerStatusChecker) { this.timerStatusChecker = timerStatusChecker; } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/util/Paginator.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/util/Paginator.java index 33e5891afb5..4cc6a7c526c 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/util/Paginator.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/util/Paginator.java @@ -1,8 +1,8 @@ /** * Function: 分页封装类,控制分页 - * + *

* File Created at 2011-6-10 - * + *

* Copyright 2011 Alibaba.com Croporation Limited. * All rights reserved. */ @@ -12,7 +12,7 @@ /** * TODO Comment of Paginator - * + * * @author guanghui.shigh */ public class Paginator implements Serializable, Cloneable { @@ -20,33 +20,33 @@ public class Paginator implements Serializable, Cloneable { private static final long serialVersionUID = 3688506614705500726L; // 每页默认的项数; 默认:10 - int itemsPerPage = 10; + int itemsPerPage = 10; // 滑动窗口默认的大小; 默认:7 - int sliderSize = 7; + int sliderSize = 7; // 当前页面; - int currentPage; + int currentPage; // 当前页面; - String path; + String path; // 总记录数 - int totalItems; + int totalItems; // 总页数 - int totalPage; + int totalPage; /** * 最简化的分页构造器。 - * + * * @param itemsPerPage 每页项数。 */ - public Paginator(int currentPage, int totalItems, String path){ + public Paginator(int currentPage, int totalItems, String path) { initPagination(currentPage, totalItems, 0, 0, path); } - public Paginator(String currentPage, int totalItems, String path){ + public Paginator(String currentPage, int totalItems, String path) { int currentPageTemp = 1; if (!(currentPage == null || currentPage.equals(""))) { currentPageTemp = Integer.parseInt(currentPage); @@ -56,7 +56,7 @@ public Paginator(String currentPage, int totalItems, String path){ /** * 完整的分页构造器。 - * + * * @param currentPage 。 * @param totalItems(必须项) 记录总数,大于等于0 * @param sliderSize @@ -80,7 +80,7 @@ public int getItemsPerPage() { /** * 取得指定大小的页码滑动窗口,并将当前页尽可能地放在滑动窗口的中间部位。例如: 总共有13页,当前页是第5页,取得一个大小为5的滑动窗口,将包括 3,4,5,6, 7这几个页码,第5页被放在中间。如果当前页是12,则返回页码为 * 9,10,11,12,13。 - * + * * @return 包含页码的数组,如果指定滑动窗口大小小于1或总页数为0,则返回空数组。 */ public int[] getSlider() { @@ -119,7 +119,7 @@ public String getPaginatorBar() { StringBuffer str = new StringBuffer("

"); str.append(""); + + "/pages/\" + page;}"); // 生成翻页部分 // 1. 总记录数 @@ -175,7 +175,7 @@ public String getPaginatorBar() { /** * 获得起始记录 - * + * * @return */ public int getStartIndex() { diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/util/UrlUtils.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/util/UrlUtils.java index a9c2b642bff..6afcf042df6 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/util/UrlUtils.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/util/UrlUtils.java @@ -20,7 +20,7 @@ /** * UrlUtils.java - * + * * @author tony.chenl */ public class UrlUtils { @@ -57,5 +57,5 @@ public static String arrayToString(String[] values) { } return paramsString.toString(); } - + } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/util/WebConstants.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/util/WebConstants.java index 6304d6a66e4..801705f7159 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/util/WebConstants.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/util/WebConstants.java @@ -4,51 +4,43 @@ /** * 包含在web层用到的常量 - * + * * @author guanghui.shigh */ public class WebConstants { - - Map context; - - /** + + /** * 在session中保存当前用户对象的key。 */ public static final String CURRENT_USER_KEY = "currentUser"; - /** * 当前的挂号服务器地址 */ - public static final String REGISTRY_ADDRESS = "registryAddress"; - - /** + public static final String REGISTRY_ADDRESS = "registryAddress"; + /** * 服务暴露地址 */ public static final String SERVICE_URL = "serviceUrl"; - /** * 服务名称 */ public static final String SERVICE_NAME = "serviceName"; - /** * 服务名称 */ public static final String ENTRY = "entry"; - /** * buc sso 登出地址 */ public static final String SSO_LOGOUT_URL = "SSO_LOGOUT_URL"; - /** * buc sso 用户名 */ public static final String BUC_SSO_USERNAME = "buc_sso_username"; - /** - * 操作记录页面默认页面记录显示条数 - */ - public static final Integer OPRATION_RECORDS_PAGE_SIZE = 100; - + * 操作记录页面默认页面记录显示条数 + */ + public static final Integer OPRATION_RECORDS_PAGE_SIZE = 100; + Map context; + } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/ChangeListener.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/ChangeListener.java index 32f82257f87..45a2da177a8 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/ChangeListener.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/ChangeListener.java @@ -2,12 +2,12 @@ public interface ChangeListener { - /** - * 数据变更 - * - * @param type 数据类型 - * @param services 影响的服务 - */ - void onChanged(String type); + /** + * 数据变更 + * + * @param type 数据类型 + * @param services 影响的服务 + */ + void onChanged(String type); } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/StatusManager.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/StatusManager.java index db73b719f29..45df139bccf 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/StatusManager.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/StatusManager.java @@ -1,12 +1,12 @@ /** * Project: dubbo.core.service.server-1.0.5-SNAPSHOT - * + *

* File Created at 2009-12-27 * $Id: StatusManager.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,32 +15,62 @@ */ package com.alibaba.dubbo.registry.common; +import com.alibaba.dubbo.common.status.Status; +import com.alibaba.dubbo.common.status.Status.Level; +import com.alibaba.dubbo.common.status.StatusChecker; + import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import com.alibaba.dubbo.common.status.Status; -import com.alibaba.dubbo.common.status.Status.Level; -import com.alibaba.dubbo.common.status.StatusChecker; - /** * StatusManager - * + * * @author william.liangf */ public class StatusManager { - + private static final StatusManager INSTANCE = new StatusManager(); + private final Map statusHandlers = new ConcurrentHashMap(); + + private StatusManager() { + } public static StatusManager getInstance() { return INSTANCE; } - private StatusManager() {} - - private final Map statusHandlers = new ConcurrentHashMap(); - + public static Status getStatusSummary(Map statusList) { + return getSummaryStatus(statusList); + } + + public static Status getSummaryStatus(Map statuses) { + Level level = Level.OK; + StringBuilder msg = new StringBuilder(); + for (Map.Entry entry : statuses.entrySet()) { + String key = entry.getKey(); + Status status = entry.getValue(); + Level l = status.getLevel(); + if (Level.ERROR.equals(l)) { + level = Level.ERROR; + if (msg.length() > 0) { + msg.append(","); + } + msg.append(key); + } else if (Level.WARN.equals(l)) { + if (!Level.ERROR.equals(level)) { + level = Level.WARN; + } + if (msg.length() > 0) { + msg.append(","); + } + msg.append(key); + } + } + return new Status(level, msg.toString()); + } + public void addStatusHandler(String name, StatusChecker statusHandler) { this.statusHandlers.put(name, statusHandler); } @@ -48,7 +78,7 @@ public void addStatusHandler(String name, StatusChecker statusHandler) { public void addStatusHandlers(Map statusHandlers) { this.statusHandlers.putAll(statusHandlers); } - + public void addStatusHandlers(Collection statusHandlers) { for (StatusChecker statusChecker : statusHandlers) { String name = statusChecker.getClass().getSimpleName(); @@ -66,11 +96,11 @@ public void removeStatusHandler(String name) { public void clearStatusHandlers() { this.statusHandlers.clear(); } - + public Map getStatusList() { return getStatusList(null); } - + /** * 过滤不需要汇总页面的监控项 */ @@ -78,45 +108,15 @@ public Map getStatusList(String[] excludes) { Map statuses = new HashMap(); Map temp = new HashMap(); temp.putAll(statusHandlers); - if(excludes != null&&excludes.length>0){ - for(String exclude : excludes){ + if (excludes != null && excludes.length > 0) { + for (String exclude : excludes) { temp.remove(exclude); } } for (Map.Entry entry : temp.entrySet()) { - statuses.put(entry.getKey(), entry.getValue().check()); + statuses.put(entry.getKey(), entry.getValue().check()); } return statuses; } - public static Status getStatusSummary(Map statusList) { - return getSummaryStatus(statusList); - } - - public static Status getSummaryStatus(Map statuses) { - Level level = Level.OK; - StringBuilder msg = new StringBuilder(); - for (Map.Entry entry : statuses.entrySet()) { - String key = entry.getKey(); - Status status = entry.getValue(); - Level l = status.getLevel(); - if (Level.ERROR.equals(l)) { - level = Level.ERROR; - if (msg.length() > 0) { - msg.append(","); - } - msg.append(key); - } else if (Level.WARN.equals(l)) { - if(! Level.ERROR.equals(level)) { - level = Level.WARN; - } - if (msg.length() > 0) { - msg.append(","); - } - msg.append(key); - } - } - return new Status(level, msg.toString()); - } - } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Access.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Access.java index fb7a518fdab..6118875ca56 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Access.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Access.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.server-2.0.0-SNAPSHOT - * + *

* File Created at 2010-7-14 * $Id: Access.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 2010 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -16,58 +16,58 @@ package com.alibaba.dubbo.registry.common.domain; /** - * + * * @author william.liangf */ public class Access extends Entity { - private static final long serialVersionUID = -962351722638094446L; + private static final long serialVersionUID = -962351722638094446L; + + private String service; /*服务名*/ + + private String address; /*消费者地址*/ - private String service; /*服务名*/ - - private String address; /*消费者地址*/ - private boolean allow; /*状态*/ - + private String username; /*用户名*/ - + public Access() { } - + public Access(Long id) { super(id); } - - public String getService() { - return service; - } - - public void setService(String service) { - this.service = service; - } - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - - public boolean isAllow() { - return allow; - } - - public void setAllow(boolean allow) { - this.allow = allow; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } + + public String getService() { + return service; + } + + public void setService(String service) { + this.service = service; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public boolean isAllow() { + return allow; + } + + public void setAllow(boolean allow) { + this.allow = allow; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Agreement.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Agreement.java index 1c1657b6f67..cbab7aacf49 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Agreement.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Agreement.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.server-1.1.0-SNAPSHOT - * + *

* File Created at 2010-7-14 * $Id: Agreement.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -17,35 +17,35 @@ /** * 指定应用的服务质量等级协定(SLA)对象。 - * + * * @author rain.chenjr * @author ding.lid */ -public class Agreement extends Entity{ +public class Agreement extends Entity { private static final long serialVersionUID = -4888604682731513790L; - + private String service; //服务名 - + private String consumerApplication; // 服务消费者应用名 - + private long invocationQuantity; // 一天调用量 private int tps; // TPS上限 - + private int responseTime; // 响应时间,毫秒 - + private double availability; // 可用率 - - private String username; + + private String username; public Agreement() { } - + public Agreement(Long id) { super(id); } - + public String getService() { return service; } @@ -101,5 +101,5 @@ public String getUsername() { public void setUsername(String username) { this.username = username; } - + } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Approval.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Approval.java index 3f23c42e17d..30726976c46 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Approval.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Approval.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.server-2.1.0-SNAPSHOT - * + *

* File Created at Sep 14, 2011 * $Id: Approval.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 1999-2100 Alibaba.com Corporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -17,26 +17,26 @@ /** * 服务上线审批。 - * + * * @author ding.lid */ public class Approval extends Entity { private static final long serialVersionUID = -8778092807313048367L; - + private String service; // 服务名称 - - private String version; + + private String version; // 可以使用通配符, *,1.1.* // 可以包含多个 1.1.3,1.1.5,2.* - + private boolean forProvider; // is Provider or consumer - + private String machineList; // 服务所在机器 // 可以使用通配符 172.3.8.* // 可以有多个 172.1.9.8,172.1.9.123,172.3.3.* - + private String username; - + private String approveUser; // 审批者 public String getService() { diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/ApprovalRequisition.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/ApprovalRequisition.java index bf1fbcba85d..9634fdeb8dc 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/ApprovalRequisition.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/ApprovalRequisition.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.server-2.1.0-SNAPSHOT - * + *

* File Created at Sep 14, 2011 * $Id: ApprovalRequisition.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 1999-2100 Alibaba.com Corporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -17,28 +17,28 @@ /** * 服务上线申请。 - * + * * @author ding.lid */ public class ApprovalRequisition extends Entity { private static final long serialVersionUID = -8778092807313048367L; - + private char operation; // 申请操作:新增(C),修改(U),删除(D) - - private Long approvalId; - + + private Long approvalId; + private String service; // 服务名称 - - private String version; + + private String version; // 可以使用通配符, *,1.1.* // 可以包含多个 1.1.3,1.1.5,2.* - + private boolean forProvider; - + private String machineList; // 服务所在机器 // 可以使用通配符 172.3.8.* // 可以有多个 172.1.9.8,172.1.9.123,172.3.3.* - + private String username; public char getOperation() { diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Change.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Change.java index 04f84886eee..c79486b19d9 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Change.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Change.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry-1.1.0-SNAPSHOT - * + *

* File Created at 2010-4-9 * $Id: Change.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -17,48 +17,33 @@ /** * 服务变更信息对象 - * + * * @author rain.chenjr */ public class Change extends Entity { - private static final long serialVersionUID = 15528419903956898L; - public static final String PROVIDER_TYPE = "P"; //服务提供变更 - public static final String CONSUMER_TYPE = "N"; //服务消费者变更 - public static final String ROUTE_TYPE = "R"; //路由变更 - public static final String WEIGHT_TYPE = "W"; //权重变更 - public static final String LOADBALANCE_TYPE = "L"; //负载均衡变更 - public static final String CLUSTER_TYPE = "G"; //分组变更 - public static final String USER_TYPE = "U"; //用户变更 - public static final String CONFIG_TYPE = "C"; //系统配置变更 - public static final String FEATURE_TYPE = "F"; //系统功能变更 - public static final String LAYER_TYPE = "Y"; //系统功能变更 - public static final String TEST_TYPE = "T"; //服务测试变更 - public static final String MOCK_TYPE = "M"; //服务测试变更 - public static final String ACCESS_TYPE = "A"; //服务访问控制变更 - public static final String OVERRIDE_TYPE = "O"; //参数覆盖变更 - - private String type; /* 变更类型 */ + private static final long serialVersionUID = 15528419903956898L; + private String type; /* 变更类型 */ + + private String service; /* 服务名称 */ - private String service; /* 服务名称 */ - - private long sequence; /* 变更序号 */ - - private String data; /* 变更内容 */ + private long sequence; /* 变更序号 */ + + private String data; /* 变更内容 */ public Change() { } @@ -66,7 +51,7 @@ public Change() { public Change(Long id) { super(id); } - + public Change(String type, String serviceName) { this.type = type; this.service = serviceName; @@ -92,17 +77,17 @@ public void setService(String service) { /** * 用change的id作为sequence */ - public long getSequence() { - return sequence; - } + public long getSequence() { + return sequence; + } @Deprecated /** * 用change的id作为sequence */ - public void setSequence(long sequence) { - this.sequence = sequence; - } + public void setSequence(long sequence) { + this.sequence = sequence; + } public String getData() { return data; diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Cluster.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Cluster.java index bdf46e833d8..52329560019 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Cluster.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Cluster.java @@ -2,12 +2,12 @@ public class Cluster extends Entity { - private static final long serialVersionUID = 8704571999015097948L; - - private String name; /* 服务提供者分组名 ,一个分组可以包含若干个提供者*/ - + private static final long serialVersionUID = 8704571999015097948L; + + private String name; /* 服务提供者分组名 ,一个分组可以包含若干个提供者*/ + private String address; /* 客户端地址 */ - + private String username; public Cluster() { @@ -16,14 +16,14 @@ public Cluster() { public Cluster(Long id) { super(id); } - - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } public String getUsername() { return username; diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Config.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Config.java index 70b19ff0d53..3cc6c643688 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Config.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Config.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.server-1.1.0-SNAPSHOT - * + *

* File Created at 2010-6-30 * $Id: Config.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -20,86 +20,49 @@ * @author rain.chenjr * */ -public class Config extends Entity{ +public class Config extends Entity { - private static final long serialVersionUID = 7938303018328907548L; - public static final String MAIL_ENABLED = "MailEnabled"; //是否允许匿名登录 - public static final String MAIL_HOST = "MailHost"; //是否允许匿名登录 - public static final String MAIL_PORT = "MailPort"; //是否允许匿名登录 - public static final String MAIL_FROM = "MailFrom"; //是否允许匿名登录 - public static final String MAIL_AUTH = "MailAuth"; //是否允许匿名登录 - public static final String MAIL_USERNAME = "MailUsername"; //是否允许匿名登录 - public static final String MAIL_PASSWORD = "MailPassword"; //是否允许匿名登录 - public static final String BULLETIN_MESSAGE = "BulletinMessage"; //是否允许匿名登录 - public static final String ALLOW_ANONYMOUS_LOGIN = "AllowAnonymousLogin"; //是否允许匿名登录 - public static final String ALLOW_LEGACY_LOGIN = "AllowLegacyLogin"; //是否允许遗留系统登录 - public static final String MAX_THREAD_SIZE = "MaxThreadSize"; // 最大线程数 - public static final String MAX_CONNECTION_SIZE = "MaxConnectionSize"; // 最大连接数 - public static final String MAX_CACHE_SIZE = "MaxCacheSize"; // 最大缓存数 - public static final String MAX_MAIL_SIZE = "MaxMailSize"; // 最大邮件队列数 - public static final String ALIVED_CHECK_INTERVAL = "AlivedCheckInterval"; - public static final String DIRTY_CHECK_INTERVAL = "DirtyCheckInterval"; - public static final String CHANGED_CHECK_INTERVAL = "ChangedCheckInterval"; - public static final String CHANGED_CLEAR_INTERVAL = "ChangedClearInterval"; - public static final String FAILED_RETRY_INTERVAL = "FailedRetryInterval"; - public static final String HEARTBEAT_CHECK_INTERVAL = "HeartbeatCheckInterval";//心跳检查间隔 - public static final String HEARTBEAT_CHECK_TIMEOUT = "HeartbeatCheckTimeout";//心跳超时时间 - public static final String WARMUP_WAIT_TIME = "WarmupWaitTime"; - public static final String AUTO_REDIRECT_INTERVAL = "AutoRedirectInterval"; - public static final String AUTO_REDIRECT_THRESHOLD = "AutoRedirectThreshold"; - public static final String AUTO_REDIRECT_TOLERATE_PERCENT = "AutoRedirectToleratePercent"; - public static final String NOTIFY_TIMEOUT = "NotifyTimeout"; - public static final String ROUTE_ENABLED = "RouteEnabled"; - public static final String BUC_SERVICE_ADDRESS = "BucServiceAddress"; - public static final String DEFAULT_SERVICE_PARAMETERS = "DefaultServiceParameters"; - public static final String WARM_UP_ENABLED = "WarmupEnabled"; - public static final String HELP_DOCUMENT_URL = "HelpDocumentUrl"; - public static final String HOMEPAGE_DOMAIN = "HomepageDomain"; - public static final String HOMEPAGE_URL = "HomepageUrl"; - public static final String LOG_LEVEL = "LogLevel"; // 日志级别 - - public static final String DEFAULT_ROLE= "DefaultRole"; // 默认创建用户的权限 - + public static final String DEFAULT_ROLE = "DefaultRole"; // 默认创建用户的权限 public static final String SERVER_ROUTE_ENABLED = "ServerRouteEnabled"; - + private static final long serialVersionUID = 7938303018328907548L; private String key; - + private String value; - + private String username; public String getKey() { @@ -126,9 +89,9 @@ public void setUsername(String username) { this.username = username; } - @java.lang.Override - public String toString() { - return key + "=" + value; - } - + @java.lang.Override + public String toString() { + return key + "=" + value; + } + } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Consumer.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Consumer.java index d7d6edcc38b..727f2755d3b 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Consumer.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Consumer.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry-1.1.0-SNAPSHOT - * + *

* File Created at 2010-4-9 * $Id: Consumer.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,17 +15,17 @@ */ package com.alibaba.dubbo.registry.common.domain; -import java.util.Date; -import java.util.List; -import java.util.Map; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.utils.StringUtils; +import java.util.Date; +import java.util.List; +import java.util.Map; + /** * Consumer - * + * * @author william.liangf */ public class Consumer extends Entity { @@ -35,31 +35,31 @@ public class Consumer extends Entity { private String service; /* 消费者所引用的服务名称 */ private String parameters; - + private String result; /*路由结果*/ private String address; /* 消费者地址 */ - - private String registry; /* 消费者连接的注册中心地址 */ - + + private String registry; /* 消费者连接的注册中心地址 */ + private String application; /* 应用名 */ private String username; /* 消费者用户名 */ - + private String statistics; /* 服务调用统计信息 */ - - private Date collected; /* 服务调用统计时间 */ - private Override override; + private Date collected; /* 服务调用统计时间 */ + + private Override override; - private List overrides; + private List overrides; private List routes; - + private List providers; - - private Date expired; /*过期时间*/ - + + private Date expired; /*过期时间*/ + private long alived; /*存活时间,单位秒*/ public Consumer() { @@ -145,52 +145,52 @@ public Date getExpired() { return expired; } - + public void setExpired(Date expired) { this.expired = expired; } - + public long getAlived() { return alived; } - + public void setAlived(long alived) { this.alived = alived; } - public Override getOverride() { - return override; - } + public Override getOverride() { + return override; + } - public void setOverride(Override override) { - this.override = override; - } + public void setOverride(Override override) { + this.override = override; + } public List getOverrides() { - return overrides; - } + return overrides; + } - public void setOverrides(List overrides) { - this.overrides = overrides; - } + public void setOverrides(List overrides) { + this.overrides = overrides; + } public List getRoutes() { - return routes; - } + return routes; + } - public void setRoutes(List routes) { - this.routes = routes; - } + public void setRoutes(List routes) { + this.routes = routes; + } - public List getProviders() { - return providers; - } + public List getProviders() { + return providers; + } - public void setProviders(List providers) { - this.providers = providers; - } + public void setProviders(List providers) { + this.providers = providers; + } public String toString() { return "Consumer [service=" + service + ", parameters=" + parameters + ", result=" + result @@ -199,7 +199,7 @@ public String toString() { + ", collected=" + collected + ", routes=" + routes + ", overrides=" + overrides + ", expired=" + expired + ", alived=" + alived + "]"; } - + public URL toUrl() { String group = null; String version = null; @@ -222,7 +222,7 @@ public URL toUrl() { if (version != null) { param.put(Constants.VERSION_KEY, version); } - return URL.valueOf(Constants.CONSUMER_PROTOCOL + "://" + address + "/" + path + return URL.valueOf(Constants.CONSUMER_PROTOCOL + "://" + address + "/" + path + "?" + StringUtils.toQueryString(param)); } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/DependItem.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/DependItem.java index 76006dc5e6c..8e6c53ba64a 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/DependItem.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/DependItem.java @@ -20,24 +20,20 @@ /** * DependItem - * + * * @author william.liangf */ public class DependItem { + private final List recursives = new ArrayList(); private String application; - private int index; - private int level; - private DependItem parent; - private final List recursives = new ArrayList(); - public DependItem() { } - + public DependItem(String application, int level) { this.application = application; this.level = level; @@ -85,7 +81,7 @@ public void setParent(DependItem parent) { public List getRecursives() { return recursives; } - + public void addRecursive(int padding, int value) { while (recursives.size() < padding) { recursives.add(0); diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Dependency.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Dependency.java index 06af878e20b..2618a67a2f7 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Dependency.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Dependency.java @@ -4,26 +4,26 @@ public class Dependency implements Serializable { - private static final long serialVersionUID = 8526869025719540547L; + private static final long serialVersionUID = 8526869025719540547L; - private String providerApplication; - - private String consumerApplication; + private String providerApplication; - public String getProviderApplication() { - return providerApplication; - } + private String consumerApplication; - public void setProviderApplication(String providerApplication) { - this.providerApplication = providerApplication; - } + public String getProviderApplication() { + return providerApplication; + } - public String getConsumerApplication() { - return consumerApplication; - } + public void setProviderApplication(String providerApplication) { + this.providerApplication = providerApplication; + } - public void setConsumerApplication(String consumerApplication) { - this.consumerApplication = consumerApplication; - } + public String getConsumerApplication() { + return consumerApplication; + } + + public void setConsumerApplication(String consumerApplication) { + this.consumerApplication = consumerApplication; + } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Document.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Document.java index e5604d53bb8..19de3a06a7d 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Document.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Document.java @@ -1,11 +1,11 @@ /** * Project: dubbo.registry.server-1.1.0-SNAPSHOT - * + *

* File Created at 2010-6-29 - * + *

* Copyright 1999-2010 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -16,19 +16,15 @@ /** * Document - * + * * @author william.liangf */ public class Document extends Entity { - private static final long serialVersionUID = 5059135057592486874L; - public static final String EXTERNAL_TYPE = "E"; - public static final String INTERNAL_TYPE = "I"; - public static final String API_TYPE = "A"; - + private static final long serialVersionUID = 5059135057592486874L; private String service; private String title; @@ -36,7 +32,7 @@ public class Document extends Entity { private String type; private String content; - + private String username; public Document() { @@ -45,7 +41,7 @@ public Document() { public Document(Long id) { super(id); } - + public String getTitle() { return title; } @@ -78,12 +74,12 @@ public void setUsername(String username) { this.username = username; } - public String getService() { - return service; - } + public String getService() { + return service; + } - public void setService(String service) { - this.service = service; - } + public void setService(String service) { + this.service = service; + } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Entity.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Entity.java index c1ca4c9300e..080b716fc7c 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Entity.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Entity.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry-1.1.0-SNAPSHOT - * + *

* File Created at 2010-4-9 * $Id: Entity.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -21,51 +21,51 @@ /** * Entity - * + * * @author william.liangf */ public abstract class Entity implements Serializable { - private static final long serialVersionUID = -3031128781434583143L; - - private List ids; + private static final long serialVersionUID = -3031128781434583143L; + + private List ids; - private Long id; + private Long id; - private Date created; + private Date created; private Date modified; - + private Date now; - + private String operator; - + private String operatorAddress; - + private boolean miss; - + public Entity() { } - + public Entity(Long id) { this.id = id; } - - public List getIds() { - return ids; - } - public void setIds(List ids) { - this.ids = ids; - } + public List getIds() { + return ids; + } + + public void setIds(List ids) { + this.ids = ids; + } public Long getId() { - return id; - } + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } public Date getCreated() { return created; @@ -83,29 +83,29 @@ public void setModified(Date modified) { this.modified = modified; } - public Date getNow() { - return now; - } + public Date getNow() { + return now; + } - public void setNow(Date now) { - this.now = now; - } + public void setNow(Date now) { + this.now = now; + } - public String getOperator() { - return operator; - } + public String getOperator() { + return operator; + } + + public void setOperator(String operator) { + if (operator != null && operator.length() > 200) { + operator = operator.substring(0, 200); + } + this.operator = operator; + } - public void setOperator(String operator) { - if (operator != null && operator.length() > 200) { - operator = operator.substring(0, 200); - } - this.operator = operator; - } - public String getOperatorAddress() { return operatorAddress; } - + public void setOperatorAddress(String operatorAddress) { this.operatorAddress = operatorAddress; } @@ -113,7 +113,7 @@ public void setOperatorAddress(String operatorAddress) { public boolean isMiss() { return miss; } - + public void setMiss(boolean miss) { this.miss = miss; } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Favorite.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Favorite.java index d8124b72abc..3cfeae9563f 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Favorite.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Favorite.java @@ -2,14 +2,14 @@ public class Favorite extends Entity { - private static final long serialVersionUID = -1281982267153430266L; - + private static final long serialVersionUID = -1281982267153430266L; + private String name; - + private String url; - + private String username; - + public Favorite() { } @@ -17,28 +17,28 @@ public Favorite(Long id) { super(id); } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getUrl() { - return url; - } + public String getUrl() { + return url; + } - public void setUrl(String url) { - this.url = url; - } + public void setUrl(String url) { + this.url = url; + } public String getUsername() { return username; } - + public void setUsername(String username) { this.username = username; } - + } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Feature.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Feature.java index d03e19def7d..2ca35ffd926 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Feature.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Feature.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.server-1.1.0-SNAPSHOT - * + *

* File Created at 2010-6-30 * $Id: Feature.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -20,14 +20,14 @@ * * @author ding.lid */ -public class Feature extends Entity{ - +public class Feature extends Entity { + private static final long serialVersionUID = 3246619851259746169L; private String name; - + private boolean enabled; - + private String username; public Feature() { @@ -36,7 +36,7 @@ public Feature() { public Feature(Long id) { super(id); } - + public String getName() { return name; } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Layer.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Layer.java index ffd8c89901d..136e9a3ab5c 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Layer.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Layer.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.server-2.1.0-SNAPSHOT - * + *

* File Created at Sep 1, 2011 * $Id: Layer.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 1999-2100 Alibaba.com Corporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -21,11 +21,18 @@ public class Layer extends Entity { private static final long serialVersionUID = 6114868933223039253L; - private String username; + private String username; - private String arch; - private String name; - private int value; + private String arch; + private String name; + private int value; + + public Layer(Long id) { + super(id); + } + + public Layer() { + } public String getUsername() { return username; @@ -58,11 +65,4 @@ public int getValue() { public void setValue(int value) { this.value = value; } - - public Layer(Long id) { - super(id); - } - - public Layer() { - } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/LoadBalance.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/LoadBalance.java index 1d83f89e405..7e173506f1d 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/LoadBalance.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/LoadBalance.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.server-1.1.0-SNAPSHOT - * + *

* File Created at 2010-10-21 * $Id: LoadBalance.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -20,19 +20,17 @@ * @author rain.chenjr * */ -public class LoadBalance extends Entity{ +public class LoadBalance extends Entity { - private static final long serialVersionUID = -6050324375352581440L; - public static final String ALL_METHOD = "*"; + private static final long serialVersionUID = -6050324375352581440L; + private String service; /* 服务名称 */ + + private String method; /* 方法名称 */ - private String service; /* 服务名称 */ - - private String method; /* 方法名称 */ - - private String strategy; /*负载均衡策略*/ - - private String username; /*用户名*/ + private String strategy; /*负载均衡策略*/ + + private String username; /*用户名*/ public LoadBalance() { } @@ -40,7 +38,7 @@ public LoadBalance() { public LoadBalance(Long id) { super(id); } - + public String getService() { return service; } @@ -73,5 +71,5 @@ public void setUsername(String username) { this.username = username; } - + } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Mock.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Mock.java index 1c74d607a0f..2a506c9248c 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Mock.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Mock.java @@ -1,8 +1,7 @@ /** - * * Copyright 1999-2011 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -13,38 +12,38 @@ /** * Mock - * + * * @author guanghui.shigh */ public class Mock extends Entity { private static final long serialVersionUID = 872527738197173003L; - - private String name; - - private String service; - private String method; + private String name; + + private String service; + + private String method; - private String parameters; + private String parameters; - private boolean exception; + private boolean exception; - private String result; + private String result; - private String username; + private String username; + + private boolean autoRun; + + private String consumerAddr; - private boolean autoRun; - - private String consumerAddr; - public Mock() { } public Mock(Long id) { super(id); } - + public String getService() { return service; } @@ -69,7 +68,7 @@ public void setParameters(String parameters) { this.parameters = parameters; } - public String getResult() { + public String getResult() { return result; } @@ -85,36 +84,36 @@ public void setUsername(String username) { this.username = username; } - public boolean isException() { - return exception; - } + public boolean isException() { + return exception; + } - public void setException(boolean exception) { - this.exception = exception; - } + public void setException(boolean exception) { + this.exception = exception; + } - public boolean isAutoRun() { - return autoRun; - } + public boolean isAutoRun() { + return autoRun; + } - public void setAutoRun(boolean autoRun) { - this.autoRun = autoRun; - } + public void setAutoRun(boolean autoRun) { + this.autoRun = autoRun; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getConsumerAddr() { - return consumerAddr; - } + public String getConsumerAddr() { + return consumerAddr; + } - public void setConsumerAddr(String consumerAddr) { - this.consumerAddr = consumerAddr; - } + public void setConsumerAddr(String consumerAddr) { + this.consumerAddr = consumerAddr; + } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Operation.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Operation.java index f08536dfebe..39560be024d 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Operation.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Operation.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.server-1.1.0-SNAPSHOT - * + *

* File Created at 2010-6-28 * $Id: Operation.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -25,52 +25,34 @@ * */ public class Operation extends Entity { - - private static final long serialVersionUID = 8220325876753890396L; public static final String PROVIDER_TYPE = "Provider"; - public static final String CONSUMER_TYPE = "Consumer"; - public static final String ROUTE_TYPE = "Route"; - public static final String WEIGHT_TYPE = "Weight"; - public static final String CLUSTER_TYPE = "Cluster"; - public static final String DOCUMENT_TYPE = "Document"; - public static final String LOADBALANCE_TYPE = "LoadBalance"; - public static final String TEST_TYPE = "Test"; - public static final String MOCK_TYPE = "Mock"; - public static final String AGREEMENT_TYPE = "Agreement"; - public static final String APPROVAL_TYPE = "Approval"; - public static final String APPROVAL_REQUISITION_TYPE = "ApprovalRequisition"; - public static final String USER_TYPE = "User"; - public static final String FEATURE_TYPE = "Feature"; - public static final String LAYER_TYPE = "Layer"; - public static final String CONFIG_TYPE = "Config"; - - public static final List TYPES = - Collections.unmodifiableList(Arrays.asList(new String[] {PROVIDER_TYPE, CONSUMER_TYPE, ROUTE_TYPE, WEIGHT_TYPE, - CLUSTER_TYPE, DOCUMENT_TYPE, LOADBALANCE_TYPE, TEST_TYPE, - AGREEMENT_TYPE, USER_TYPE, FEATURE_TYPE, CONFIG_TYPE})); - + public static final List TYPES = + Collections.unmodifiableList(Arrays.asList(new String[]{PROVIDER_TYPE, CONSUMER_TYPE, ROUTE_TYPE, WEIGHT_TYPE, + CLUSTER_TYPE, DOCUMENT_TYPE, LOADBALANCE_TYPE, TEST_TYPE, + AGREEMENT_TYPE, USER_TYPE, FEATURE_TYPE, CONFIG_TYPE})); + private static final long serialVersionUID = 8220325876753890396L; private String username; //操作者 - + private String dataType; //数据类型,如route,cluster - + private String operateType; //操作类型,如删除、修改 、创建 - + private String data; //记录数据信息 public Operation() { @@ -79,7 +61,7 @@ public Operation() { public Operation(Long id) { super(id); } - + public String getUsername() { return username; } @@ -101,9 +83,9 @@ public String getData() { } public void setData(String data) { - if (data != null && data.length() > 1000) { - data = data.substring(0, 1000); - } + if (data != null && data.length() > 1000) { + data = data.substring(0, 1000); + } this.data = data; } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Override.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Override.java index 778064a0ac1..1d8b99129a1 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Override.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Override.java @@ -15,73 +15,73 @@ */ package com.alibaba.dubbo.registry.common.domain; -import java.util.Map; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.utils.StringUtils; +import java.util.Map; + /** * @author tony.chenl */ public class Override extends Entity { - + private static final long serialVersionUID = 114828505391757846L; private String service; - + private String params; - + private String application; - + private String address; - + private String username; - + private boolean enabled; - - public Override(){ + + public Override() { } - public Override(long id){ + public Override(long id) { super(id); } - + public String getService() { return service; } - + public void setService(String service) { this.service = service; } - + public String getParams() { return params; } - + public void setParams(String params) { this.params = params; } - + public String getApplication() { return application; } - + public void setApplication(String application) { this.application = application; } - + public String getAddress() { return address; } - + public void setAddress(String address) { this.address = address; } @@ -94,12 +94,12 @@ public void setUsername(String username) { this.username = username; } - + public boolean isEnabled() { return enabled; } - + public void setEnabled(boolean enabled) { this.enabled = enabled; } @@ -108,55 +108,55 @@ public String toString() { return "Override [service=" + service + ", params=" + params + ", application=" + application + ", address=" + address + ", username=" + username + ", enabled=" + enabled + "]"; } - + public boolean isDefault() { - return (getAddress() == null || getAddress().length() == 0 || Constants.ANY_VALUE.equals(getAddress()) || Constants.ANYHOST_VALUE.equals(getAddress())) - && (getApplication() == null || getApplication().length() == 0 || Constants.ANY_VALUE.equals(getApplication())); + return (getAddress() == null || getAddress().length() == 0 || Constants.ANY_VALUE.equals(getAddress()) || Constants.ANYHOST_VALUE.equals(getAddress())) + && (getApplication() == null || getApplication().length() == 0 || Constants.ANY_VALUE.equals(getApplication())); } - + public boolean isMatch(String service, String address, String application) { - return isEnabled() && getParams() != null && getParams().length() > 0 - && service.equals(getService()) - && (address == null || getAddress() == null || getAddress().length() == 0 || getAddress().equals(Constants.ANY_VALUE) || getAddress().equals(Constants.ANYHOST_VALUE) || getAddress().equals(address)) - && (application == null || getApplication() == null || getApplication().length() == 0 || getApplication().equals(Constants.ANY_VALUE) || getApplication().equals(application)); + return isEnabled() && getParams() != null && getParams().length() > 0 + && service.equals(getService()) + && (address == null || getAddress() == null || getAddress().length() == 0 || getAddress().equals(Constants.ANY_VALUE) || getAddress().equals(Constants.ANYHOST_VALUE) || getAddress().equals(address)) + && (application == null || getApplication() == null || getApplication().length() == 0 || getApplication().equals(Constants.ANY_VALUE) || getApplication().equals(application)); } - + public boolean isUniqueMatch(Provider provider) { - return isEnabled() && getParams() != null && getParams().length() > 0 - && provider.getService().equals(getService()) - && provider.getAddress().equals(getAddress()); + return isEnabled() && getParams() != null && getParams().length() > 0 + && provider.getService().equals(getService()) + && provider.getAddress().equals(getAddress()); } - + public boolean isMatch(Provider provider) { - return isEnabled() && getParams() != null && getParams().length() > 0 - && provider.getService().equals(getService()) - && (getAddress() == null || getAddress().length() == 0 || getAddress().equals(Constants.ANY_VALUE) || getAddress().equals(Constants.ANYHOST_VALUE) || getAddress().equals(provider.getAddress())) - && (getApplication() == null || getApplication().length() == 0 || getApplication().equals(Constants.ANY_VALUE) || getApplication().equals(provider.getApplication())); + return isEnabled() && getParams() != null && getParams().length() > 0 + && provider.getService().equals(getService()) + && (getAddress() == null || getAddress().length() == 0 || getAddress().equals(Constants.ANY_VALUE) || getAddress().equals(Constants.ANYHOST_VALUE) || getAddress().equals(provider.getAddress())) + && (getApplication() == null || getApplication().length() == 0 || getApplication().equals(Constants.ANY_VALUE) || getApplication().equals(provider.getApplication())); } public boolean isUniqueMatch(Consumer consumer) { - return isEnabled() && getParams() != null && getParams().length() > 0 - && consumer.getService().equals(getService()) - && consumer.getAddress().equals(getAddress()); + return isEnabled() && getParams() != null && getParams().length() > 0 + && consumer.getService().equals(getService()) + && consumer.getAddress().equals(getAddress()); } - + public boolean isMatch(Consumer consumer) { - return isEnabled() && getParams() != null && getParams().length() > 0 - && consumer.getService().equals(getService()) - && (getAddress() == null || getAddress().length() == 0 || getAddress().equals(Constants.ANY_VALUE) || getAddress().equals(Constants.ANYHOST_VALUE) || getAddress().equals(consumer.getAddress())) - && (getApplication() == null || getApplication().length() == 0 || getApplication().equals(Constants.ANY_VALUE) || getApplication().equals(consumer.getApplication())); + return isEnabled() && getParams() != null && getParams().length() > 0 + && consumer.getService().equals(getService()) + && (getAddress() == null || getAddress().length() == 0 || getAddress().equals(Constants.ANY_VALUE) || getAddress().equals(Constants.ANYHOST_VALUE) || getAddress().equals(consumer.getAddress())) + && (getApplication() == null || getApplication().length() == 0 || getApplication().equals(Constants.ANY_VALUE) || getApplication().equals(consumer.getApplication())); } - + public Map toParametersMap() { - Map map = StringUtils.parseQueryString(getParams()); - map.remove(Constants.INTERFACE_KEY); - map.remove(Constants.GROUP_KEY); - map.remove(Constants.VERSION_KEY); - map.remove(Constants.APPLICATION_KEY); - map.remove(Constants.CATEGORY_KEY); - map.remove(Constants.DYNAMIC_KEY); - map.remove(Constants.ENABLED_KEY); - return map; + Map map = StringUtils.parseQueryString(getParams()); + map.remove(Constants.INTERFACE_KEY); + map.remove(Constants.GROUP_KEY); + map.remove(Constants.VERSION_KEY); + map.remove(Constants.APPLICATION_KEY); + map.remove(Constants.CATEGORY_KEY); + map.remove(Constants.DYNAMIC_KEY); + map.remove(Constants.ENABLED_KEY); + return map; } public URL toUrl() { @@ -176,7 +176,7 @@ public URL toUrl() { StringBuilder sb = new StringBuilder(); sb.append(Constants.OVERRIDE_PROTOCOL); sb.append("://"); - if(! StringUtils.isBlank(address) && ! Constants.ANY_VALUE.equals(address)) { + if (!StringUtils.isBlank(address) && !Constants.ANY_VALUE.equals(address)) { sb.append(address); } else { sb.append(Constants.ANYHOST_VALUE); @@ -188,7 +188,7 @@ public URL toUrl() { param.put(Constants.CATEGORY_KEY, Constants.CONFIGURATORS_CATEGORY); param.put(Constants.ENABLED_KEY, String.valueOf(isEnabled())); param.put(Constants.DYNAMIC_KEY, "false"); - if(! StringUtils.isBlank(application) && ! Constants.ANY_VALUE.equals(application)) { + if (!StringUtils.isBlank(application) && !Constants.ANY_VALUE.equals(application)) { param.put(Constants.APPLICATION_KEY, application); } if (group != null) { diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Owner.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Owner.java index ace59a4e5a7..0bcdcb38312 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Owner.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Owner.java @@ -1,17 +1,17 @@ package com.alibaba.dubbo.registry.common.domain; public class Owner extends Entity { - - private static final long serialVersionUID = -4891350118145794727L; - - /** - * 可以包含通配符。 - */ - private String service; - - private String username; - - private User user; + + private static final long serialVersionUID = -4891350118145794727L; + + /** + * 可以包含通配符。 + */ + private String service; + + private String username; + + private User user; public Owner() { } @@ -19,22 +19,22 @@ public Owner() { public Owner(Long id) { super(id); } - - public String getService() { - return service; - } - public void setService(String service) { - this.service = service; - } + public String getService() { + return service; + } - public String getUsername() { - return username; - } + public void setService(String service) { + this.service = service; + } + + public String getUsername() { + return username; + } - public void setUsername(String username) { - this.username = username; - } + public void setUsername(String username) { + this.username = username; + } public User getUser() { return user; diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/PageList.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/PageList.java index 8decc634f07..d7938e4ea6a 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/PageList.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/PageList.java @@ -1,11 +1,11 @@ /** * Project: dubbo.registry.server-1.1.0-SNAPSHOT - * + *

* File Created at 2010-7-7 - * + *

* Copyright 1999-2010 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -19,7 +19,7 @@ /** * PageList - * + * * @author william.liangf */ public class PageList implements Serializable { @@ -31,9 +31,9 @@ public class PageList implements Serializable { private int limit; private int total; - + private List list; - + public PageList() { } @@ -75,25 +75,25 @@ public List getList() { public void setList(List list) { this.list = list; } - - public int getPageCount(){ + + public int getPageCount() { int lim = limit; - if(limit < 1){ + if (limit < 1) { lim = 1; } - + int page = total / lim; - if (page < 1){ + if (page < 1) { return 1; } - + int remain = total % lim; - - if(remain > 0){ + + if (remain > 0) { page += 1; } - + return page; } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Provider.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Provider.java index 04aa1cd5fa4..388de3833c0 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Provider.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Provider.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry-1.1.0-SNAPSHOT - * + *

* File Created at 2010-4-9 * $Id: Provider.java 182846 2012-06-28 09:37:59Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,17 +15,17 @@ */ package com.alibaba.dubbo.registry.common.domain; -import java.util.Date; -import java.util.List; -import java.util.Map; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.registry.common.registry.ConvertUtil; +import java.util.Date; +import java.util.List; +import java.util.Map; + /** * Provider - * + * * @author william.liangf * @author tony.chenl */ @@ -34,36 +34,36 @@ public class Provider extends Entity { private static final long serialVersionUID = 5981342400350878171L; private String service;/* 提供者所提供的服务名称 */ - + private String url; /* 提供者提供服务的地址 */ - + private String parameters; /* 提供者提供服务的参数 */ - + private String address; /* 提供者地址 */ private String registry;/* 提供者连接的注册中心地址 */ - + private boolean dynamic; /* 是否为动态注册服务 */ - + private boolean enabled; /* 是否启用 */ private int weight; /* 权重 */ - private String application; /* 应用名 */ + private String application; /* 应用名 */ private String username; /* 提供者用户名 */ - + private Date expired; /*过期时间*/ - + private long alived; /*存活时间,单位秒*/ private Override override; - private List overrides; - + private List overrides; + public Provider() { } - + public Provider(Long id) { super(id); } @@ -75,7 +75,7 @@ public String getService() { public void setService(String service) { this.service = service; } - + public String getUrl() { return url; } @@ -124,32 +124,32 @@ public void setApplication(String application) { this.application = application; } - public boolean isDynamic() { - return dynamic; - } + public boolean isDynamic() { + return dynamic; + } - public void setDynamic(boolean dynamic) { - this.dynamic = dynamic; - } + public void setDynamic(boolean dynamic) { + this.dynamic = dynamic; + } - public boolean isEnabled() { - return enabled; - } + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - public Date getExpired() { return expired; } - + public void setExpired(Date expired) { this.expired = expired; } - + public long getAlived() { return alived; } @@ -159,28 +159,28 @@ public void setAlived(long aliveSeconds) { } public int getWeight() { - return weight; - } + return weight; + } - public void setWeight(int weight) { - this.weight = weight; - } + public void setWeight(int weight) { + this.weight = weight; + } public Override getOverride() { - return override; - } + return override; + } - public void setOverride(Override override) { - this.override = override; - } + public void setOverride(Override override) { + this.override = override; + } - public List getOverrides() { - return overrides; - } + public List getOverrides() { + return overrides; + } - public void setOverrides(List overrides) { - this.overrides = overrides; - } + public void setOverrides(List overrides) { + this.overrides = overrides; + } public URL toUrl() { Map serviceName2Map = ConvertUtil.serviceName2Map(getService()); @@ -190,27 +190,26 @@ public URL toUrl() { if(!serviceName2Map.containsKey(Constants.VERSION_KEY)) { throw new IllegalArgumentException("No version info"); }*/ - + String u = getUrl(); URL url = URL.valueOf(u + "?" + getParameters()); - + url = url.addParameters(serviceName2Map); - + boolean dynamic = isDynamic(); - if(!dynamic) { + if (!dynamic) { url = url.addParameter(Constants.DYNAMIC_KEY, false); } boolean enabled = isEnabled(); - if(enabled != url.getParameter("enabled", true)) { - if(enabled) { + if (enabled != url.getParameter("enabled", true)) { + if (enabled) { url = url.removeParameter("enabled"); - } - else { + } else { url = url.addParameter("enabled", false); } } - + return url; } - + } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Registry.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Registry.java index 4c00f8eb4d1..64523ebe9ff 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Registry.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Registry.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry-1.1.0-SNAPSHOT - * + *

* File Created at 2010-4-9 * $Id: Registry.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -19,7 +19,7 @@ /** * Registry - * + * * @author william.liangf */ public class Registry extends Entity { @@ -27,22 +27,22 @@ public class Registry extends Entity { private static final long serialVersionUID = -8866645978415551309L; private String registry;/* 注册中心地址 */ - + private String url; - + private int connections = 0;/*注册中心连接数*/ private Date expired; /*过期时间*/ - + private long alived; - + public Registry() { } public Registry(Long id) { super(id); } - + public Registry(String registryAddress, String consoleUrl, int aliveSeconds) { this.registry = registryAddress; this.url = consoleUrl; @@ -81,12 +81,12 @@ public void setAlived(long aliveSeconds) { this.alived = aliveSeconds; } - + public int getConnections() { return connections; } - + public void setConnections(int connections) { this.connections = connections; } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Route.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Route.java index 50f15f51bb6..0caa616f6a1 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Route.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Route.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry-1.1.0-SNAPSHOT - * + *

* File Created at 2010-4-15 * $Id: Route.java 184666 2012-07-05 11:13:17Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,79 +15,65 @@ */ package com.alibaba.dubbo.registry.common.domain; -import java.util.List; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; +import java.util.List; + /** * Route - * + * * @author william.liangf */ public class Route extends Entity { - - private static final long serialVersionUID = -7630589008164140656L; public static final String ALL_METHOD = "*"; + public static final String KEY_METHOD = "method"; // WHEN KEY - - public static final String KEY_METHOD = "method"; - public static final String KEY_CONSUMER_APPLICATION = "consumer.application"; - public static final String KEY_CONSUMER_GROUP = "consumer.cluster"; - public static final String KEY_CONSUMER_VERSION = "consumer.version"; - public static final String KEY_CONSUMER_HOST = "consumer.host"; - public static final String KEY_CONSUMER_METHODS = "consumer.methods"; - - // THEN KEY - public static final String KEY_PROVIDER_APPLICATION = "provider.application"; - + + // THEN KEY public static final String KEY_PROVIDER_GROUP = "provider.cluster"; - public static final String KEY_PROVIDER_PROTOCOL = "provider.protocol"; - public static final String KEY_PROVIDER_VERSION = "provider.version"; - public static final String KEY_PROVIDER_HOST = "provider.host"; - public static final String KEY_PROVIDER_PORT = "provider.port"; - + private static final long serialVersionUID = -7630589008164140656L; private long parentId; //默认为0 - + private String name; - + private String service; - + private String rule; - + private String matchRule; - + private String filterRule; private int priority; - + private String username; - + private boolean enabled; private boolean force; - + private List children; - + public Route() { } public Route(Long id) { super(id); } - + public int getPriority() { return priority; } @@ -104,21 +90,21 @@ public void setUsername(String username) { this.username = username; } - public long getParentId() { - return parentId; - } + public long getParentId() { + return parentId; + } - public void setParentId(long parentId) { - this.parentId = parentId; - } + public void setParentId(long parentId) { + this.parentId = parentId; + } - public List getChildren() { - return children; - } + public List getChildren() { + return children; + } - public void setChildren(List subRules) { - this.children = subRules; - } + public void setChildren(List subRules) { + this.children = subRules; + } public String getName() { return name; @@ -128,13 +114,13 @@ public void setName(String name) { this.name = name; } - public boolean isEnabled() { - return enabled; - } + public boolean isEnabled() { + return enabled; + } - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } public boolean isForce() { return force; @@ -144,22 +130,22 @@ public void setForce(boolean force) { this.force = force; } - public String getService() { - return service; - } + public String getService() { + return service; + } + + public void setService(String service) { + this.service = service; + } - public void setService(String service) { - this.service = service; - } - - public String getRule() { + public String getRule() { return rule; } public void setRule(String rule) { this.rule = rule; String[] rules = rule.split(" => "); - if(rules.length != 2){ + if (rules.length != 2) { throw new IllegalArgumentException("Illegal Route Condition Rule"); } this.matchRule = rules[0]; @@ -167,31 +153,31 @@ public void setRule(String rule) { } public String getMatchRule() { - return matchRule; - } - - public void setMatchRule(String matchRule) { - this.matchRule = matchRule; - } - - public String getFilterRule() { - return filterRule; - } - - public void setFilterRule(String filterRule) { - this.filterRule = filterRule; - } - - @java.lang.Override - public String toString() { - return "Route [parentId=" + parentId + ", name=" + name - + ", serviceName=" + service + ", matchRule=" + matchRule - + ", filterRule=" + filterRule + ", priority=" + priority - + ", username=" + username + ", enabled=" + enabled + "]"; - } - - public URL toUrl() { - String group = null; + return matchRule; + } + + public void setMatchRule(String matchRule) { + this.matchRule = matchRule; + } + + public String getFilterRule() { + return filterRule; + } + + public void setFilterRule(String filterRule) { + this.filterRule = filterRule; + } + + @java.lang.Override + public String toString() { + return "Route [parentId=" + parentId + ", name=" + name + + ", serviceName=" + service + ", matchRule=" + matchRule + + ", filterRule=" + filterRule + ", priority=" + priority + + ", username=" + username + ", enabled=" + enabled + "]"; + } + + public URL toUrl() { + String group = null; String version = null; String path = service; int i = path.indexOf("/"); @@ -204,12 +190,12 @@ public URL toUrl() { version = path.substring(i + 1); path = path.substring(0, i); } - return URL.valueOf(Constants.ROUTE_PROTOCOL + "://" + Constants.ANYHOST_VALUE + "/" + path - + "?" + Constants.CATEGORY_KEY + "=" + Constants.ROUTERS_CATEGORY - + "&router=condition&runtime=false&enabled=" + isEnabled() + "&priority=" + getPriority() + "&force=" + isForce() + "&dynamic=false" - + "&name=" + getName() + "&" + Constants.RULE_KEY + "=" + URL.encode(getMatchRule() + " => " + getFilterRule()) - + (group == null ? "" : "&" + Constants.GROUP_KEY + "=" + group) - + (version == null ? "" : "&" + Constants.VERSION_KEY + "=" + version)); - } + return URL.valueOf(Constants.ROUTE_PROTOCOL + "://" + Constants.ANYHOST_VALUE + "/" + path + + "?" + Constants.CATEGORY_KEY + "=" + Constants.ROUTERS_CATEGORY + + "&router=condition&runtime=false&enabled=" + isEnabled() + "&priority=" + getPriority() + "&force=" + isForce() + "&dynamic=false" + + "&name=" + getName() + "&" + Constants.RULE_KEY + "=" + URL.encode(getMatchRule() + " => " + getFilterRule()) + + (group == null ? "" : "&" + Constants.GROUP_KEY + "=" + group) + + (version == null ? "" : "&" + Constants.VERSION_KEY + "=" + version)); + } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/SearchHistory.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/SearchHistory.java index 016b5bab64e..e54cba32ed2 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/SearchHistory.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/SearchHistory.java @@ -2,14 +2,14 @@ public class SearchHistory extends Entity { - private static final long serialVersionUID = -1281982267153430266L; - + private static final long serialVersionUID = -1281982267153430266L; + private String name; - + private String type; - + private String url; - + public SearchHistory() { } @@ -17,28 +17,28 @@ public SearchHistory(Long id) { super(id); } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public String getUrl() { - return url; - } + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } - public void setUrl(String url) { - this.url = url; - } - } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Test.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Test.java index 89ec3e4dfe1..153e6a3d81a 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Test.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Test.java @@ -1,11 +1,11 @@ /** * Project: dubbo.registry-1.1.0-SNAPSHOT - * + *

* File Created at 2010-5-26 - * + *

* Copyright 1999-2010 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -16,36 +16,36 @@ /** * Test - * + * * @author william.liangf */ public class Test extends Entity { private static final long serialVersionUID = 872527738197173003L; - - private String name; - - private String service; - private String method; + private String name; + + private String service; - private String parameters; + private String method; - private boolean exception; + private String parameters; - private String result; + private boolean exception; - private String username; + private String result; + + private String username; + + private boolean autoRun; - private boolean autoRun; - public Test() { } public Test(Long id) { super(id); } - + public String getService() { return service; } @@ -70,7 +70,7 @@ public void setParameters(String parameters) { this.parameters = parameters; } - public String getResult() { + public String getResult() { return result; } @@ -86,28 +86,28 @@ public void setUsername(String username) { this.username = username; } - public boolean isException() { - return exception; - } + public boolean isException() { + return exception; + } - public void setException(boolean exception) { - this.exception = exception; - } + public void setException(boolean exception) { + this.exception = exception; + } - public boolean isAutoRun() { - return autoRun; - } + public boolean isAutoRun() { + return autoRun; + } - public void setAutoRun(boolean autoRun) { - this.autoRun = autoRun; - } + public void setAutoRun(boolean autoRun) { + this.autoRun = autoRun; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/User.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/User.java index a470d2522ac..aa28f616455 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/User.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/User.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry-1.1.0-SNAPSHOT - * + *

* File Created at 2010-4-15 * $Id: User.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,67 +15,75 @@ */ package com.alibaba.dubbo.registry.common.domain; +import com.alibaba.dubbo.registry.common.route.ParseUtils; + import java.util.Arrays; import java.util.List; -import com.alibaba.dubbo.registry.common.route.ParseUtils; - /** * User - * + * * @author william.liangf */ public class User extends Entity { - private static final long serialVersionUID = 7330539198581235339L; - public static final String REALM = "dubbo"; - public static final String ROOT = "R"; - public static final String ADMINISTRATOR = "A"; - public static final String MANAGER = "M"; - public static final String GUEST = "G"; - public static final String ANONYMOUS = "anonymous"; - public static final String LEGACY = "legacy"; - + private static final long serialVersionUID = 7330539198581235339L; private String username; private String password; - + private String role; - + private String creator; - + private boolean enabled; - + private String name; - + private String department; - + private String email; - + private String phone; - + private String alitalk; - + private String locale; - + private String servicePrivilege; private List servicePrivileges; - + public User() { } public User(Long id) { super(id); } - + + public static boolean isValidPrivilege(String servicePrivilege) { + if (servicePrivilege == null || servicePrivilege.length() == 0) { + return true; + } + String[] privileges = servicePrivilege.trim().split("\\s*,\\s*"); + for (String privilege : privileges) { + if (privilege.endsWith("*")) { + privilege = privilege.substring(0, privilege.length() - 1); + } + if (privilege.indexOf('*') > -1) { + return false; + } + } + return true; + } + public String getUsername() { return username; } @@ -108,160 +116,144 @@ public void setCreator(String creator) { this.creator = creator; } - public String getEmail() { - return email; - } + public String getEmail() { + return email; + } - public void setEmail(String email) { - this.email = email; - } + public void setEmail(String email) { + this.email = email; + } public boolean hasServicePrivilege(String[] services) { if (services == null || services.length == 0) throw new IllegalArgumentException("services == null"); for (String service : services) { boolean r = hasServicePrivilege(service); - if (! r) + if (!r) return false; } return true; } - - public static boolean isValidPrivilege(String servicePrivilege) { - if (servicePrivilege == null || servicePrivilege.length() == 0) { - return true; - } - String[] privileges = servicePrivilege.trim().split("\\s*,\\s*"); - for (String privilege : privileges) { - if(privilege.endsWith("*")){ - privilege = privilege.substring(0, privilege.length() - 1); + + public boolean canGrantPrivilege(String servicePrivilege) { + if (servicePrivilege == null || servicePrivilege.length() == 0) { + return true; + } + if (servicePrivileges == null || servicePrivileges.size() == 0) { + return false; + } + String[] privileges = servicePrivilege.trim().split("\\s*,\\s*"); + for (String privilege : privileges) { + boolean hasPrivilege = false; + for (String ownPrivilege : servicePrivileges) { + if (matchPrivilege(ownPrivilege, privilege)) { + hasPrivilege = true; + } } - if (privilege.indexOf('*') > -1) { - return false; - } - } + if (!hasPrivilege) { + return false; + } + } return true; } - - public boolean canGrantPrivilege(String servicePrivilege) { - if (servicePrivilege == null || servicePrivilege.length() == 0) { - return true; - } - if (servicePrivileges == null || servicePrivileges.size() == 0) { - return false; - } - String[] privileges = servicePrivilege.trim().split("\\s*,\\s*"); - for (String privilege : privileges) { - boolean hasPrivilege = false; - for (String ownPrivilege : servicePrivileges) { - if (matchPrivilege(ownPrivilege, privilege)) { - hasPrivilege = true; - } - } - if (! hasPrivilege) { - return false; - } - } - return true; - } private boolean matchPrivilege(String ownPrivilege, String privilege) { - if ("*".equals(ownPrivilege) || ownPrivilege.equals(privilege)) { - return true; - } - if(privilege.endsWith("*")){ - if(! ownPrivilege.endsWith("*")){ - return false; + if ("*".equals(ownPrivilege) || ownPrivilege.equals(privilege)) { + return true; + } + if (privilege.endsWith("*")) { + if (!ownPrivilege.endsWith("*")) { + return false; } - privilege = privilege.substring(0, privilege.length() - 1); - ownPrivilege = ownPrivilege.substring(0, ownPrivilege.length() - 1); - return privilege.startsWith(ownPrivilege); + privilege = privilege.substring(0, privilege.length() - 1); + ownPrivilege = ownPrivilege.substring(0, ownPrivilege.length() - 1); + return privilege.startsWith(ownPrivilege); } else { - if(ownPrivilege.endsWith("*")){ - ownPrivilege = ownPrivilege.substring(0, ownPrivilege.length() - 1); + if (ownPrivilege.endsWith("*")) { + ownPrivilege = ownPrivilege.substring(0, ownPrivilege.length() - 1); } - return privilege.startsWith(ownPrivilege); + return privilege.startsWith(ownPrivilege); } } - public boolean hasServicePrivilege(String service) { - if (service == null || service.length() == 0) - return false; - if (role == null || GUEST.equalsIgnoreCase(role)) { - return false; - } - if(ROOT.equalsIgnoreCase(role)) { - return true; - } - - if (servicePrivileges != null && servicePrivileges.size() > 0) { - for (String privilege : servicePrivileges) { - boolean ok = ParseUtils.isMatchGlobPattern(privilege,service); + public boolean hasServicePrivilege(String service) { + if (service == null || service.length() == 0) + return false; + if (role == null || GUEST.equalsIgnoreCase(role)) { + return false; + } + if (ROOT.equalsIgnoreCase(role)) { + return true; + } + + if (servicePrivileges != null && servicePrivileges.size() > 0) { + for (String privilege : servicePrivileges) { + boolean ok = ParseUtils.isMatchGlobPattern(privilege, service); if (ok) { - return true; + return true; } - } - } - return false; - } - - public String getServicePrivilege() { - return servicePrivilege; - } - - public void setServicePrivilege(String servicePrivilege) { - this.servicePrivilege = servicePrivilege; - if (servicePrivilege != null && servicePrivilege.length() > 0) { - servicePrivileges = Arrays.asList(servicePrivilege.trim().split("\\s*,\\s*")); - } - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDepartment() { - return department; - } - - public void setDepartment(String department) { - this.department = department; - } - - public String getPhone() { - return phone; - } - - public void setPhone(String phone) { - this.phone = phone; - } - - public String getAlitalk() { - return alitalk; - } - - public void setAlitalk(String alitalk) { - this.alitalk = alitalk; - } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public String getLocale() { - return locale; - } - - public void setLocale(String locale) { - this.locale = locale; - } + } + } + return false; + } + + public String getServicePrivilege() { + return servicePrivilege; + } + + public void setServicePrivilege(String servicePrivilege) { + this.servicePrivilege = servicePrivilege; + if (servicePrivilege != null && servicePrivilege.length() > 0) { + servicePrivileges = Arrays.asList(servicePrivilege.trim().split("\\s*,\\s*")); + } + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDepartment() { + return department; + } + + public void setDepartment(String department) { + this.department = department; + } + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public String getAlitalk() { + return alitalk; + } + + public void setAlitalk(String alitalk) { + this.alitalk = alitalk; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public String getLocale() { + return locale; + } + + public void setLocale(String locale) { + this.locale = locale; + } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Weight.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Weight.java index dff1afbb27b..aab0b60ee41 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Weight.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Weight.java @@ -2,35 +2,33 @@ public class Weight extends Entity { - private static final long serialVersionUID = -1281982267153430266L; - - //缺省的权重值 + //缺省的权重值 public static final int DEFAULT_WEIGHT = 5; - + private static final long serialVersionUID = -1281982267153430266L; private String address; /* 用户配置的提供者地址表达式 */ - + private String serviceName; - + private int weight; /*权重值*/ - + private String username; - + public Weight() { } public Weight(Long id) { super(id); } - - public String getAddress() { - return address; - } - public void setAddress(String address) { - this.address = address; - } - - public String getService() { + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getService() { return serviceName; } @@ -38,13 +36,13 @@ public void setService(String serviceName) { this.serviceName = serviceName; } - public int getWeight() { - return weight; - } + public int getWeight() { + return weight; + } - public void setWeight(int weight) { - this.weight = weight; - } + public void setWeight(int weight) { + this.weight = weight; + } public String getUsername() { return username; @@ -53,5 +51,5 @@ public String getUsername() { public void setUsername(String username) { this.username = username; } - + } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/registry/ConvertUtil.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/registry/ConvertUtil.java index 253f557595c..a35651fd905 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/registry/ConvertUtil.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/registry/ConvertUtil.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.common-2.2.0-SNAPSHOT - * + *

* File Created at Mar 21, 2012 * $Id: ConvertUtil.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 1999-2100 Alibaba.com Corporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,23 +15,26 @@ */ package com.alibaba.dubbo.registry.common.registry; -import java.util.HashMap; -import java.util.Map; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.utils.StringUtils; +import java.util.HashMap; +import java.util.Map; + /** * @author ding.lid * */ public class ConvertUtil { + private ConvertUtil() { + } + public static Map> convertRegister(Map> register) { Map> newRegister = new HashMap>(); for (Map.Entry> entry : register.entrySet()) { String serviceName = entry.getKey(); Map serviceUrls = entry.getValue(); - if (! serviceName.contains(":") && ! serviceName.contains("/")) { + if (!serviceName.contains(":") && !serviceName.contains("/")) { for (Map.Entry entry2 : serviceUrls.entrySet()) { String serviceUrl = entry2.getKey(); String serviceQuery = entry2.getValue(); @@ -44,7 +47,7 @@ public static Map> convertRegister(Map 0) { name = group + "/" + name; } - if (version != null && version.length() > 0 && ! "0.0.0".equals(version)) { + if (version != null && version.length() > 0 && !"0.0.0".equals(version)) { name = name + ":" + version; } Map newUrls = newRegister.get(name); @@ -60,13 +63,13 @@ public static Map> convertRegister(Map convertSubscribe(Map subscribe) { Map newSubscribe = new HashMap(); for (Map.Entry entry : subscribe.entrySet()) { String serviceName = entry.getKey(); String serviceQuery = entry.getValue(); - if (! serviceName.contains(":") && ! serviceName.contains("/")) { + if (!serviceName.contains(":") && !serviceName.contains("/")) { Map params = StringUtils.parseQueryString(serviceQuery); String group = params.get("group"); String version = params.get("version"); @@ -76,7 +79,7 @@ public static Map convertSubscribe(Map subscribe if (group != null && group.length() > 0) { name = group + "/" + name; } - if (version != null && version.length() > 0 && ! "0.0.0".equals(version)) { + if (version != null && version.length() > 0 && !"0.0.0".equals(version)) { name = name + ":" + version; } newSubscribe.put(name, StringUtils.toQueryString(params)); @@ -86,7 +89,7 @@ public static Map convertSubscribe(Map subscribe } return newSubscribe; } - + public static Map serviceName2Map(String serviceName) { String group = null; String version = null; @@ -100,20 +103,18 @@ public static Map serviceName2Map(String serviceName) { version = serviceName.substring(i + 1); serviceName = serviceName.substring(0, i); } - + Map ret = new HashMap(); - if(!StringUtils.isEmpty(serviceName)) { + if (!StringUtils.isEmpty(serviceName)) { ret.put(Constants.INTERFACE_KEY, serviceName); } - if(!StringUtils.isEmpty(version)) { + if (!StringUtils.isEmpty(version)) { ret.put(Constants.VERSION_KEY, version); } - if(!StringUtils.isEmpty(group)) { + if (!StringUtils.isEmpty(group)) { ret.put(Constants.GROUP_KEY, group); } - + return ret; } - - private ConvertUtil() {} } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/route/OverrideUtils.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/route/OverrideUtils.java index 5b4e6337641..f433929e775 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/route/OverrideUtils.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/route/OverrideUtils.java @@ -15,103 +15,104 @@ */ package com.alibaba.dubbo.registry.common.route; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.registry.common.domain.Consumer; import com.alibaba.dubbo.registry.common.domain.Override; import com.alibaba.dubbo.registry.common.domain.Provider; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + public class OverrideUtils { - - public static final Comparator OVERRIDE_COMPARATOR = new Comparator() { - public int compare(Override o1, Override o2) { - if (o1 == null && o2 == null) { - return 0; - } - if (o1 == null) { - return -1; - } - if (o2 == null) { - return 1; - } - int cmp = cmp(o1.getAddress(), o2.getAddress()); - if (cmp != 0) { - return cmp; - } - cmp = cmp(o1.getApplication(), o2.getApplication()); - if (cmp != 0) { - return cmp; - } - return cmp(o1.getService(), o2.getService()); - } - - private int cmp(String s1, String s2) { - if (s1 == null && s2 == null) { - return 0; - } - if (s1 == null) { - return -1; - } - if (s2 == null) { - return 1; - } - if (s1.equals(s2)) { - return 0; - } - if (isAny(s1)) { - return 1; - } - if (isAny(s2)) { - return -1; - } - return s1.compareTo(s2); - } - private boolean isAny(String s) { - return s == null || s.length() == 0 || Constants.ANY_VALUE.equals(s) || Constants.ANYHOST_VALUE.equals(s); - } - }; - - public static void setConsumerOverrides(Consumer consumer, List overrides) { - if (consumer == null || overrides == null) { - return; - } - List result = new ArrayList(overrides.size()); - for(Override override : overrides){ - if (! override.isEnabled()) { - continue; - } - if (override.isMatch(consumer)) { - result.add(override); - } - if (override.isUniqueMatch(consumer)) { - consumer.setOverride(override); - } - } - Collections.sort(result, OverrideUtils.OVERRIDE_COMPARATOR); - consumer.setOverrides(result); - } - - public static void setProviderOverrides(Provider provider, List overrides) { - if (provider == null || overrides == null) { - return; - } - List result = new ArrayList(overrides.size()); - for(Override override : overrides){ - if (! override.isEnabled()) { - continue; - } - if (override.isMatch(provider)) { - result.add(override); - } - if (override.isUniqueMatch(provider)) { - provider.setOverride(override); - } - } - provider.setOverrides(overrides); - } + + public static final Comparator OVERRIDE_COMPARATOR = new Comparator() { + public int compare(Override o1, Override o2) { + if (o1 == null && o2 == null) { + return 0; + } + if (o1 == null) { + return -1; + } + if (o2 == null) { + return 1; + } + int cmp = cmp(o1.getAddress(), o2.getAddress()); + if (cmp != 0) { + return cmp; + } + cmp = cmp(o1.getApplication(), o2.getApplication()); + if (cmp != 0) { + return cmp; + } + return cmp(o1.getService(), o2.getService()); + } + + private int cmp(String s1, String s2) { + if (s1 == null && s2 == null) { + return 0; + } + if (s1 == null) { + return -1; + } + if (s2 == null) { + return 1; + } + if (s1.equals(s2)) { + return 0; + } + if (isAny(s1)) { + return 1; + } + if (isAny(s2)) { + return -1; + } + return s1.compareTo(s2); + } + + private boolean isAny(String s) { + return s == null || s.length() == 0 || Constants.ANY_VALUE.equals(s) || Constants.ANYHOST_VALUE.equals(s); + } + }; + + public static void setConsumerOverrides(Consumer consumer, List overrides) { + if (consumer == null || overrides == null) { + return; + } + List result = new ArrayList(overrides.size()); + for (Override override : overrides) { + if (!override.isEnabled()) { + continue; + } + if (override.isMatch(consumer)) { + result.add(override); + } + if (override.isUniqueMatch(consumer)) { + consumer.setOverride(override); + } + } + Collections.sort(result, OverrideUtils.OVERRIDE_COMPARATOR); + consumer.setOverrides(result); + } + + public static void setProviderOverrides(Provider provider, List overrides) { + if (provider == null || overrides == null) { + return; + } + List result = new ArrayList(overrides.size()); + for (Override override : overrides) { + if (!override.isEnabled()) { + continue; + } + if (override.isMatch(provider)) { + result.add(override); + } + if (override.isUniqueMatch(provider)) { + provider.setOverride(override); + } + } + provider.setOverrides(overrides); + } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/route/ParseUtils.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/route/ParseUtils.java index 7ab7c3a21b6..ab433fd585a 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/route/ParseUtils.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/route/ParseUtils.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.server - * + *

* File Created at Oct 19, 2010 * $Id: ParseUtils.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 1999-2100 Alibaba.com Corporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,6 +15,8 @@ */ package com.alibaba.dubbo.registry.common.route; +import com.alibaba.dubbo.common.utils.StringUtils; + import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -27,26 +29,27 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import com.alibaba.dubbo.common.utils.StringUtils; - /** * 字符串解析相关的工具方法,涉及interpolation、Glob模式、Query字串、Service URL处理。 - * + * * @author william.liangf * @author ding.lid */ public class ParseUtils { - + + private static final ConcurrentMap REPLACE_PARAMETER_PATTERNS = new ConcurrentHashMap(); public static String METHOD_SPLIT = ","; - - private ParseUtils() {} - private static Pattern VARIABLE_PATTERN = Pattern.compile( "\\$\\s*\\{?\\s*([\\._0-9a-zA-Z]+)\\s*\\}?"); - + private static Pattern QUERY_PATTERN = Pattern + .compile("([&=]?)\\s*([^&=\\s]+)"); + + private ParseUtils() { + } + /** * 执行interpolation(变量插入)。 - * + * * @param expression 含有变量的表达式字符串。表达式中的变量名也可以用{}括起来。 * @param params 变量集。变量名可以包含._字符。 * @return 完成interpolation后的字符串。 如:

xxx${name}zzz -> xxxjerryzzz
(其中变量name="jerry") @@ -64,30 +67,29 @@ public static String interpolate(String expression, Map params) StringBuffer sb = new StringBuffer(); while (matcher.find()) { // 逐个匹配 String key = matcher.group(1); - String value = params == null ? null: params.get(key); + String value = params == null ? null : params.get(key); if (value == null) { - value = ""; + value = ""; } matcher.appendReplacement(sb, value); } matcher.appendTail(sb); return sb.toString(); } - + public static List interpolate(List expressions, Map params) { List ret = new ArrayList(); - - if(null == expressions || expressions.isEmpty()) { + + if (null == expressions || expressions.isEmpty()) { return ret; } - - for(String expr : expressions) { + + for (String expr : expressions) { ret.add(interpolate(expr, params)); } - + return ret; } - /** * 匹配Glob模式。目前的实现只支持*,且只支持一个。不支持?。 @@ -95,17 +97,17 @@ public static List interpolate(List expressions, Map patternsNeedInterpolate, Map interpolateParams, String value) { - if(patternsNeedInterpolate != null && ! patternsNeedInterpolate.isEmpty()) { - for (String patternNeedItp : patternsNeedInterpolate) { - if(StringUtils.isEmpty(patternNeedItp)) { - continue; + if (patternsNeedInterpolate != null && !patternsNeedInterpolate.isEmpty()) { + for (String patternNeedItp : patternsNeedInterpolate) { + if (StringUtils.isEmpty(patternNeedItp)) { + continue; } // FIXME ERROR!! 原来的实现,这里只和第一个不为空的pattern比较,返回对应的结果! 和梁飞确认 String pattern = interpolate(patternNeedItp, interpolateParams); - if(isMatchGlobPattern(pattern, value)) { - return true; + if (isMatchGlobPattern(pattern, value)) { + return true; } } } @@ -154,30 +156,30 @@ public static boolean isMatchGlobPatternsNeedInterpolate( */ public static Set filterByGlobPattern(String pattern, Collection values) { Set ret = new HashSet(); - if(pattern == null || values == null) { + if (pattern == null || values == null) { return ret; } - - for(String v : values) { - if(isMatchGlobPattern(pattern, v)) { + + for (String v : values) { + if (isMatchGlobPattern(pattern, v)) { ret.add(v); } } return ret; } - + /** - * 找到了配合Glob模式的字符串。模式有多个,只要匹配一个模式,就返回这个字符串。 + * 找到了配合Glob模式的字符串。模式有多个,只要匹配一个模式,就返回这个字符串。 */ public static Set filterByGlobPattern(Collection patterns, Collection values) { Set ret = new HashSet(); - if(null == patterns || values == null || patterns.isEmpty() || values.isEmpty()) { + if (null == patterns || values == null || patterns.isEmpty() || values.isEmpty()) { return ret; } - - for(String p : patterns) { - for(String v : values) { - if(isMatchGlobPattern(p, v)) { + + for (String p : patterns) { + for (String v : values) { + if (isMatchGlobPattern(p, v)) { ret.add(v); } } @@ -199,12 +201,12 @@ public static boolean hasIntersection(String glob1, String glob2) { String s11 = glob1.substring(0, index1); String s12 = glob1.substring(index1 + 1, glob1.length()); - + String s21 = glob2.substring(0, index2); String s22 = glob2.substring(index2 + 1, glob2.length()); - - if(!s11.startsWith(s21) && !s21.startsWith(s11)) return false; - if(!s12.endsWith(s22) && !s22.endsWith(s12)) return false; + + if (!s11.startsWith(s21) && !s21.startsWith(s11)) return false; + if (!s12.endsWith(s22) && !s22.endsWith(s12)) return false; return true; } else if (glob1.contains("*")) { return isMatchGlobPattern(glob1, glob2); @@ -214,13 +216,10 @@ public static boolean hasIntersection(String glob1, String glob2) { return glob1.equals(glob2); } } - - private static Pattern QUERY_PATTERN = Pattern - .compile("([&=]?)\\s*([^&=\\s]+)"); - + /** * 把Query String解析成Map。对于有只有Key的串key3=,忽略。 - * + * * @param keyPrefix 在输出的Map的Key加上统一前缀。 * @param query Query String,形如:key1=value1&key2=value2 * @return Query String为key1=value1&key2=value2,前缀为pre.时, @@ -232,7 +231,7 @@ public static Map parseQuery(String keyPrefix, String query) { return new HashMap(); if (keyPrefix == null) keyPrefix = ""; - + Matcher matcher = QUERY_PATTERN.matcher(query); Map routeQuery = new HashMap(); String key = null; @@ -268,13 +267,11 @@ public static Map parseQuery(String keyPrefix, String query) { + "\", The error in the end char: " + key);*/ return routeQuery; } - + public static Map parseQuery(String query) { return parseQuery("", query); } - - private static final ConcurrentMap REPLACE_PARAMETER_PATTERNS = new ConcurrentHashMap(); - + /** * 替换url中参数的值。 */ @@ -283,11 +280,11 @@ public static String replaceParameter(String query, String key, String value) { return key + "=" + value; } if (query.indexOf(key + "=") == -1) { - return query + "&" + key + "=" + value; + return query + "&" + key + "=" + value; } Pattern pattern = REPLACE_PARAMETER_PATTERNS.get(key); if (pattern == null) { - pattern = Pattern.compile(key.replaceAll("([^(_0-9A-Za-z)])", "\\\\$0") + "=[^&]+"); + pattern = Pattern.compile(key.replaceAll("([^(_0-9A-Za-z)])", "\\\\$0") + "=[^&]+"); } Matcher matcher = pattern.matcher(query); StringBuffer sb = new StringBuffer(); @@ -307,30 +304,30 @@ public static String appendParamToUri(String uri, String name, String value) { } return uri; } - + public static String appendParamsToUri(String uri, Map params) { - StringBuilder buf = new StringBuilder(uri); - boolean first = (uri.indexOf('?') < 0); - for(Map.Entry entry : params.entrySet()) { + StringBuilder buf = new StringBuilder(uri); + boolean first = (uri.indexOf('?') < 0); + for (Map.Entry entry : params.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); - if(StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) - continue; + if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) + continue; if (first) { - buf.append("?"); + buf.append("?"); first = false; } else { - buf.append("&"); + buf.append("&"); } buf.append(key); - buf.append("="); - buf.append(value); + buf.append("="); + buf.append(value); } return buf.toString(); } - + public static boolean matchEndStarPattern(String value, String pattern) { - if(!pattern.endsWith("*")) throw new IllegalArgumentException("not end star pattern!"); + if (!pattern.endsWith("*")) throw new IllegalArgumentException("not end star pattern!"); String perfix = pattern.substring(0, pattern.length() - 1); return value.startsWith(perfix); } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/route/RouteRule.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/route/RouteRule.java index 6f2732e7d98..ec0223a1c59 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/route/RouteRule.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/route/RouteRule.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.server - * + *

* File Created at Oct 18, 2010 * $Id: RouteRule.java 182348 2012-06-27 09:16:58Z tony.chenl $ - * + *

* Copyright 1999-2100 Alibaba.com Corporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,6 +15,9 @@ */ package com.alibaba.dubbo.registry.common.route; +import com.alibaba.dubbo.common.utils.StringUtils; +import com.alibaba.dubbo.registry.common.domain.Route; + import java.text.ParseException; import java.util.Collections; import java.util.HashMap; @@ -25,9 +28,6 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.registry.common.domain.Route; - /** * Rule分成两部分,When条件和Then条件。
@@ -37,130 +37,47 @@ * 使用条件对样本进行的匹配的过程称为“过滤”(或称为“筛选”)(Filter)。 * 使用When条件过滤和使用Then条件过滤的样本,不需要是相同的集合。如在Dubbo中,分别对应的是Consumer和Provider。 * 对于RouteRule(路由规则)含义即,符合When条件的Consumer,则对Provider进行Then过滤,出来的Provide即是提供给这个Consumer的Provider。
- * + * * Rule的字符串格式如下: * key1 = value11,value12 & key2 = value21 & key2 != value22 => key3 = value3 & key4 = value41,vlaue42 & key5 !=value51 * 。 * =>之前的称为When条件,是KV对;之后是Then条件,是KV对。KV的Value可以有多个值。

- * + * * 值对象,线程安全。 - * + * * @author william.liangf * @author ding.lid */ public class RouteRule { - public static class MatchPair { - Set matches = new HashSet(); - Set unmatches = new HashSet(); + @SuppressWarnings("unchecked") + static RouteRule EMPTY = new RouteRule(Collections.EMPTY_MAP, Collections.EMPTY_MAP); + private static Pattern ROUTE_PATTERN = Pattern.compile("([&!=,]*)\\s*([^&!=,\\s]+)"); + private static Pattern CONDITION_SEPERATOR = Pattern.compile("(.*)=>(.*)"); + private static Pattern VALUE_LIST_SEPARATOR = Pattern.compile("\\s*,\\s*"); + final Map whenCondition; + final Map thenCondition; + private volatile String tostring = null; - public MatchPair() { - } - - public MatchPair(Set matches, Set unmatches) { - if(matches == null || unmatches == null) { - throw new IllegalArgumentException("argument of MatchPair is null!"); - } - - this.matches = matches; - this.unmatches = unmatches; - } - - public Set getMatches() { - return matches; - } - - public Set getUnmatches() { - return unmatches; - } - - public MatchPair copy() { - MatchPair ret = new MatchPair(); - ret.matches.addAll(matches); - ret.unmatches.addAll(unmatches); - return ret; - } - - private volatile boolean freezed = false; - void freeze() { - if(freezed) return; - synchronized (this) { - if(freezed) return; - matches = Collections.unmodifiableSet(matches); - unmatches = Collections.unmodifiableSet(unmatches); - } - } - - public boolean containeValue(String value) { - return matches.contains(value) || unmatches.contains(value); - } - - /** - * 给定的值是否通过该{@link MatchPair}匹配。

- * 返回{@code false},如果 - *

    - *
  1. value在unmatches列表中 - *
  2. matches列表有值,但value不在matches列表中。 - *
- * otherwise返回true。 - */ - public boolean pass(String sample) { - if(unmatches.contains(sample)) return false; - if(matches.isEmpty()) return true; - return matches.contains(sample); - } - - @Override - public String toString() { - return String.format("{matches=%s,unmatches=%s}", matches.toString(), unmatches.toString()); + // FIXME 集合都要加上unmodified的Wrapper,避免构造后的对象被修改 + private RouteRule(Map when, Map then) { + for (Map.Entry entry : when.entrySet()) { + entry.getValue().freeze(); } - - // 用Eclipse自动生成 - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((matches == null) ? 0 : matches.hashCode()); - result = prime * result + ((unmatches == null) ? 0 : unmatches.hashCode()); - return result; + for (Map.Entry entry : then.entrySet()) { + entry.getValue().freeze(); } - // 用Eclipse自动生成 - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - MatchPair other = (MatchPair) obj; - if (matches == null) { - if (other.matches != null) - return false; - } else if (!matches.equals(other.matches)) - return false; - if (unmatches == null) { - if (other.unmatches != null) - return false; - } else if (!unmatches.equals(other.unmatches)) - return false; - return true; - } + // NOTE: When条件是允许为空的,外部业务来保证类似的约束条件 + this.whenCondition = when; + this.thenCondition = then; } - final Map whenCondition; - final Map thenCondition; - - private static Pattern ROUTE_PATTERN = Pattern.compile("([&!=,]*)\\s*([^&!=,\\s]+)"); - - private static Pattern CONDITION_SEPERATOR = Pattern.compile("(.*)=>(.*)"); - public static Map parseRule(String rule) throws ParseException { - Map condition = new HashMap(); - if(StringUtils.isBlank(rule)) { + Map condition = new HashMap(); + if (StringUtils.isBlank(rule)) { return condition; - } + } // 匹配或不匹配Key-Value对 MatchPair pair = null; // 多个Value值 @@ -222,27 +139,10 @@ else if (",".equals(separator)) { // 如果为逗号表示 } return condition; } - - // FIXME 集合都要加上unmodified的Wrapper,避免构造后的对象被修改 - private RouteRule(Map when, Map then) { - for(Map.Entry entry : when.entrySet()) { - entry.getValue().freeze(); - } - for(Map.Entry entry : then.entrySet()) { - entry.getValue().freeze(); - } - - // NOTE: When条件是允许为空的,外部业务来保证类似的约束条件 - this.whenCondition = when; - this.thenCondition = then; - } - @SuppressWarnings("unchecked") - static RouteRule EMPTY = new RouteRule(Collections.EMPTY_MAP, Collections.EMPTY_MAP); - /** * 把字符串形式的RouteRule的解析成对象。 - * + * * @throws ParseException RouteRule字符串格式不对了。以下输入的情况,RouteRule都是非法的。 *
  • 输入是null。 *
  • 输入是空串,或是空白串。 @@ -251,39 +151,39 @@ private RouteRule(Map when, Map then) { *
*/ public static RouteRule parse(Route route) throws ParseException { - if(route == null) + if (route == null) throw new ParseException("null route!", 0); - - if(route.getMatchRule() == null && route.getFilterRule() == null) { + + if (route.getMatchRule() == null && route.getFilterRule() == null) { return parse(route.getRule()); } - + return parse(route == null ? null : route.getMatchRule(), route == null ? null : route.getFilterRule()); } - + public static RouteRule parse(String whenRule, String thenRule) throws ParseException { - /*if (whenRule == null || whenRule.trim().length() == 0) { - throw new ParseException("Illegal route rule without when express", 0); + /*if (whenRule == null || whenRule.trim().length() == 0) { + throw new ParseException("Illegal route rule without when express", 0); }*/ - if (thenRule == null || thenRule.trim().length() == 0) { - throw new ParseException("Illegal route rule without then express", 0); - } - Map when = parseRule(whenRule.trim()); + if (thenRule == null || thenRule.trim().length() == 0) { + throw new ParseException("Illegal route rule without then express", 0); + } + Map when = parseRule(whenRule.trim()); Map then = parseRule(thenRule.trim()); return new RouteRule(when, then); } - + public static RouteRule parse(String rule) throws ParseException { - if(StringUtils.isBlank(rule)) { + if (StringUtils.isBlank(rule)) { throw new ParseException("Illegal blank route rule", 0); } - + final Matcher matcher = CONDITION_SEPERATOR.matcher(rule); - if(!matcher.matches()) throw new ParseException("condition seperator => not found!", 0); - + if (!matcher.matches()) throw new ParseException("condition seperator => not found!", 0); + return parse(matcher.group(1), matcher.group(2)); } - + /** * @see #parse(String) * @throws RuntimeException 解析出错时,Wrap了{@link #parse(String)}方法的抛出的{@link ParseException}的异常。 @@ -292,150 +192,147 @@ public static RouteRule parseQuitely(Route route) { try { return parse(route); } catch (ParseException e) { - throw new RuntimeException(e); + throw new RuntimeException(e); } } - - private static Pattern VALUE_LIST_SEPARATOR = Pattern.compile("\\s*,\\s*"); - + static Map parseNameAndValueListString2Condition(Map params, Map notParams) { Map condition = new HashMap(); - - for(Entry entry : params.entrySet()) { + + for (Entry entry : params.entrySet()) { String valueListString = entry.getValue(); - if(StringUtils.isBlank(valueListString)) { + if (StringUtils.isBlank(valueListString)) { continue; } String[] list = VALUE_LIST_SEPARATOR.split(valueListString); Set set = new HashSet(); - for(String item : list) { - if(StringUtils.isBlank(item)) { + for (String item : list) { + if (StringUtils.isBlank(item)) { continue; } set.add(item.trim()); } - if(set.isEmpty()) { + if (set.isEmpty()) { continue; } - + String key = entry.getKey(); MatchPair matchPair = condition.get(key); - if(null == matchPair) { + if (null == matchPair) { matchPair = new MatchPair(); condition.put(key, matchPair); } - + matchPair.matches = set; } - for(Entry entry : notParams.entrySet()) { + for (Entry entry : notParams.entrySet()) { String valueListString = entry.getValue(); - if(StringUtils.isBlank(valueListString)) { + if (StringUtils.isBlank(valueListString)) { continue; } String[] list = VALUE_LIST_SEPARATOR.split(valueListString); Set set = new HashSet(); - for(String item : list) { - if(StringUtils.isBlank(item)) { + for (String item : list) { + if (StringUtils.isBlank(item)) { continue; } set.add(item.trim()); } - if(set.isEmpty()) { + if (set.isEmpty()) { continue; } - + String key = entry.getKey(); MatchPair matchPair = condition.get(key); - if(null == matchPair) { + if (null == matchPair) { matchPair = new MatchPair(); condition.put(key, matchPair); } - + matchPair.unmatches = set; } - + return condition; } - + public static RouteRule createFromNameAndValueListString(Map whenParams, Map notWhenParams, Map thenParams, Map notThenParams) { Map when = parseNameAndValueListString2Condition(whenParams, notWhenParams); Map then = parseNameAndValueListString2Condition(thenParams, notThenParams); - + return new RouteRule(when, then); } - + public static RouteRule createFromCondition(Map whenCondition, Map thenCondition) { return new RouteRule(whenCondition, thenCondition); } - + public static RouteRule copyWithRemove(RouteRule copy, Set whenParams, Set thenParams) { Map when = new HashMap(); - for(Entry entry : copy.getWhenCondition().entrySet()) { - if(whenParams == null || !whenParams.contains(entry.getKey())) { + for (Entry entry : copy.getWhenCondition().entrySet()) { + if (whenParams == null || !whenParams.contains(entry.getKey())) { when.put(entry.getKey(), entry.getValue()); } } - + Map then = new HashMap(); - for(Entry entry : copy.getThenCondition().entrySet()) { - if(thenParams ==null || !thenParams.contains(entry.getKey())) { + for (Entry entry : copy.getThenCondition().entrySet()) { + if (thenParams == null || !thenParams.contains(entry.getKey())) { then.put(entry.getKey(), entry.getValue()); } } - + return new RouteRule(when, then); } - + /** * 使用新的条件值来替换。 - * + * * @param copy 替换的Base * @param whenCondition 要替换的whenCondition,如果Base没有项目,则直接插入。 * @param thenCondition 要替换的thenCondition,如果Base没有项目,则直接插入。 * @return 替换后的RouteRule */ public static RouteRule copyWithReplace(RouteRule copy, Map whenCondition, Map thenCondition) { - if(null == copy) { + if (null == copy) { throw new NullPointerException("Argument copy is null!"); } - + Map when = new HashMap(); when.putAll(copy.getWhenCondition()); - if(whenCondition != null) { + if (whenCondition != null) { when.putAll(whenCondition); } - + Map then = new HashMap(); then.putAll(copy.getThenCondition()); - if(thenCondition != null) { + if (thenCondition != null) { then.putAll(thenCondition); } - + return new RouteRule(when, then); } - + // TODO 目前ToString出来的列表是乱序的,是否要排序? static void join(StringBuilder sb, Set valueSet) { boolean isFirst = true; - for(String s : valueSet) { - if(isFirst) { - isFirst = false; - } - else { - sb.append(","); - } - - sb.append(s); + for (String s : valueSet) { + if (isFirst) { + isFirst = false; + } else { + sb.append(","); + } + + sb.append(s); } } - + /** * 样本是否通过条件。 *

* 如果样本的KV中,存在Key有对应的MatchPair,且Value不通过MatchPair里,返回{@code false}; * 否则返回{@code true}。 - * + * * @see MatchPair#pass(String) */ public static boolean matchCondition(Map sample, @@ -450,66 +347,65 @@ public static boolean matchCondition(Map sample, } return true; } - - + + // FIXME 去掉这样的方法调用 public static String join(Set valueSet) { StringBuilder sb = new StringBuilder(128); join(sb, valueSet); return sb.toString(); } - + // TODO 目前Condition的多个Key是乱序的,是否要排序? public static void contidionToString(StringBuilder sb, Map condition) { boolean isFirst = true; - for(Entry entry: condition.entrySet()) { + for (Entry entry : condition.entrySet()) { String keyName = entry.getKey(); MatchPair p = entry.getValue(); - + @SuppressWarnings("unchecked") Set[] setArray = new Set[]{p.matches, p.unmatches}; String[] opArray = {" = ", " != "}; - - for(int i = 0; i < setArray.length; ++i) { - if(setArray[i].isEmpty()) { + + for (int i = 0; i < setArray.length; ++i) { + if (setArray[i].isEmpty()) { continue; } - if(isFirst) { + if (isFirst) { isFirst = false; - } - else { + } else { sb.append(" & "); } - + sb.append(keyName); sb.append(opArray[i]); join(sb, setArray[i]); } } } - + public boolean isWhenContainValue(String key, String value) { MatchPair matchPair = whenCondition.get(key); - if(null == matchPair) { + if (null == matchPair) { return false; } - + return matchPair.containeValue(value); } - + public boolean isThenContainValue(String key, String value) { MatchPair matchPair = thenCondition.get(key); - if(null == matchPair) { + if (null == matchPair) { return false; } - + return matchPair.containeValue(value); } - + public boolean isContainValue(String key, String value) { return isWhenContainValue(key, value) || isThenContainValue(key, value); } - + public Map getWhenCondition() { return whenCondition; } @@ -517,25 +413,23 @@ public Map getWhenCondition() { public Map getThenCondition() { return thenCondition; } - + public String getWhenConditionString() { - StringBuilder sb = new StringBuilder(512); + StringBuilder sb = new StringBuilder(512); contidionToString(sb, whenCondition); - return sb.toString(); + return sb.toString(); } public String getThenConditionString() { - StringBuilder sb = new StringBuilder(512); + StringBuilder sb = new StringBuilder(512); contidionToString(sb, thenCondition); - return sb.toString(); + return sb.toString(); } - private volatile String tostring = null; - @Override public String toString() { - if(tostring != null) - return tostring; + if (tostring != null) + return tostring; StringBuilder sb = new StringBuilder(512); contidionToString(sb, whenCondition); sb.append(" => "); @@ -575,4 +469,103 @@ public boolean equals(Object obj) { return false; return true; } + + public static class MatchPair { + Set matches = new HashSet(); + Set unmatches = new HashSet(); + private volatile boolean freezed = false; + + public MatchPair() { + } + + public MatchPair(Set matches, Set unmatches) { + if (matches == null || unmatches == null) { + throw new IllegalArgumentException("argument of MatchPair is null!"); + } + + this.matches = matches; + this.unmatches = unmatches; + } + + public Set getMatches() { + return matches; + } + + public Set getUnmatches() { + return unmatches; + } + + public MatchPair copy() { + MatchPair ret = new MatchPair(); + ret.matches.addAll(matches); + ret.unmatches.addAll(unmatches); + return ret; + } + + void freeze() { + if (freezed) return; + synchronized (this) { + if (freezed) return; + matches = Collections.unmodifiableSet(matches); + unmatches = Collections.unmodifiableSet(unmatches); + } + } + + public boolean containeValue(String value) { + return matches.contains(value) || unmatches.contains(value); + } + + /** + * 给定的值是否通过该{@link MatchPair}匹配。

+ * 返回{@code false},如果 + *

    + *
  1. value在unmatches列表中 + *
  2. matches列表有值,但value不在matches列表中。 + *
+ * otherwise返回true。 + */ + public boolean pass(String sample) { + if (unmatches.contains(sample)) return false; + if (matches.isEmpty()) return true; + return matches.contains(sample); + } + + @Override + public String toString() { + return String.format("{matches=%s,unmatches=%s}", matches.toString(), unmatches.toString()); + } + + // 用Eclipse自动生成 + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((matches == null) ? 0 : matches.hashCode()); + result = prime * result + ((unmatches == null) ? 0 : unmatches.hashCode()); + return result; + } + + // 用Eclipse自动生成 + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + MatchPair other = (MatchPair) obj; + if (matches == null) { + if (other.matches != null) + return false; + } else if (!matches.equals(other.matches)) + return false; + if (unmatches == null) { + if (other.unmatches != null) + return false; + } else if (!unmatches.equals(other.unmatches)) + return false; + return true; + } + } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/route/RouteRuleUtils.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/route/RouteRuleUtils.java index 49b27be1078..a59fda62f64 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/route/RouteRuleUtils.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/route/RouteRuleUtils.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.server - * + *

* File Created at Oct 20, 2010 * $Id: RouteRuleUtils.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 1999-2100 Alibaba.com Corporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,6 +15,8 @@ */ package com.alibaba.dubbo.registry.common.route; +import com.alibaba.dubbo.common.utils.StringUtils; + import java.util.Collection; import java.util.HashMap; import java.util.HashSet; @@ -24,15 +26,14 @@ import java.util.Map.Entry; import java.util.Set; -import com.alibaba.dubbo.common.utils.StringUtils; - /** * @author william.liangf * @author ding.lid */ public class RouteRuleUtils { - private RouteRuleUtils() {} - + private RouteRuleUtils() { + } + /** * 把条件的一个键值展开后,合并到另外指定的键值中。 * @param 集合类型 @@ -44,94 +45,94 @@ private RouteRuleUtils() {} public static > Map expandCondition( Map condition, String srcKeyName, String destKeyName, Map expandName2Set) { - if(null == condition || StringUtils.isEmpty(srcKeyName) || StringUtils.isEmpty(destKeyName)) { + if (null == condition || StringUtils.isEmpty(srcKeyName) || StringUtils.isEmpty(destKeyName)) { return condition; } - + RouteRule.MatchPair matchPair = condition.get(srcKeyName); - if(matchPair == null) { + if (matchPair == null) { return condition; } - + Map ret = new HashMap(); - + Iterator> iterator = condition.entrySet().iterator(); - for(; iterator.hasNext();) { + for (; iterator.hasNext(); ) { Entry entry = iterator.next(); String condName = entry.getKey(); - + // 即不是源也不目的 - if(!condName.equals(srcKeyName) && !condName.equals(destKeyName)) { + if (!condName.equals(srcKeyName) && !condName.equals(destKeyName)) { RouteRule.MatchPair p = entry.getValue(); - if(p != null) ret.put(condName, p); + if (p != null) ret.put(condName, p); } // 等于源 - else if(condName.equals(srcKeyName)) { + else if (condName.equals(srcKeyName)) { RouteRule.MatchPair from = condition.get(srcKeyName); RouteRule.MatchPair to = condition.get(destKeyName); - + // 没有可Expand条目 - if(from == null || from.getMatches().isEmpty() && from.getUnmatches().isEmpty()) { - if(to != null) ret.put(destKeyName, to); + if (from == null || from.getMatches().isEmpty() && from.getUnmatches().isEmpty()) { + if (to != null) ret.put(destKeyName, to); continue; } - + Set matches = new HashSet(); Set unmatches = new HashSet(); // 添加上Expand来的条目 - for(String s : from.getMatches()) { - if(expandName2Set == null || !expandName2Set.containsKey(s)) continue; - + for (String s : from.getMatches()) { + if (expandName2Set == null || !expandName2Set.containsKey(s)) continue; + matches.addAll(expandName2Set.get(s)); } - for(String s : from.getUnmatches()) { - if(expandName2Set == null || !expandName2Set.containsKey(s)) continue; - + for (String s : from.getUnmatches()) { + if (expandName2Set == null || !expandName2Set.containsKey(s)) continue; + unmatches.addAll(expandName2Set.get(s)); } // 添加原来的条目 - if(to != null) { + if (to != null) { matches.addAll(to.getMatches()); unmatches.addAll(to.getUnmatches()); } - + ret.put(destKeyName, new RouteRule.MatchPair(matches, unmatches)); } // else 是 Key == destKeyName 的情况,无操作 } - + return ret; } - + /** * 判断KV(即条件对应的样本)是否符合条件。 - * + * * @param condition 条件,可以包含变量声明。 如{key1={matches={value1,value2,$var1},unmatches={Vx,Vy,$var2}}} * @param valueParams 条件中插值变量的值集合 * @param kv 校验条件的样本 * @see RouteRule */ public static boolean isMatchCondition(Map condition, - Map valueParams, Map kv) { - if (condition != null && condition.size() > 0) { - for (Map.Entry entry : condition.entrySet()) { - String condName = entry.getKey(); - RouteRule.MatchPair p = entry.getValue(); - String value = kv.get(condName); - Set matches = p.getMatches(); - if (matches != null && matches.size() > 0 - && ! ParseUtils.isMatchGlobPatternsNeedInterpolate(matches, valueParams, value)) { // 如何Value为null,返回False - // 不满足 匹配 - return false; - } - Set unmatches = p.getUnmatches(); - if (unmatches != null && unmatches.size() > 0 - && ParseUtils.isMatchGlobPatternsNeedInterpolate(unmatches, valueParams, value)) { - // 满足了 不匹配 - return false; - } - } - } + Map valueParams, Map kv) { + if (condition != null && condition.size() > 0) { + for (Map.Entry entry : condition.entrySet()) { + String condName = entry.getKey(); + RouteRule.MatchPair p = entry.getValue(); + String value = kv.get(condName); + Set matches = p.getMatches(); + if (matches != null && matches.size() > 0 + && !ParseUtils.isMatchGlobPatternsNeedInterpolate(matches, valueParams, value)) { // 如何Value为null,返回False + // 不满足 匹配 + return false; + } + Set unmatches = p.getUnmatches(); + if (unmatches != null && unmatches.size() > 0 + && ParseUtils.isMatchGlobPatternsNeedInterpolate(unmatches, valueParams, value)) { + // 满足了 不匹配 + return false; + } + } + } return true; } @@ -140,15 +141,15 @@ public static boolean isMatchCondition(Map conditio * 返回被RouteRule的When的service匹配到的Service。使用Glob匹配。 */ public static Set filterServiceByRule(List services, RouteRule rule) { - if(null == services || services.isEmpty() || rule == null) { + if (null == services || services.isEmpty() || rule == null) { return new HashSet(); } - + RouteRule.MatchPair p = rule.getWhenCondition().get("service"); - if(p == null) { + if (p == null) { return new HashSet(); } - + Set filter = ParseUtils.filterByGlobPattern(p.getMatches(), services); Set set = ParseUtils.filterByGlobPattern(p.getUnmatches(), services); filter.addAll(set); diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/route/RouteUtils.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/route/RouteUtils.java index 6318d95dbad..4c7604fa450 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/route/RouteUtils.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/route/RouteUtils.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.client-1.1.0-SNAPSHOT - * + *

* File Created at 2010-4-22 * $Id: RouteUtils.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,6 +15,11 @@ */ package com.alibaba.dubbo.registry.common.route; +import com.alibaba.dubbo.common.utils.StringUtils; +import com.alibaba.dubbo.registry.common.domain.Override; +import com.alibaba.dubbo.registry.common.domain.Provider; +import com.alibaba.dubbo.registry.common.domain.Route; + import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; @@ -24,40 +29,34 @@ import java.util.Map; import java.util.Set; -import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.registry.common.domain.Provider; -import com.alibaba.dubbo.registry.common.domain.Route; -import com.alibaba.dubbo.registry.common.domain.Override; - /** * RouteParser 路由规则解析。 - * + * * @author ding.lid */ public class RouteUtils { - + public static boolean matchRoute(String consumerAddress, String consumerQueryUrl, Route route, Map> clusters) { RouteRule rule = RouteRule.parseQuitely(route); Map when = RouteRuleUtils.expandCondition( rule.getWhenCondition(), "consumer.cluster", "consumer.host", clusters); Map consumerSample = ParseUtils.parseQuery("consumer.", consumerQueryUrl); - + final int index = consumerAddress.lastIndexOf(":"); String consumerHost = null; - if(index != -1){ + if (index != -1) { consumerHost = consumerAddress.substring(0, index); - } - else { + } else { consumerHost = consumerAddress; } consumerSample.put("consumer.host", consumerHost); - + return RouteRuleUtils.isMatchCondition(when, consumerSample, consumerSample); } - + public static Map previewRoute(String serviceName, String consumerAddress, String queryUrl, Map serviceUrls, - Route route, Map> clusters, List routed) { - if(null == route) { + Route route, Map> clusters, List routed) { + if (null == route) { throw new IllegalArgumentException("Route is null."); } List routes = new ArrayList(); @@ -69,36 +68,36 @@ public static Map previewRoute(String serviceName, String consum * @return Map */ public static List findUsedRoute(String serviceName, String consumerAddress, String consumerQueryUrl, - List routes, Map> clusters) { - List routed = new ArrayList(); - Map urls = new HashMap(); - urls.put("dubbo://" + consumerAddress + "/" + serviceName, consumerQueryUrl); - RouteUtils.route(serviceName, consumerAddress, consumerQueryUrl, urls, routes, clusters, routed); - return routed; + List routes, Map> clusters) { + List routed = new ArrayList(); + Map urls = new HashMap(); + urls.put("dubbo://" + consumerAddress + "/" + serviceName, consumerQueryUrl); + RouteUtils.route(serviceName, consumerAddress, consumerQueryUrl, urls, routes, clusters, routed); + return routed; } - + public static List route(String serviceName, String consumerAddress, String consumerQueryUrl, List providers, - List overrides, List routes, Map> clusters, List routed) { - if (providers == null) { - return null; - } - Map urls = new HashMap(); - urls.put("consumer://" + consumerAddress + "/" + serviceName, consumerQueryUrl); // not empty dummy data - for (Provider provider : providers) { - if (com.alibaba.dubbo.governance.web.common.pulltool.Tool.isProviderEnabled(provider, overrides)) { - urls.put(provider.getUrl(), provider.getParameters()); - } - } - urls = RouteUtils.route(serviceName, consumerAddress, consumerQueryUrl, urls, routes, clusters, routed); - List result = new ArrayList(); - for (Provider provider : providers) { - if (urls.containsKey(provider.getUrl())) { - result.add(provider); - } - } - return result; + List overrides, List routes, Map> clusters, List routed) { + if (providers == null) { + return null; + } + Map urls = new HashMap(); + urls.put("consumer://" + consumerAddress + "/" + serviceName, consumerQueryUrl); // not empty dummy data + for (Provider provider : providers) { + if (com.alibaba.dubbo.governance.web.common.pulltool.Tool.isProviderEnabled(provider, overrides)) { + urls.put(provider.getUrl(), provider.getParameters()); + } + } + urls = RouteUtils.route(serviceName, consumerAddress, consumerQueryUrl, urls, routes, clusters, routed); + List result = new ArrayList(); + for (Provider provider : providers) { + if (urls.containsKey(provider.getUrl())) { + result.add(provider); + } + } + return result; } - + /** * @param serviceName 服务名,如{@code com.alibaba.morgan.MemberService} * @param consumerAddress 消费者地址,如{@code 192.168.1.3:54333} @@ -111,7 +110,7 @@ public static List route(String serviceName, String consumerAddress, S // FIXME clusters和routes的合并,可以在clusters或routes变化时预先做 // FIXME 从Util方法中分离出Cache的操作 public static Map route(String serviceName, String consumerAddress, String consumerQueryUrl, Map serviceUrls, - List routes, Map> clusters, List routed) { + List routes, Map> clusters, List routed) { if (serviceUrls == null || serviceUrls.size() == 0) { return serviceUrls; } @@ -120,18 +119,17 @@ public static Map route(String serviceName, String consumerAddre } Map rules = route2RouteRule(routes, clusters); - + final Map consumerSample = ParseUtils.parseQuery("consumer.", consumerQueryUrl); final int index = consumerAddress.lastIndexOf(":"); final String consumerHost; - if(consumerAddress != null && index != -1){ + if (consumerAddress != null && index != -1) { consumerHost = consumerAddress.substring(0, index); - } - else { + } else { consumerHost = consumerAddress; } consumerSample.put("consumer.host", consumerHost); - + Map> url2ProviderSample = new HashMap>(); for (Map.Entry entry : serviceUrls.entrySet()) { URI uri; @@ -145,13 +143,13 @@ public static Map route(String serviceName, String consumerAddre sample.put("provider.protocol", uri.getScheme()); sample.put("provider.host", uri.getHost()); sample.put("provider.port", String.valueOf(uri.getPort())); - + url2ProviderSample.put(entry.getKey(), sample); } - - + + Map> url2Methods = new HashMap>(); - + // consumer可以通过consumer.methods Key指定需要的方法 String methodsString = consumerSample.get("consumer.methods"); String[] methods = methodsString == null || methodsString.length() == 0 ? new String[]{Route.ALL_METHOD} : methodsString.split(ParseUtils.METHOD_SPLIT); @@ -167,14 +165,14 @@ public static Map route(String serviceName, String consumerAddre // 当满足when条件时 if (rule != null && RouteRuleUtils.isMatchCondition( rule.getWhenCondition(), consumerSample, consumerSample)) { - if (routed != null && ! routed.contains(route)) { - routed.add(route); - } + if (routed != null && !routed.contains(route)) { + routed.add(route); + } Map then = rule.getThenCondition(); if (then != null) { Map> tmp = getUrlsMatchedCondition(then, consumerSample, url2ProviderSample); // 如果规则的结果是空,则该规则无效,使用所有Provider - if (route.isForce() || ! tmp.isEmpty()){ + if (route.isForce() || !tmp.isEmpty()) { url2ProviderSample = tmp; } } @@ -194,13 +192,13 @@ public static Map route(String serviceName, String consumerAddre return appendMethodsToUrls(serviceUrls, url2Methods); } - + static Map route2RouteRule(List routes, Map> clusters) { Map rules = new HashMap(); // route -> RouteRule if (routes != null && routes.size() > 0) { - for(Route route: routes) { + for (Route route : routes) { rules.put(route.getId(), RouteRule.parseQuitely(route)); } } @@ -209,12 +207,12 @@ static Map route2RouteRule(List routes, Map rrs = new HashMap(); for (Map.Entry entry : rules.entrySet()) { RouteRule rr = entry.getValue(); - + Map when = RouteRuleUtils.expandCondition( rr.getWhenCondition(), "consumer.cluster", "consumer.host", clusters); Map then = RouteRuleUtils.expandCondition( rr.getThenCondition(), "provider.cluster", "provider.host", clusters); - + rrs.put(entry.getKey(), RouteRule.createFromCondition(when, then)); } rules = rrs; @@ -223,13 +221,13 @@ static Map route2RouteRule(List routes, } static Map appendMethodsToUrls(Map serviceUrls, - Map> url2Methods) { + Map> url2Methods) { // 为URL上加上方法参数 Map results = new HashMap(); for (Map.Entry> entry : url2Methods.entrySet()) { String url = entry.getKey(); String query = serviceUrls.get(url); - + Set methodNames = entry.getValue(); if (methodNames != null && methodNames.size() > 0) { String ms = StringUtils.join(methodNames.toArray(new String[0]), ParseUtils.METHOD_SPLIT); @@ -239,7 +237,7 @@ static Map appendMethodsToUrls(Map serviceUrls, } return results; } - + static Route getFirstRouteMatchedWhenConditionOfRule(String serviceName, Map consumerSample, List routes, Map routeRuleMap) { if (serviceName == null || serviceName.length() == 0) { return null; @@ -258,55 +256,55 @@ static Route getFirstRouteMatchedWhenConditionOfRule(String serviceName, Map> getUrlsMatchedCondition(Map condition, - Map parameters, Map> url2Sample) { + Map parameters, Map> url2Sample) { Map> result = new HashMap>(); for (Map.Entry> entry : url2Sample.entrySet()) { Map sample = entry.getValue(); - + Map params = new HashMap(); params.putAll(sample); params.putAll(parameters); - + if (RouteRuleUtils.isMatchCondition(condition, params, sample)) { result.put(entry.getKey(), entry.getValue()); } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/status/DatabaseStatusChecker.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/status/DatabaseStatusChecker.java index fae4e953717..0659d6bcb82 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/status/DatabaseStatusChecker.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/status/DatabaseStatusChecker.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.server-1.1.0-SNAPSHOT - * + *

* File Created at 2009-12-27 * $Id: DatabaseStatusChecker.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,32 +15,31 @@ */ package com.alibaba.dubbo.registry.common.status; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.ResultSet; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; - import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.status.Status; import com.alibaba.dubbo.common.status.StatusChecker; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; + /** * DatabaseStatus - * + * * @author william.liangf */ public class DatabaseStatusChecker implements StatusChecker { private static final Logger logger = LoggerFactory.getLogger(DatabaseStatusChecker.class); - + private int version; - + private String message; - + @Autowired private DataSource dataSource; @@ -63,9 +62,9 @@ public Status check() { } if (message == null) { message = metaData.getURL() - + " (" + metaData.getDatabaseProductName() - + " " + metaData.getDatabaseProductVersion() - + ", " + getIsolation(metaData.getDefaultTransactionIsolation()) + ")"; + + " (" + metaData.getDatabaseProductName() + + " " + metaData.getDatabaseProductVersion() + + ", " + getIsolation(metaData.getDefaultTransactionIsolation()) + ")"; } if (version == 0) { version = metaData.getDatabaseMajorVersion(); @@ -77,9 +76,9 @@ public Status check() { logger.error(e.getMessage(), e); ok = false; } - return new Status(! ok ? Status.Level.ERROR : (version < 5 ? Status.Level.WARN : Status.Level.OK), message); + return new Status(!ok ? Status.Level.ERROR : (version < 5 ? Status.Level.WARN : Status.Level.OK), message); } - + private String getIsolation(int i) { if (i == Connection.TRANSACTION_READ_COMMITTED) { return "READ_COMMITTED"; diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/status/LoadStatusChecker.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/status/LoadStatusChecker.java index b717cff8206..2571a7f9de9 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/status/LoadStatusChecker.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/status/LoadStatusChecker.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.server-1.1.0-SNAPSHOT - * + *

* File Created at 2009-12-27 * $Id: LoadStatusChecker.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,30 +15,30 @@ */ package com.alibaba.dubbo.registry.common.status; +import com.alibaba.dubbo.common.status.Status; +import com.alibaba.dubbo.common.status.StatusChecker; + import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; import java.lang.reflect.Method; -import com.alibaba.dubbo.common.status.Status; -import com.alibaba.dubbo.common.status.StatusChecker; - /** * Load Status - * + * * @author william.liangf */ public class LoadStatusChecker implements StatusChecker { public Status check() { - OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean(); - double load; - try { - Method method = OperatingSystemMXBean.class.getMethod("getSystemLoadAverage", new Class[0]); - load = (Double)method.invoke(operatingSystemMXBean, new Object[0]); - } catch (Throwable e) { - load = -1; - } - int cpu = operatingSystemMXBean.getAvailableProcessors(); + OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean(); + double load; + try { + Method method = OperatingSystemMXBean.class.getMethod("getSystemLoadAverage", new Class[0]); + load = (Double) method.invoke(operatingSystemMXBean, new Object[0]); + } catch (Throwable e) { + load = -1; + } + int cpu = operatingSystemMXBean.getAvailableProcessors(); return new Status(load < 0 ? Status.Level.UNKNOWN : (load < cpu ? Status.Level.OK : Status.Level.WARN), "Load: " + load + " / CPU: " + cpu); } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/status/MemoryStatusChecker.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/status/MemoryStatusChecker.java index 7968623bae6..83c13464076 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/status/MemoryStatusChecker.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/status/MemoryStatusChecker.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.server-1.1.0-SNAPSHOT - * + *

* File Created at 2009-12-27 * $Id: MemoryStatusChecker.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -20,7 +20,7 @@ /** * MemoryStatus - * + * * @author william.liangf */ public class MemoryStatusChecker implements StatusChecker { @@ -31,9 +31,9 @@ public Status check() { long totalMemory = runtime.totalMemory(); long maxMemory = runtime.maxMemory(); boolean ok = (maxMemory - (totalMemory - freeMemory) > 2048); // 剩余空间小于2M报警 - String msg = "Max:" + (maxMemory / 1024 / 1024) + "M, Total:" - + (totalMemory / 1024 / 1024) + "M, Free:" + (freeMemory / 1024 / 1024) - + "M, Use:" + ((totalMemory / 1024 / 1024) - (freeMemory / 1024 / 1024)) + "M"; + String msg = "Max:" + (maxMemory / 1024 / 1024) + "M, Total:" + + (totalMemory / 1024 / 1024) + "M, Free:" + (freeMemory / 1024 / 1024) + + "M, Use:" + ((totalMemory / 1024 / 1024) - (freeMemory / 1024 / 1024)) + "M"; return new Status(ok ? Status.Level.OK : Status.Level.WARN, msg); } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/Coder.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/Coder.java index a3df6a16f8e..f50fc6d3c7b 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/Coder.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/Coder.java @@ -1,42 +1,43 @@ package com.alibaba.dubbo.registry.common.util; +import com.alibaba.dubbo.common.io.Bytes; + import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import com.alibaba.dubbo.common.io.Bytes; - public class Coder { - public static String encodeHex(byte[] bytes) { - StringBuffer buffer = new StringBuffer(bytes.length * 2); - for (int i = 0; i < bytes.length; i++) { - if (((int) bytes[i] & 0xff) < 0x10) - buffer.append("0"); - buffer.append(Long.toString((int) bytes[i] & 0xff, 16)); - } - return buffer.toString(); - } - - public static String encodeMd5(String source) { - return encodeMd5(source.getBytes()); - } - - public static String encodeMd5(byte[] source) { - try { - return encodeHex(MessageDigest.getInstance("MD5").digest(source)); - } catch (NoSuchAlgorithmException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public static String encodeBase64(String source) { - return Bytes.bytes2base64(source.getBytes()); - } - - public static String decodeBase64(String source) { - return new String(Bytes.base642bytes(source)); - } - - private Coder() {} - + private Coder() { + } + + public static String encodeHex(byte[] bytes) { + StringBuffer buffer = new StringBuffer(bytes.length * 2); + for (int i = 0; i < bytes.length; i++) { + if (((int) bytes[i] & 0xff) < 0x10) + buffer.append("0"); + buffer.append(Long.toString((int) bytes[i] & 0xff, 16)); + } + return buffer.toString(); + } + + public static String encodeMd5(String source) { + return encodeMd5(source.getBytes()); + } + + public static String encodeMd5(byte[] source) { + try { + return encodeHex(MessageDigest.getInstance("MD5").digest(source)); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e.getMessage(), e); + } + } + + public static String encodeBase64(String source) { + return Bytes.bytes2base64(source.getBytes()); + } + + public static String decodeBase64(String source) { + return new String(Bytes.base642bytes(source)); + } + } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/Entities.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/Entities.java index 25cab4c3eab..64cba7a3a0d 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/Entities.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/Entities.java @@ -28,347 +28,340 @@ *

* Provides HTML and XML entity utilities. *

- * + * + * @author Alexander Day Chaffee + * @author Gary Gregory + * @version $Id: Entities.java 181192 2012-06-21 05:05:47Z tony.chenl $ * @see ISO Entities * @see HTML 3.2 Character Entities for ISO Latin-1 * @see HTML 4.0 Character entity references * @see HTML 4.01 Character References * @see HTML 4.01 Code positions - * - * @author Alexander Day Chaffee - * @author Gary Gregory * @since 2.0 - * @version $Id: Entities.java 181192 2012-06-21 05:05:47Z tony.chenl $ */ class Entities { - private static final String[][] BASIC_ARRAY = {{"quot", "34"}, // " - double-quote - {"amp", "38"}, // & - ampersand - {"lt", "60"}, // < - less-than - {"gt", "62"}, // > - greater-than - }; - - private static final String[][] APOS_ARRAY = {{"apos", "39"}, // XML apostrophe - }; - - // package scoped for testing - static final String[][] ISO8859_1_ARRAY = {{"nbsp", "160"}, // non-breaking space - {"iexcl", "161"}, // inverted exclamation mark - {"cent", "162"}, // cent sign - {"pound", "163"}, // pound sign - {"curren", "164"}, // currency sign - {"yen", "165"}, // yen sign = yuan sign - {"brvbar", "166"}, // broken bar = broken vertical bar - {"sect", "167"}, // section sign - {"uml", "168"}, // diaeresis = spacing diaeresis - {"copy", "169"}, // � - copyright sign - {"ordf", "170"}, // feminine ordinal indicator - {"laquo", "171"}, // left-pointing double angle quotation mark = left pointing guillemet - {"not", "172"}, // not sign - {"shy", "173"}, // soft hyphen = discretionary hyphen - {"reg", "174"}, // � - registered trademark sign - {"macr", "175"}, // macron = spacing macron = overline = APL overbar - {"deg", "176"}, // degree sign - {"plusmn", "177"}, // plus-minus sign = plus-or-minus sign - {"sup2", "178"}, // superscript two = superscript digit two = squared - {"sup3", "179"}, // superscript three = superscript digit three = cubed - {"acute", "180"}, // acute accent = spacing acute - {"micro", "181"}, // micro sign - {"para", "182"}, // pilcrow sign = paragraph sign - {"middot", "183"}, // middle dot = Georgian comma = Greek middle dot - {"cedil", "184"}, // cedilla = spacing cedilla - {"sup1", "185"}, // superscript one = superscript digit one - {"ordm", "186"}, // masculine ordinal indicator - {"raquo", "187"}, // right-pointing double angle quotation mark = right pointing guillemet - {"frac14", "188"}, // vulgar fraction one quarter = fraction one quarter - {"frac12", "189"}, // vulgar fraction one half = fraction one half - {"frac34", "190"}, // vulgar fraction three quarters = fraction three quarters - {"iquest", "191"}, // inverted question mark = turned question mark - {"Agrave", "192"}, // � - uppercase A, grave accent - {"Aacute", "193"}, // � - uppercase A, acute accent - {"Acirc", "194"}, // � - uppercase A, circumflex accent - {"Atilde", "195"}, // � - uppercase A, tilde - {"Auml", "196"}, // � - uppercase A, umlaut - {"Aring", "197"}, // � - uppercase A, ring - {"AElig", "198"}, // � - uppercase AE - {"Ccedil", "199"}, // � - uppercase C, cedilla - {"Egrave", "200"}, // � - uppercase E, grave accent - {"Eacute", "201"}, // � - uppercase E, acute accent - {"Ecirc", "202"}, // � - uppercase E, circumflex accent - {"Euml", "203"}, // � - uppercase E, umlaut - {"Igrave", "204"}, // � - uppercase I, grave accent - {"Iacute", "205"}, // � - uppercase I, acute accent - {"Icirc", "206"}, // � - uppercase I, circumflex accent - {"Iuml", "207"}, // � - uppercase I, umlaut - {"ETH", "208"}, // � - uppercase Eth, Icelandic - {"Ntilde", "209"}, // � - uppercase N, tilde - {"Ograve", "210"}, // � - uppercase O, grave accent - {"Oacute", "211"}, // � - uppercase O, acute accent - {"Ocirc", "212"}, // � - uppercase O, circumflex accent - {"Otilde", "213"}, // � - uppercase O, tilde - {"Ouml", "214"}, // � - uppercase O, umlaut - {"times", "215"}, // multiplication sign - {"Oslash", "216"}, // � - uppercase O, slash - {"Ugrave", "217"}, // � - uppercase U, grave accent - {"Uacute", "218"}, // � - uppercase U, acute accent - {"Ucirc", "219"}, // � - uppercase U, circumflex accent - {"Uuml", "220"}, // � - uppercase U, umlaut - {"Yacute", "221"}, // � - uppercase Y, acute accent - {"THORN", "222"}, // � - uppercase THORN, Icelandic - {"szlig", "223"}, // � - lowercase sharps, German - {"agrave", "224"}, // � - lowercase a, grave accent - {"aacute", "225"}, // � - lowercase a, acute accent - {"acirc", "226"}, // � - lowercase a, circumflex accent - {"atilde", "227"}, // � - lowercase a, tilde - {"auml", "228"}, // � - lowercase a, umlaut - {"aring", "229"}, // � - lowercase a, ring - {"aelig", "230"}, // � - lowercase ae - {"ccedil", "231"}, // � - lowercase c, cedilla - {"egrave", "232"}, // � - lowercase e, grave accent - {"eacute", "233"}, // � - lowercase e, acute accent - {"ecirc", "234"}, // � - lowercase e, circumflex accent - {"euml", "235"}, // � - lowercase e, umlaut - {"igrave", "236"}, // � - lowercase i, grave accent - {"iacute", "237"}, // � - lowercase i, acute accent - {"icirc", "238"}, // � - lowercase i, circumflex accent - {"iuml", "239"}, // � - lowercase i, umlaut - {"eth", "240"}, // � - lowercase eth, Icelandic - {"ntilde", "241"}, // � - lowercase n, tilde - {"ograve", "242"}, // � - lowercase o, grave accent - {"oacute", "243"}, // � - lowercase o, acute accent - {"ocirc", "244"}, // � - lowercase o, circumflex accent - {"otilde", "245"}, // � - lowercase o, tilde - {"ouml", "246"}, // � - lowercase o, umlaut - {"divide", "247"}, // division sign - {"oslash", "248"}, // � - lowercase o, slash - {"ugrave", "249"}, // � - lowercase u, grave accent - {"uacute", "250"}, // � - lowercase u, acute accent - {"ucirc", "251"}, // � - lowercase u, circumflex accent - {"uuml", "252"}, // � - lowercase u, umlaut - {"yacute", "253"}, // � - lowercase y, acute accent - {"thorn", "254"}, // � - lowercase thorn, Icelandic - {"yuml", "255"}, // � - lowercase y, umlaut - }; - - // http://www.w3.org/TR/REC-html40/sgml/entities.html - // package scoped for testing - static final String[][] HTML40_ARRAY = { - // - {"fnof", "402"}, // latin small f with hook = function= florin, U+0192 ISOtech --> - // - {"Alpha", "913"}, // greek capital letter alpha, U+0391 --> - {"Beta", "914"}, // greek capital letter beta, U+0392 --> - {"Gamma", "915"}, // greek capital letter gamma,U+0393 ISOgrk3 --> - {"Delta", "916"}, // greek capital letter delta,U+0394 ISOgrk3 --> - {"Epsilon", "917"}, // greek capital letter epsilon, U+0395 --> - {"Zeta", "918"}, // greek capital letter zeta, U+0396 --> - {"Eta", "919"}, // greek capital letter eta, U+0397 --> - {"Theta", "920"}, // greek capital letter theta,U+0398 ISOgrk3 --> - {"Iota", "921"}, // greek capital letter iota, U+0399 --> - {"Kappa", "922"}, // greek capital letter kappa, U+039A --> - {"Lambda", "923"}, // greek capital letter lambda,U+039B ISOgrk3 --> - {"Mu", "924"}, // greek capital letter mu, U+039C --> - {"Nu", "925"}, // greek capital letter nu, U+039D --> - {"Xi", "926"}, // greek capital letter xi, U+039E ISOgrk3 --> - {"Omicron", "927"}, // greek capital letter omicron, U+039F --> - {"Pi", "928"}, // greek capital letter pi, U+03A0 ISOgrk3 --> - {"Rho", "929"}, // greek capital letter rho, U+03A1 --> - // - {"Sigma", "931"}, // greek capital letter sigma,U+03A3 ISOgrk3 --> - {"Tau", "932"}, // greek capital letter tau, U+03A4 --> - {"Upsilon", "933"}, // greek capital letter upsilon,U+03A5 ISOgrk3 --> - {"Phi", "934"}, // greek capital letter phi,U+03A6 ISOgrk3 --> - {"Chi", "935"}, // greek capital letter chi, U+03A7 --> - {"Psi", "936"}, // greek capital letter psi,U+03A8 ISOgrk3 --> - {"Omega", "937"}, // greek capital letter omega,U+03A9 ISOgrk3 --> - {"alpha", "945"}, // greek small letter alpha,U+03B1 ISOgrk3 --> - {"beta", "946"}, // greek small letter beta, U+03B2 ISOgrk3 --> - {"gamma", "947"}, // greek small letter gamma,U+03B3 ISOgrk3 --> - {"delta", "948"}, // greek small letter delta,U+03B4 ISOgrk3 --> - {"epsilon", "949"}, // greek small letter epsilon,U+03B5 ISOgrk3 --> - {"zeta", "950"}, // greek small letter zeta, U+03B6 ISOgrk3 --> - {"eta", "951"}, // greek small letter eta, U+03B7 ISOgrk3 --> - {"theta", "952"}, // greek small letter theta,U+03B8 ISOgrk3 --> - {"iota", "953"}, // greek small letter iota, U+03B9 ISOgrk3 --> - {"kappa", "954"}, // greek small letter kappa,U+03BA ISOgrk3 --> - {"lambda", "955"}, // greek small letter lambda,U+03BB ISOgrk3 --> - {"mu", "956"}, // greek small letter mu, U+03BC ISOgrk3 --> - {"nu", "957"}, // greek small letter nu, U+03BD ISOgrk3 --> - {"xi", "958"}, // greek small letter xi, U+03BE ISOgrk3 --> - {"omicron", "959"}, // greek small letter omicron, U+03BF NEW --> - {"pi", "960"}, // greek small letter pi, U+03C0 ISOgrk3 --> - {"rho", "961"}, // greek small letter rho, U+03C1 ISOgrk3 --> - {"sigmaf", "962"}, // greek small letter final sigma,U+03C2 ISOgrk3 --> - {"sigma", "963"}, // greek small letter sigma,U+03C3 ISOgrk3 --> - {"tau", "964"}, // greek small letter tau, U+03C4 ISOgrk3 --> - {"upsilon", "965"}, // greek small letter upsilon,U+03C5 ISOgrk3 --> - {"phi", "966"}, // greek small letter phi, U+03C6 ISOgrk3 --> - {"chi", "967"}, // greek small letter chi, U+03C7 ISOgrk3 --> - {"psi", "968"}, // greek small letter psi, U+03C8 ISOgrk3 --> - {"omega", "969"}, // greek small letter omega,U+03C9 ISOgrk3 --> - {"thetasym", "977"}, // greek small letter theta symbol,U+03D1 NEW --> - {"upsih", "978"}, // greek upsilon with hook symbol,U+03D2 NEW --> - {"piv", "982"}, // greek pi symbol, U+03D6 ISOgrk3 --> - // - {"bull", "8226"}, // bullet = black small circle,U+2022 ISOpub --> - // - {"hellip", "8230"}, // horizontal ellipsis = three dot leader,U+2026 ISOpub --> - {"prime", "8242"}, // prime = minutes = feet, U+2032 ISOtech --> - {"Prime", "8243"}, // double prime = seconds = inches,U+2033 ISOtech --> - {"oline", "8254"}, // overline = spacing overscore,U+203E NEW --> - {"frasl", "8260"}, // fraction slash, U+2044 NEW --> - // - {"weierp", "8472"}, // script capital P = power set= Weierstrass p, U+2118 ISOamso --> - {"image", "8465"}, // blackletter capital I = imaginary part,U+2111 ISOamso --> - {"real", "8476"}, // blackletter capital R = real part symbol,U+211C ISOamso --> - {"trade", "8482"}, // trade mark sign, U+2122 ISOnum --> - {"alefsym", "8501"}, // alef symbol = first transfinite cardinal,U+2135 NEW --> - // - // - {"larr", "8592"}, // leftwards arrow, U+2190 ISOnum --> - {"uarr", "8593"}, // upwards arrow, U+2191 ISOnum--> - {"rarr", "8594"}, // rightwards arrow, U+2192 ISOnum --> - {"darr", "8595"}, // downwards arrow, U+2193 ISOnum --> - {"harr", "8596"}, // left right arrow, U+2194 ISOamsa --> - {"crarr", "8629"}, // downwards arrow with corner leftwards= carriage return, U+21B5 NEW --> - {"lArr", "8656"}, // leftwards double arrow, U+21D0 ISOtech --> - // - {"uArr", "8657"}, // upwards double arrow, U+21D1 ISOamsa --> - {"rArr", "8658"}, // rightwards double arrow,U+21D2 ISOtech --> - // - {"dArr", "8659"}, // downwards double arrow, U+21D3 ISOamsa --> - {"hArr", "8660"}, // left right double arrow,U+21D4 ISOamsa --> - // - {"forall", "8704"}, // for all, U+2200 ISOtech --> - {"part", "8706"}, // partial differential, U+2202 ISOtech --> - {"exist", "8707"}, // there exists, U+2203 ISOtech --> - {"empty", "8709"}, // empty set = null set = diameter,U+2205 ISOamso --> - {"nabla", "8711"}, // nabla = backward difference,U+2207 ISOtech --> - {"isin", "8712"}, // element of, U+2208 ISOtech --> - {"notin", "8713"}, // not an element of, U+2209 ISOtech --> - {"ni", "8715"}, // contains as member, U+220B ISOtech --> - // - {"prod", "8719"}, // n-ary product = product sign,U+220F ISOamsb --> - // - {"sum", "8721"}, // n-ary summation, U+2211 ISOamsb --> - // - {"minus", "8722"}, // minus sign, U+2212 ISOtech --> - {"lowast", "8727"}, // asterisk operator, U+2217 ISOtech --> - {"radic", "8730"}, // square root = radical sign,U+221A ISOtech --> - {"prop", "8733"}, // proportional to, U+221D ISOtech --> - {"infin", "8734"}, // infinity, U+221E ISOtech --> - {"ang", "8736"}, // angle, U+2220 ISOamso --> - {"and", "8743"}, // logical and = wedge, U+2227 ISOtech --> - {"or", "8744"}, // logical or = vee, U+2228 ISOtech --> - {"cap", "8745"}, // intersection = cap, U+2229 ISOtech --> - {"cup", "8746"}, // union = cup, U+222A ISOtech --> - {"int", "8747"}, // integral, U+222B ISOtech --> - {"there4", "8756"}, // therefore, U+2234 ISOtech --> - {"sim", "8764"}, // tilde operator = varies with = similar to,U+223C ISOtech --> - // - {"cong", "8773"}, // approximately equal to, U+2245 ISOtech --> - {"asymp", "8776"}, // almost equal to = asymptotic to,U+2248 ISOamsr --> - {"ne", "8800"}, // not equal to, U+2260 ISOtech --> - {"equiv", "8801"}, // identical to, U+2261 ISOtech --> - {"le", "8804"}, // less-than or equal to, U+2264 ISOtech --> - {"ge", "8805"}, // greater-than or equal to,U+2265 ISOtech --> - {"sub", "8834"}, // subset of, U+2282 ISOtech --> - {"sup", "8835"}, // superset of, U+2283 ISOtech --> - // - {"sube", "8838"}, // subset of or equal to, U+2286 ISOtech --> - {"supe", "8839"}, // superset of or equal to,U+2287 ISOtech --> - {"oplus", "8853"}, // circled plus = direct sum,U+2295 ISOamsb --> - {"otimes", "8855"}, // circled times = vector product,U+2297 ISOamsb --> - {"perp", "8869"}, // up tack = orthogonal to = perpendicular,U+22A5 ISOtech --> - {"sdot", "8901"}, // dot operator, U+22C5 ISOamsb --> - // - // - {"lceil", "8968"}, // left ceiling = apl upstile,U+2308 ISOamsc --> - {"rceil", "8969"}, // right ceiling, U+2309 ISOamsc --> - {"lfloor", "8970"}, // left floor = apl downstile,U+230A ISOamsc --> - {"rfloor", "8971"}, // right floor, U+230B ISOamsc --> - {"lang", "9001"}, // left-pointing angle bracket = bra,U+2329 ISOtech --> - // - {"rang", "9002"}, // right-pointing angle bracket = ket,U+232A ISOtech --> - // - // - {"loz", "9674"}, // lozenge, U+25CA ISOpub --> - // - {"spades", "9824"}, // black spade suit, U+2660 ISOpub --> - // - {"clubs", "9827"}, // black club suit = shamrock,U+2663 ISOpub --> - {"hearts", "9829"}, // black heart suit = valentine,U+2665 ISOpub --> - {"diams", "9830"}, // black diamond suit, U+2666 ISOpub --> - - // - {"OElig", "338"}, // -- latin capital ligature OE,U+0152 ISOlat2 --> - {"oelig", "339"}, // -- latin small ligature oe, U+0153 ISOlat2 --> - // - {"Scaron", "352"}, // -- latin capital letter S with caron,U+0160 ISOlat2 --> - {"scaron", "353"}, // -- latin small letter s with caron,U+0161 ISOlat2 --> - {"Yuml", "376"}, // -- latin capital letter Y with diaeresis,U+0178 ISOlat2 --> - // - {"circ", "710"}, // -- modifier letter circumflex accent,U+02C6 ISOpub --> - {"tilde", "732"}, // small tilde, U+02DC ISOdia --> - // - {"ensp", "8194"}, // en space, U+2002 ISOpub --> - {"emsp", "8195"}, // em space, U+2003 ISOpub --> - {"thinsp", "8201"}, // thin space, U+2009 ISOpub --> - {"zwnj", "8204"}, // zero width non-joiner,U+200C NEW RFC 2070 --> - {"zwj", "8205"}, // zero width joiner, U+200D NEW RFC 2070 --> - {"lrm", "8206"}, // left-to-right mark, U+200E NEW RFC 2070 --> - {"rlm", "8207"}, // right-to-left mark, U+200F NEW RFC 2070 --> - {"ndash", "8211"}, // en dash, U+2013 ISOpub --> - {"mdash", "8212"}, // em dash, U+2014 ISOpub --> - {"lsquo", "8216"}, // left single quotation mark,U+2018 ISOnum --> - {"rsquo", "8217"}, // right single quotation mark,U+2019 ISOnum --> - {"sbquo", "8218"}, // single low-9 quotation mark, U+201A NEW --> - {"ldquo", "8220"}, // left double quotation mark,U+201C ISOnum --> - {"rdquo", "8221"}, // right double quotation mark,U+201D ISOnum --> - {"bdquo", "8222"}, // double low-9 quotation mark, U+201E NEW --> - {"dagger", "8224"}, // dagger, U+2020 ISOpub --> - {"Dagger", "8225"}, // double dagger, U+2021 ISOpub --> - {"permil", "8240"}, // per mille sign, U+2030 ISOtech --> - {"lsaquo", "8249"}, // single left-pointing angle quotation mark,U+2039 ISO proposed --> - // - {"rsaquo", "8250"}, // single right-pointing angle quotation mark,U+203A ISO proposed --> - // - {"euro", "8364"}, // -- euro sign, U+20AC NEW --> - }; - /** *

* The set of entities supported by standard XML. *

*/ public static final Entities XML; - /** *

* The set of entities supported by HTML 3.2. *

*/ public static final Entities HTML32; - /** *

* The set of entities supported by HTML 4.0. *

*/ public static final Entities HTML40; + // package scoped for testing + static final String[][] ISO8859_1_ARRAY = {{"nbsp", "160"}, // non-breaking space + {"iexcl", "161"}, // inverted exclamation mark + {"cent", "162"}, // cent sign + {"pound", "163"}, // pound sign + {"curren", "164"}, // currency sign + {"yen", "165"}, // yen sign = yuan sign + {"brvbar", "166"}, // broken bar = broken vertical bar + {"sect", "167"}, // section sign + {"uml", "168"}, // diaeresis = spacing diaeresis + {"copy", "169"}, // � - copyright sign + {"ordf", "170"}, // feminine ordinal indicator + {"laquo", "171"}, // left-pointing double angle quotation mark = left pointing guillemet + {"not", "172"}, // not sign + {"shy", "173"}, // soft hyphen = discretionary hyphen + {"reg", "174"}, // � - registered trademark sign + {"macr", "175"}, // macron = spacing macron = overline = APL overbar + {"deg", "176"}, // degree sign + {"plusmn", "177"}, // plus-minus sign = plus-or-minus sign + {"sup2", "178"}, // superscript two = superscript digit two = squared + {"sup3", "179"}, // superscript three = superscript digit three = cubed + {"acute", "180"}, // acute accent = spacing acute + {"micro", "181"}, // micro sign + {"para", "182"}, // pilcrow sign = paragraph sign + {"middot", "183"}, // middle dot = Georgian comma = Greek middle dot + {"cedil", "184"}, // cedilla = spacing cedilla + {"sup1", "185"}, // superscript one = superscript digit one + {"ordm", "186"}, // masculine ordinal indicator + {"raquo", "187"}, // right-pointing double angle quotation mark = right pointing guillemet + {"frac14", "188"}, // vulgar fraction one quarter = fraction one quarter + {"frac12", "189"}, // vulgar fraction one half = fraction one half + {"frac34", "190"}, // vulgar fraction three quarters = fraction three quarters + {"iquest", "191"}, // inverted question mark = turned question mark + {"Agrave", "192"}, // � - uppercase A, grave accent + {"Aacute", "193"}, // � - uppercase A, acute accent + {"Acirc", "194"}, // � - uppercase A, circumflex accent + {"Atilde", "195"}, // � - uppercase A, tilde + {"Auml", "196"}, // � - uppercase A, umlaut + {"Aring", "197"}, // � - uppercase A, ring + {"AElig", "198"}, // � - uppercase AE + {"Ccedil", "199"}, // � - uppercase C, cedilla + {"Egrave", "200"}, // � - uppercase E, grave accent + {"Eacute", "201"}, // � - uppercase E, acute accent + {"Ecirc", "202"}, // � - uppercase E, circumflex accent + {"Euml", "203"}, // � - uppercase E, umlaut + {"Igrave", "204"}, // � - uppercase I, grave accent + {"Iacute", "205"}, // � - uppercase I, acute accent + {"Icirc", "206"}, // � - uppercase I, circumflex accent + {"Iuml", "207"}, // � - uppercase I, umlaut + {"ETH", "208"}, // � - uppercase Eth, Icelandic + {"Ntilde", "209"}, // � - uppercase N, tilde + {"Ograve", "210"}, // � - uppercase O, grave accent + {"Oacute", "211"}, // � - uppercase O, acute accent + {"Ocirc", "212"}, // � - uppercase O, circumflex accent + {"Otilde", "213"}, // � - uppercase O, tilde + {"Ouml", "214"}, // � - uppercase O, umlaut + {"times", "215"}, // multiplication sign + {"Oslash", "216"}, // � - uppercase O, slash + {"Ugrave", "217"}, // � - uppercase U, grave accent + {"Uacute", "218"}, // � - uppercase U, acute accent + {"Ucirc", "219"}, // � - uppercase U, circumflex accent + {"Uuml", "220"}, // � - uppercase U, umlaut + {"Yacute", "221"}, // � - uppercase Y, acute accent + {"THORN", "222"}, // � - uppercase THORN, Icelandic + {"szlig", "223"}, // � - lowercase sharps, German + {"agrave", "224"}, // � - lowercase a, grave accent + {"aacute", "225"}, // � - lowercase a, acute accent + {"acirc", "226"}, // � - lowercase a, circumflex accent + {"atilde", "227"}, // � - lowercase a, tilde + {"auml", "228"}, // � - lowercase a, umlaut + {"aring", "229"}, // � - lowercase a, ring + {"aelig", "230"}, // � - lowercase ae + {"ccedil", "231"}, // � - lowercase c, cedilla + {"egrave", "232"}, // � - lowercase e, grave accent + {"eacute", "233"}, // � - lowercase e, acute accent + {"ecirc", "234"}, // � - lowercase e, circumflex accent + {"euml", "235"}, // � - lowercase e, umlaut + {"igrave", "236"}, // � - lowercase i, grave accent + {"iacute", "237"}, // � - lowercase i, acute accent + {"icirc", "238"}, // � - lowercase i, circumflex accent + {"iuml", "239"}, // � - lowercase i, umlaut + {"eth", "240"}, // � - lowercase eth, Icelandic + {"ntilde", "241"}, // � - lowercase n, tilde + {"ograve", "242"}, // � - lowercase o, grave accent + {"oacute", "243"}, // � - lowercase o, acute accent + {"ocirc", "244"}, // � - lowercase o, circumflex accent + {"otilde", "245"}, // � - lowercase o, tilde + {"ouml", "246"}, // � - lowercase o, umlaut + {"divide", "247"}, // division sign + {"oslash", "248"}, // � - lowercase o, slash + {"ugrave", "249"}, // � - lowercase u, grave accent + {"uacute", "250"}, // � - lowercase u, acute accent + {"ucirc", "251"}, // � - lowercase u, circumflex accent + {"uuml", "252"}, // � - lowercase u, umlaut + {"yacute", "253"}, // � - lowercase y, acute accent + {"thorn", "254"}, // � - lowercase thorn, Icelandic + {"yuml", "255"}, // � - lowercase y, umlaut + }; + // http://www.w3.org/TR/REC-html40/sgml/entities.html + // package scoped for testing + static final String[][] HTML40_ARRAY = { + // + {"fnof", "402"}, // latin small f with hook = function= florin, U+0192 ISOtech --> + // + {"Alpha", "913"}, // greek capital letter alpha, U+0391 --> + {"Beta", "914"}, // greek capital letter beta, U+0392 --> + {"Gamma", "915"}, // greek capital letter gamma,U+0393 ISOgrk3 --> + {"Delta", "916"}, // greek capital letter delta,U+0394 ISOgrk3 --> + {"Epsilon", "917"}, // greek capital letter epsilon, U+0395 --> + {"Zeta", "918"}, // greek capital letter zeta, U+0396 --> + {"Eta", "919"}, // greek capital letter eta, U+0397 --> + {"Theta", "920"}, // greek capital letter theta,U+0398 ISOgrk3 --> + {"Iota", "921"}, // greek capital letter iota, U+0399 --> + {"Kappa", "922"}, // greek capital letter kappa, U+039A --> + {"Lambda", "923"}, // greek capital letter lambda,U+039B ISOgrk3 --> + {"Mu", "924"}, // greek capital letter mu, U+039C --> + {"Nu", "925"}, // greek capital letter nu, U+039D --> + {"Xi", "926"}, // greek capital letter xi, U+039E ISOgrk3 --> + {"Omicron", "927"}, // greek capital letter omicron, U+039F --> + {"Pi", "928"}, // greek capital letter pi, U+03A0 ISOgrk3 --> + {"Rho", "929"}, // greek capital letter rho, U+03A1 --> + // + {"Sigma", "931"}, // greek capital letter sigma,U+03A3 ISOgrk3 --> + {"Tau", "932"}, // greek capital letter tau, U+03A4 --> + {"Upsilon", "933"}, // greek capital letter upsilon,U+03A5 ISOgrk3 --> + {"Phi", "934"}, // greek capital letter phi,U+03A6 ISOgrk3 --> + {"Chi", "935"}, // greek capital letter chi, U+03A7 --> + {"Psi", "936"}, // greek capital letter psi,U+03A8 ISOgrk3 --> + {"Omega", "937"}, // greek capital letter omega,U+03A9 ISOgrk3 --> + {"alpha", "945"}, // greek small letter alpha,U+03B1 ISOgrk3 --> + {"beta", "946"}, // greek small letter beta, U+03B2 ISOgrk3 --> + {"gamma", "947"}, // greek small letter gamma,U+03B3 ISOgrk3 --> + {"delta", "948"}, // greek small letter delta,U+03B4 ISOgrk3 --> + {"epsilon", "949"}, // greek small letter epsilon,U+03B5 ISOgrk3 --> + {"zeta", "950"}, // greek small letter zeta, U+03B6 ISOgrk3 --> + {"eta", "951"}, // greek small letter eta, U+03B7 ISOgrk3 --> + {"theta", "952"}, // greek small letter theta,U+03B8 ISOgrk3 --> + {"iota", "953"}, // greek small letter iota, U+03B9 ISOgrk3 --> + {"kappa", "954"}, // greek small letter kappa,U+03BA ISOgrk3 --> + {"lambda", "955"}, // greek small letter lambda,U+03BB ISOgrk3 --> + {"mu", "956"}, // greek small letter mu, U+03BC ISOgrk3 --> + {"nu", "957"}, // greek small letter nu, U+03BD ISOgrk3 --> + {"xi", "958"}, // greek small letter xi, U+03BE ISOgrk3 --> + {"omicron", "959"}, // greek small letter omicron, U+03BF NEW --> + {"pi", "960"}, // greek small letter pi, U+03C0 ISOgrk3 --> + {"rho", "961"}, // greek small letter rho, U+03C1 ISOgrk3 --> + {"sigmaf", "962"}, // greek small letter final sigma,U+03C2 ISOgrk3 --> + {"sigma", "963"}, // greek small letter sigma,U+03C3 ISOgrk3 --> + {"tau", "964"}, // greek small letter tau, U+03C4 ISOgrk3 --> + {"upsilon", "965"}, // greek small letter upsilon,U+03C5 ISOgrk3 --> + {"phi", "966"}, // greek small letter phi, U+03C6 ISOgrk3 --> + {"chi", "967"}, // greek small letter chi, U+03C7 ISOgrk3 --> + {"psi", "968"}, // greek small letter psi, U+03C8 ISOgrk3 --> + {"omega", "969"}, // greek small letter omega,U+03C9 ISOgrk3 --> + {"thetasym", "977"}, // greek small letter theta symbol,U+03D1 NEW --> + {"upsih", "978"}, // greek upsilon with hook symbol,U+03D2 NEW --> + {"piv", "982"}, // greek pi symbol, U+03D6 ISOgrk3 --> + // + {"bull", "8226"}, // bullet = black small circle,U+2022 ISOpub --> + // + {"hellip", "8230"}, // horizontal ellipsis = three dot leader,U+2026 ISOpub --> + {"prime", "8242"}, // prime = minutes = feet, U+2032 ISOtech --> + {"Prime", "8243"}, // double prime = seconds = inches,U+2033 ISOtech --> + {"oline", "8254"}, // overline = spacing overscore,U+203E NEW --> + {"frasl", "8260"}, // fraction slash, U+2044 NEW --> + // + {"weierp", "8472"}, // script capital P = power set= Weierstrass p, U+2118 ISOamso --> + {"image", "8465"}, // blackletter capital I = imaginary part,U+2111 ISOamso --> + {"real", "8476"}, // blackletter capital R = real part symbol,U+211C ISOamso --> + {"trade", "8482"}, // trade mark sign, U+2122 ISOnum --> + {"alefsym", "8501"}, // alef symbol = first transfinite cardinal,U+2135 NEW --> + // + // + {"larr", "8592"}, // leftwards arrow, U+2190 ISOnum --> + {"uarr", "8593"}, // upwards arrow, U+2191 ISOnum--> + {"rarr", "8594"}, // rightwards arrow, U+2192 ISOnum --> + {"darr", "8595"}, // downwards arrow, U+2193 ISOnum --> + {"harr", "8596"}, // left right arrow, U+2194 ISOamsa --> + {"crarr", "8629"}, // downwards arrow with corner leftwards= carriage return, U+21B5 NEW --> + {"lArr", "8656"}, // leftwards double arrow, U+21D0 ISOtech --> + // + {"uArr", "8657"}, // upwards double arrow, U+21D1 ISOamsa --> + {"rArr", "8658"}, // rightwards double arrow,U+21D2 ISOtech --> + // + {"dArr", "8659"}, // downwards double arrow, U+21D3 ISOamsa --> + {"hArr", "8660"}, // left right double arrow,U+21D4 ISOamsa --> + // + {"forall", "8704"}, // for all, U+2200 ISOtech --> + {"part", "8706"}, // partial differential, U+2202 ISOtech --> + {"exist", "8707"}, // there exists, U+2203 ISOtech --> + {"empty", "8709"}, // empty set = null set = diameter,U+2205 ISOamso --> + {"nabla", "8711"}, // nabla = backward difference,U+2207 ISOtech --> + {"isin", "8712"}, // element of, U+2208 ISOtech --> + {"notin", "8713"}, // not an element of, U+2209 ISOtech --> + {"ni", "8715"}, // contains as member, U+220B ISOtech --> + // + {"prod", "8719"}, // n-ary product = product sign,U+220F ISOamsb --> + // + {"sum", "8721"}, // n-ary summation, U+2211 ISOamsb --> + // + {"minus", "8722"}, // minus sign, U+2212 ISOtech --> + {"lowast", "8727"}, // asterisk operator, U+2217 ISOtech --> + {"radic", "8730"}, // square root = radical sign,U+221A ISOtech --> + {"prop", "8733"}, // proportional to, U+221D ISOtech --> + {"infin", "8734"}, // infinity, U+221E ISOtech --> + {"ang", "8736"}, // angle, U+2220 ISOamso --> + {"and", "8743"}, // logical and = wedge, U+2227 ISOtech --> + {"or", "8744"}, // logical or = vee, U+2228 ISOtech --> + {"cap", "8745"}, // intersection = cap, U+2229 ISOtech --> + {"cup", "8746"}, // union = cup, U+222A ISOtech --> + {"int", "8747"}, // integral, U+222B ISOtech --> + {"there4", "8756"}, // therefore, U+2234 ISOtech --> + {"sim", "8764"}, // tilde operator = varies with = similar to,U+223C ISOtech --> + // + {"cong", "8773"}, // approximately equal to, U+2245 ISOtech --> + {"asymp", "8776"}, // almost equal to = asymptotic to,U+2248 ISOamsr --> + {"ne", "8800"}, // not equal to, U+2260 ISOtech --> + {"equiv", "8801"}, // identical to, U+2261 ISOtech --> + {"le", "8804"}, // less-than or equal to, U+2264 ISOtech --> + {"ge", "8805"}, // greater-than or equal to,U+2265 ISOtech --> + {"sub", "8834"}, // subset of, U+2282 ISOtech --> + {"sup", "8835"}, // superset of, U+2283 ISOtech --> + // + {"sube", "8838"}, // subset of or equal to, U+2286 ISOtech --> + {"supe", "8839"}, // superset of or equal to,U+2287 ISOtech --> + {"oplus", "8853"}, // circled plus = direct sum,U+2295 ISOamsb --> + {"otimes", "8855"}, // circled times = vector product,U+2297 ISOamsb --> + {"perp", "8869"}, // up tack = orthogonal to = perpendicular,U+22A5 ISOtech --> + {"sdot", "8901"}, // dot operator, U+22C5 ISOamsb --> + // + // + {"lceil", "8968"}, // left ceiling = apl upstile,U+2308 ISOamsc --> + {"rceil", "8969"}, // right ceiling, U+2309 ISOamsc --> + {"lfloor", "8970"}, // left floor = apl downstile,U+230A ISOamsc --> + {"rfloor", "8971"}, // right floor, U+230B ISOamsc --> + {"lang", "9001"}, // left-pointing angle bracket = bra,U+2329 ISOtech --> + // + {"rang", "9002"}, // right-pointing angle bracket = ket,U+232A ISOtech --> + // + // + {"loz", "9674"}, // lozenge, U+25CA ISOpub --> + // + {"spades", "9824"}, // black spade suit, U+2660 ISOpub --> + // + {"clubs", "9827"}, // black club suit = shamrock,U+2663 ISOpub --> + {"hearts", "9829"}, // black heart suit = valentine,U+2665 ISOpub --> + {"diams", "9830"}, // black diamond suit, U+2666 ISOpub --> + + // + {"OElig", "338"}, // -- latin capital ligature OE,U+0152 ISOlat2 --> + {"oelig", "339"}, // -- latin small ligature oe, U+0153 ISOlat2 --> + // + {"Scaron", "352"}, // -- latin capital letter S with caron,U+0160 ISOlat2 --> + {"scaron", "353"}, // -- latin small letter s with caron,U+0161 ISOlat2 --> + {"Yuml", "376"}, // -- latin capital letter Y with diaeresis,U+0178 ISOlat2 --> + // + {"circ", "710"}, // -- modifier letter circumflex accent,U+02C6 ISOpub --> + {"tilde", "732"}, // small tilde, U+02DC ISOdia --> + // + {"ensp", "8194"}, // en space, U+2002 ISOpub --> + {"emsp", "8195"}, // em space, U+2003 ISOpub --> + {"thinsp", "8201"}, // thin space, U+2009 ISOpub --> + {"zwnj", "8204"}, // zero width non-joiner,U+200C NEW RFC 2070 --> + {"zwj", "8205"}, // zero width joiner, U+200D NEW RFC 2070 --> + {"lrm", "8206"}, // left-to-right mark, U+200E NEW RFC 2070 --> + {"rlm", "8207"}, // right-to-left mark, U+200F NEW RFC 2070 --> + {"ndash", "8211"}, // en dash, U+2013 ISOpub --> + {"mdash", "8212"}, // em dash, U+2014 ISOpub --> + {"lsquo", "8216"}, // left single quotation mark,U+2018 ISOnum --> + {"rsquo", "8217"}, // right single quotation mark,U+2019 ISOnum --> + {"sbquo", "8218"}, // single low-9 quotation mark, U+201A NEW --> + {"ldquo", "8220"}, // left double quotation mark,U+201C ISOnum --> + {"rdquo", "8221"}, // right double quotation mark,U+201D ISOnum --> + {"bdquo", "8222"}, // double low-9 quotation mark, U+201E NEW --> + {"dagger", "8224"}, // dagger, U+2020 ISOpub --> + {"Dagger", "8225"}, // double dagger, U+2021 ISOpub --> + {"permil", "8240"}, // per mille sign, U+2030 ISOtech --> + {"lsaquo", "8249"}, // single left-pointing angle quotation mark,U+2039 ISO proposed --> + // + {"rsaquo", "8250"}, // single right-pointing angle quotation mark,U+203A ISO proposed --> + // + {"euro", "8364"}, // -- euro sign, U+20AC NEW --> + }; + private static final String[][] BASIC_ARRAY = {{"quot", "34"}, // " - double-quote + {"amp", "38"}, // & - ampersand + {"lt", "60"}, // < - less-than + {"gt", "62"}, // > - greater-than + }; + private static final String[][] APOS_ARRAY = {{"apos", "39"}, // XML apostrophe + }; static { XML = new Entities(); @@ -387,13 +380,15 @@ class Entities { fillWithHtml40Entities(HTML40); } + // package scoped for testing + EntityMap map = new Entities.LookupEntityMap(); + /** *

* Fills the specified entities instance with HTML 40 entities. *

- * - * @param entities - * the instance to be filled. + * + * @param entities the instance to be filled. */ static void fillWithHtml40Entities(Entities entities) { entities.addEntities(BASIC_ARRAY); @@ -401,16 +396,257 @@ static void fillWithHtml40Entities(Entities entities) { entities.addEntities(HTML40_ARRAY); } + /** + *

+ * Adds entities to this entity. + *

+ * + * @param entityArray array of entities to be added + */ + public void addEntities(String[][] entityArray) { + for (int i = 0; i < entityArray.length; ++i) { + addEntity(entityArray[i][0], Integer.parseInt(entityArray[i][1])); + } + } + + /** + *

+ * Add an entity to this entity. + *

+ * + * @param name name of the entity + * @param value vale of the entity + */ + public void addEntity(String name, int value) { + map.add(name, value); + } + + /** + *

+ * Returns the name of the entity identified by the specified value. + *

+ * + * @param value the value to locate + * @return entity name associated with the specified value + */ + public String entityName(int value) { + return map.name(value); + } + + /** + *

+ * Returns the value of the entity identified by the specified name. + *

+ * + * @param name the name to locate + * @return entity value associated with the specified name + */ + public int entityValue(String name) { + return map.value(name); + } + + /** + *

+ * Escapes the characters in a String. + *

+ *

+ *

+ * For example, if you have called addEntity("foo", 0xA1), escape("\u00A1") will return + * "&foo;" + *

+ * + * @param str The String to escape. + * @return A new escaped String. + */ + public String escape(String str) { + StringWriter stringWriter = createStringWriter(str); + try { + this.escape(stringWriter, str); + } catch (IOException e) { + // This should never happen because ALL the StringWriter methods called by #escape(Writer, String) do not + // throw IOExceptions. + throw new IllegalStateException(e); + } + return stringWriter.toString(); + } + + /** + *

+ * Escapes the characters in the String passed and writes the result to the Writer + * passed. + *

+ * + * @param writer The Writer to write the results of the escaping to. Assumed to be a non-null value. + * @param str The String to escape. Assumed to be a non-null value. + * @throws IOException when Writer passed throws the exception from calls to the {@link Writer#write(int)} + * methods. + * @see #escape(String) + * @see Writer + */ + public void escape(Writer writer, String str) throws IOException { + int len = str.length(); + for (int i = 0; i < len; i++) { + char c = str.charAt(i); + String entityName = this.entityName(c); + if (entityName == null) { + if (c > 0x7F) { + writer.write("&#"); + writer.write(Integer.toString(c, 10)); + writer.write(';'); + } else { + writer.write(c); + } + } else { + writer.write('&'); + writer.write(entityName); + writer.write(';'); + } + } + } + + /** + *

+ * Unescapes the entities in a String. + *

+ *

+ *

+ * For example, if you have called addEntity("foo", 0xA1), unescape("&foo;") will return + * "\u00A1" + *

+ * + * @param str The String to escape. + * @return A new escaped String. + */ + public String unescape(String str) { + int firstAmp = str.indexOf('&'); + if (firstAmp < 0) { + return str; + } else { + StringWriter stringWriter = createStringWriter(str); + try { + this.doUnescape(stringWriter, str, firstAmp); + } catch (IOException e) { + // This should never happen because ALL the StringWriter methods called by #escape(Writer, String) + // do not throw IOExceptions. + throw new IllegalStateException(e); + } + return stringWriter.toString(); + } + } + + /** + * Make the StringWriter 10% larger than the source String to avoid growing the writer + * + * @param str The source string + * @return A newly created StringWriter + */ + private StringWriter createStringWriter(String str) { + return new StringWriter((int) (str.length() + (str.length() * 0.1))); + } + + /** + *

+ * Unescapes the escaped entities in the String passed and writes the result to the + * Writer passed. + *

+ * + * @param writer The Writer to write the results to; assumed to be non-null. + * @param str The source String to unescape; assumed to be non-null. + * @throws IOException when Writer passed throws the exception from calls to the {@link Writer#write(int)} + * methods. + * @see #escape(String) + * @see Writer + */ + public void unescape(Writer writer, String str) throws IOException { + int firstAmp = str.indexOf('&'); + if (firstAmp < 0) { + writer.write(str); + return; + } else { + doUnescape(writer, str, firstAmp); + } + } + + /** + * Underlying unescape method that allows the optimisation of not starting from the 0 index again. + * + * @param writer The Writer to write the results to; assumed to be non-null. + * @param str The source String to unescape; assumed to be non-null. + * @param firstAmp The int index of the first ampersand in the source String. + * @throws IOException when Writer passed throws the exception from calls to the {@link Writer#write(int)} + * methods. + */ + private void doUnescape(Writer writer, String str, int firstAmp) throws IOException { + writer.write(str, 0, firstAmp); + int len = str.length(); + for (int i = firstAmp; i < len; i++) { + char c = str.charAt(i); + if (c == '&') { + int nextIdx = i + 1; + int semiColonIdx = str.indexOf(';', nextIdx); + if (semiColonIdx == -1) { + writer.write(c); + continue; + } + int amphersandIdx = str.indexOf('&', i + 1); + if (amphersandIdx != -1 && amphersandIdx < semiColonIdx) { + // Then the text looks like &...&...; + writer.write(c); + continue; + } + String entityContent = str.substring(nextIdx, semiColonIdx); + int entityValue = -1; + int entityContentLen = entityContent.length(); + if (entityContentLen > 0) { + if (entityContent.charAt(0) == '#') { // escaped value content is an integer (decimal or + // hexidecimal) + if (entityContentLen > 1) { + char isHexChar = entityContent.charAt(1); + try { + switch (isHexChar) { + case 'X': + case 'x': { + entityValue = Integer.parseInt(entityContent.substring(2), 16); + break; + } + default: { + entityValue = Integer.parseInt(entityContent.substring(1), 10); + } + } + if (entityValue > 0xFFFF) { + entityValue = -1; + } + } catch (NumberFormatException e) { + entityValue = -1; + } + } + } else { // escaped value content is an entity name + entityValue = this.entityValue(entityContent); + } + } + + if (entityValue == -1) { + writer.write('&'); + writer.write(entityContent); + writer.write(';'); + } else { + writer.write(entityValue); + } + i = semiColonIdx; // move index up to the semi-colon + } else { + writer.write(c); + } + } + } + static interface EntityMap { /** *

* Add an entry to this entity map. *

- * - * @param name - * the entity name - * @param value - * the entity value + * + * @param name the entity name + * @param value the entity value */ void add(String name, int value); @@ -418,9 +654,8 @@ static interface EntityMap { *

* Returns the name of the entity identified by the specified value. *

- * - * @param value - * the value to locate + * + * @param value the value to locate * @return entity name associated with the specified value */ String name(int value); @@ -429,9 +664,8 @@ static interface EntityMap { *

* Returns the value of the entity identified by the specified name. *

- * - * @param name - * the name to locate + * + * @param name the name to locate * @return entity value associated with the specified name */ int value(String name); @@ -540,7 +774,7 @@ public String name(int value) { *

* Returns the lookup table for this entity map. The lookup table is created if it has not been previously. *

- * + * * @return the lookup table */ private String[] lookupTable() { @@ -583,9 +817,8 @@ public ArrayEntityMap() { /** * Constructs a new instance of ArrayEntityMap specifying the size by which the array should * grow. - * - * @param growBy - * array will be initialized to and will grow by this amount + * + * @param growBy array will be initialized to and will grow by this amount */ public ArrayEntityMap(int growBy) { this.growBy = growBy; @@ -605,9 +838,8 @@ public void add(String name, int value) { /** * Verifies the capacity of the entity array, adjusting the size if necessary. - * - * @param capacity - * size the array should be + * + * @param capacity size the array should be */ protected void ensureCapacity(int capacity) { if (capacity > names.length) { @@ -658,9 +890,8 @@ public BinaryEntityMap() { /** * Constructs a new instance of ArrayEntityMap specifying the size by which the underlying array * should grow. - * - * @param growBy - * array will be initialized to and will grow by this amount + * + * @param growBy array will be initialized to and will grow by this amount */ public BinaryEntityMap(int growBy) { super(growBy); @@ -669,9 +900,8 @@ public BinaryEntityMap(int growBy) { /** * Performs a binary search of the entity array for the specified key. This method is based on code in * {@link java.util.Arrays}. - * - * @param key - * the key to be found + * + * @param key the key to be found * @return the index of the entity array matching the specified key */ private int binarySearch(int key) { @@ -722,269 +952,4 @@ public String name(int value) { } } - // package scoped for testing - EntityMap map = new Entities.LookupEntityMap(); - - /** - *

- * Adds entities to this entity. - *

- * - * @param entityArray - * array of entities to be added - */ - public void addEntities(String[][] entityArray) { - for (int i = 0; i < entityArray.length; ++i) { - addEntity(entityArray[i][0], Integer.parseInt(entityArray[i][1])); - } - } - - /** - *

- * Add an entity to this entity. - *

- * - * @param name - * name of the entity - * @param value - * vale of the entity - */ - public void addEntity(String name, int value) { - map.add(name, value); - } - - /** - *

- * Returns the name of the entity identified by the specified value. - *

- * - * @param value - * the value to locate - * @return entity name associated with the specified value - */ - public String entityName(int value) { - return map.name(value); - } - - /** - *

- * Returns the value of the entity identified by the specified name. - *

- * - * @param name - * the name to locate - * @return entity value associated with the specified name - */ - public int entityValue(String name) { - return map.value(name); - } - - /** - *

- * Escapes the characters in a String. - *

- * - *

- * For example, if you have called addEntity("foo", 0xA1), escape("\u00A1") will return - * "&foo;" - *

- * - * @param str - * The String to escape. - * @return A new escaped String. - */ - public String escape(String str) { - StringWriter stringWriter = createStringWriter(str); - try { - this.escape(stringWriter, str); - } catch (IOException e) { - // This should never happen because ALL the StringWriter methods called by #escape(Writer, String) do not - // throw IOExceptions. - throw new IllegalStateException(e); - } - return stringWriter.toString(); - } - - /** - *

- * Escapes the characters in the String passed and writes the result to the Writer - * passed. - *

- * - * @param writer - * The Writer to write the results of the escaping to. Assumed to be a non-null value. - * @param str - * The String to escape. Assumed to be a non-null value. - * @throws IOException - * when Writer passed throws the exception from calls to the {@link Writer#write(int)} - * methods. - * - * @see #escape(String) - * @see Writer - */ - public void escape(Writer writer, String str) throws IOException { - int len = str.length(); - for (int i = 0; i < len; i++) { - char c = str.charAt(i); - String entityName = this.entityName(c); - if (entityName == null) { - if (c > 0x7F) { - writer.write("&#"); - writer.write(Integer.toString(c, 10)); - writer.write(';'); - } else { - writer.write(c); - } - } else { - writer.write('&'); - writer.write(entityName); - writer.write(';'); - } - } - } - - /** - *

- * Unescapes the entities in a String. - *

- * - *

- * For example, if you have called addEntity("foo", 0xA1), unescape("&foo;") will return - * "\u00A1" - *

- * - * @param str - * The String to escape. - * @return A new escaped String. - */ - public String unescape(String str) { - int firstAmp = str.indexOf('&'); - if (firstAmp < 0) { - return str; - } else { - StringWriter stringWriter = createStringWriter(str); - try { - this.doUnescape(stringWriter, str, firstAmp); - } catch (IOException e) { - // This should never happen because ALL the StringWriter methods called by #escape(Writer, String) - // do not throw IOExceptions. - throw new IllegalStateException(e); - } - return stringWriter.toString(); - } - } - - /** - * Make the StringWriter 10% larger than the source String to avoid growing the writer - * - * @param str The source string - * @return A newly created StringWriter - */ - private StringWriter createStringWriter(String str) { - return new StringWriter((int) (str.length() + (str.length() * 0.1))); - } - - /** - *

- * Unescapes the escaped entities in the String passed and writes the result to the - * Writer passed. - *

- * - * @param writer - * The Writer to write the results to; assumed to be non-null. - * @param str - * The source String to unescape; assumed to be non-null. - * @throws IOException - * when Writer passed throws the exception from calls to the {@link Writer#write(int)} - * methods. - * - * @see #escape(String) - * @see Writer - */ - public void unescape(Writer writer, String str) throws IOException { - int firstAmp = str.indexOf('&'); - if (firstAmp < 0) { - writer.write(str); - return; - } else { - doUnescape(writer, str, firstAmp); - } - } - - /** - * Underlying unescape method that allows the optimisation of not starting from the 0 index again. - * - * @param writer - * The Writer to write the results to; assumed to be non-null. - * @param str - * The source String to unescape; assumed to be non-null. - * @param firstAmp - * The int index of the first ampersand in the source String. - * @throws IOException - * when Writer passed throws the exception from calls to the {@link Writer#write(int)} - * methods. - */ - private void doUnescape(Writer writer, String str, int firstAmp) throws IOException { - writer.write(str, 0, firstAmp); - int len = str.length(); - for (int i = firstAmp; i < len; i++) { - char c = str.charAt(i); - if (c == '&') { - int nextIdx = i + 1; - int semiColonIdx = str.indexOf(';', nextIdx); - if (semiColonIdx == -1) { - writer.write(c); - continue; - } - int amphersandIdx = str.indexOf('&', i + 1); - if (amphersandIdx != -1 && amphersandIdx < semiColonIdx) { - // Then the text looks like &...&...; - writer.write(c); - continue; - } - String entityContent = str.substring(nextIdx, semiColonIdx); - int entityValue = -1; - int entityContentLen = entityContent.length(); - if (entityContentLen > 0) { - if (entityContent.charAt(0) == '#') { // escaped value content is an integer (decimal or - // hexidecimal) - if (entityContentLen > 1) { - char isHexChar = entityContent.charAt(1); - try { - switch (isHexChar) { - case 'X' : - case 'x' : { - entityValue = Integer.parseInt(entityContent.substring(2), 16); - break; - } - default : { - entityValue = Integer.parseInt(entityContent.substring(1), 10); - } - } - if (entityValue > 0xFFFF) { - entityValue = -1; - } - } catch (NumberFormatException e) { - entityValue = -1; - } - } - } else { // escaped value content is an entity name - entityValue = this.entityValue(entityContent); - } - } - - if (entityValue == -1) { - writer.write('&'); - writer.write(entityContent); - writer.write(';'); - } else { - writer.write(entityValue); - } - i = semiColonIdx; // move index up to the semi-colon - } else { - writer.write(c); - } - } - } - } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/IntHashMap.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/IntHashMap.java index e29405ff84d..17c65467c39 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/IntHashMap.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/IntHashMap.java @@ -23,7 +23,7 @@ /** *

A hash map that uses primitive ints for the key rather than objects.

- * + *

*

Note that this class is for internal optimization purposes only, and may * not be supported in future releases of Apache Commons Lang. Utilities of * this sort may be included in future releases of Apache Commons Collections.

@@ -31,9 +31,9 @@ * @author Justin Couch * @author Alex Chaffee (alex@apache.org) * @author Stephen Colebourne - * @since 2.0 * @version $Revision: 181192 $ * @see java.util.HashMap + * @since 2.0 */ class IntHashMap { @@ -62,32 +62,6 @@ class IntHashMap { */ private float loadFactor; - /** - *

Innerclass that acts as a datastructure to create a new entry in the - * table.

- */ - private static class Entry { - int hash; - int key; - Object value; - Entry next; - - /** - *

Create a new entry with the given values.

- * - * @param hash The code used to hash the object with - * @param key The key used to enter this in the table - * @param value The value for this key - * @param next A reference to the next entry in the table - */ - protected Entry(int hash, int key, Object value, Entry next) { - this.hash = hash; - this.key = key; - this.value = value; - this.next = next; - } - } - /** *

Constructs a new, empty hashtable with a default capacity and load * factor, which is 20 and 0.75 respectively.

@@ -100,9 +74,9 @@ public IntHashMap() { *

Constructs a new, empty hashtable with the specified initial capacity * and default load factor, which is 0.75.

* - * @param initialCapacity the initial capacity of the hashtable. + * @param initialCapacity the initial capacity of the hashtable. * @throws IllegalArgumentException if the initial capacity is less - * than zero. + * than zero. */ public IntHashMap(int initialCapacity) { this(initialCapacity, 0.75f); @@ -113,9 +87,9 @@ public IntHashMap(int initialCapacity) { * capacity and the specified load factor.

* * @param initialCapacity the initial capacity of the hashtable. - * @param loadFactor the load factor of the hashtable. - * @throws IllegalArgumentException if the initial capacity is less - * than zero, or if the load factor is nonpositive. + * @param loadFactor the load factor of the hashtable. + * @throws IllegalArgumentException if the initial capacity is less + * than zero, or if the load factor is nonpositive. */ public IntHashMap(int initialCapacity, float loadFactor) { super(); @@ -137,7 +111,7 @@ public IntHashMap(int initialCapacity, float loadFactor) { /** *

Returns the number of keys in this hashtable.

* - * @return the number of keys in this hashtable. + * @return the number of keys in this hashtable. */ public int size() { return count; @@ -146,8 +120,8 @@ public int size() { /** *

Tests if this hashtable maps no keys to values.

* - * @return true if this hashtable maps no keys to values; - * false otherwise. + * @return true if this hashtable maps no keys to values; + * false otherwise. */ public boolean isEmpty() { return count == 0; @@ -157,19 +131,19 @@ public boolean isEmpty() { *

Tests if some key maps into the specified value in this hashtable. * This operation is more expensive than the containsKey * method.

- * + *

*

Note that this method is identical in functionality to containsValue, * (which is part of the Map interface in the collections framework).

* - * @param value a value to search for. - * @return true if and only if some key maps to the - * value argument in this hashtable as - * determined by the equals method; - * false otherwise. - * @throws NullPointerException if the value is null. - * @see #containsKey(int) - * @see #containsValue(Object) - * @see java.util.Map + * @param value a value to search for. + * @return true if and only if some key maps to the + * value argument in this hashtable as + * determined by the equals method; + * false otherwise. + * @throws NullPointerException if the value is null. + * @see #containsKey(int) + * @see #containsValue(Object) + * @see java.util.Map */ public boolean contains(Object value) { if (value == null) { @@ -177,7 +151,7 @@ public boolean contains(Object value) { } Entry tab[] = table; - for (int i = tab.length; i-- > 0;) { + for (int i = tab.length; i-- > 0; ) { for (Entry e = tab[i]; e != null; e = e.next) { if (e.value.equals(value)) { return true; @@ -190,13 +164,13 @@ public boolean contains(Object value) { /** *

Returns true if this HashMap maps one or more keys * to this value.

- * + *

*

Note that this method is identical in functionality to contains * (which predates the Map interface).

* * @param value value whose presence in this HashMap is to be tested. * @return boolean true if the value is contained - * @see java.util.Map + * @see java.util.Map * @since JDK1.2 */ public boolean containsValue(Object value) { @@ -206,10 +180,10 @@ public boolean containsValue(Object value) { /** *

Tests if the specified object is a key in this hashtable.

* - * @param key possible key. + * @param key possible key. * @return true if and only if the specified object is a - * key in this hashtable, as determined by the equals - * method; false otherwise. + * key in this hashtable, as determined by the equals + * method; false otherwise. * @see #contains(Object) */ public boolean containsKey(int key) { @@ -227,11 +201,11 @@ public boolean containsKey(int key) { /** *

Returns the value to which the specified key is mapped in this map.

* - * @param key a key in the hashtable. - * @return the value to which the key is mapped in this hashtable; - * null if the key is not mapped to any value in - * this hashtable. - * @see #put(int, Object) + * @param key a key in the hashtable. + * @return the value to which the key is mapped in this hashtable; + * null if the key is not mapped to any value in + * this hashtable. + * @see #put(int, Object) */ public Object get(int key) { Entry tab[] = table; @@ -249,7 +223,7 @@ public Object get(int key) { *

Increases the capacity of and internally reorganizes this * hashtable, in order to accommodate and access its entries more * efficiently.

- * + *

*

This method is called automatically when the number of keys * in the hashtable exceeds this hashtable's capacity and load * factor.

@@ -264,8 +238,8 @@ protected void rehash() { threshold = (int) (newCapacity * loadFactor); table = newMap; - for (int i = oldCapacity; i-- > 0;) { - for (Entry old = oldMap[i]; old != null;) { + for (int i = oldCapacity; i-- > 0; ) { + for (Entry old = oldMap[i]; old != null; ) { Entry e = old; old = old.next; @@ -280,16 +254,16 @@ protected void rehash() { *

Maps the specified key to the specified * value in this hashtable. The key cannot be * null.

- * + *

*

The value can be retrieved by calling the get method * with a key that is equal to the original key.

* - * @param key the hashtable key. - * @param value the value. + * @param key the hashtable key. + * @param value the value. * @return the previous value of the specified key in this hashtable, - * or null if it did not have one. - * @throws NullPointerException if the key is null. - * @see #get(int) + * or null if it did not have one. + * @throws NullPointerException if the key is null. + * @see #get(int) */ public Object put(int key, Object value) { // Makes sure the key is not already in the hashtable. @@ -322,13 +296,13 @@ public Object put(int key, Object value) { /** *

Removes the key (and its corresponding value) from this * hashtable.

- * + *

*

This method does nothing if the key is not present in the * hashtable.

* - * @param key the key that needs to be removed. - * @return the value to which the key had been mapped in this hashtable, - * or null if the key did not have a mapping. + * @param key the key that needs to be removed. + * @return the value to which the key had been mapped in this hashtable, + * or null if the key did not have a mapping. */ public Object remove(int key) { Entry tab[] = table; @@ -355,10 +329,36 @@ public Object remove(int key) { */ public synchronized void clear() { Entry tab[] = table; - for (int index = tab.length; --index >= 0;) { + for (int index = tab.length; --index >= 0; ) { tab[index] = null; } count = 0; } - + + /** + *

Innerclass that acts as a datastructure to create a new entry in the + * table.

+ */ + private static class Entry { + int hash; + int key; + Object value; + Entry next; + + /** + *

Create a new entry with the given values.

+ * + * @param hash The code used to hash the object with + * @param key The key used to enter this in the table + * @param value The value for this key + * @param next A reference to the next entry in the table + */ + protected Entry(int hash, int key, Object value, Entry next) { + this.hash = hash; + this.key = key; + this.value = value; + this.next = next; + } + } + } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/LocaleUtils.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/LocaleUtils.java index 6600f8d2b43..f4cf01a354c 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/LocaleUtils.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/LocaleUtils.java @@ -3,16 +3,17 @@ import java.util.Locale; public class LocaleUtils { - - private LocaleUtils() {} - public static Locale getLocale(String language) { - if ("en".equalsIgnoreCase(language)) { - return Locale.ENGLISH; + private LocaleUtils() { + } + + public static Locale getLocale(String language) { + if ("en".equalsIgnoreCase(language)) { + return Locale.ENGLISH; } else if ("zh".equalsIgnoreCase(language)) { - return Locale.SIMPLIFIED_CHINESE; + return Locale.SIMPLIFIED_CHINESE; } else if ("zh_TW".equalsIgnoreCase(language)) { - return Locale.TRADITIONAL_CHINESE; + return Locale.TRADITIONAL_CHINESE; } return Locale.getDefault(); } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/MessageSource.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/MessageSource.java index 8a1c7e5c6fe..70403cb93a7 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/MessageSource.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/MessageSource.java @@ -1,11 +1,11 @@ /** * Project: dubbo.registry.server-1.1.0-SNAPSHOT - * + *

* File Created at 2010-7-7 - * + *

* Copyright 1999-2010 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -14,15 +14,15 @@ */ package com.alibaba.dubbo.registry.common.util; -import java.text.MessageFormat; -import java.util.ResourceBundle; - import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; +import java.text.MessageFormat; +import java.util.ResourceBundle; + /** * MessageSource - * + * * @author william.liangf */ public class MessageSource { @@ -31,34 +31,34 @@ public class MessageSource { private static final Logger logger = LoggerFactory.getLogger(MessageSource.class); private final ResourceBundle resourceBundle; - + private final String errorPrefix; public MessageSource(ResourceBundle resourceBundle) { this(resourceBundle, null); } - + public MessageSource(ResourceBundle resourceBundle, String errorPrefix) { this.resourceBundle = resourceBundle; this.errorPrefix = errorPrefix == null ? "" : errorPrefix + " "; } - + public String getString(String key) { - try { - return resourceBundle.getString(key); - } catch (Throwable t) { - logger.warn(errorPrefix + t.getMessage(), t); - return key; - } + try { + return resourceBundle.getString(key); + } catch (Throwable t) { + logger.warn(errorPrefix + t.getMessage(), t); + return key; + } } - + public String getString(String key, Object... args) { - try { - return new MessageFormat(resourceBundle.getString(key)).format(args); - } catch (Throwable t) { - logger.warn(errorPrefix + t.getMessage(), t); - return key; - } + try { + return new MessageFormat(resourceBundle.getString(key)).format(args); + } catch (Throwable t) { + logger.warn(errorPrefix + t.getMessage(), t); + return key; + } } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/OverrideUtils.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/OverrideUtils.java index c04e33f7855..16d4fa0ac1c 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/OverrideUtils.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/OverrideUtils.java @@ -14,110 +14,112 @@ * limitations under the License. */ package com.alibaba.dubbo.registry.common.util; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.registry.common.domain.LoadBalance; import com.alibaba.dubbo.registry.common.domain.Override; import com.alibaba.dubbo.registry.common.domain.Weight; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + /** * OverrideUtils.java + * * @author tony.chenl */ public class OverrideUtils { - public static List overridesToWeights(List overrides){ - List weights = new ArrayList(); - if(overrides == null){ - return weights; - } - for(Override o : overrides){ - if(StringUtils.isEmpty(o.getParams())){ - continue; - }else{ - Map params = StringUtils.parseQueryString(o.getParams()); - for(Map.Entry entry : params.entrySet()){ - if(entry.getKey().equals("weight")){ - Weight weight = new Weight(); - weight.setAddress(o.getAddress()); - weight.setId(o.getId()); - weight.setService(o.getService()); - weight.setWeight(Integer.valueOf(entry.getValue())); - weights.add(weight); - } - } - } - } - return weights; - } - - public static Weight overrideToWeight(Override override){ - return overridesToWeights(Arrays.asList(override)).get(0); - } - - public static Override weightToOverride(Weight weight){ - Override override = new Override(); - override.setId(weight.getId()); - override.setAddress(weight.getAddress()); - override.setEnabled(true); - override.setParams("weight=" + weight.getWeight()); - override.setService(weight.getService()); - return override; - } - - public static List overridesToLoadBalances(List overrides){ - List loadBalances = new ArrayList(); - if(overrides == null){ - return loadBalances; - } - for(Override o : overrides){ - if(StringUtils.isEmpty(o.getParams())){ - continue; - }else{ - Map params = StringUtils.parseQueryString(o.getParams()); - for(Map.Entry entry : params.entrySet()){ - if(entry.getKey().endsWith("loadbalance")){ - LoadBalance loadBalance = new LoadBalance(); - String method = null; - if(entry.getKey().endsWith(".loadbalance")){ - method = entry.getKey().split(".loadbalance")[0]; - }else{ - method = "*"; - } - - loadBalance.setMethod(method); - loadBalance.setId(o.getId()); - loadBalance.setService(o.getService()); - loadBalance.setStrategy(entry.getValue()); - loadBalances.add(loadBalance); - - } - } - } - } - return loadBalances; - } - - public static LoadBalance overrideToLoadBalance(Override override){ - return OverrideUtils.overridesToLoadBalances(Arrays.asList(override)).get(0); - } - - public static Override loadBalanceToOverride(LoadBalance loadBalance){ - Override override = new Override(); - override.setId(loadBalance.getId()); - override.setService(loadBalance.getService()); - override.setEnabled(true); - String method = loadBalance.getMethod(); - String strategy = loadBalance.getStrategy(); - if(StringUtils.isEmpty(method) ||method.equals("*")){ - override.setParams("loadbalance=" + strategy); - }else{ - override.setParams(method + ".loadbalance=" + strategy); - } - return override; - } + public static List overridesToWeights(List overrides) { + List weights = new ArrayList(); + if (overrides == null) { + return weights; + } + for (Override o : overrides) { + if (StringUtils.isEmpty(o.getParams())) { + continue; + } else { + Map params = StringUtils.parseQueryString(o.getParams()); + for (Map.Entry entry : params.entrySet()) { + if (entry.getKey().equals("weight")) { + Weight weight = new Weight(); + weight.setAddress(o.getAddress()); + weight.setId(o.getId()); + weight.setService(o.getService()); + weight.setWeight(Integer.valueOf(entry.getValue())); + weights.add(weight); + } + } + } + } + return weights; + } + + public static Weight overrideToWeight(Override override) { + return overridesToWeights(Arrays.asList(override)).get(0); + } + + public static Override weightToOverride(Weight weight) { + Override override = new Override(); + override.setId(weight.getId()); + override.setAddress(weight.getAddress()); + override.setEnabled(true); + override.setParams("weight=" + weight.getWeight()); + override.setService(weight.getService()); + return override; + } + + public static List overridesToLoadBalances(List overrides) { + List loadBalances = new ArrayList(); + if (overrides == null) { + return loadBalances; + } + for (Override o : overrides) { + if (StringUtils.isEmpty(o.getParams())) { + continue; + } else { + Map params = StringUtils.parseQueryString(o.getParams()); + for (Map.Entry entry : params.entrySet()) { + if (entry.getKey().endsWith("loadbalance")) { + LoadBalance loadBalance = new LoadBalance(); + String method = null; + if (entry.getKey().endsWith(".loadbalance")) { + method = entry.getKey().split(".loadbalance")[0]; + } else { + method = "*"; + } + + loadBalance.setMethod(method); + loadBalance.setId(o.getId()); + loadBalance.setService(o.getService()); + loadBalance.setStrategy(entry.getValue()); + loadBalances.add(loadBalance); + + } + } + } + } + return loadBalances; + } + + public static LoadBalance overrideToLoadBalance(Override override) { + return OverrideUtils.overridesToLoadBalances(Arrays.asList(override)).get(0); + } + + public static Override loadBalanceToOverride(LoadBalance loadBalance) { + Override override = new Override(); + override.setId(loadBalance.getId()); + override.setService(loadBalance.getService()); + override.setEnabled(true); + String method = loadBalance.getMethod(); + String strategy = loadBalance.getStrategy(); + if (StringUtils.isEmpty(method) || method.equals("*")) { + override.setParams("loadbalance=" + strategy); + } else { + override.setParams(method + ".loadbalance=" + strategy); + } + return override; + } } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/StringEscapeUtils.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/StringEscapeUtils.java index 5a842ce2933..e1a366eec73 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/StringEscapeUtils.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/StringEscapeUtils.java @@ -33,20 +33,20 @@ * @author Gary Gregory * @author Phil Steitz * @author Pete Gieser - * @since 2.0 * @version $Id: StringEscapeUtils.java 181192 2012-06-21 05:05:47Z tony.chenl $ + * @since 2.0 */ public class StringEscapeUtils { private static final char CSV_DELIMITER = ','; private static final char CSV_QUOTE = '"'; private static final String CSV_QUOTE_STR = String.valueOf(CSV_QUOTE); - private static final char[] CSV_SEARCH_CHARS = new char[] {CSV_DELIMITER, CSV_QUOTE, '\r', '\n'}; + private static final char[] CSV_SEARCH_CHARS = new char[]{CSV_DELIMITER, CSV_QUOTE, '\r', '\n'}; /** *

StringEscapeUtils instances should NOT be constructed in * standard programming.

- * + *

*

Instead, the class should be used as: *

StringEscapeUtils.escapeJava("foo");

* @@ -54,22 +54,23 @@ public class StringEscapeUtils { * instance to operate.

*/ public StringEscapeUtils() { - super(); + super(); } // Java and JavaScript //-------------------------------------------------------------------------- + /** *

Escapes the characters in a String using Java String rules.

- * + *

*

Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)

- * + *

*

So a tab becomes the characters '\\' and * 't'.

- * + *

*

The only difference between Java strings and JavaScript strings * is that in JavaScript, a single quote must be escaped.

- * + *

*

Example: *

      * input string: He didn't say, "Stop!"
@@ -77,7 +78,7 @@ public StringEscapeUtils() {
      * 
*

* - * @param str String to escape values in, may be null + * @param str String to escape values in, may be null * @return String with escaped values, null if null string input */ public static String escapeJava(String str) { @@ -87,14 +88,14 @@ public static String escapeJava(String str) { /** *

Escapes the characters in a String using Java String rules to * a Writer.

- * + *

*

A null string input has no effect.

- * - * @see #escapeJava(java.lang.String) - * @param out Writer to write escaped string into - * @param str String to escape values in, may be null + * + * @param out Writer to write escaped string into + * @param str String to escape values in, may be null * @throws IllegalArgumentException if the Writer is null - * @throws IOException if error occurs on underlying Writer + * @throws IOException if error occurs on underlying Writer + * @see #escapeJava(java.lang.String) */ public static void escapeJava(Writer out, String str) throws IOException { escapeJavaStyleString(out, str, false); @@ -104,13 +105,13 @@ public static void escapeJava(Writer out, String str) throws IOException { *

Escapes the characters in a String using JavaScript String rules.

*

Escapes any values it finds into their JavaScript String form. * Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)

- * + *

*

So a tab becomes the characters '\\' and * 't'.

- * + *

*

The only difference between Java strings and JavaScript strings * is that in JavaScript, a single quote must be escaped.

- * + *

*

Example: *

      * input string: He didn't say, "Stop!"
@@ -118,7 +119,7 @@ public static void escapeJava(Writer out, String str) throws IOException {
      * 
*

* - * @param str String to escape values in, may be null + * @param str String to escape values in, may be null * @return String with escaped values, null if null string input */ public static String escapeJavaScript(String str) { @@ -128,14 +129,14 @@ public static String escapeJavaScript(String str) { /** *

Escapes the characters in a String using JavaScript String rules * to a Writer.

- * + *

*

A null string input has no effect.

- * - * @see #escapeJavaScript(java.lang.String) - * @param out Writer to write escaped string into - * @param str String to escape values in, may be null + * + * @param out Writer to write escaped string into + * @param str String to escape values in, may be null * @throws IllegalArgumentException if the Writer is null - * @throws IOException if error occurs on underlying Writer + * @throws IOException if error occurs on underlying Writer + * @see #escapeJavaScript(java.lang.String) **/ public static void escapeJavaScript(Writer out, String str) throws IOException { escapeJavaStyleString(out, str, true); @@ -143,8 +144,8 @@ public static void escapeJavaScript(Writer out, String str) throws IOException { /** *

Worker method for the {@link #escapeJavaScript(String)} method.

- * - * @param str String to escape values in, may be null + * + * @param str String to escape values in, may be null * @param escapeSingleQuotes escapes single quotes if true * @return the escaped string */ @@ -165,9 +166,9 @@ private static String escapeJavaStyleString(String str, boolean escapeSingleQuot /** *

Worker method for the {@link #escapeJavaScript(String)} method.

- * - * @param out write to receieve the escaped string - * @param str String to escape values in, may be null + * + * @param out write to receieve the escaped string + * @param str String to escape values in, may be null * @param escapeSingleQuote escapes single quotes if true * @throws IOException if an IOException occurs */ @@ -212,7 +213,7 @@ private static void escapeJavaStyleString(Writer out, String str, boolean escape out.write('\\'); out.write('r'); break; - default : + default: if (ch > 0xf) { out.write("\\u00" + hex(ch)); } else { @@ -224,7 +225,7 @@ private static void escapeJavaStyleString(Writer out, String str, boolean escape switch (ch) { case '\'': if (escapeSingleQuote) { - out.write('\\'); + out.write('\\'); } out.write('\''); break; @@ -240,7 +241,7 @@ private static void escapeJavaStyleString(Writer out, String str, boolean escape out.write('\\'); out.write('/'); break; - default : + default: out.write(ch); break; } @@ -251,7 +252,7 @@ private static void escapeJavaStyleString(Writer out, String str, boolean escape /** *

Returns an upper case hexadecimal String for the given * character.

- * + * * @param ch The character to convert. * @return An upper case hexadecimal String */ @@ -264,8 +265,8 @@ private static String hex(char ch) { * For example, it will turn a sequence of '\' and * 'n' into a newline character, unless the '\' * is preceded by another '\'.

- * - * @param str the String to unescape, may be null + * + * @param str the String to unescape, may be null * @return a new unescaped String, null if null string input */ public static String unescapeJava(String str) { @@ -286,17 +287,17 @@ public static String unescapeJava(String str) { /** *

Unescapes any Java literals found in the String to a * Writer.

- * + *

*

For example, it will turn a sequence of '\' and * 'n' into a newline character, unless the '\' * is preceded by another '\'.

- * + *

*

A null string input has no effect.

- * - * @param out the Writer used to output unescaped characters - * @param str the String to unescape, may be null + * + * @param out the Writer used to output unescaped characters + * @param str the String to unescape, may be null * @throws IllegalArgumentException if the Writer is null - * @throws IOException if error occurs on underlying Writer + * @throws IOException if error occurs on underlying Writer */ public static void unescapeJava(Writer out, String str) throws IOException { if (out == null) { @@ -358,13 +359,12 @@ public static void unescapeJava(Writer out, String str) throws IOException { case 'b': out.write('\b'); break; - case 'u': - { - // uh-oh, we're in unicode country.... - inUnicode = true; - break; - } - default : + case 'u': { + // uh-oh, we're in unicode country.... + inUnicode = true; + break; + } + default: out.write(ch); break; } @@ -384,14 +384,14 @@ public static void unescapeJava(Writer out, String str) throws IOException { /** *

Unescapes any JavaScript literals found in the String.

- * + *

*

For example, it will turn a sequence of '\' and 'n' * into a newline character, unless the '\' is preceded by another * '\'.

* - * @see #unescapeJava(String) - * @param str the String to unescape, may be null + * @param str the String to unescape, may be null * @return A new unescaped String, null if null string input + * @see #unescapeJava(String) */ public static String unescapeJavaScript(String str) { return unescapeJava(str); @@ -400,18 +400,18 @@ public static String unescapeJavaScript(String str) { /** *

Unescapes any JavaScript literals found in the String to a * Writer.

- * + *

*

For example, it will turn a sequence of '\' and 'n' * into a newline character, unless the '\' is preceded by another * '\'.

- * + *

*

A null string input has no effect.

- * - * @see #unescapeJava(Writer,String) - * @param out the Writer used to output unescaped characters - * @param str the String to unescape, may be null + * + * @param out the Writer used to output unescaped characters + * @param str the String to unescape, may be null * @throws IllegalArgumentException if the Writer is null - * @throws IOException if error occurs on underlying Writer + * @throws IOException if error occurs on underlying Writer + * @see #unescapeJava(Writer, String) */ public static void unescapeJavaScript(Writer out, String str) throws IOException { unescapeJava(out, str); @@ -419,25 +419,25 @@ public static void unescapeJavaScript(Writer out, String str) throws IOException // HTML and XML //-------------------------------------------------------------------------- + /** *

Escapes the characters in a String using HTML entities.

- * + *

*

* For example: - *

+ *

*

"bread" & "butter"

* becomes: *

* &quot;bread&quot; &amp; &quot;butter&quot;. *

- * + *

*

Supports all known HTML 4.0 entities, including funky accents. * Note that the commonly used apostrophe escape character (&apos;) * is not a legal entity and so is not supported).

* - * @param str the String to escape, may be null + * @param str the String to escape, may be null * @return a new escaped String, null if null string input - * * @see #unescapeHtml(String) * @see ISO Entities * @see HTML 3.2 Character Entities for ISO Latin-1 @@ -450,7 +450,7 @@ public static String escapeHtml(String str) { return null; } try { - StringWriter writer = new StringWriter ((int)(str.length() * 1.5)); + StringWriter writer = new StringWriter((int) (str.length() * 1.5)); escapeHtml(writer, str); return writer.toString(); } catch (IOException e) { @@ -464,24 +464,23 @@ public static String escapeHtml(String str) { /** *

Escapes the characters in a String using HTML entities and writes * them to a Writer.

- * + *

*

* For example: - *

+ *

* "bread" & "butter" *

becomes:

* &quot;bread&quot; &amp; &quot;butter&quot;. - * + *

*

Supports all known HTML 4.0 entities, including funky accents. * Note that the commonly used apostrophe escape character (&apos;) * is not a legal entity and so is not supported).

* - * @param writer the writer receiving the escaped string, not null - * @param string the String to escape, may be null + * @param writer the writer receiving the escaped string, not null + * @param string the String to escape, may be null * @throws IllegalArgumentException if the writer is null - * @throws IOException when Writer passed throws the exception from - * calls to the {@link Writer#write(int)} methods. - * + * @throws IOException when Writer passed throws the exception from + * calls to the {@link Writer#write(int)} methods. * @see #escapeHtml(String) * @see #unescapeHtml(String) * @see ISO Entities @@ -491,8 +490,8 @@ public static String escapeHtml(String str) { * @see HTML 4.01 Code positions */ public static void escapeHtml(Writer writer, String string) throws IOException { - if (writer == null ) { - throw new IllegalArgumentException ("The Writer must not be null."); + if (writer == null) { + throw new IllegalArgumentException("The Writer must not be null."); } if (string == null) { return; @@ -501,19 +500,20 @@ public static void escapeHtml(Writer writer, String string) throws IOException { } //----------------------------------------------------------------------- + /** *

Unescapes a string containing entity escapes to a string * containing the actual Unicode characters corresponding to the * escapes. Supports HTML 4.0 entities.

- * + *

*

For example, the string "&lt;Fran&ccedil;ais&gt;" * will become "<Français>"

- * + *

*

If an entity is unrecognized, it is left alone, and inserted * verbatim into the result string. e.g. "&gt;&zzzz;x" will * become ">&zzzz;x".

* - * @param str the String to unescape, may be null + * @param str the String to unescape, may be null * @return a new unescaped String, null if null string input * @see #escapeHtml(Writer, String) */ @@ -522,7 +522,7 @@ public static String unescapeHtml(String str) { return null; } try { - StringWriter writer = new StringWriter ((int)(str.length() * 1.5)); + StringWriter writer = new StringWriter((int) (str.length() * 1.5)); unescapeHtml(writer, str); return writer.toString(); } catch (IOException e) { @@ -537,23 +537,23 @@ public static String unescapeHtml(String str) { *

Unescapes a string containing entity escapes to a string * containing the actual Unicode characters corresponding to the * escapes. Supports HTML 4.0 entities.

- * + *

*

For example, the string "&lt;Fran&ccedil;ais&gt;" * will become "<Français>"

- * + *

*

If an entity is unrecognized, it is left alone, and inserted * verbatim into the result string. e.g. "&gt;&zzzz;x" will * become ">&zzzz;x".

* - * @param writer the writer receiving the unescaped string, not null - * @param string the String to unescape, may be null + * @param writer the writer receiving the unescaped string, not null + * @param string the String to unescape, may be null * @throws IllegalArgumentException if the writer is null - * @throws IOException if an IOException occurs + * @throws IOException if an IOException occurs * @see #escapeHtml(String) */ public static void unescapeHtml(Writer writer, String string) throws IOException { - if (writer == null ) { - throw new IllegalArgumentException ("The Writer must not be null."); + if (writer == null) { + throw new IllegalArgumentException("The Writer must not be null."); } if (string == null) { return; @@ -562,28 +562,29 @@ public static void unescapeHtml(Writer writer, String string) throws IOException } //----------------------------------------------------------------------- + /** *

Escapes the characters in a String using XML entities.

- * + *

*

For example: "bread" & "butter" => * &quot;bread&quot; &amp; &quot;butter&quot;. *

- * + *

*

Supports only the five basic XML entities (gt, lt, quot, amp, apos). * Does not support DTDs or external entities.

+ *

+ *

Note that unicode characters greater than 0x7f are currently escaped to + * their numerical \\u equivalent. This may change in future releases.

* - *

Note that unicode characters greater than 0x7f are currently escaped to - * their numerical \\u equivalent. This may change in future releases.

- * - * @param writer the writer receiving the unescaped string, not null - * @param str the String to escape, may be null + * @param writer the writer receiving the unescaped string, not null + * @param str the String to escape, may be null * @throws IllegalArgumentException if the writer is null - * @throws IOException if there is a problem writing + * @throws IOException if there is a problem writing * @see #unescapeXml(java.lang.String) */ public static void escapeXml(Writer writer, String str) throws IOException { - if (writer == null ) { - throw new IllegalArgumentException ("The Writer must not be null."); + if (writer == null) { + throw new IllegalArgumentException("The Writer must not be null."); } if (str == null) { return; @@ -593,18 +594,18 @@ public static void escapeXml(Writer writer, String str) throws IOException { /** *

Escapes the characters in a String using XML entities.

- * + *

*

For example: "bread" & "butter" => * &quot;bread&quot; &amp; &quot;butter&quot;. *

- * + *

*

Supports only the five basic XML entities (gt, lt, quot, amp, apos). * Does not support DTDs or external entities.

+ *

+ *

Note that unicode characters greater than 0x7f are currently escaped to + * their numerical \\u equivalent. This may change in future releases.

* - *

Note that unicode characters greater than 0x7f are currently escaped to - * their numerical \\u equivalent. This may change in future releases.

- * - * @param str the String to escape, may be null + * @param str the String to escape, may be null * @return a new escaped String, null if null string input * @see #unescapeXml(java.lang.String) */ @@ -616,26 +617,27 @@ public static String escapeXml(String str) { } //----------------------------------------------------------------------- + /** *

Unescapes a string containing XML entity escapes to a string * containing the actual Unicode characters corresponding to the * escapes.

- * + *

*

Supports only the five basic XML entities (gt, lt, quot, amp, apos). * Does not support DTDs or external entities.

+ *

+ *

Note that numerical \\u unicode codes are unescaped to their respective + * unicode characters. This may change in future releases.

* - *

Note that numerical \\u unicode codes are unescaped to their respective - * unicode characters. This may change in future releases.

- * - * @param writer the writer receiving the unescaped string, not null - * @param str the String to unescape, may be null + * @param writer the writer receiving the unescaped string, not null + * @param str the String to unescape, may be null * @throws IllegalArgumentException if the writer is null - * @throws IOException if there is a problem writing + * @throws IOException if there is a problem writing * @see #escapeXml(String) */ public static void unescapeXml(Writer writer, String str) throws IOException { - if (writer == null ) { - throw new IllegalArgumentException ("The Writer must not be null."); + if (writer == null) { + throw new IllegalArgumentException("The Writer must not be null."); } if (str == null) { return; @@ -647,14 +649,14 @@ public static void unescapeXml(Writer writer, String str) throws IOException { *

Unescapes a string containing XML entity escapes to a string * containing the actual Unicode characters corresponding to the * escapes.

- * + *

*

Supports only the five basic XML entities (gt, lt, quot, amp, apos). * Does not support DTDs or external entities.

+ *

+ *

Note that numerical \\u unicode codes are unescaped to their respective + * unicode characters. This may change in future releases.

* - *

Note that numerical \\u unicode codes are unescaped to their respective - * unicode characters. This may change in future releases.

- * - * @param str the String to unescape, may be null + * @param str the String to unescape, may be null * @return a new unescaped String, null if null string input * @see #escapeXml(String) */ diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/Tool.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/Tool.java index b4b1c4c7946..ccd44a879a7 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/Tool.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/Tool.java @@ -1,11 +1,11 @@ /** * Project: dubbo.registry.server-1.1.0-SNAPSHOT - * + *

* File Created at 2010-7-27 - * + *

* Copyright 1999-2010 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -14,6 +14,10 @@ */ package com.alibaba.dubbo.registry.common.util; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.utils.NetUtils; +import com.alibaba.dubbo.common.utils.StringUtils; + import java.lang.reflect.Array; import java.net.InetAddress; import java.net.UnknownHostException; @@ -24,48 +28,60 @@ import java.util.Map; import java.util.regex.Pattern; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.common.utils.StringUtils; - /** * Tool - * + * * @author william.liangf */ public class Tool { - + private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$"); + private static final Comparator SIMPLE_NAME_COMPARATOR = new Comparator() { + public int compare(String s1, String s2) { + if (s1 == null && s2 == null) { + return 0; + } + if (s1 == null) { + return -1; + } + if (s2 == null) { + return 1; + } + s1 = getSimpleName(s1); + s2 = getSimpleName(s2); + return s1.compareToIgnoreCase(s2); + } + }; public static boolean startWith(String value, String prefix) { return value.startsWith(prefix); } - + public static boolean isContains(String[] values, String value) { return StringUtils.isContains(values, value); } - - public static boolean isValidAddress(String address){ + + public static boolean isValidAddress(String address) { return IP_PATTERN.matcher(address).matches(); } public static String getHostName(String address) { if (address != null && address.length() > 0) { String hostname = NetUtils.getHostName(address); - if (! address.equals(hostname)) { + if (!address.equals(hostname)) { return hostname + "/"; } } return ""; } - + public static String getIP(String address) { - if (address != null && address.length() > 0) { - int i = address.indexOf("://"); - if (i >= 0) { - address = address.substring(i + 3); - } - i = address.indexOf('/'); + if (address != null && address.length() > 0) { + int i = address.indexOf("://"); + if (i >= 0) { + address = address.substring(i + 3); + } + i = address.indexOf('/'); if (i >= 0) { address = address.substring(0, i); } @@ -83,77 +99,60 @@ public static String getIP(String address) { } catch (UnknownHostException e) { } } - } - return address; + } + return address; } - + public static String encodeUrl(String url) { - return URL.encode(url); + return URL.encode(url); } - + public static String decodeUrl(String url) { return URL.decode(url); } - + public static String encodeHtml(String html) { - return StringEscapeUtils.escapeHtml(html); + return StringEscapeUtils.escapeHtml(html); } public static String decodeHtml(String html) { return StringEscapeUtils.unescapeHtml(html); } - + public static int countMapValues(Map map) { - int total = 0; - if (map != null && map.size() > 0) { - for (Object value : map.values()) { - if (value != null) { - if (value instanceof Number) { - total += ((Number)value).intValue(); - } else if (value.getClass().isArray()) { - total += Array.getLength(value); - } else if (value instanceof Collection) { - total += ((Collection)value).size(); - } else if (value instanceof Map) { - total += ((Map)value).size(); - } else { - total += 1; - } - } - } - } - return total; + int total = 0; + if (map != null && map.size() > 0) { + for (Object value : map.values()) { + if (value != null) { + if (value instanceof Number) { + total += ((Number) value).intValue(); + } else if (value.getClass().isArray()) { + total += Array.getLength(value); + } else if (value instanceof Collection) { + total += ((Collection) value).size(); + } else if (value instanceof Map) { + total += ((Map) value).size(); + } else { + total += 1; + } + } + } + } + return total; + } + + public static List sortSimpleName(List list) { + if (list != null && list.size() > 0) { + Collections.sort(list, SIMPLE_NAME_COMPARATOR); + } + return list; } - - private static final Comparator SIMPLE_NAME_COMPARATOR = new Comparator() { - public int compare(String s1, String s2) { - if (s1 == null && s2 == null) { - return 0; - } - if (s1 == null) { - return -1; - } - if (s2 == null) { - return 1; - } - s1 = getSimpleName(s1); - s2 = getSimpleName(s2); - return s1.compareToIgnoreCase(s2); - } - }; - - public static List sortSimpleName(List list) { - if (list != null && list.size() > 0) { - Collections.sort(list, SIMPLE_NAME_COMPARATOR); - } - return list; - } - - public static String getSimpleName(String name) { + + public static String getSimpleName(String name) { if (name != null && name.length() > 0) { final int ip = name.indexOf('/'); String v = ip != -1 ? name.substring(0, ip + 1) : ""; - + int i = name.lastIndexOf(':'); int j = (i >= 0 ? name.lastIndexOf('.', i) : name.lastIndexOf('.')); if (j >= 0) { diff --git a/dubbo-admin/src/main/resources/META-INF/spring/dubbo-admin.xml b/dubbo-admin/src/main/resources/META-INF/spring/dubbo-admin.xml index 64cd261eee7..0a491179c27 100644 --- a/dubbo-admin/src/main/resources/META-INF/spring/dubbo-admin.xml +++ b/dubbo-admin/src/main/resources/META-INF/spring/dubbo-admin.xml @@ -1,46 +1,45 @@ - - - - - - - /WEB-INF/dubbo.properties - file://${user.home}/dubbo.properties - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + /WEB-INF/dubbo.properties + file://${user.home}/dubbo.properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo-admin/src/main/webapp/META-INF/autoconf/auto-config.xml b/dubbo-admin/src/main/webapp/META-INF/autoconf/auto-config.xml index 6dc3e8572d2..30e6371d61a 100644 --- a/dubbo-admin/src/main/webapp/META-INF/autoconf/auto-config.xml +++ b/dubbo-admin/src/main/webapp/META-INF/autoconf/auto-config.xml @@ -4,33 +4,41 @@ - + - + - + - + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - $control.setTemplate("home:menu.vm") - -

-
-
- #set($tabs = []) - #if($service && $service != '*') - #set($tabs = ["providers", "consumers", "applications", "routes", "overrides", "accesses", "weights", "loadbalances", "owners"]) - #elseif($address && $address != '*') - #set($tabs = ["providers", "consumers", "routes", "accesses", "weights"]) - #elseif($application && $application != '*') - #set($tabs = ["services", "addresses", "overrides"]) - #else - #if($_type != "services" && $_type != "applications" && $_type != "addresses") - #set($tabs = ["providers", "consumers", "routes", "overrides", "accesses", "weights", "loadbalances", "owners"]) - #end - #end - #if($tabs.size() > 0) - - #end -
-
- $screen_placeholder -
-
-
-
- - -
- - -
+ + + Dubbo Admin + + + + + + + + + + + + $control.setTemplate("home:menu.vm") + + +
+
+ #set($tabs = []) + #if($service && $service != '*') + #set($tabs = ["providers", "consumers", "applications", "routes", "overrides", "accesses", "weights", + "loadbalances", "owners"]) + #elseif($address && $address != '*') + #set($tabs = ["providers", "consumers", "routes", "accesses", "weights"]) + #elseif($application && $application != '*') + #set($tabs = ["services", "addresses", "overrides"]) + #else + #if($_type != "services" && $_type != "applications" && $_type != "addresses") + #set($tabs = ["providers", "consumers", "routes", "overrides", "accesses", "weights", "loadbalances", + "owners"]) + #end + #end + #if($tabs.size() > 0) + + #end +
+
+ $screen_placeholder +
+
+
+
+ + +
+ + +
\ No newline at end of file diff --git a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/layout/noServicePrivilege.vm b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/layout/noServicePrivilege.vm index c0854bef89e..e190bc20f70 100644 --- a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/layout/noServicePrivilege.vm +++ b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/layout/noServicePrivilege.vm @@ -1,14 +1,15 @@ - + - -dubbo - - - - + + dubbo + + + + -$screen_placeholder + $screen_placeholder \ No newline at end of file diff --git a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/layout/redirect.vm b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/layout/redirect.vm index c0854bef89e..e190bc20f70 100644 --- a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/layout/redirect.vm +++ b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/layout/redirect.vm @@ -1,14 +1,15 @@ - + - -dubbo - - - - + + dubbo + + + + -$screen_placeholder + $screen_placeholder \ No newline at end of file diff --git a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/accesses/add.vm b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/accesses/add.vm index f63991f1108..2dae076d3f0 100644 --- a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/accesses/add.vm +++ b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/accesses/add.vm @@ -1,87 +1,93 @@
- - - - - - - - - - - - - - - - - -
$i18n.get("service")  * - #if($service) - $service - #else - - #if ($serviceList && $serviceList.size() > 0) - - #end - #end -
$i18n.get("ConsumerAddress"):  * - #if($address) - $tool.getIP($address) - #else - - #end - $i18n.get("BatchAddressTip") -
$i18n.get("status"): - - $i18n.get("AccessControlTip") -
+ + + + + + + + + + + + + + + + + +
$i18n.get("service")  * + #if($service) + $service + #else + + #if ($serviceList && $serviceList.size() > 0) + + #end + #end +
$i18n.get("ConsumerAddress"):  * + #if($address) + $tool.getIP($address) + #else + + #end + $i18n.get("BatchAddressTip") +
$i18n.get("status"): + + $i18n.get("AccessControlTip") +
+ +
- + \ No newline at end of file diff --git a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/accesses/index.vm b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/accesses/index.vm index b0e9f8c9fc1..6ae631cdf1d 100644 --- a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/accesses/index.vm +++ b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/accesses/index.vm @@ -1,63 +1,77 @@
- #if($currentUser.role != "G") - $i18n.get("add") - | - $i18n.get("batch.delete") - #end + #if($currentUser.role != "G") + $i18n.get("add") + | + $i18n.get("batch.delete") + #end

- - - - #set($column = 2) ## 是否显示 服务名一列 - #if(!$service) - - #set($column = $column + 1) - #end - - #if($currentUser.role != "G")#end - -#foreach($access in $accesses) - - - - #if(!$service) - - #end - - #if($currentUser.role != "G") - - #end - -#end + + + + #set($column = 2) ## 是否显示 服务名一列 + #if(!$service) + + #set($column = $column + 1) + #end + + #if($currentUser.role != "G") + #end + + #foreach($access in $accesses) + + + + #if(!$service) + + #end + + #if($currentUser.role != "G") + + #end + + #end
$i18n.get("consumer.address"):  $i18n.get("service"): -   - - $i18n.get("type"): - - $i18n.get("operation")
$access.address$access.service#if($access.allow==true) $i18n.get("whitelist") #elseif($access.allow==false) $i18n.get("blacklist") #end - - - $i18n.get("delete") -
$i18n.get("consumer.address"):  $i18n.get("service"): +   + + $i18n.get("type"): + + $i18n.get("operation")
$access.address$access.service#if($access.allow==true) $i18n.get("whitelist") #elseif($access.allow==false) + $i18n.get("blacklist") #end + + + $i18n.get("delete") +
$i18n.get("page.total")$accesses.size()$i18n.get("page.records")
\ No newline at end of file diff --git a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/addresses/index.vm b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/addresses/index.vm index 8826cd08e5c..867f806b322 100644 --- a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/addresses/index.vm +++ b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/addresses/index.vm @@ -2,39 +2,46 @@ $i18n.get("not.found") ($i18n.get("show.all") ) #elseif($keyword && $addresses.size() == 1) #else - - - - -#foreach($address in $addresses) - - - - -#end + + + + + #foreach($address in $addresses) + + + + + #end
$i18n.get("address"): -   - $i18n.get("role"):
- #if($providerAddresses.contains($address)) - $address - #else - $address - #end - - #if($providerAddresses.contains($address)) - $i18n.get("provider") - #end - #if($consumerAddresses.contains($address)) - $i18n.get("consumer") - #end -
$i18n.get("address"): +   + $i18n.get("role"):
+ #if($providerAddresses.contains($address)) + $address + #else + $address + #end + + #if($providerAddresses.contains($address)) + $i18n.get("provider") + #end + #if($consumerAddresses.contains($address)) + $i18n.get("consumer") + #end +
$i18n.get("page.total")$addresses.size()$i18n.get("page.records")
#end \ No newline at end of file diff --git a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/addresses/search.vm b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/addresses/search.vm index 7ae143eeaa5..65fc3f73efd 100644 --- a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/addresses/search.vm +++ b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/addresses/search.vm @@ -1,4 +1,4 @@ [#foreach($address in $addresses) -#if ($velocityCount > 1),#end + #if ($velocityCount > 1),#end "$address" #end] \ No newline at end of file diff --git a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/applications/index.vm b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/applications/index.vm index d10e39ff7cf..f9eb0b352c8 100644 --- a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/applications/index.vm +++ b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/applications/index.vm @@ -2,85 +2,140 @@ $i18n.get("not.found") ($i18n.get("show.all") ) #elseif($keyword && $applications.size() == 1) #else
- - - - - #if($service) - - - #end - -#foreach($application in $applications) - - - - - #if($service) - - - #end - -#end + + + + + #if($service) + + + #end + + #foreach($application in $applications) + + + + + #if($service) + + + #end + + #end
$i18n.get("application"): -   - $i18n.get("role"): $i18n.get("mock"): $i18n.get("operation")
#if($service)$application#else$application#end - #if($providerApplications.contains($application)) - $i18n.get("provider") - #end - #if($consumerApplications.contains($application)) - $i18n.get("consumer") - #end - - #if($consumerApplications.contains($application)) - #set($mock=$tool.getOverridesMock($overrides.get($application))) - #if($mock == "force%3Areturn+null") - $i18n.get("force.mocked") - #elseif ($mock == "fail%3Areturn+null") - $i18n.get("fail.mocked") - #else - $i18n.get("no.mocked") - #end - #end - - #if($consumerApplications.contains($application)) - #set($mock=$tool.getOverridesMock($overrides.get($application))) - #if($mock == "force%3Areturn+null") - $i18n.get("cancel.mock") - | - $i18n.get("fail.mock") - #elseif ($mock == "fail%3Areturn+null") - $i18n.get("force.mock") - | - $i18n.get("cancel.mock") - #else - $i18n.get("force.mock") - | - $i18n.get("fail.mock") - #end - #end -
$i18n.get("application"): +   + $i18n.get("role"): $i18n.get("mock"): $i18n.get("operation")
#if($service)$application#else$application#end + #if($providerApplications.contains($application)) + $i18n.get("provider") + #end + #if($consumerApplications.contains($application)) + $i18n.get("consumer") + #end + + #if($consumerApplications.contains($application)) + #set($mock=$tool.getOverridesMock($overrides.get($application))) + #if($mock == "force%3Areturn+null") + $i18n.get("force.mocked") + #elseif ($mock == "fail%3Areturn+null") + $i18n.get("fail.mocked") + #else + $i18n.get("no.mocked") + #end + #end + + #if($consumerApplications.contains($application)) + #set($mock=$tool.getOverridesMock($overrides.get($application))) + #if($mock == "force%3Areturn+null") + $i18n.get("cancel.mock") + | + $i18n.get("fail.mock") + #elseif ($mock == "fail%3Areturn+null") + $i18n.get("force.mock") + | + $i18n.get("cancel.mock") + #else + $i18n.get("force.mock") + | + $i18n.get("fail.mock") + #end + #end +
$i18n.get("page.total")$applications.size()$i18n.get("page.records")
#end \ No newline at end of file diff --git a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/applications/search.vm b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/applications/search.vm index b3a99ea4cd1..7e8fd9dfdd2 100644 --- a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/applications/search.vm +++ b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/applications/search.vm @@ -1,4 +1,4 @@ [#foreach($application in $applications) -#if ($velocityCount > 1),#end + #if ($velocityCount > 1),#end "$application" #end] \ No newline at end of file diff --git a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/consumers/edit.vm b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/consumers/edit.vm index a2e445ef03e..b86a6d82fc1 100644 --- a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/consumers/edit.vm +++ b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/consumers/edit.vm @@ -1,95 +1,123 @@
- $i18n.get("back") - | - $i18n.get("show") - #set($mock=$tool.getConsumerMock($consumer)) - #if($currentUser.hasServicePrivilege($consumer.service)) - | - #if($mock.equals("force%3Areturn+null")) - $i18n.get("cancel.mock") - | - $i18n.get("fail.mock") - #elseif ($mock.equals("fail%3Areturn+null")) - $i18n.get("force.mock") - | - $i18n.get("cancel.mock") - #else - $i18n.get("force.mock") - | - $i18n.get("fail.mock") - #end - #end - #if ($consumer.routes && $consumer.routes.size() > 0) - | - $i18n.get("routed")($consumer.routes.size()) - #end - #if ($consumer.providers && $consumer.providers.size() > 0) - | - $i18n.get("notified")($consumer.providers.size()) - #end + $i18n.get("back") + | + $i18n.get("show") + #set($mock=$tool.getConsumerMock($consumer)) + #if($currentUser.hasServicePrivilege($consumer.service)) + | + #if($mock.equals("force%3Areturn+null")) + $i18n.get("cancel.mock") + | + $i18n.get("fail.mock") + #elseif ($mock.equals("fail%3Areturn+null")) + $i18n.get("force.mock") + | + $i18n.get("cancel.mock") + #else + $i18n.get("force.mock") + | + $i18n.get("fail.mock") + #end + #end + #if ($consumer.routes && $consumer.routes.size() > 0) + | + $i18n.get("routed") + ($consumer.routes.size()) + #end + #if ($consumer.providers && $consumer.providers.size() > 0) + | + $i18n.get("notified") + ($consumer.providers.size()) + #end

- - #if(! $service) - - - - - #end - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
$i18n.get("service"): $!consumer.service
$i18n.get("consumerAddress"):consumer://$!consumer.address/$!consumer.service?$!consumer.parameters
$i18n.get("overrides"): $i18n.get("dynamic.parameters.tip")
$i18n.get("mock"): - #if($mock.equals("force%3Areturn+null")) - $i18n.get("force.mocked") - #elseif ($mock.equals("fail%3Areturn+null")) - $i18n.get("fail.mocked") - #else - $i18n.get("no.mocked") - #end -
$i18n.get("Status"): - #if($tool.isInBlackList($consumer)) - $i18n.get("Forbidden") - #else - $i18n.get("Allowed") - #end -
$i18n.get("Route"): - #if($consumer.routes && $consumer.routes.size() > 0) - $i18n.get("routed")($consumer.routes.size()) - #else - $i18n.get("unrouted") - #end -
$i18n.get("notify"): - #if($consumer.providers && $consumer.providers.size() > 0) - $i18n.get("notified")($consumer.providers.size()) - #else - $i18n.get("NoProvider") - #end -
+ + #if(! $service) + + + + + #end + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
$i18n.get("service"):$!consumer.service
$i18n.get("consumerAddress"):consumer://$!consumer.address/$!consumer.service?$!consumer.parameters
$i18n.get("overrides"): $i18n.get("dynamic.parameters.tip")
$i18n.get("mock"): + #if($mock.equals("force%3Areturn+null")) + $i18n.get("force.mocked") + #elseif ($mock.equals("fail%3Areturn+null")) + $i18n.get("fail.mocked") + #else + $i18n.get("no.mocked") + #end +
$i18n.get("Status"): + #if($tool.isInBlackList($consumer)) + $i18n.get("Forbidden") + #else + $i18n.get("Allowed") + #end +
$i18n.get("Route"): + #if($consumer.routes && $consumer.routes.size() > 0) + $i18n.get("routed")($consumer.routes.size()) + #else + $i18n.get("unrouted") + #end +
$i18n.get("notify"): + #if($consumer.providers && $consumer.providers.size() > 0) + $i18n.get("notified")($consumer.providers.size()) + #else + $i18n.get("NoProvider") + #end +
+ +
\ No newline at end of file diff --git a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/consumers/index.vm b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/consumers/index.vm index 1858a1127d3..ccd231f3e46 100644 --- a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/consumers/index.vm +++ b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/consumers/index.vm @@ -1,104 +1,204 @@
- - - - - - - - - #if($currentUser.role != "G")#end - -#foreach($consumer in $consumers) - - - - - - - - - #if($currentUser.role != "G") - - #end - -#end + + + + + + + + + #if($currentUser.role != "G") + #end + + #foreach($consumer in $consumers) + + + + + + + + + #if($currentUser.role != "G") + + #end + + #end
#if($address)$i18n.get("service")#else$i18n.get("address")#end:  $i18n.get("application"):  $i18n.get("access"): $i18n.get("mock"): $i18n.get("Route"): $i18n.get("notify"): $i18n.get("operation")
#if($address)$tool.getSimpleName($consumer.service)#else$consumer.address#end$consumer.application - #if($tool.isInBlackList($consumer)) - $i18n.get("Forbidden") - #else - $i18n.get("Allowed") - #end - - #set($mock=$tool.getConsumerMock($consumer)) - #if($mock.equals("force%3Areturn+null")) - $i18n.get("force.mocked") - #elseif ($mock.equals("fail%3Areturn+null")) - $i18n.get("fail.mocked") - #else - $i18n.get("no.mocked") - #end - - #if($consumer.routes && $consumer.routes.size() > 0) - $i18n.get("routed")($consumer.routes.size()) - #else - $i18n.get("unrouted") - #end - - #if($consumer.providers && $consumer.providers.size() > 0) - $i18n.get("notified")($consumer.providers.size()) - #else - $i18n.get("NoProvider") - #end - - #if($currentUser.hasServicePrivilege($consumer.service)) - $i18n.get("edit") - | - #if($tool.isInBlackList($consumer)) - $i18n.get("allow") - #else - $i18n.get("forbid") - #end - | - #if($mock.equals("force%3Areturn+null")) - $i18n.get("cancel.mock") - | - $i18n.get("fail.mock") - #elseif ($mock.equals("fail%3Areturn+null")) - $i18n.get("force.mock") - | - $i18n.get("cancel.mock") - #else - $i18n.get("force.mock") - | - $i18n.get("fail.mock") - #end - #end -
#if($address)$i18n.get("service")#else$i18n.get("address")#end:  $i18n.get("application"):  $i18n.get("access"): $i18n.get("mock"): $i18n.get("Route"): $i18n.get("notify"): $i18n.get("operation")
+ #if($address)$tool.getSimpleName($consumer.service)#else$consumer.address#end + $consumer.application + #if($tool.isInBlackList($consumer)) + $i18n.get("Forbidden") + #else + $i18n.get("Allowed") + #end + + #set($mock=$tool.getConsumerMock($consumer)) + #if($mock.equals("force%3Areturn+null")) + $i18n.get("force.mocked") + #elseif ($mock.equals("fail%3Areturn+null")) + $i18n.get("fail.mocked") + #else + $i18n.get("no.mocked") + #end + + #if($consumer.routes && $consumer.routes.size() > 0) + $i18n.get("routed")($consumer.routes.size()) + #else + $i18n.get("unrouted") + #end + + #if($consumer.providers && $consumer.providers.size() > 0) + $i18n.get("notified")($consumer.providers.size()) + #else + $i18n.get("NoProvider") + #end + + #if($currentUser.hasServicePrivilege($consumer.service)) + $i18n.get("edit") + | + #if($tool.isInBlackList($consumer)) + $i18n.get("allow") + #else + $i18n.get("forbid") + #end + | + #if($mock.equals("force%3Areturn+null")) + $i18n.get("cancel.mock") + | + $i18n.get("fail.mock") + #elseif ($mock.equals("fail%3Areturn+null")) + $i18n.get("force.mock") + | + $i18n.get("cancel.mock") + #else + $i18n.get("force.mock") + | + $i18n.get("fail.mock") + #end + #end +
$i18n.get("page.total")$consumers.size()$i18n.get("page.records")
diff --git a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/consumers/notified.vm b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/consumers/notified.vm index 1bc23063612..fa526f90ab9 100644 --- a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/consumers/notified.vm +++ b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/consumers/notified.vm @@ -1,93 +1,118 @@
- $i18n.get("back") - #set($mock=$tool.getConsumerMock($consumer)) - #if($currentUser.hasServicePrivilege($consumer.service)) - | - $i18n.get("edit") - | - #if($mock.equals("force%3Areturn+null")) - $i18n.get("cancel.mock") - | - $i18n.get("fail.mock") - #elseif ($mock.equals("fail%3Areturn+null")) - $i18n.get("force.mock") - | - $i18n.get("cancel.mock") - #else - $i18n.get("force.mock") - | - $i18n.get("fail.mock") - #end - #end - #if ($consumer.routes && $consumer.routes.size() > 0) - | - $i18n.get("routed")($consumer.routes.size()) - #end - | - $i18n.get("show") + $i18n.get("back") + #set($mock=$tool.getConsumerMock($consumer)) + #if($currentUser.hasServicePrivilege($consumer.service)) + | + $i18n.get("edit") + | + #if($mock.equals("force%3Areturn+null")) + $i18n.get("cancel.mock") + | + $i18n.get("fail.mock") + #elseif ($mock.equals("fail%3Areturn+null")) + $i18n.get("force.mock") + | + $i18n.get("cancel.mock") + #else + $i18n.get("force.mock") + | + $i18n.get("fail.mock") + #end + #end + #if ($consumer.routes && $consumer.routes.size() > 0) + | + $i18n.get("routed") + ($consumer.routes.size()) + #end + | + $i18n.get("show")

- #if(! $service) - - - - - #end - - - - - - - - - - - - - - - - - - - - - - - - + #if(! $service) + + + + + #end + + + + + + + + + + + + + + + + + + + + + + + +
$i18n.get("service"): $!consumer.service
$i18n.get("consumerAddress"):consumer://$!consumer.address/$!consumer.service?$!consumer.parameters
$i18n.get("overrides"): $!consumer.override.params
$i18n.get("mock"): - #if($mock.equals("force%3Areturn+null")) - $i18n.get("force.mocked") - #elseif ($mock.equals("fail%3Areturn+null")) - $i18n.get("fail.mocked") - #else - $i18n.get("no.mocked") - #end -
$i18n.get("Status"): - #if($tool.isInBlackList($consumer)) - $i18n.get("Forbidden") - #else - $i18n.get("Allowed") - #end -
$i18n.get("Route"): - #if($consumer.routes && $consumer.routes.size() > 0) - $i18n.get("routed")($consumer.routes.size()) - #else - $i18n.get("unrouted") - #end -
$i18n.get("notify"):
$i18n.get("service"):$!consumer.service
$i18n.get("consumerAddress"):consumer://$!consumer.address/$!consumer.service?$!consumer.parameters
$i18n.get("overrides"):$!consumer.override.params
$i18n.get("mock"): + #if($mock.equals("force%3Areturn+null")) + $i18n.get("force.mocked") + #elseif ($mock.equals("fail%3Areturn+null")) + $i18n.get("fail.mocked") + #else + $i18n.get("no.mocked") + #end +
$i18n.get("Status"): + #if($tool.isInBlackList($consumer)) + $i18n.get("Forbidden") + #else + $i18n.get("Allowed") + #end +
$i18n.get("Route"): + #if($consumer.routes && $consumer.routes.size() > 0) + $i18n.get("routed")($consumer.routes.size()) + #else + $i18n.get("unrouted") + #end +
$i18n.get("notify"):

- - - -#foreach($provider in $providers) - - - -#end + + + + #foreach($provider in $providers) + + + + #end
$i18n.get("url"):  
$provider.url?$provider.parameters
$i18n.get("url"):  
$provider.url?$provider.parameters
$i18n.get("page.total")$providers.size()$i18n.get("page.records")
diff --git a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/consumers/routed.vm b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/consumers/routed.vm index fbc5fb3a642..6e477a20311 100644 --- a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/consumers/routed.vm +++ b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/consumers/routed.vm @@ -1,95 +1,124 @@
- $i18n.get("back") - #set($mock=$tool.getConsumerMock($consumer)) - #if($currentUser.hasServicePrivilege($consumer.service)) - | - $i18n.get("edit") - | - #if($mock.equals("force%3Areturn+null")) - $i18n.get("cancel.mock") - | - $i18n.get("fail.mock") - #elseif ($mock.equals("fail%3Areturn+null")) - $i18n.get("force.mock") - | - $i18n.get("cancel.mock") - #else - $i18n.get("force.mock") - | - $i18n.get("fail.mock") - #end - #end - | - $i18n.get("show") - #if ($consumer.providers && $consumer.providers.size() > 0) - | - $i18n.get("notified")($consumer.providers.size()) - #end + $i18n.get("back") + #set($mock=$tool.getConsumerMock($consumer)) + #if($currentUser.hasServicePrivilege($consumer.service)) + | + $i18n.get("edit") + | + #if($mock.equals("force%3Areturn+null")) + $i18n.get("cancel.mock") + | + $i18n.get("fail.mock") + #elseif ($mock.equals("fail%3Areturn+null")) + $i18n.get("force.mock") + | + $i18n.get("cancel.mock") + #else + $i18n.get("force.mock") + | + $i18n.get("fail.mock") + #end + #end + | + $i18n.get("show") + #if ($consumer.providers && $consumer.providers.size() > 0) + | + $i18n.get("notified") + ($consumer.providers.size()) + #end

- #if(! $service) - - - - - #end - - - - - - - - - - - - - - - - - - - - - - - - + #if(! $service) + + + + + #end + + + + + + + + + + + + + + + + + + + + + + + +
$i18n.get("service"): $!consumer.service
$i18n.get("consumerAddress"):consumer://$!consumer.address/$!consumer.service?$!consumer.parameters
$i18n.get("overrides"): $!consumer.override.params
$i18n.get("mock"): - #if($mock.equals("force%3Areturn+null")) - $i18n.get("force.mocked") - #elseif ($mock.equals("fail%3Areturn+null")) - $i18n.get("fail.mocked") - #else - $i18n.get("no.mocked") - #end -
$i18n.get("Status"): - #if($tool.isInBlackList($consumer)) - $i18n.get("Forbidden") - #else - $i18n.get("Allowed") - #end -
$i18n.get("notify"): - #if($consumer.providers && $consumer.providers.size() > 0) - $i18n.get("notified")($consumer.providers.size()) - #else - $i18n.get("NoProvider") - #end -
$i18n.get("Route"):
$i18n.get("service"):$!consumer.service
$i18n.get("consumerAddress"):consumer://$!consumer.address/$!consumer.service?$!consumer.parameters
$i18n.get("overrides"):$!consumer.override.params
$i18n.get("mock"): + #if($mock.equals("force%3Areturn+null")) + $i18n.get("force.mocked") + #elseif ($mock.equals("fail%3Areturn+null")) + $i18n.get("fail.mocked") + #else + $i18n.get("no.mocked") + #end +
$i18n.get("Status"): + #if($tool.isInBlackList($consumer)) + $i18n.get("Forbidden") + #else + $i18n.get("Allowed") + #end +
$i18n.get("notify"): + #if($consumer.providers && $consumer.providers.size() > 0) + $i18n.get("notified")($consumer.providers.size()) + #else + $i18n.get("NoProvider") + #end +
$i18n.get("Route"):

- - - - -#foreach($route in $routes) - - - - -#end + + + + + #foreach($route in $routes) + + + + + #end
$i18n.get("routeName"):  $i18n.get("routeRule"):  
$route.name$route.matchRule => $route.filterRule
$i18n.get("routeName"):  $i18n.get("routeRule"):  
$route.name$route.matchRule => $route.filterRule
$i18n.get("page.total")$providers.size()$i18n.get("page.records")
\ No newline at end of file diff --git a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/consumers/show.vm b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/consumers/show.vm index 6156438ffcc..4ebc8e718a1 100644 --- a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/consumers/show.vm +++ b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/consumers/show.vm @@ -1,99 +1,124 @@
- $i18n.get("back") - #set($mock=$tool.getConsumerMock($consumer)) - #if($currentUser.hasServicePrivilege($consumer.service)) - | - $i18n.get("edit") - | - #if($mock.equals("force%3Areturn+null")) - $i18n.get("cancel.mock") - | - $i18n.get("fail.mock") - #elseif ($mock.equals("fail%3Areturn+null")) - $i18n.get("force.mock") - | - $i18n.get("cancel.mock") - #else - $i18n.get("force.mock") - | - $i18n.get("fail.mock") - #end - #end - #if ($consumer.routes && $consumer.routes.size() > 0) - | - $i18n.get("routed")($consumer.routes.size()) - #end - #if ($consumer.providers && $consumer.providers.size() > 0) - | - $i18n.get("notified")($consumer.providers.size()) - #end + $i18n.get("back") + #set($mock=$tool.getConsumerMock($consumer)) + #if($currentUser.hasServicePrivilege($consumer.service)) + | + $i18n.get("edit") + | + #if($mock.equals("force%3Areturn+null")) + $i18n.get("cancel.mock") + | + $i18n.get("fail.mock") + #elseif ($mock.equals("fail%3Areturn+null")) + $i18n.get("force.mock") + | + $i18n.get("cancel.mock") + #else + $i18n.get("force.mock") + | + $i18n.get("fail.mock") + #end + #end + #if ($consumer.routes && $consumer.routes.size() > 0) + | + $i18n.get("routed") + ($consumer.routes.size()) + #end + #if ($consumer.providers && $consumer.providers.size() > 0) + | + $i18n.get("notified") + ($consumer.providers.size()) + #end

- #if(! $service) - - - - - #end - - - - - - - - - - - - - #foreach($entry in $tool.toParameterMap($!consumer.parameters).entrySet()) - - - - - #end - - - - - - - - - - - - - - - - + #if(! $service) + + + + + #end + + + + + + + + + + + + + #foreach($entry in $tool.toParameterMap($!consumer.parameters).entrySet()) + + + + + #end + + + + + + + + + + + + + + + +
$i18n.get("service"): $!consumer.service
$i18n.get("consumerAddress"):consumer://$!consumer.address/$!consumer.service?$!consumer.parameters
$i18n.get("overrides"): $!consumer.override.params
$i18n.get("host"):$tool.getHostPrefix($!consumer.address)$!consumer.address
$i18n.get($entry.key):#if($entry.key == "timestamp") $tool.formatTimestamp($entry.value) ($entry.value) #else $entry.value #end
$i18n.get("mock"): - #if($mock.equals("force%3Areturn+null")) - $i18n.get("force.mocked") - #elseif ($mock.equals("fail%3Areturn+null")) - $i18n.get("fail.mocked") - #else - $i18n.get("no.mocked") - #end -
$i18n.get("Status"): - #if($tool.isInBlackList($consumer)) - $i18n.get("Forbidden") - #else - $i18n.get("Allowed") - #end -
$i18n.get("Route"): - #if($consumer.routes && $consumer.routes.size() > 0) - $i18n.get("routed")($consumer.routes.size()) - #else - $i18n.get("unrouted") - #end -
$i18n.get("notify"): - #if($consumer.providers && $consumer.providers.size() > 0) - $i18n.get("notified")($consumer.providers.size()) - #else - $i18n.get("NoProvider") - #end -
$i18n.get("service"):$!consumer.service
$i18n.get("consumerAddress"):consumer://$!consumer.address/$!consumer.service?$!consumer.parameters
$i18n.get("overrides"):$!consumer.override.params
$i18n.get("host"):$tool.getHostPrefix($!consumer.address)$!consumer.address
$i18n.get($entry.key):#if($entry.key == "timestamp") $tool.formatTimestamp($entry.value) + ($entry.value) #else $entry.value #end
$i18n.get("mock"): + #if($mock.equals("force%3Areturn+null")) + $i18n.get("force.mocked") + #elseif ($mock.equals("fail%3Areturn+null")) + $i18n.get("fail.mocked") + #else + $i18n.get("no.mocked") + #end +
$i18n.get("Status"): + #if($tool.isInBlackList($consumer)) + $i18n.get("Forbidden") + #else + $i18n.get("Allowed") + #end +
$i18n.get("Route"): + #if($consumer.routes && $consumer.routes.size() > 0) + $i18n.get("routed")($consumer.routes.size()) + #else + $i18n.get("unrouted") + #end +
$i18n.get("notify"): + #if($consumer.providers && $consumer.providers.size() > 0) + $i18n.get("notified")($consumer.providers.size()) + #else + $i18n.get("NoProvider") + #end +
\ No newline at end of file diff --git a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/loadbalances/add.vm b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/loadbalances/add.vm index 4f92e408591..7f42126218c 100644 --- a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/loadbalances/add.vm +++ b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/loadbalances/add.vm @@ -1,96 +1,105 @@
- - - - - - - - - - - - - - - - - -
$i18n.get("service")  *#if($service) - $service - #if($input) - - #end - #else - - #if ($serviceList && $serviceList.size() > 0) - - #end - -
- $i18n.get("MultiServiceTip") - #end -
$i18n.get("methodName")  * - - #if ($methods) - - #end -   “*”代表所有方法 -
$i18n.get("loadBalanceStrategy"): - - -
+ + + + + + + + + + + + + + + + + +
$i18n.get("service")  *#if($service) + $service + #if($input) + + #end + #else + + #if ($serviceList && $serviceList.size() > 0) + + #end + +
+ $i18n.get("MultiServiceTip") + #end +
$i18n.get("methodName")  * + + #if ($methods) + + #end +   “*”代表所有方法 +
$i18n.get("loadBalanceStrategy"): + + +
+ +
\ No newline at end of file diff --git a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/loadbalances/edit.vm b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/loadbalances/edit.vm index cac5ec35de2..7caa2209eb0 100644 --- a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/loadbalances/edit.vm +++ b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/loadbalances/edit.vm @@ -1,74 +1,83 @@
- - - - - - - - - - - - - - - - - -
$i18n.get("service")  * - $loadbalance.service -
$i18n.get("methodName")  * - $loadbalance.method -
$i18n.get("loadBalanceStrategy"): - - - - -
+ + + + + + + + + + + + + + + + + +
$i18n.get("service")  * + $loadbalance.service +
$i18n.get("methodName")  * + $loadbalance.method +
$i18n.get("loadBalanceStrategy"): + + + + +
+ +
\ No newline at end of file diff --git a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/loadbalances/index.vm b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/loadbalances/index.vm index f9ae23a6964..efd66c57a4c 100644 --- a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/loadbalances/index.vm +++ b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/loadbalances/index.vm @@ -1,41 +1,67 @@
- #if($currentUser.role != "G") - $i18n.get("add") - | - $i18n.get("batch.delete") - #end + #if($currentUser.role != "G") + $i18n.get("add") + | + $i18n.get("batch.delete") + #end

- - - - #if(! $service) - - - #else - - #end - #if($currentUser.role != "G")#end - -#foreach($loadbalance in $loadbalances) - - - - #if(! $service) - - #end - - #if($currentUser.role != "G") - - #end - -#end + + + + #if(! $service) + + + #else + + #end + #if($currentUser.role != "G") + #end + + #foreach($loadbalance in $loadbalances) + + + + #if(! $service) + + #end + + #if($currentUser.role != "G") + + #end + + #end
$i18n.get("service.method"):  $i18n.get("service"):  $i18n.get("loadBalanceStrategy"): $i18n.get("loadBalanceStrategy"): $i18n.get("operation")
$loadbalance.method$loadbalance.service$i18n.get($loadbalance.strategy) - $i18n.get("edit") - | - - - $i18n.get("delete") -
$i18n.get("service.method"):  $i18n.get("service"):  $i18n.get("loadBalanceStrategy"): $i18n.get("loadBalanceStrategy"): $i18n.get("operation")
$loadbalance.method$loadbalance.service$i18n.get($loadbalance.strategy) + $i18n.get("edit") + | + + + $i18n.get("delete") +
$i18n.get("page.total")$loadbalances.size()$i18n.get("page.records")
diff --git a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/loadbalances/show.vm b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/loadbalances/show.vm index 20ce8e9c37a..a91745238c0 100644 --- a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/loadbalances/show.vm +++ b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/loadbalances/show.vm @@ -1,28 +1,30 @@
- - - - - - - - - - - - - -
$i18n.get("service")  * - $service -
$i18n.get("methodName")  * - $loadbalance.method -
$i18n.get("LoadBalanceStrategy"): - $loadbalance.strategy -
+ + + + + + + + + + + + + +
$i18n.get("service")  * + $service +
$i18n.get("methodName")  * + $loadbalance.method +
$i18n.get("LoadBalanceStrategy"): + $loadbalance.strategy +
\ No newline at end of file diff --git a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/noServicePrivilege.vm b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/noServicePrivilege.vm index bb02a39b1f1..4594dbf4b6d 100644 --- a/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/noServicePrivilege.vm +++ b/dubbo-admin/src/main/webapp/WEB-INF/templates/governance/screen/noServicePrivilege.vm @@ -1,14 +1,29 @@