From ddcdb299f0d8d4029c28b9ea94cb5bafb3924cfd Mon Sep 17 00:00:00 2001 From: min Date: Wed, 24 Apr 2019 10:47:00 +0800 Subject: [PATCH 001/115] do not filter thread pool by port (#3919) --- .../java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java index c613f75b70f..90544aaf8a1 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java +++ b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java @@ -173,10 +173,6 @@ private List getThreadPoolMessage() { ExecutorService executor = (ExecutorService) entry.getValue(); if (executor instanceof ThreadPoolExecutor) { ThreadPoolExecutor tp = (ThreadPoolExecutor) executor; - // ignore metrcis service - if (port.equals(this.port + "")) { - continue; - } threadPoolMtricList.add(value2MetricObject("threadPool.active", tp.getActiveCount(), MetricLevel.MAJOR)); threadPoolMtricList.add(value2MetricObject("threadPool.core", tp.getCorePoolSize(), MetricLevel.MAJOR)); From 9b11b7ac89c0d897220bc9b42b3e5e9c3eb708f2 Mon Sep 17 00:00:00 2001 From: zhangfei Date: Wed, 24 Apr 2019 15:08:04 +0800 Subject: [PATCH 002/115] [Dubbo-3914]Fix protostuff serialize java.sql.Timestamp (#3915) * fix: #3727 * style: code tidy up * style: add apache license * fix: #3914 protostuff serialize java.sql.Timestamp --- .../delegate/TimestampDelegate.java | 57 +++++++++++++++++++ .../protostuff/utils/WrapperUtils.java | 4 ++ .../ProtostuffObjectOutputTest.java | 12 ++++ 3 files changed, 73 insertions(+) create mode 100644 dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/delegate/TimestampDelegate.java diff --git a/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/delegate/TimestampDelegate.java b/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/delegate/TimestampDelegate.java new file mode 100644 index 00000000000..083e69c0d93 --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/delegate/TimestampDelegate.java @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.serialize.protostuff.delegate; + +import io.protostuff.Input; +import io.protostuff.Output; +import io.protostuff.Pipe; +import io.protostuff.WireFormat.FieldType; +import io.protostuff.runtime.Delegate; + +import java.io.IOException; +import java.sql.Timestamp; + +/** + * Custom {@link Timestamp} delegate + */ +public class TimestampDelegate implements Delegate { + + @Override + public FieldType getFieldType() { + return FieldType.FIXED64; + } + + @Override + public Timestamp readFrom(Input input) throws IOException { + return new Timestamp(input.readFixed64()); + } + + @Override + public void writeTo(Output output, int number, Timestamp value, boolean repeated) throws IOException { + output.writeFixed64(number, value.getTime(), repeated); + } + + @Override + public void transfer(Pipe pipe, Input input, Output output, int number, boolean repeated) throws IOException { + output.writeFixed64(number, input.readFixed64(), repeated); + } + + @Override + public Class typeClass() { + return Timestamp.class; + } +} diff --git a/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/utils/WrapperUtils.java b/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/utils/WrapperUtils.java index 02ea4f0123d..9ebcc464151 100644 --- a/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/utils/WrapperUtils.java +++ b/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/utils/WrapperUtils.java @@ -22,9 +22,11 @@ import io.protostuff.runtime.DefaultIdStrategy; import io.protostuff.runtime.RuntimeEnv; +import org.apache.dubbo.common.serialize.protostuff.delegate.TimestampDelegate; import java.math.BigDecimal; import java.sql.Time; +import java.sql.Timestamp; import java.util.ArrayList; import java.util.BitSet; import java.util.Calendar; @@ -52,6 +54,7 @@ public class WrapperUtils { static { if (RuntimeEnv.ID_STRATEGY instanceof DefaultIdStrategy) { ((DefaultIdStrategy) RuntimeEnv.ID_STRATEGY).registerDelegate(new TimeDelegate()); + ((DefaultIdStrategy) RuntimeEnv.ID_STRATEGY).registerDelegate(new TimestampDelegate()); } WRAPPER_SET.add(Map.class); @@ -80,6 +83,7 @@ public class WrapperUtils { WRAPPER_SET.add(Date.class); WRAPPER_SET.add(Calendar.class); WRAPPER_SET.add(Time.class); + WRAPPER_SET.add(Timestamp.class); WRAPPER_SET.add(Wrapper.class); diff --git a/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffObjectOutputTest.java b/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffObjectOutputTest.java index bb28386271d..39a621b0b8e 100644 --- a/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffObjectOutputTest.java +++ b/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffObjectOutputTest.java @@ -16,12 +16,14 @@ */ package org.apache.dubbo.common.serialize.protostuff; +import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.nullValue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.sql.Timestamp; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -46,6 +48,16 @@ public void testWriteObjectNull() throws IOException, ClassNotFoundException { assertThat(protostuffObjectInput.readObject(), nullValue()); } + @Test + public void testSerializeTimestamp() throws IOException, ClassNotFoundException { + Timestamp originTime = new Timestamp(System.currentTimeMillis()); + this.protostuffObjectOutput.writeObject(originTime); + this.flushToInput(); + + Timestamp serializedTime = protostuffObjectInput.readObject(Timestamp.class); + assertThat(serializedTime, is(originTime)); + } + private void flushToInput() throws IOException { this.protostuffObjectOutput.flushBuffer(); this.byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); From 9ce0676908adbb5d073727c47b5a32dda153230e Mon Sep 17 00:00:00 2001 From: Dlive Date: Fri, 26 Apr 2019 09:38:54 +0800 Subject: [PATCH 003/115] Add Erlang Implementation (#3898) --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 513da15bd55..440da311822 100644 --- a/README.md +++ b/README.md @@ -223,6 +223,7 @@ Please report security vulnerability to [us](mailto:security@dubbo.incubator.apa * [Python](https://github.com/dubbo/dubbo-client-py) * [PHP](https://github.com/dubbo/dubbo-php-framework) * [Go](https://github.com/dubbo/dubbo-go) +* [Erlang](https://github.com/dubboerl/dubboerl) ## License From d2be44d672a70eb2efd22bebf49f5885c7866da8 Mon Sep 17 00:00:00 2001 From: "ken.lj" Date: Fri, 26 Apr 2019 10:54:26 +0800 Subject: [PATCH 004/115] [Dubbo-3875] dubbo TagRouter does not work with dubbo:parameter. (#3883) * avoid 'dubbo.tag' from provider side being override on consumer side * not necessary to keep 'default.' prefix for configs come from ConsumerConfig and ProviderConfig * fix ut caused by removing of 'default.' prefix --- .../rpc/cluster/support/ClusterUtils.java | 30 ++++++++----------- .../dubbo/config/AbstractInterfaceConfig.java | 11 +++++++ .../dubbo/config/AbstractServiceConfig.java | 14 ++------- .../apache/dubbo/config/ReferenceConfig.java | 22 +++++--------- .../apache/dubbo/config/ServiceConfig.java | 4 ++- .../dubbo/config/annotation/Reference.java | 5 ++++ .../builders/AbstractInterfaceBuilder.java | 10 +++++++ .../builders/AbstractServiceBuilder.java | 11 +------ .../dubbo/config/ServiceConfigTest.java | 2 +- .../config/url/InvokerSideConfigUrlTest.java | 13 ++------ .../apache/dubbo/config/url/UrlTestBase.java | 8 +---- .../main/resources/META-INF/compat/dubbo.xsd | 12 ++++---- .../src/main/resources/META-INF/dubbo.xsd | 12 ++++---- 13 files changed, 69 insertions(+), 85 deletions(-) diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java index 37b3e719283..e6ed749f0cb 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java @@ -95,24 +95,11 @@ public static URL mergeUrl(URL remoteUrl, Map localMap) { } if (remoteMap != null && remoteMap.size() > 0) { // Use version passed from provider side - String dubbo = remoteMap.get(Constants.DUBBO_VERSION_KEY); - if (dubbo != null && dubbo.length() > 0) { - map.put(Constants.DUBBO_VERSION_KEY, dubbo); - } - String version = remoteMap.get(Constants.VERSION_KEY); - if (version != null && version.length() > 0) { - map.put(Constants.VERSION_KEY, version); - } - String methods = remoteMap.get(Constants.METHODS_KEY); - if (methods != null && methods.length() > 0) { - map.put(Constants.METHODS_KEY, methods); - } - // Reserve timestamp of provider url. - String remoteTimestamp = remoteMap.get(Constants.TIMESTAMP_KEY); - if (remoteTimestamp != null && remoteTimestamp.length() > 0) { - map.put(Constants.REMOTE_TIMESTAMP_KEY, remoteMap.get(Constants.TIMESTAMP_KEY)); - } - + reserveRemoteValue(Constants.DUBBO_VERSION_KEY, map, remoteMap); + reserveRemoteValue(Constants.VERSION_KEY, map, remoteMap); + reserveRemoteValue(Constants.METHODS_KEY, map, remoteMap); + reserveRemoteValue(Constants.TIMESTAMP_KEY, map, remoteMap); + reserveRemoteValue(Constants.TAG_KEY, map, remoteMap); // TODO, for compatibility consideration, we cannot simply change the value behind APPLICATION_KEY from Consumer to Provider. So just add an extra key here. // Reserve application name from provider. map.put(Constants.REMOTE_APPLICATION_KEY, remoteMap.get(Constants.APPLICATION_KEY)); @@ -135,4 +122,11 @@ public static URL mergeUrl(URL remoteUrl, Map localMap) { return remoteUrl.clearParameters().addParameters(map); } + private static void reserveRemoteValue(String key, Map map, Map remoteMap) { + String remoteValue = remoteMap.get(key); + if (StringUtils.isNotEmpty(remoteValue)) { + map.put(key, remoteValue); + } + } + } \ No newline at end of file diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java index 57cb6c34d0e..59cdd5cae9b 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java @@ -155,6 +155,8 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { // the scope for referring/exporting a service, if it's local, it means searching in current JVM only. private String scope; + protected String tag; + /** * Check whether the registry config is exists, and then conversion it to {@link RegistryConfig} */ @@ -837,4 +839,13 @@ public MetricsConfig getMetrics() { public void setMetrics(MetricsConfig metrics) { this.metrics = metrics; } + + @Parameter(key = Constants.TAG_KEY, useKeyAsProperty = false) + public String getTag() { + return tag; + } + + public void setTag(String tag) { + this.tag = tag; + } } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java index 0fb29091696..35607fad2f7 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java @@ -17,8 +17,8 @@ package org.apache.dubbo.config; import org.apache.dubbo.common.Constants; -import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.common.utils.CollectionUtils; +import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.config.support.Parameter; import org.apache.dubbo.rpc.ExporterListener; @@ -92,8 +92,7 @@ public abstract class AbstractServiceConfig extends AbstractInterfaceConfig { */ protected List protocols; protected String protocolIds; - // provider tag - protected String tag; + // max allowed execute times private Integer executes; @@ -288,13 +287,4 @@ public String getSerialization() { public void setSerialization(String serialization) { this.serialization = serialization; } - - @Parameter(key = Constants.TAG_KEY, useKeyAsProperty = false) - public String getTag() { - return tag; - } - - public void setTag(String tag) { - this.tag = tag; - } } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java index 87ccdf3330e..18008b989cb 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java @@ -280,7 +280,9 @@ private void init() { appendParameters(map, metrics); appendParameters(map, application); appendParameters(map, module); - appendParameters(map, consumer, Constants.DEFAULT_KEY); + // remove 'default.' prefix for configs from ConsumerConfig + // appendParameters(map, consumer, Constants.DEFAULT_KEY); + appendParameters(map, consumer); appendParameters(map, this); Map attributes = null; if (CollectionUtils.isNotEmpty(methods)) { @@ -457,22 +459,14 @@ protected boolean shouldInit() { } private void checkDefault() { - createConsumerIfAbsent(); - } - - private void createConsumerIfAbsent() { if (consumer != null) { return; } - setConsumer( - ConfigManager.getInstance() - .getDefaultConsumer() - .orElseGet(() -> { - ConsumerConfig consumerConfig = new ConsumerConfig(); - consumerConfig.refresh(); - return consumerConfig; - }) - ); + setConsumer(ConfigManager.getInstance().getDefaultConsumer().orElseGet(() -> { + ConsumerConfig consumerConfig = new ConsumerConfig(); + consumerConfig.refresh(); + return consumerConfig; + })); } private void completeCompoundConfigs() { diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index 1f14dd26066..9e24ac99f27 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -431,7 +431,9 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r appendParameters(map, metrics); appendParameters(map, application); appendParameters(map, module); - appendParameters(map, provider, Constants.DEFAULT_KEY); + // remove 'default.' prefix for configs from ProviderConfig + // appendParameters(map, provider, Constants.DEFAULT_KEY); + appendParameters(map, provider); appendParameters(map, protocolConfig); appendParameters(map, this); if (CollectionUtils.isNotEmpty(methods)) { diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java index bdbbd356cb4..c4851bd1031 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java @@ -257,6 +257,11 @@ */ String protocol() default ""; + /** + * Service tag name + */ + String tag() default ""; + /** * methods support * @return diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/AbstractInterfaceBuilder.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/AbstractInterfaceBuilder.java index e8272d0f8c3..fbc6912ee6e 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/AbstractInterfaceBuilder.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/AbstractInterfaceBuilder.java @@ -121,6 +121,8 @@ public abstract class AbstractInterfaceBuilder protocols; protected String protocolIds; - // provider tag - protected String tag; + // max allowed execute times private Integer executes; @@ -197,11 +196,6 @@ public B protocolIds(String protocolIds) { return getThis(); } - public B tag(String tag) { - this.tag = tag; - return getThis(); - } - public B executes(Integer executes) { this.executes = executes; return getThis(); @@ -262,9 +256,6 @@ public void build(T instance) { if (!StringUtils.isEmpty(protocolIds)) { instance.setProtocolIds(protocolIds); } - if (tag != null) { - instance.setTag(tag); - } if (executes != null) { instance.setExecutes(executes); } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java index 296538cbd94..2dff18b5af5 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java @@ -134,7 +134,7 @@ public void testExport() throws Exception { assertThat(url.getParameters(), hasEntry(Constants.APPLICATION_KEY, "app")); assertThat(url.getParameters(), hasKey(Constants.BIND_IP_KEY)); assertThat(url.getParameters(), hasKey(Constants.BIND_PORT_KEY)); - assertThat(url.getParameters(), hasEntry(Constants.DEFAULT_KEY + "." + Constants.EXPORT_KEY, "true")); + assertThat(url.getParameters(), hasEntry(Constants.EXPORT_KEY, "true")); assertThat(url.getParameters(), hasEntry("echo.0.callback", "false")); assertThat(url.getParameters(), hasEntry(Constants.GENERIC_KEY, "false")); assertThat(url.getParameters(), hasEntry(Constants.INTERFACE_KEY, DemoService.class.getName())); diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/InvokerSideConfigUrlTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/InvokerSideConfigUrlTest.java index da0f6071776..1155ec4a1f8 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/InvokerSideConfigUrlTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/InvokerSideConfigUrlTest.java @@ -28,8 +28,8 @@ import org.apache.dubbo.config.mock.MockRegistry; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -112,18 +112,11 @@ public class InvokerSideConfigUrlTest extends UrlTestBase { //{"", "", "", "", "", "", "", "", "", ""}, }; - private Object consumerConfTable[][] = { - {"timeout", "default.timeout", "int", 5000, 8000, "", "", "", "", ""}, - {"retries", "default.retries", "int", 2, 5, "", "", "", "", ""}, - {"loadbalance", "default.loadbalance", "string", "random", "leastactive", "", "", "", "", ""}, - {"async", "default.async", "boolean", false, true, "", "", "", "", ""}, - {"connections", "default.connections", "int", 100, 5, "", "", "", "", ""}, + private Object consumerConfTable[][] = {{"timeout", "timeout", "int", 5000, 8000, "", "", "", "", ""}, {"retries", "retries", "int", 2, 5, "", "", "", "", ""}, {"loadbalance", "loadbalance", "string", "random", "leastactive", "", "", "", "", ""}, {"async", "async", "boolean", false, true, "", "", "", "", ""}, {"connections", "connections", "int", 100, 5, "", "", "", "", ""}, // {"generic", "generic", "boolean", false, false, "", "", "", "", ""}, {"check", "check", "boolean", true, false, "", "", "", "", ""}, {"proxy", "proxy", "string", "javassist", "jdk", "javassist", "", "", "", ""}, - {"owner", "owner", "string", "", "haomin", "", "", "", "", ""}, - {"actives", "default.actives", "int", 0, 5, "", "", "", "", ""}, - {"cluster", "default.cluster", "string", "failover", "forking", "", "", "", "", ""}, + {"owner", "owner", "string", "", "haomin", "", "", "", "", ""}, {"actives", "actives", "int", 0, 5, "", "", "", "", ""}, {"cluster", "cluster", "string", "failover", "forking", "", "", "", "", ""}, {"filter", "", "string", "", "", "", "", "", "", ""}, {"listener", "", "string", "", "", "", "", "", "", ""}, // {"", "", "", "", "", "", "", "", "", ""}, diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/UrlTestBase.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/UrlTestBase.java index a752842cf76..950b89efa6f 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/UrlTestBase.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/UrlTestBase.java @@ -81,13 +81,7 @@ public class UrlTestBase { // {"subscribe", "subscribe", "boolean", true, false, "", "", "", "", ""}, {"dynamic", "dynamic", "boolean", true, false, "", "", "", "", ""}, }; - protected Object provConfTable[][] = { - {"cluster", "default.cluster", "string", "string", "failover", "failfast", "failsafe", "", "", ""}, - {"async", "default.async", "boolean", false, true, "", "", "", "", ""}, - {"loadbalance", "default.loadbalance", "string", "random", "leastactive", "", "", "", "", ""}, - {"connections", "default.connections", "int", 0, 60, "", "", "", "", ""}, - {"retries", "default.retries", "int", 2, 60, "", "", "", "", ""}, - {"timeout", "default.timeout", "int", 5000, 60, "", "", "", "", ""}, + protected Object provConfTable[][] = {{"cluster", "cluster", "string", "string", "failover", "failfast", "failsafe", "", "", ""}, {"async", "async", "boolean", false, true, "", "", "", "", ""}, {"loadbalance", "loadbalance", "string", "random", "leastactive", "", "", "", "", ""}, {"connections", "connections", "int", 0, 60, "", "", "", "", ""}, {"retries", "retries", "int", 2, 60, "", "", "", "", ""}, {"timeout", "timeout", "int", 5000, 60, "", "", "", "", ""}, //change by fengting listener 没有缺省值 //{"listener", "exporter.listener", "string", "", "", "", "", "", "", ""}, //{"filter", "service.filter", "string", "", "", "", "", "", "", ""}, diff --git a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/compat/dubbo.xsd b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/compat/dubbo.xsd index 01996aefbf8..9e179ef287a 100644 --- a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/compat/dubbo.xsd +++ b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/compat/dubbo.xsd @@ -172,6 +172,12 @@ + + + + + + @@ -317,12 +323,6 @@ - - - - - - diff --git a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd index 33ff3ad5b2b..e517f0cb4f3 100644 --- a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd +++ b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd @@ -172,6 +172,12 @@ + + + + + + @@ -317,12 +323,6 @@ - - - - - - From 083605ad06dbccc7d833ff7dc84a62b736df44b5 Mon Sep 17 00:00:00 2001 From: hongye Date: Fri, 26 Apr 2019 11:00:55 +0800 Subject: [PATCH 005/115] add socks5 proxy support (#3624) --- .../remoting/transport/netty4/NettyClient.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java index 7ba4a63248f..322d658b856 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java @@ -21,6 +21,7 @@ import org.apache.dubbo.common.Version; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.UrlUtils; import org.apache.dubbo.remoting.ChannelHandler; @@ -35,11 +36,14 @@ import io.netty.channel.ChannelOption; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; +import io.netty.handler.proxy.Socks5ProxyHandler; import io.netty.handler.timeout.IdleStateHandler; import io.netty.util.concurrent.DefaultThreadFactory; import static java.util.concurrent.TimeUnit.MILLISECONDS; +import java.net.InetSocketAddress; + /** * NettyClient. */ @@ -48,6 +52,12 @@ public class NettyClient extends AbstractClient { private static final Logger logger = LoggerFactory.getLogger(NettyClient.class); private static final NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup(Constants.DEFAULT_IO_THREADS, new DefaultThreadFactory("NettyClientWorker", true)); + + private static final String SOCKS_PROXY_HOST = "socksProxyHost"; + + private static final String SOCKS_PROXY_PORT = "socksProxyPort"; + + private static final String DEFAULT_SOCKS_PROXY_PORT = "1080"; private Bootstrap bootstrap; @@ -85,6 +95,12 @@ protected void initChannel(Channel ch) throws Exception { .addLast("encoder", adapter.getEncoder()) .addLast("client-idle-handler", new IdleStateHandler(heartbeatInterval, 0, 0, MILLISECONDS)) .addLast("handler", nettyClientHandler); + String socksProxyHost = ConfigUtils.getProperty(SOCKS_PROXY_HOST); + if(socksProxyHost != null) { + int socksProxyPort = Integer.parseInt(ConfigUtils.getProperty(SOCKS_PROXY_PORT, DEFAULT_SOCKS_PROXY_PORT)); + Socks5ProxyHandler socks5ProxyHandler = new Socks5ProxyHandler(new InetSocketAddress(socksProxyHost, socksProxyPort)); + ch.pipeline().addFirst(socks5ProxyHandler); + } } }); } From 793bf8244411c33b675e08f1499122bc82654d44 Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Fri, 26 Apr 2019 14:01:23 +0800 Subject: [PATCH 006/115] Defensive check to solve issue #3923 (#3931) --- .../org/apache/dubbo/registry/consul/ConsulRegistry.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java b/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java index 72f7ff43b86..f9a30f3fee1 100644 --- a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java +++ b/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java @@ -37,6 +37,7 @@ import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; @@ -200,7 +201,11 @@ private boolean isProviderSide(URL url) { private List convert(List services) { return services.stream() - .map(s -> s.getService().getMeta().get(URL_META_KEY)) + .map(HealthService::getService) + .filter(Objects::nonNull) + .map(HealthService.Service::getMeta) + .filter(m -> m != null && m.containsKey(URL_META_KEY)) + .map(m -> m.get(URL_META_KEY)) .map(URL::valueOf) .collect(Collectors.toList()); } From 7d83fde30e3864f7115c2650f77ee2e28bcdb051 Mon Sep 17 00:00:00 2001 From: tomatofrommars Date: Fri, 26 Apr 2019 14:11:34 +0800 Subject: [PATCH 007/115] [Dubbo-3826] Auth support for redis metadata report (#3888) --- .../store/redis/RedisMetadataReport.java | 4 +- .../store/redis/RedisMetadataReportTest.java | 37 +++++++++++++++++-- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java b/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java index 4f001484422..42d88802e5b 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java +++ b/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java @@ -16,6 +16,7 @@ */ package org.apache.dubbo.metadata.store.redis; +import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -37,7 +38,8 @@ public class RedisMetadataReport extends AbstractMetadataReport { public RedisMetadataReport(URL url) { super(url); - pool = new JedisPool(new JedisPoolConfig(), url.getHost(), url.getPort()); + int timeout = url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); + pool = new JedisPool(new JedisPoolConfig(), url.getHost(), url.getPort(), timeout, url.getPassword()); } @Override diff --git a/dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java b/dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java index d7cbe346aee..4984bde5b19 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java +++ b/dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java @@ -28,7 +28,10 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; import redis.clients.jedis.Jedis; +import redis.clients.jedis.exceptions.JedisConnectionException; +import redis.clients.jedis.exceptions.JedisDataException; import redis.embedded.RedisServer; import java.io.IOException; @@ -45,13 +48,22 @@ public class RedisMetadataReportTest { RedisMetadataReport redisMetadataReport; RedisMetadataReport syncRedisMetadataReport; RedisServer redisServer; + URL registryUrl; @BeforeEach - public void constructor() throws IOException { + public void constructor(TestInfo testInfo) throws IOException { int redisPort = NetUtils.getAvailablePort(); - this.redisServer = new RedisServer(redisPort); + String methodName = testInfo.getTestMethod().get().getName(); + if ("testAuthRedisMetadata".equals(methodName) || ("testWrongAuthRedisMetadata".equals(methodName))) { + String password = "チェリー"; + redisServer = RedisServer.builder().port(redisPort).setting("requirepass " + password).build(); + registryUrl = URL.valueOf("redis://username:" + password + "@localhost:" + redisPort); + } else { + redisServer = RedisServer.builder().port(redisPort).build(); + registryUrl = URL.valueOf("redis://localhost:" + redisPort); + } + this.redisServer.start(); - URL registryUrl = URL.valueOf("redis://localhost:" + redisPort); redisMetadataReport = (RedisMetadataReport) new RedisMetadataReportFactory().createMetadataReport(registryUrl); URL asyncRegistryUrl = URL.valueOf("redis://localhost:" + redisPort + "?" + SYNC_REPORT_KEY + "=true"); syncRedisMetadataReport = (RedisMetadataReport) new RedisMetadataReportFactory().createMetadataReport(registryUrl); @@ -173,4 +185,23 @@ private MetadataIdentifier storeConsumer(RedisMetadataReport redisMetadataReport return consumerMetadataIdentifier; } + @Test + public void testAuthRedisMetadata() throws ClassNotFoundException { + testStoreProvider(redisMetadataReport, "1.0.0.redis.md.p1", 3000); + } + + @Test + public void testWrongAuthRedisMetadata() throws ClassNotFoundException { + registryUrl = registryUrl.setPassword("123456"); + redisMetadataReport = (RedisMetadataReport) new RedisMetadataReportFactory().createMetadataReport(registryUrl); + try { + testStoreProvider(redisMetadataReport, "1.0.0.redis.md.p1", 3000); + } catch (RpcException e) { + if (e.getCause() instanceof JedisConnectionException && e.getCause().getCause() instanceof JedisDataException) { + Assertions.assertEquals("ERR invalid password", e.getCause().getCause().getMessage()); + } else { + Assertions.fail("no invalid password exception!"); + } + } + } } From 2d0c07d84dac9c6750d307d3a4ec47c4c88c1fef Mon Sep 17 00:00:00 2001 From: myPrecious Date: Fri, 26 Apr 2019 14:16:50 +0800 Subject: [PATCH 008/115] etcd3 integration test api (#3887) * etcd config center integrate test * clean code --- .../dubbo-configcenter-etcd/pom.xml | 10 +++ .../etcd/EtcdDynamicConfigurationTest.java | 76 +++++++++++-------- dubbo-dependencies-bom/pom.xml | 13 ++++ 3 files changed, 67 insertions(+), 32 deletions(-) diff --git a/dubbo-configcenter/dubbo-configcenter-etcd/pom.xml b/dubbo-configcenter/dubbo-configcenter-etcd/pom.xml index 2eb1e358d4c..66d2dfa0f42 100644 --- a/dubbo-configcenter/dubbo-configcenter-etcd/pom.xml +++ b/dubbo-configcenter/dubbo-configcenter-etcd/pom.xml @@ -37,6 +37,16 @@ dubbo-configcenter-api ${project.parent.version} + + io.etcd + jetcd-launcher + test + + + org.testcontainers + testcontainers + test + org.apache.dubbo dubbo-remoting-etcd3 diff --git a/dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java index 87143fdcacc..4e305eaf01e 100644 --- a/dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java +++ b/dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java @@ -19,17 +19,20 @@ import io.etcd.jetcd.ByteSequence; import io.etcd.jetcd.Client; +import io.etcd.jetcd.launcher.EtcdCluster; +import io.etcd.jetcd.launcher.EtcdClusterFactory; import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.configcenter.ConfigChangeEvent; import org.apache.dubbo.configcenter.ConfigurationListener; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import java.net.URI; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -38,23 +41,23 @@ /** * Unit test for etcd config center support - * TODO Integrate with https://github.com/etcd-io/jetcd#launcher or using mock data. + * Integrate with https://github.com/etcd-io/jetcd#launcher */ -@Disabled public class EtcdDynamicConfigurationTest { - private static final String ENDPOINT = "http://127.0.0.1:2379"; - private static EtcdDynamicConfiguration config; - private static Client etcdClient; + public EtcdCluster etcdCluster = EtcdClusterFactory.buildCluster(getClass().getSimpleName(), 3, false, false); + + private static Client client; @Test public void testGetConfig() { + put("/dubbo/config/org.apache.dubbo.etcd.testService/configurators", "hello"); put("/dubbo/config/test/dubbo.properties", "aaa=bbb"); - Assertions.assertEquals("hello", config.getConfig("org.apache.dubbo.etcd.testService.configurators")); - Assertions.assertEquals("aaa=bbb", config.getConfig("dubbo.properties", "test")); + Assert.assertEquals("hello", config.getConfig("org.apache.dubbo.etcd.testService.configurators")); + Assert.assertEquals("aaa=bbb", config.getConfig("dubbo.properties", "test")); } @Test @@ -77,16 +80,16 @@ public void testAddListener() throws Exception { Thread.sleep(1000); - Assertions.assertTrue(latch.await(5, TimeUnit.SECONDS)); - Assertions.assertEquals(1, listener1.getCount("/dubbo/config/AService/configurators")); - Assertions.assertEquals(1, listener2.getCount("/dubbo/config/AService/configurators")); - Assertions.assertEquals(1, listener3.getCount("/dubbo/config/testapp/tagrouters")); - Assertions.assertEquals(1, listener4.getCount("/dubbo/config/testapp/tagrouters")); + Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + Assert.assertEquals(1, listener1.getCount("/dubbo/config/AService/configurators")); + Assert.assertEquals(1, listener2.getCount("/dubbo/config/AService/configurators")); + Assert.assertEquals(1, listener3.getCount("/dubbo/config/testapp/tagrouters")); + Assert.assertEquals(1, listener4.getCount("/dubbo/config/testapp/tagrouters")); - Assertions.assertEquals("new value1", listener1.getValue()); - Assertions.assertEquals("new value1", listener2.getValue()); - Assertions.assertEquals("new value2", listener3.getValue()); - Assertions.assertEquals("new value2", listener4.getValue()); + Assert.assertEquals("new value1", listener1.getValue()); + Assert.assertEquals("new value1", listener2.getValue()); + Assert.assertEquals("new value2", listener3.getValue()); + Assert.assertEquals("new value2", listener4.getValue()); } private class TestListener implements ConfigurationListener { @@ -115,27 +118,36 @@ public String getValue() { } } - static void put(String key, String value) { + private void put(String key, String value) { try { - etcdClient.getKVClient() - .put(ByteSequence.from(key, UTF_8), ByteSequence.from(value, UTF_8)) - .get(); + + client.getKVClient().put(ByteSequence.from(key, UTF_8), ByteSequence.from(value, UTF_8)).get(); } catch (Exception e) { System.out.println("Error put value to etcd."); } } - @BeforeAll - static void setUp() { - etcdClient = Client.builder().endpoints(ENDPOINT).build(); + @Before + public void setUp() { + + etcdCluster.start(); + + client = Client.builder().endpoints(etcdCluster.getClientEndpoints()).build(); + + List clientEndPoints = etcdCluster.getClientEndpoints(); + + String ipAddress = clientEndPoints.get(0).getHost() + ":" + clientEndPoints.get(0).getPort(); + String urlForDubbo = "etcd3://" + ipAddress + "/org.apache.dubbo.etcd.testService"; + // timeout in 15 seconds. - URL url = URL.valueOf("etcd3://127.0.0.1:2379/org.apache.dubbo.etcd.testService") + URL url = URL.valueOf(urlForDubbo) .addParameter(Constants.SESSION_TIMEOUT_KEY, 15000); config = new EtcdDynamicConfiguration(url); } - @AfterAll - static void tearDown() { - etcdClient.close(); + @After + public void tearDown() { + etcdCluster.close(); } + } diff --git a/dubbo-dependencies-bom/pom.xml b/dubbo-dependencies-bom/pom.xml index 0329e73ba60..1ba31db4c43 100644 --- a/dubbo-dependencies-bom/pom.xml +++ b/dubbo-dependencies-bom/pom.xml @@ -137,6 +137,8 @@ 2.2.7 1.2.0 + 1.11.2 + 0.3.0 3.2.5 1.5.19 4.3.16.RELEASE @@ -552,6 +554,17 @@ portlet-api ${portlet_version} + + + io.etcd + jetcd-launcher + ${etcd_launcher_version} + + + org.testcontainers + testcontainers + ${test_container_version} + From b8d9f76af68746788df39bbbbf6cb18f10c89a7c Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Fri, 26 Apr 2019 15:54:29 +0800 Subject: [PATCH 009/115] Revert "Merge pull request #3520, fix #538 polish the process of deciding the ip to bind." (#3935) This reverts commit ade0cd70 --- .../apache/dubbo/common/utils/NetUtils.java | 25 +++----- .../dubbo/common/utils/NetUtilsTest.java | 2 + .../dubbo/config/AbstractInterfaceConfig.java | 3 + .../apache/dubbo/config/ReferenceConfig.java | 5 +- .../apache/dubbo/config/ServiceConfig.java | 61 +++++++++++-------- 5 files changed, 54 insertions(+), 42 deletions(-) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java index 187e0e20c5d..f03d91a0d5a 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java @@ -106,7 +106,6 @@ public static boolean isAnyHost(String host) { return Constants.ANYHOST_VALUE.equals(host); } - // FIXME: should remove this method completely public static boolean isInvalidLocalHost(String host) { return host == null || host.length() == 0 @@ -115,7 +114,6 @@ public static boolean isInvalidLocalHost(String host) { || (LOCAL_IP_PATTERN.matcher(host).matches()); } - // FIXME: should remove this method completely public static boolean isValidLocalHost(String host) { return !isInvalidLocalHost(host); } @@ -126,6 +124,9 @@ public static InetSocketAddress getLocalSocketAddress(String host, int port) { } static boolean isValidV4Address(InetAddress address) { + if (address == null || address.isLoopbackAddress()) { + return false; + } String name = address.getHostAddress(); return (name != null && IP_PATTERN.matcher(name).matches() @@ -152,10 +153,6 @@ static boolean isValidV6Address(Inet6Address address) { return false; } - static boolean isValidPublicAddress(InetAddress address) { - return !address.isSiteLocalAddress() && !address.isLoopbackAddress(); - } - /** * normalize the ipv6 Address, convert scope name to scope id. * e.g. @@ -235,17 +232,15 @@ public static InetAddress getLocalAddress() { } private static Optional toValidAddress(InetAddress address) { - if (isValidPublicAddress(address)) { - if (address instanceof Inet6Address) { - Inet6Address v6Address = (Inet6Address) address; - if (isValidV6Address(v6Address)) { - return Optional.ofNullable(normalizeV6Address(v6Address)); - } - } - if (isValidV4Address(address)) { - return Optional.of(address); + if (address instanceof Inet6Address) { + Inet6Address v6Address = (Inet6Address) address; + if (isValidV6Address(v6Address)) { + return Optional.ofNullable(normalizeV6Address(v6Address)); } } + if (isValidV4Address(address)) { + return Optional.of(address); + } return Optional.empty(); } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/NetUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/NetUtilsTest.java index 2fe0a636815..797f2b42b15 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/NetUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/NetUtilsTest.java @@ -106,6 +106,7 @@ public void testGetLocalSocketAddress() throws Exception { @Test public void testIsValidAddress() throws Exception { + assertFalse(NetUtils.isValidV4Address((InetAddress) null)); InetAddress address = mock(InetAddress.class); when(address.isLoopbackAddress()).thenReturn(true); assertFalse(NetUtils.isValidV4Address(address)); @@ -132,6 +133,7 @@ public void testGetLocalHost() throws Exception { public void testGetLocalAddress() throws Exception { InetAddress address = NetUtils.getLocalAddress(); assertNotNull(address); + assertTrue(NetUtils.isValidLocalHost(address.getHostAddress())); } @Test diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java index 59cdd5cae9b..ca21e4b3a74 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java @@ -343,6 +343,9 @@ protected URL loadMonitor(URL registryURL) { String hostToRegistry = ConfigUtils.getSystemProperty(Constants.DUBBO_IP_TO_REGISTRY); if (StringUtils.isEmpty(hostToRegistry)) { hostToRegistry = NetUtils.getLocalHost(); + } else if (NetUtils.isInvalidLocalHost(hostToRegistry)) { + throw new IllegalArgumentException("Specified invalid registry ip from property:" + + Constants.DUBBO_IP_TO_REGISTRY + ", value:" + hostToRegistry); } map.put(Constants.REGISTER_IP_KEY, hostToRegistry); appendParameters(map, monitor); diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java index 18008b989cb..fe0f43a1865 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java @@ -55,6 +55,7 @@ import java.util.Map; import java.util.Properties; +import static org.apache.dubbo.common.utils.NetUtils.isInvalidLocalHost; /** * ReferenceConfig @@ -107,7 +108,7 @@ public class ReferenceConfig extends AbstractReferenceConfig { * The interface class of the reference service */ private Class interfaceClass; - + /** * client type */ @@ -303,6 +304,8 @@ private void init() { String hostToRegistry = ConfigUtils.getSystemProperty(Constants.DUBBO_IP_TO_REGISTRY); if (StringUtils.isEmpty(hostToRegistry)) { hostToRegistry = NetUtils.getLocalHost(); + } else if (isInvalidLocalHost(hostToRegistry)) { + throw new IllegalArgumentException("Specified invalid registry ip from property:" + Constants.DUBBO_IP_TO_REGISTRY + ", value:" + hostToRegistry); } map.put(Constants.REGISTER_IP_KEY, hostToRegistry); diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index 9e24ac99f27..602b5d4f467 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -44,9 +44,11 @@ import org.apache.dubbo.rpc.support.ProtocolUtils; import java.lang.reflect.Method; +import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; +import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -62,6 +64,7 @@ import static org.apache.dubbo.common.Constants.LOCALHOST_VALUE; import static org.apache.dubbo.common.utils.NetUtils.getAvailablePort; import static org.apache.dubbo.common.utils.NetUtils.getLocalHost; +import static org.apache.dubbo.common.utils.NetUtils.isInvalidLocalHost; import static org.apache.dubbo.common.utils.NetUtils.isInvalidPort; /** @@ -624,6 +627,9 @@ private String findConfigedHosts(ProtocolConfig protocolConfig, List regist boolean anyhost = false; String hostToBind = getValueFromConfig(protocolConfig, Constants.DUBBO_IP_TO_BIND); + if (hostToBind != null && hostToBind.length() > 0 && isInvalidLocalHost(hostToBind)) { + throw new IllegalArgumentException("Specified invalid bind ip from property:" + Constants.DUBBO_IP_TO_BIND + ", value:" + hostToBind); + } // if bind ip is not found in environment, keep looking up if (StringUtils.isEmpty(hostToBind)) { @@ -631,13 +637,33 @@ private String findConfigedHosts(ProtocolConfig protocolConfig, List regist if (provider != null && StringUtils.isEmpty(hostToBind)) { hostToBind = provider.getHost(); } - - if (StringUtils.isEmpty(hostToBind)) { + if (isInvalidLocalHost(hostToBind)) { anyhost = true; - hostToBind = getLocalHost(); - - if (StringUtils.isEmpty(hostToBind)) { - hostToBind = findHostToBindByConnectRegistries(registryURLs); + try { + hostToBind = InetAddress.getLocalHost().getHostAddress(); + } catch (UnknownHostException e) { + logger.warn(e.getMessage(), e); + } + if (isInvalidLocalHost(hostToBind)) { + if (CollectionUtils.isNotEmpty(registryURLs)) { + for (URL registryURL : registryURLs) { + if (Constants.MULTICAST.equalsIgnoreCase(registryURL.getParameter("registry"))) { + // skip multicast registry since we cannot connect to it via Socket + continue; + } + try (Socket socket = new Socket()) { + SocketAddress addr = new InetSocketAddress(registryURL.getHost(), registryURL.getPort()); + socket.connect(addr, 1000); + hostToBind = socket.getLocalAddress().getHostAddress(); + break; + } catch (Exception e) { + logger.warn(e.getMessage(), e); + } + } + } + if (isInvalidLocalHost(hostToBind)) { + hostToBind = getLocalHost(); + } } } } @@ -646,7 +672,9 @@ private String findConfigedHosts(ProtocolConfig protocolConfig, List regist // registry ip is not used for bind ip by default String hostToRegistry = getValueFromConfig(protocolConfig, Constants.DUBBO_IP_TO_REGISTRY); - if (StringUtils.isEmpty(hostToRegistry)) { + if (hostToRegistry != null && hostToRegistry.length() > 0 && isInvalidLocalHost(hostToRegistry)) { + throw new IllegalArgumentException("Specified invalid registry ip from property:" + Constants.DUBBO_IP_TO_REGISTRY + ", value:" + hostToRegistry); + } else if (StringUtils.isEmpty(hostToRegistry)) { // bind ip is used as registry ip by default hostToRegistry = hostToBind; } @@ -656,25 +684,6 @@ private String findConfigedHosts(ProtocolConfig protocolConfig, List regist return hostToRegistry; } - private String findHostToBindByConnectRegistries(List registryURLs) { - if (CollectionUtils.isNotEmpty(registryURLs)) { - for (URL registryURL : registryURLs) { - if (Constants.MULTICAST.equalsIgnoreCase(registryURL.getParameter(Constants.REGISTRY_KEY))) { - // skip multicast registry since we cannot connect to it via Socket - continue; - } - try (Socket socket = new Socket()) { - SocketAddress addr = new InetSocketAddress(registryURL.getHost(), registryURL.getPort()); - socket.connect(addr, 1000); - return socket.getLocalAddress().getHostAddress(); - } catch (Exception e) { - logger.warn(e.getMessage(), e); - } - } - } - return null; - } - /** * Register port and bind port for the provider, can be configured separately * Configuration priority: environment variable -> java system properties -> port property in protocol config file From efa83324ddd86080422eeb91b907b121dd11a347 Mon Sep 17 00:00:00 2001 From: myPrecious Date: Fri, 26 Apr 2019 17:50:11 +0800 Subject: [PATCH 010/115] fix typo in dubbo (#3937) --- .../loadbalance/LeastActiveLoadBalance.java | 4 +- .../loadbalance/LeastActiveBalanceTest.java | 2 +- .../support/FailfastClusterInvokerTest.java | 4 +- .../extension/AdaptiveClassCodeGenerator.java | 4 +- .../beanutil/JavaBeanSerializeUtilTest.java | 18 +++---- .../dubbo/config/AbstractConfigTest.java | 2 +- .../support/AbstractRegistryTest.java | 52 +++++++++---------- .../remoting/transport/AbstractClient.java | 2 +- .../etcd/support/AbstractEtcdClient.java | 6 +-- .../dubbo/rpc/protocol/AbstractProtocol.java | 2 +- 10 files changed, 48 insertions(+), 48 deletions(-) diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/LeastActiveLoadBalance.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/LeastActiveLoadBalance.java index 784195877be..0706053b52f 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/LeastActiveLoadBalance.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/LeastActiveLoadBalance.java @@ -71,7 +71,7 @@ protected Invoker doSelect(List> invokers, URL url, Invocation leastActive = active; // Reset the number of least active invokers leastCount = 1; - // Put the first least active invoker first in leastIndexs + // Put the first least active invoker first in leastIndexes leastIndexes[0] = i; // Reset totalWeight totalWeight = afterWarmup; @@ -81,7 +81,7 @@ protected Invoker doSelect(List> invokers, URL url, Invocation sameWeight = true; // If current invoker's active value equals with leaseActive, then accumulating. } else if (active == leastActive) { - // Record the index of the least active invoker in leastIndexs order + // Record the index of the least active invoker in leastIndexes order leastIndexes[leastCount++] = i; // Accumulate the total weight of the least active invoker totalWeight += afterWarmup; diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LeastActiveBalanceTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LeastActiveBalanceTest.java index 00b5c14db1b..89dc66be01c 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LeastActiveBalanceTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LeastActiveBalanceTest.java @@ -35,7 +35,7 @@ public void testLeastActiveLoadBalance_select() { Long count = entry.getValue().get(); // System.out.println(count); Assertions.assertTrue( - Math.abs(count - runs / (0f + invokers.size())) < runs / (0f + invokers.size()), "abs diff shoud < avg"); + Math.abs(count - runs / (0f + invokers.size())) < runs / (0f + invokers.size()), "abs diff should < avg"); } } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailfastClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailfastClusterInvokerTest.java index d8dd653f34e..9b6d2e88b73 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailfastClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailfastClusterInvokerTest.java @@ -80,7 +80,7 @@ private void resetInvoker1ToNoException() { } @Test - public void testInvokeExceptoin() { + public void testInvokeException() { Assertions.assertThrows(RpcException.class, () -> { resetInvoker1ToException(); FailfastClusterInvoker invoker = new FailfastClusterInvoker(dic); @@ -90,7 +90,7 @@ public void testInvokeExceptoin() { } @Test() - public void testInvokeNoExceptoin() { + public void testInvokeNoException() { resetInvoker1ToNoException(); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/AdaptiveClassCodeGenerator.java b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/AdaptiveClassCodeGenerator.java index fcce47feaf1..50bf9508359 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/AdaptiveClassCodeGenerator.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/AdaptiveClassCodeGenerator.java @@ -224,7 +224,7 @@ private String generateMethodContent(Method method) { code.append(generateExtensionAssignment()); // return statement - code.append(generateReturnAndInovation(method)); + code.append(generateReturnAndInvocation(method)); } return code.toString(); @@ -292,7 +292,7 @@ private String generateExtensionAssignment() { /** * generate method invocation statement and return it if necessary */ - private String generateReturnAndInovation(Method method) { + private String generateReturnAndInvocation(Method method) { String returnStatement = method.getReturnType().equals(void.class) ? "" : "return "; String args = Arrays.stream(method.getParameters()).map(Parameter::getName).collect(Collectors.joining(", ")); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java index 5c72a14d3d0..4b3654a73d5 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java @@ -441,20 +441,20 @@ static void assertEqualsBigPerson(BigPerson person, Object obj) { assertEqualsPrimitive(person.getInfoProfile().isMale(), infoProfile.getProperty("male")); } - static void assertEqualsPhone(Phone excpected, Object obj) { + static void assertEqualsPhone(Phone expected, Object obj) { JavaBeanDescriptor descriptor = (JavaBeanDescriptor) obj; Assertions.assertTrue(descriptor.isBeanType()); - if (excpected.getArea() != null) { - assertEqualsPrimitive(excpected.getArea(), descriptor.getProperty("area")); + if (expected.getArea() != null) { + assertEqualsPrimitive(expected.getArea(), descriptor.getProperty("area")); } - if (excpected.getCountry() != null) { - assertEqualsPrimitive(excpected.getCountry(), descriptor.getProperty("country")); + if (expected.getCountry() != null) { + assertEqualsPrimitive(expected.getCountry(), descriptor.getProperty("country")); } - if (excpected.getExtensionNumber() != null) { - assertEqualsPrimitive(excpected.getExtensionNumber(), descriptor.getProperty("extensionNumber")); + if (expected.getExtensionNumber() != null) { + assertEqualsPrimitive(expected.getExtensionNumber(), descriptor.getProperty("extensionNumber")); } - if (excpected.getNumber() != null) { - assertEqualsPrimitive(excpected.getNumber(), descriptor.getProperty("number")); + if (expected.getNumber() != null) { + assertEqualsPrimitive(expected.getNumber(), descriptor.getProperty("number")); } } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractConfigTest.java index 2d40cc369fd..10cac653e99 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractConfigTest.java @@ -306,7 +306,7 @@ public void testRefreshAll() { System.setProperty("dubbo.override.address", "system://127.0.0.1:2181"); System.setProperty("dubbo.override.protocol", "system"); - // this will not override, use 'key' instread, @Parameter(key="key1", useKeyAsProperty=false) + // this will not override, use 'key' instead, @Parameter(key="key1", useKeyAsProperty=false) System.setProperty("dubbo.override.key1", "system"); System.setProperty("dubbo.override.key2", "system"); diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryTest.java index 23364d06e4f..8c959ebe8a0 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryTest.java @@ -312,20 +312,20 @@ public void testRecover2() throws Exception { @Test public void testNotify() throws Exception { final AtomicReference notified = new AtomicReference(false); - NotifyListener listner1 = urls -> notified.set(Boolean.TRUE); + NotifyListener listener1 = urls -> notified.set(Boolean.TRUE); URL url1 = new URL("dubbo", "192.168.0.1", 2200, parametersConsumer); - abstractRegistry.subscribe(url1, listner1); - NotifyListener listner2 = urls -> notified.set(Boolean.TRUE); + abstractRegistry.subscribe(url1, listener1); + NotifyListener listener2 = urls -> notified.set(Boolean.TRUE); URL url2 = new URL("dubbo", "192.168.0.2", 2201, parametersConsumer); - abstractRegistry.subscribe(url2, listner2); - NotifyListener listner3 = urls -> notified.set(Boolean.TRUE); + abstractRegistry.subscribe(url2, listener2); + NotifyListener listener3 = urls -> notified.set(Boolean.TRUE); URL url3 = new URL("dubbo", "192.168.0.3", 2202, parametersConsumer); - abstractRegistry.subscribe(url3, listner3); + abstractRegistry.subscribe(url3, listener3); List urls = new ArrayList<>(); urls.add(url1); urls.add(url2); urls.add(url3); - abstractRegistry.notify(url1, listner1, urls); + abstractRegistry.notify(url1, listener1, urls); Map>> map = abstractRegistry.getNotified(); MatcherAssert.assertThat(true, Matchers.equalTo(map.containsKey(url1))); MatcherAssert.assertThat(false, Matchers.equalTo(map.containsKey(url2))); @@ -338,15 +338,15 @@ public void testNotify() throws Exception { @Test public void testNotifyList() throws Exception { final AtomicReference notified = new AtomicReference(false); - NotifyListener listner1 = urls -> notified.set(Boolean.TRUE); + NotifyListener listener1 = urls -> notified.set(Boolean.TRUE); URL url1 = new URL("dubbo", "192.168.0.1", 2200, parametersConsumer); - abstractRegistry.subscribe(url1, listner1); - NotifyListener listner2 = urls -> notified.set(Boolean.TRUE); + abstractRegistry.subscribe(url1, listener1); + NotifyListener listener2 = urls -> notified.set(Boolean.TRUE); URL url2 = new URL("dubbo", "192.168.0.2", 2201, parametersConsumer); - abstractRegistry.subscribe(url2, listner2); - NotifyListener listner3 = urls -> notified.set(Boolean.TRUE); + abstractRegistry.subscribe(url2, listener2); + NotifyListener listener3 = urls -> notified.set(Boolean.TRUE); URL url3 = new URL("dubbo", "192.168.0.3", 2202, parametersConsumer); - abstractRegistry.subscribe(url3, listner3); + abstractRegistry.subscribe(url3, listener3); List urls = new ArrayList<>(); urls.add(url1); urls.add(url2); @@ -362,20 +362,20 @@ public void testNotifyList() throws Exception { public void testNotifyIfURLNull() throws Exception { Assertions.assertThrows(IllegalArgumentException.class, () -> { final AtomicReference notified = new AtomicReference(false); - NotifyListener listner1 = urls -> notified.set(Boolean.TRUE); + NotifyListener listener1 = urls -> notified.set(Boolean.TRUE); URL url1 = new URL("dubbo", "192.168.0.1", 2200, parametersConsumer); - abstractRegistry.subscribe(url1, listner1); - NotifyListener listner2 = urls -> notified.set(Boolean.TRUE); + abstractRegistry.subscribe(url1, listener1); + NotifyListener listener2 = urls -> notified.set(Boolean.TRUE); URL url2 = new URL("dubbo", "192.168.0.2", 2201, parametersConsumer); - abstractRegistry.subscribe(url2, listner2); - NotifyListener listner3 = urls -> notified.set(Boolean.TRUE); + abstractRegistry.subscribe(url2, listener2); + NotifyListener listener3 = urls -> notified.set(Boolean.TRUE); URL url3 = new URL("dubbo", "192.168.0.3", 2202, parametersConsumer); - abstractRegistry.subscribe(url3, listner3); + abstractRegistry.subscribe(url3, listener3); List urls = new ArrayList<>(); urls.add(url1); urls.add(url2); urls.add(url3); - abstractRegistry.notify(null, listner1, urls); + abstractRegistry.notify(null, listener1, urls); Assertions.fail("notify url == null"); }); } @@ -384,15 +384,15 @@ public void testNotifyIfURLNull() throws Exception { public void testNotifyIfNotifyNull() { Assertions.assertThrows(IllegalArgumentException.class, () -> { final AtomicReference notified = new AtomicReference(false); - NotifyListener listner1 = urls -> notified.set(Boolean.TRUE); + NotifyListener listener1 = urls -> notified.set(Boolean.TRUE); URL url1 = new URL("dubbo", "192.168.0.1", 2200, parametersConsumer); - abstractRegistry.subscribe(url1, listner1); - NotifyListener listner2 = urls -> notified.set(Boolean.TRUE); + abstractRegistry.subscribe(url1, listener1); + NotifyListener listener2 = urls -> notified.set(Boolean.TRUE); URL url2 = new URL("dubbo", "192.168.0.2", 2201, parametersConsumer); - abstractRegistry.subscribe(url2, listner2); - NotifyListener listner3 = urls -> notified.set(Boolean.TRUE); + abstractRegistry.subscribe(url2, listener2); + NotifyListener listener3 = urls -> notified.set(Boolean.TRUE); URL url3 = new URL("dubbo", "192.168.0.3", 2202, parametersConsumer); - abstractRegistry.subscribe(url3, listner3); + abstractRegistry.subscribe(url3, listener3); List urls = new ArrayList<>(); urls.add(url1); urls.add(url2); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractClient.java index 2afdc4d0f02..dd02651e018 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractClient.java @@ -192,7 +192,7 @@ protected void connect() throws RemotingException { } else { if (logger.isInfoEnabled()) { - logger.info("Successed connect to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " " + logger.info("Succeed connect to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " " + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() + ", channel is " + this.getChannel()); } diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/support/AbstractEtcdClient.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/support/AbstractEtcdClient.java index bf639ab3c93..0a6d26f90e9 100644 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/support/AbstractEtcdClient.java +++ b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/support/AbstractEtcdClient.java @@ -58,7 +58,7 @@ public abstract class AbstractEtcdClient implements EtcdClient private final Set stateListeners = new ConcurrentHashSet<>(); private final ConcurrentMap> childListeners = new ConcurrentHashMap<>(); - private final List categroies = Arrays.asList(Constants.PROVIDERS_CATEGORY + private final List categories = Arrays.asList(Constants.PROVIDERS_CATEGORY , Constants.CONSUMERS_CATEGORY , Constants.ROUTERS_CATEGORY , Constants.CONFIGURATORS_CATEGORY); @@ -158,11 +158,11 @@ protected void createParentIfAbsent(String fixedPath) { int i = fixedPath.lastIndexOf('/'); if (i > 0) { String parentPath = fixedPath.substring(0, i); - if (categroies.stream().anyMatch(c -> fixedPath.endsWith(c))) { + if (categories.stream().anyMatch(c -> fixedPath.endsWith(c))) { if (!checkExists(parentPath)) { this.doCreatePersistent(parentPath); } - } else if (categroies.stream().anyMatch(c -> parentPath.endsWith(c))) { + } else if (categories.stream().anyMatch(c -> parentPath.endsWith(c))) { String grandfather = parentPath.substring(0, parentPath.lastIndexOf('/')); if (!checkExists(grandfather)) { this.doCreatePersistent(grandfather); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java index 86ef44ca54a..814e9182280 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java @@ -40,7 +40,7 @@ public abstract class AbstractProtocol implements Protocol { protected final Map> exporterMap = new ConcurrentHashMap>(); - //TODO SOFEREFENCE + //TODO SoftReference protected final Set> invokers = new ConcurrentHashSet>(); protected static String serviceKey(URL url) { From 86b1a9862c97f8857eb73022481082fd429df023 Mon Sep 17 00:00:00 2001 From: myPrecious Date: Mon, 29 Apr 2019 17:06:43 +0800 Subject: [PATCH 011/115] complete lookup method of consul registry and add integration test (#3906) * add test case * fix bug * add something * complete lookup method of consul registry and add test * clean code * correct dependency of embedded-consul --- dubbo-dependencies-bom/pom.xml | 6 + dubbo-registry/dubbo-registry-consul/pom.xml | 5 + .../dubbo/registry/consul/ConsulRegistry.java | 20 +++ .../registry/consul/ConsulRegistryTest.java | 134 ++++++++++++++++++ 4 files changed, 165 insertions(+) create mode 100644 dubbo-registry/dubbo-registry-consul/src/test/java/org/apache/dubbo/registry/consul/ConsulRegistryTest.java diff --git a/dubbo-dependencies-bom/pom.xml b/dubbo-dependencies-bom/pom.xml index 1ba31db4c43..2d8be674495 100644 --- a/dubbo-dependencies-bom/pom.xml +++ b/dubbo-dependencies-bom/pom.xml @@ -103,6 +103,7 @@ 2.12.0 2.9.0 1.4.2 + 2.0.0 1.3.6 3.1.15 0.8.0 @@ -233,6 +234,11 @@ consul-api ${consul_version} + + com.pszymczyk.consul + embedded-consul + ${consul_process_version} + com.googlecode.xmemcached xmemcached diff --git a/dubbo-registry/dubbo-registry-consul/pom.xml b/dubbo-registry/dubbo-registry-consul/pom.xml index ec32dbe4340..0b40fbf0b06 100644 --- a/dubbo-registry/dubbo-registry-consul/pom.xml +++ b/dubbo-registry/dubbo-registry-consul/pom.xml @@ -36,6 +36,11 @@ com.ecwid.consul consul-api + + com.pszymczyk.consul + embedded-consul + test + diff --git a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java b/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java index f9a30f3fee1..888faa47ca5 100644 --- a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java +++ b/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java @@ -32,10 +32,12 @@ import com.ecwid.consul.v1.catalog.CatalogServicesRequest; import com.ecwid.consul.v1.health.HealthServicesRequest; import com.ecwid.consul.v1.health.model.HealthService; +import org.apache.dubbo.rpc.RpcException; import java.util.Collection; import java.util.Collections; import java.util.List; +import java.util.ArrayList; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; @@ -155,6 +157,24 @@ public void doUnsubscribe(URL url, NotifyListener listener) { notifier.stop(); } + @Override + public List lookup(URL url) { + if (url == null) { + throw new IllegalArgumentException("lookup url == null"); + } + try { + String service = url.getServiceKey(); + Response> result = client.getHealthServices(service, HealthServicesRequest.newBuilder().setTag(SERVICE_TAG).build()); + if (result == null || result.getValue() == null || result.getValue().isEmpty()) { + return new ArrayList<>(); + } else { + return convert(result.getValue()); + } + } catch (Throwable e) { + throw new RpcException("Failed to lookup " + url + " from consul " + getUrl() + ", cause: " + e.getMessage(), e); + } + } + @Override public boolean isAvailable() { return client.getAgentSelf() != null; diff --git a/dubbo-registry/dubbo-registry-consul/src/test/java/org/apache/dubbo/registry/consul/ConsulRegistryTest.java b/dubbo-registry/dubbo-registry-consul/src/test/java/org/apache/dubbo/registry/consul/ConsulRegistryTest.java new file mode 100644 index 00000000000..08203f37b5d --- /dev/null +++ b/dubbo-registry/dubbo-registry-consul/src/test/java/org/apache/dubbo/registry/consul/ConsulRegistryTest.java @@ -0,0 +1,134 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.registry.consul; + +import com.pszymczyk.consul.ConsulProcess; +import com.pszymczyk.consul.ConsulStarterBuilder; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.status.Status; +import org.apache.dubbo.registry.NotifyListener; +import org.apache.dubbo.registry.Registry; +import org.apache.dubbo.registry.status.RegistryStatusChecker; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.Mockito.mock; + +public class ConsulRegistryTest { + + private static ConsulProcess consul; + private ConsulRegistry consulRegistry; + private String service = "org.apache.dubbo.test.injvmServie"; + private URL serviceUrl = URL.valueOf("consul://127.0.0.1:8012/" + service + "?notify=false&methods=test1,test2"); + private URL registryUrl; + private ConsulRegistryFactory consulRegistryFactory; + + @BeforeEach + public void setUp() throws Exception { + this.consul = ConsulStarterBuilder.consulStarter() + .build() + .start(); + this.registryUrl = URL.valueOf("consul://localhost:" + consul.getHttpPort()); + + consulRegistryFactory = new ConsulRegistryFactory(); + this.consulRegistry = (ConsulRegistry) consulRegistryFactory.createRegistry(registryUrl); + } + + @AfterEach + public void tearDown() throws Exception { + consul.close(); + this.consulRegistry.destroy(); + } + + @Test + public void testRegister() { + Set registered; + + for (int i = 0; i < 2; i++) { + consulRegistry.register(serviceUrl); + registered = consulRegistry.getRegistered(); + assertThat(registered.contains(serviceUrl), is(true)); + } + + registered = consulRegistry.getRegistered(); + + assertThat(registered.size(), is(1)); + } + + @Test + public void testSubscribe() { + NotifyListener listener = mock(NotifyListener.class); + consulRegistry.subscribe(serviceUrl, listener); + + Map> subscribed = consulRegistry.getSubscribed(); + assertThat(subscribed.size(), is(1)); + assertThat(subscribed.get(serviceUrl).size(), is(1)); + + consulRegistry.unsubscribe(serviceUrl, listener); + subscribed = consulRegistry.getSubscribed(); + assertThat(subscribed.size(), is(1)); + assertThat(subscribed.get(serviceUrl).size(), is(0)); + } + + @Test + public void testAvailable() { + consulRegistry.register(serviceUrl); + assertThat(consulRegistry.isAvailable(), is(true)); + +// consulRegistry.destroy(); +// assertThat(consulRegistry.isAvailable(), is(false)); + } + + @Test + public void testLookup() throws InterruptedException { + List lookup = consulRegistry.lookup(serviceUrl); + assertThat(lookup.size(), is(0)); + + consulRegistry.register(serviceUrl); + Thread.sleep(5000); + lookup = consulRegistry.lookup(serviceUrl); + assertThat(lookup.size(), is(1)); + } + + @Test + public void testStatusChecker() { + RegistryStatusChecker registryStatusChecker = new RegistryStatusChecker(); + Status status = registryStatusChecker.check(); + assertThat(status.getLevel(), is(Status.Level.UNKNOWN)); + + Registry registry = consulRegistryFactory.getRegistry(registryUrl); + assertThat(registry, not(nullValue())); + + status = registryStatusChecker.check(); + assertThat(status.getLevel(), is(Status.Level.OK)); + + registry.register(serviceUrl); + status = registryStatusChecker.check(); + assertThat(status.getLevel(), is(Status.Level.OK)); + } + +} From 72fe93bf22c1f7db88b5d083c9570b27e1032542 Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Mon, 29 Apr 2019 17:41:53 +0800 Subject: [PATCH 012/115] fix issue #3713: org.apache.dubbo.rpc.support.MockInvoker#getInterface should not return null (#3716) --- .../rpc/cluster/support/wrapper/MockClusterInvoker.java | 4 ++-- .../java/org/apache/dubbo/rpc/support/MockInvoker.java | 7 ++++--- .../java/org/apache/dubbo/rpc/support/MockProtocol.java | 2 +- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java index 009f4df4428..59303142d85 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java @@ -88,7 +88,7 @@ public Result invoke(Invocation invocation) throws RpcException { if (e.isBiz()) { throw e; } - + if (logger.isWarnEnabled()) { logger.warn("fail-mock: " + invocation.getMethodName() + " fail-mock enabled , url : " + directory.getUrl(), e); } @@ -105,7 +105,7 @@ private Result doMockInvoke(Invocation invocation, RpcException e) { List> mockInvokers = selectMockInvoker(invocation); if (CollectionUtils.isEmpty(mockInvokers)) { - minvoker = (Invoker) new MockInvoker(directory.getUrl()); + minvoker = (Invoker) new MockInvoker(directory.getUrl(), directory.getInterface()); } else { minvoker = mockInvokers.get(0); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java index 436fb4799b5..923c7cb0fd1 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java @@ -46,9 +46,11 @@ final public class MockInvoker implements Invoker { private final static Map throwables = new ConcurrentHashMap(); private final URL url; + private final Class type; - public MockInvoker(URL url) { + public MockInvoker(URL url, Class type) { this.url = url; + this.type = type; } public static Object parseMockValue(String mock) throws Exception { @@ -251,7 +253,6 @@ public void destroy() { @Override public Class getInterface() { - //FIXME - return null; + return type; } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockProtocol.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockProtocol.java index 0b6f4d145fc..9237ab955c0 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockProtocol.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockProtocol.java @@ -39,6 +39,6 @@ public Exporter export(Invoker invoker) throws RpcException { @Override public Invoker refer(Class type, URL url) throws RpcException { - return new MockInvoker(url); + return new MockInvoker<>(url, type); } } From d54633edf0c396f8a18b17d6ba6970de436c6964 Mon Sep 17 00:00:00 2001 From: liugddx <48236177+liugddx@users.noreply.github.com> Date: Mon, 29 Apr 2019 23:35:46 +0800 Subject: [PATCH 013/115] Remove unnecessary null check in conjunction with instanceof --- .../java/org/apache/dubbo/remoting/transport/DecodeHandler.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/DecodeHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/DecodeHandler.java index 050dc78ad21..a342c4b757e 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/DecodeHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/DecodeHandler.java @@ -52,7 +52,7 @@ public void received(Channel channel, Object message) throws RemotingException { } private void decode(Object message) { - if (message != null && message instanceof Decodeable) { + if (message instanceof Decodeable) { try { ((Decodeable) message).decode(); if (log.isDebugEnabled()) { From e18904832791e878e7e3362a1d7280a7c0481f0f Mon Sep 17 00:00:00 2001 From: LiZhen Date: Tue, 30 Apr 2019 14:57:19 +0800 Subject: [PATCH 014/115] rename ClassHelper to ClassUtils, add MethodUtils (#3806) * rename ClassHelper to ClassUtils, add MethodUtils * remove import with '*' * ClassUtils add apache license --- .../java/org/apache/dubbo/common/Version.java | 4 +- .../dubbo/common/bytecode/ClassGenerator.java | 9 +- .../apache/dubbo/common/bytecode/Mixin.java | 4 +- .../apache/dubbo/common/bytecode/Proxy.java | 4 +- .../apache/dubbo/common/bytecode/Wrapper.java | 4 +- .../compiler/support/AbstractCompiler.java | 3 +- .../compiler/support/JavassistCompiler.java | 13 +- .../common/compiler/support/JdkCompiler.java | 3 +- .../common/extension/ExtensionLoader.java | 7 +- .../dubbo/common/timer/HashedWheelTimer.java | 6 +- .../dubbo/common/utils/ClassHelper.java | 209 ++----------- .../apache/dubbo/common/utils/ClassUtils.java | 288 ++++++++++++++++++ .../dubbo/common/utils/ConfigUtils.java | 4 +- .../dubbo/common/utils/MethodUtils.java | 41 +++ .../apache/dubbo/common/utils/PojoUtils.java | 2 +- .../dubbo/common/utils/ReflectUtils.java | 10 +- .../dubbo/common/utils/ClassHelperTest.java | 161 ---------- .../dubbo/common/utils/ClassUtilsTest.java | 155 ++++++++++ .../dubbo/common/utils/MethodUtilsTest.java | 62 ++++ .../apache/dubbo/config/AbstractConfig.java | 19 +- .../apache/dubbo/config/ReferenceConfig.java | 9 +- .../apache/dubbo/config/ServiceConfig.java | 6 +- .../rpc/protocol/thrift/ThriftCodec.java | 10 +- .../java/CompactedObjectInputStream.java | 5 +- 24 files changed, 633 insertions(+), 405 deletions(-) create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassUtils.java create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/utils/MethodUtils.java delete mode 100644 dubbo-common/src/test/java/org/apache/dubbo/common/utils/ClassHelperTest.java create mode 100644 dubbo-common/src/test/java/org/apache/dubbo/common/utils/ClassUtilsTest.java create mode 100644 dubbo-common/src/test/java/org/apache/dubbo/common/utils/MethodUtilsTest.java diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Version.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Version.java index 0ab48a6c4fc..ffbc31241a1 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/Version.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Version.java @@ -18,7 +18,7 @@ import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.ClassHelper; +import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.StringUtils; import java.io.IOException; @@ -240,7 +240,7 @@ public static void checkDuplicate(String path, boolean failOnError) { * search resources in caller's classloader */ private static Set getResources(String path) throws IOException { - Enumeration urls = ClassHelper.getCallerClassLoader(Version.class).getResources(path); + Enumeration urls = ClassUtils.getCallerClassLoader(Version.class).getResources(path); Set files = new HashSet(); while (urls.hasMoreElements()) { URL url = urls.nextElement(); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/ClassGenerator.java b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/ClassGenerator.java index 40ae8856cfe..fdcabb8c0f5 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/ClassGenerator.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/ClassGenerator.java @@ -16,10 +16,6 @@ */ package org.apache.dubbo.common.bytecode; -import org.apache.dubbo.common.utils.ArrayUtils; -import org.apache.dubbo.common.utils.ClassHelper; -import org.apache.dubbo.common.utils.ReflectUtils; - import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; @@ -30,6 +26,9 @@ import javassist.CtNewMethod; import javassist.LoaderClassPath; import javassist.NotFoundException; +import org.apache.dubbo.common.utils.ArrayUtils; +import org.apache.dubbo.common.utils.ClassUtils; +import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; import java.lang.reflect.Constructor; @@ -285,7 +284,7 @@ public ClassPool getClassPool() { } public Class toClass() { - return toClass(ClassHelper.getClassLoader(ClassGenerator.class), + return toClass(ClassUtils.getClassLoader(ClassGenerator.class), getClass().getProtectionDomain()); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Mixin.java b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Mixin.java index df95dabf445..f7a84236384 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Mixin.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Mixin.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.common.bytecode; -import org.apache.dubbo.common.utils.ClassHelper; +import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.ReflectUtils; import java.lang.reflect.Method; @@ -69,7 +69,7 @@ public static Mixin mixin(Class[] ics, Class dc, ClassLoader cl) { * @return Mixin instance. */ public static Mixin mixin(Class[] ics, Class[] dcs) { - return mixin(ics, dcs, ClassHelper.getCallerClassLoader(Mixin.class)); + return mixin(ics, dcs, ClassUtils.getCallerClassLoader(Mixin.class)); } /** diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Proxy.java b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Proxy.java index e72faae2cb1..8381bd20ca0 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Proxy.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Proxy.java @@ -17,7 +17,7 @@ package org.apache.dubbo.common.bytecode; import org.apache.dubbo.common.Constants; -import org.apache.dubbo.common.utils.ClassHelper; +import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.ReflectUtils; import java.lang.ref.Reference; @@ -62,7 +62,7 @@ protected Proxy() { * @return Proxy instance. */ public static Proxy getProxy(Class... ics) { - return getProxy(ClassHelper.getClassLoader(Proxy.class), ics); + return getProxy(ClassUtils.getClassLoader(Proxy.class), ics); } /** diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Wrapper.java b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Wrapper.java index 6d3f42bd8fe..7f83f97efd1 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Wrapper.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Wrapper.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.common.bytecode; -import org.apache.dubbo.common.utils.ClassHelper; +import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.ReflectUtils; import java.lang.reflect.Field; @@ -127,7 +127,7 @@ private static Wrapper makeWrapper(Class c) { } String name = c.getName(); - ClassLoader cl = ClassHelper.getClassLoader(c); + ClassLoader cl = ClassUtils.getClassLoader(c); StringBuilder c1 = new StringBuilder("public void setPropertyValue(Object o, String n, Object v){ "); StringBuilder c2 = new StringBuilder("public Object getPropertyValue(Object o, String n){ "); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/AbstractCompiler.java b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/AbstractCompiler.java index 7323641284d..f0794302849 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/AbstractCompiler.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/AbstractCompiler.java @@ -17,7 +17,6 @@ package org.apache.dubbo.common.compiler.support; import org.apache.dubbo.common.compiler.Compiler; -import org.apache.dubbo.common.utils.ClassHelper; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -50,7 +49,7 @@ public Class compile(String code, ClassLoader classLoader) { } String className = pkg != null && pkg.length() > 0 ? pkg + "." + cls : cls; try { - return Class.forName(className, true, ClassHelper.getCallerClassLoader(getClass())); + return Class.forName(className, true, org.apache.dubbo.common.utils.ClassUtils.getCallerClassLoader(getClass())); } catch (ClassNotFoundException e) { if (!code.endsWith("}")) { throw new IllegalStateException("The java code not endsWith \"}\", code: \n" + code + "\n"); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/JavassistCompiler.java b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/JavassistCompiler.java index 11f76b1e6bd..3a058849d8f 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/JavassistCompiler.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/JavassistCompiler.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.compiler.support; -import org.apache.dubbo.common.utils.ClassHelper; import javassist.CtClass; @@ -49,25 +48,25 @@ public Class doCompile(String name, String source) throws Throwable { while (matcher.find()) { builder.addImports(matcher.group(1).trim()); } - + // process extended super class matcher = EXTENDS_PATTERN.matcher(source); if (matcher.find()) { builder.setSuperClassName(matcher.group(1).trim()); } - + // process implemented interfaces matcher = IMPLEMENTS_PATTERN.matcher(source); if (matcher.find()) { String[] ifaces = matcher.group(1).trim().split("\\,"); Arrays.stream(ifaces).forEach(i -> builder.addInterface(i.trim())); } - + // process constructors, fields, methods String body = source.substring(source.indexOf('{') + 1, source.length() - 1); String[] methods = METHODS_PATTERN.split(body); String className = ClassUtils.getSimpleClassName(name); - Arrays.stream(methods).map(String::trim).filter(m -> !m.isEmpty()).forEach(method-> { + Arrays.stream(methods).map(String::trim).filter(m -> !m.isEmpty()).forEach(method -> { if (method.startsWith(className)) { builder.addConstructor("public " + method); } else if (FIELD_PATTERN.matcher(method).matches()) { @@ -76,9 +75,9 @@ public Class doCompile(String name, String source) throws Throwable { builder.addMethod("public " + method); } }); - + // compile - ClassLoader classLoader = ClassHelper.getCallerClassLoader(getClass()); + ClassLoader classLoader = org.apache.dubbo.common.utils.ClassUtils.getCallerClassLoader(getClass()); CtClass cls = builder.build(classLoader); return cls.toClass(classLoader, JavassistCompiler.class.getProtectionDomain()); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/JdkCompiler.java b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/JdkCompiler.java index 9c2800cc217..78619eeb7a7 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/JdkCompiler.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/JdkCompiler.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.compiler.support; -import org.apache.dubbo.common.utils.ClassHelper; import javax.tools.DiagnosticCollector; import javax.tools.FileObject; @@ -261,7 +260,7 @@ protected Class findClass(final String qualifiedClassName) throws ClassNotFou return defineClass(qualifiedClassName, bytes, 0, bytes.length); } try { - return ClassHelper.forNameWithCallerClassLoader(qualifiedClassName, getClass()); + return org.apache.dubbo.common.utils.ClassUtils.forNameWithCallerClassLoader(qualifiedClassName, getClass()); } catch (ClassNotFoundException nf) { return super.findClass(qualifiedClassName); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionLoader.java b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionLoader.java index 3f2709e8621..9d0b46c4469 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionLoader.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionLoader.java @@ -22,13 +22,14 @@ import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ArrayUtils; -import org.apache.dubbo.common.utils.ClassHelper; +import org.apache.dubbo.common.utils.ClassUtils; +import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.Holder; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.common.utils.CollectionUtils; + import java.io.BufferedReader; import java.io.InputStreamReader; import java.lang.reflect.Method; @@ -142,7 +143,7 @@ public static void resetExtensionLoader(Class type) { } private static ClassLoader findClassLoader() { - return ClassHelper.getClassLoader(ExtensionLoader.class); + return ClassUtils.getClassLoader(ExtensionLoader.class); } public String getExtensionName(T extensionInstance) { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/timer/HashedWheelTimer.java b/dubbo-common/src/main/java/org/apache/dubbo/common/timer/HashedWheelTimer.java index 3abeb660a64..d695b46d169 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/timer/HashedWheelTimer.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/timer/HashedWheelTimer.java @@ -18,7 +18,7 @@ import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.ClassHelper; +import org.apache.dubbo.common.utils.ClassUtils; import java.util.Collections; import java.util.HashSet; @@ -415,7 +415,7 @@ public long pendingTimeouts() { } private static void reportTooManyInstances() { - String resourceType = ClassHelper.simpleClassName(HashedWheelTimer.class); + String resourceType = ClassUtils.simpleClassName(HashedWheelTimer.class); logger.error("You are creating too many " + resourceType + " instances. " + resourceType + " is a shared resource that must be reused across the JVM," + "so that only a few instances are created."); @@ -657,7 +657,7 @@ public void expire() { public String toString() { final long currentTime = System.nanoTime(); long remaining = deadline - currentTime + timer.startTime; - String simpleClassName = ClassHelper.simpleClassName(this.getClass()); + String simpleClassName = ClassUtils.simpleClassName(this.getClass()); StringBuilder buf = new StringBuilder(192) .append(simpleClassName) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassHelper.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassHelper.java index d249645c2bf..fe3a21586f9 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassHelper.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassHelper.java @@ -17,68 +17,19 @@ package org.apache.dubbo.common.utils; -import java.lang.reflect.Array; import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; +/** + * @see org.apache.dubbo.common.utils.ClassUtils + * @deprecated Replace to ClassUtils + */ public class ClassHelper { - - /** - * Suffix for array class names: "[]" - */ - public static final String ARRAY_SUFFIX = "[]"; - /** - * Prefix for internal array class names: "[L" - */ - private static final String INTERNAL_ARRAY_PREFIX = "[L"; - /** - * Map with primitive type name as key and corresponding primitive type as - * value, for example: "int" -> "int.class". - */ - private static final Map> primitiveTypeNameMap = new HashMap>(16); - /** - * Map with primitive wrapper type as key and corresponding primitive type - * as value, for example: Integer.class -> int.class. - */ - private static final Map, Class> primitiveWrapperTypeMap = new HashMap, Class>(8); - - private static final char PACKAGE_SEPARATOR_CHAR = '.'; - - static { - primitiveWrapperTypeMap.put(Boolean.class, boolean.class); - primitiveWrapperTypeMap.put(Byte.class, byte.class); - primitiveWrapperTypeMap.put(Character.class, char.class); - primitiveWrapperTypeMap.put(Double.class, double.class); - primitiveWrapperTypeMap.put(Float.class, float.class); - primitiveWrapperTypeMap.put(Integer.class, int.class); - primitiveWrapperTypeMap.put(Long.class, long.class); - primitiveWrapperTypeMap.put(Short.class, short.class); - - Set> primitiveTypeNames = new HashSet>(16); - primitiveTypeNames.addAll(primitiveWrapperTypeMap.values()); - primitiveTypeNames.addAll(Arrays - .asList(new Class[]{boolean[].class, byte[].class, char[].class, double[].class, - float[].class, int[].class, long[].class, short[].class})); - for (Iterator> it = primitiveTypeNames.iterator(); it.hasNext(); ) { - Class primitiveClass = (Class) it.next(); - primitiveTypeNameMap.put(primitiveClass.getName(), primitiveClass); - } - } - - public static Class forNameWithThreadContextClassLoader(String name) - throws ClassNotFoundException { - return forName(name, Thread.currentThread().getContextClassLoader()); + public static Class forNameWithThreadContextClassLoader(String name) throws ClassNotFoundException { + return ClassUtils.forName(name, Thread.currentThread().getContextClassLoader()); } - public static Class forNameWithCallerClassLoader(String name, Class caller) - throws ClassNotFoundException { - return forName(name, caller.getClassLoader()); + public static Class forNameWithCallerClassLoader(String name, Class caller) throws ClassNotFoundException { + return ClassUtils.forName(name, caller.getClassLoader()); } public static ClassLoader getCallerClassLoader(Class caller) { @@ -92,26 +43,7 @@ public static ClassLoader getCallerClassLoader(Class caller) { * @return class loader */ public static ClassLoader getClassLoader(Class clazz) { - ClassLoader cl = null; - try { - cl = Thread.currentThread().getContextClassLoader(); - } catch (Throwable ex) { - // Cannot access thread context ClassLoader - falling back to system class loader... - } - if (cl == null) { - // No thread context class loader -> use class loader of this class. - cl = clazz.getClassLoader(); - if (cl == null) { - // getClassLoader() returning null indicates the bootstrap ClassLoader - try { - cl = ClassLoader.getSystemClassLoader(); - } catch (Throwable ex) { - // Cannot access system ClassLoader - oh well, maybe the caller can live with null... - } - } - } - - return cl; + return ClassUtils.getClassLoader(clazz); } /** @@ -155,38 +87,7 @@ public static Class forName(String name) throws ClassNotFoundException { */ public static Class forName(String name, ClassLoader classLoader) throws ClassNotFoundException, LinkageError { - - Class clazz = resolvePrimitiveClassName(name); - if (clazz != null) { - return clazz; - } - - // "java.lang.String[]" style arrays - if (name.endsWith(ARRAY_SUFFIX)) { - String elementClassName = name.substring(0, name.length() - ARRAY_SUFFIX.length()); - Class elementClass = forName(elementClassName, classLoader); - return Array.newInstance(elementClass, 0).getClass(); - } - - // "[Ljava.lang.String;" style arrays - int internalArrayMarker = name.indexOf(INTERNAL_ARRAY_PREFIX); - if (internalArrayMarker != -1 && name.endsWith(";")) { - String elementClassName = null; - if (internalArrayMarker == 0) { - elementClassName = name - .substring(INTERNAL_ARRAY_PREFIX.length(), name.length() - 1); - } else if (name.startsWith("[")) { - elementClassName = name.substring(1); - } - Class elementClass = forName(elementClassName, classLoader); - return Array.newInstance(elementClass, 0).getClass(); - } - - ClassLoader classLoaderToUse = classLoader; - if (classLoaderToUse == null) { - classLoaderToUse = getClassLoader(); - } - return classLoaderToUse.loadClass(name); + return ClassUtils.forName(name, classLoader); } /** @@ -202,94 +103,40 @@ public static Class forName(String name, ClassLoader classLoader) * denote a primitive class or primitive array class */ public static Class resolvePrimitiveClassName(String name) { - Class result = null; - // Most class names will be quite long, considering that they - // SHOULD sit in a package, so a length check is worthwhile. - if (name != null && name.length() <= 8) { - // Could be a primitive - likely. - result = (Class) primitiveTypeNameMap.get(name); - } - return result; + return ClassUtils.resolvePrimitiveClassName(name); } public static String toShortString(Object obj) { - if (obj == null) { - return "null"; - } - return obj.getClass().getSimpleName() + "@" + System.identityHashCode(obj); + return ClassUtils.toShortString(obj); } public static String simpleClassName(Class clazz) { - if (clazz == null) { - throw new NullPointerException("clazz"); - } - String className = clazz.getName(); - final int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR); - if (lastDotIdx > -1) { - return className.substring(lastDotIdx + 1); - } - return className; + return ClassUtils.simpleClassName(clazz); } + /** + * @see org.apache.dubbo.common.utils.MethodUtils#isSetter(Method) + * @deprecated Replace to MethodUtils#isSetter(Method) + */ public static boolean isSetter(Method method) { - return method.getName().startsWith("set") - && !"set".equals(method.getName()) - && Modifier.isPublic(method.getModifiers()) - && method.getParameterCount() == 1 - && isPrimitive(method.getParameterTypes()[0]); + return MethodUtils.isSetter(method); } + /** + * @see org.apache.dubbo.common.utils.MethodUtils#isGetter(Method) (Method) + * @deprecated Replace to MethodUtils#isGetter(Method) + */ public static boolean isGetter(Method method) { - String name = method.getName(); - return (name.startsWith("get") || name.startsWith("is")) - && !"get".equals(name) && !"is".equals(name) - && !"getClass".equals(name) && !"getObject".equals(name) - && Modifier.isPublic(method.getModifiers()) - && method.getParameterTypes().length == 0 - && isPrimitive(method.getReturnType()); + return MethodUtils.isGetter(method); } public static boolean isPrimitive(Class type) { - return type.isPrimitive() - || type == String.class - || type == Character.class - || type == Boolean.class - || type == Byte.class - || type == Short.class - || type == Integer.class - || type == Long.class - || type == Float.class - || type == Double.class - || type == Object.class; + return ClassUtils.isPrimitive(type); } public static Object convertPrimitive(Class type, String value) { - if (value == null) { - return null; - } else if (type == char.class || type == Character.class) { - return value.length() > 0 ? value.charAt(0) : '\0'; - } else if (type == boolean.class || type == Boolean.class) { - return Boolean.valueOf(value); - } - try { - if (type == byte.class || type == Byte.class) { - return Byte.valueOf(value); - } else if (type == short.class || type == Short.class) { - return Short.valueOf(value); - } else if (type == int.class || type == Integer.class) { - return Integer.valueOf(value); - } else if (type == long.class || type == Long.class) { - return Long.valueOf(value); - } else if (type == float.class || type == Float.class) { - return Float.valueOf(value); - } else if (type == double.class || type == Double.class) { - return Double.valueOf(value); - } - } catch (NumberFormatException e) { - return null; - } - return value; + return ClassUtils.convertPrimitive(type,value); } @@ -301,10 +148,6 @@ public static Object convertPrimitive(Class type, String value) { * @return */ public static boolean isTypeMatch(Class type, String value) { - if ((type == boolean.class || type == Boolean.class) - && !("true".equals(value) || "false".equals(value))) { - return false; - } - return true; + return ClassUtils.isTypeMatch(type,value); } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassUtils.java new file mode 100644 index 00000000000..51e4ee516b0 --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassUtils.java @@ -0,0 +1,288 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.utils; + + +import java.lang.reflect.Array; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class ClassUtils { + /** + * Suffix for array class names: "[]" + */ + public static final String ARRAY_SUFFIX = "[]"; + /** + * Prefix for internal array class names: "[L" + */ + private static final String INTERNAL_ARRAY_PREFIX = "[L"; + /** + * Map with primitive type name as key and corresponding primitive type as + * value, for example: "int" -> "int.class". + */ + private static final Map> primitiveTypeNameMap = new HashMap>(16); + /** + * Map with primitive wrapper type as key and corresponding primitive type + * as value, for example: Integer.class -> int.class. + */ + private static final Map, Class> primitiveWrapperTypeMap = new HashMap, Class>(8); + + private static final char PACKAGE_SEPARATOR_CHAR = '.'; + + static { + primitiveWrapperTypeMap.put(Boolean.class, boolean.class); + primitiveWrapperTypeMap.put(Byte.class, byte.class); + primitiveWrapperTypeMap.put(Character.class, char.class); + primitiveWrapperTypeMap.put(Double.class, double.class); + primitiveWrapperTypeMap.put(Float.class, float.class); + primitiveWrapperTypeMap.put(Integer.class, int.class); + primitiveWrapperTypeMap.put(Long.class, long.class); + primitiveWrapperTypeMap.put(Short.class, short.class); + + Set> primitiveTypeNames = new HashSet<>(16); + primitiveTypeNames.addAll(primitiveWrapperTypeMap.values()); + primitiveTypeNames.addAll(Arrays + .asList(boolean[].class, byte[].class, char[].class, double[].class, + float[].class, int[].class, long[].class, short[].class)); + for (Class primitiveTypeName : primitiveTypeNames) { + primitiveTypeNameMap.put(primitiveTypeName.getName(), primitiveTypeName); + } + } + + public static Class forNameWithThreadContextClassLoader(String name) + throws ClassNotFoundException { + return forName(name, Thread.currentThread().getContextClassLoader()); + } + + public static Class forNameWithCallerClassLoader(String name, Class caller) + throws ClassNotFoundException { + return forName(name, caller.getClassLoader()); + } + + public static ClassLoader getCallerClassLoader(Class caller) { + return caller.getClassLoader(); + } + + /** + * get class loader + * + * @param clazz + * @return class loader + */ + public static ClassLoader getClassLoader(Class clazz) { + ClassLoader cl = null; + try { + cl = Thread.currentThread().getContextClassLoader(); + } catch (Throwable ex) { + // Cannot access thread context ClassLoader - falling back to system class loader... + } + if (cl == null) { + // No thread context class loader -> use class loader of this class. + cl = clazz.getClassLoader(); + if (cl == null) { + // getClassLoader() returning null indicates the bootstrap ClassLoader + try { + cl = ClassLoader.getSystemClassLoader(); + } catch (Throwable ex) { + // Cannot access system ClassLoader - oh well, maybe the caller can live with null... + } + } + } + + return cl; + } + + /** + * Return the default ClassLoader to use: typically the thread context + * ClassLoader, if available; the ClassLoader that loaded the ClassUtils + * class will be used as fallback. + *

+ * Call this method if you intend to use the thread context ClassLoader in a + * scenario where you absolutely need a non-null ClassLoader reference: for + * example, for class path resource loading (but not necessarily for + * Class.forName, which accepts a null ClassLoader + * reference as well). + * + * @return the default ClassLoader (never null) + * @see java.lang.Thread#getContextClassLoader() + */ + public static ClassLoader getClassLoader() { + return getClassLoader(ClassUtils.class); + } + + /** + * Same as Class.forName(), except that it works for primitive + * types. + */ + public static Class forName(String name) throws ClassNotFoundException { + return forName(name, getClassLoader()); + } + + /** + * Replacement for Class.forName() that also returns Class + * instances for primitives (like "int") and array class names (like + * "String[]"). + * + * @param name the name of the Class + * @param classLoader the class loader to use (may be null, + * which indicates the default class loader) + * @return Class instance for the supplied name + * @throws ClassNotFoundException if the class was not found + * @throws LinkageError if the class file could not be loaded + * @see Class#forName(String, boolean, ClassLoader) + */ + public static Class forName(String name, ClassLoader classLoader) + throws ClassNotFoundException, LinkageError { + + Class clazz = resolvePrimitiveClassName(name); + if (clazz != null) { + return clazz; + } + + // "java.lang.String[]" style arrays + if (name.endsWith(ARRAY_SUFFIX)) { + String elementClassName = name.substring(0, name.length() - ARRAY_SUFFIX.length()); + Class elementClass = forName(elementClassName, classLoader); + return Array.newInstance(elementClass, 0).getClass(); + } + + // "[Ljava.lang.String;" style arrays + int internalArrayMarker = name.indexOf(INTERNAL_ARRAY_PREFIX); + if (internalArrayMarker != -1 && name.endsWith(";")) { + String elementClassName = null; + if (internalArrayMarker == 0) { + elementClassName = name + .substring(INTERNAL_ARRAY_PREFIX.length(), name.length() - 1); + } else if (name.startsWith("[")) { + elementClassName = name.substring(1); + } + Class elementClass = forName(elementClassName, classLoader); + return Array.newInstance(elementClass, 0).getClass(); + } + + ClassLoader classLoaderToUse = classLoader; + if (classLoaderToUse == null) { + classLoaderToUse = getClassLoader(); + } + return classLoaderToUse.loadClass(name); + } + + /** + * Resolve the given class name as primitive class, if appropriate, + * according to the JVM's naming rules for primitive classes. + *

+ * Also supports the JVM's internal class names for primitive arrays. Does + * not support the "[]" suffix notation for primitive arrays; this is + * only supported by {@link #forName}. + * + * @param name the name of the potentially primitive class + * @return the primitive class, or null if the name does not + * denote a primitive class or primitive array class + */ + public static Class resolvePrimitiveClassName(String name) { + Class result = null; + // Most class names will be quite long, considering that they + // SHOULD sit in a package, so a length check is worthwhile. + if (name != null && name.length() <= 8) { + // Could be a primitive - likely. + result = (Class) primitiveTypeNameMap.get(name); + } + return result; + } + + public static String toShortString(Object obj) { + if (obj == null) { + return "null"; + } + return obj.getClass().getSimpleName() + "@" + System.identityHashCode(obj); + + } + + public static String simpleClassName(Class clazz) { + if (clazz == null) { + throw new NullPointerException("clazz"); + } + String className = clazz.getName(); + final int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR); + if (lastDotIdx > -1) { + return className.substring(lastDotIdx + 1); + } + return className; + } + + + public static boolean isPrimitive(Class type) { + return type.isPrimitive() + || type == String.class + || type == Character.class + || type == Boolean.class + || type == Byte.class + || type == Short.class + || type == Integer.class + || type == Long.class + || type == Float.class + || type == Double.class + || type == Object.class; + } + + public static Object convertPrimitive(Class type, String value) { + if (value == null) { + return null; + } else if (type == char.class || type == Character.class) { + return value.length() > 0 ? value.charAt(0) : '\0'; + } else if (type == boolean.class || type == Boolean.class) { + return Boolean.valueOf(value); + } + try { + if (type == byte.class || type == Byte.class) { + return Byte.valueOf(value); + } else if (type == short.class || type == Short.class) { + return Short.valueOf(value); + } else if (type == int.class || type == Integer.class) { + return Integer.valueOf(value); + } else if (type == long.class || type == Long.class) { + return Long.valueOf(value); + } else if (type == float.class || type == Float.class) { + return Float.valueOf(value); + } else if (type == double.class || type == Double.class) { + return Double.valueOf(value); + } + } catch (NumberFormatException e) { + return null; + } + return value; + } + + + /** + * We only check boolean value at this moment. + * + * @param type + * @param value + * @return + */ + public static boolean isTypeMatch(Class type, String value) { + if ((type == boolean.class || type == Boolean.class) + && !("true".equals(value) || "false".equals(value))) { + return false; + } + return true; + } +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConfigUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConfigUtils.java index 0c68512c20e..1f26bf035a7 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConfigUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConfigUtils.java @@ -235,7 +235,7 @@ public static Properties loadProperties(String fileName, boolean allowMultiFile, List list = new ArrayList(); try { - Enumeration urls = ClassHelper.getClassLoader().getResources(fileName); + Enumeration urls = ClassUtils.getClassLoader().getResources(fileName); list = new ArrayList(); while (urls.hasMoreElements()) { list.add(urls.nextElement()); @@ -261,7 +261,7 @@ public static Properties loadProperties(String fileName, boolean allowMultiFile, // fall back to use method getResourceAsStream try { - properties.load(ClassHelper.getClassLoader().getResourceAsStream(fileName)); + properties.load(ClassUtils.getClassLoader().getResourceAsStream(fileName)); } catch (Throwable e) { logger.warn("Failed to load " + fileName + " file from " + fileName + "(ignore this file): " + e.getMessage(), e); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MethodUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MethodUtils.java new file mode 100644 index 00000000000..00ea97a663a --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MethodUtils.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.utils; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +public class MethodUtils { + + public static boolean isSetter(Method method) { + return method.getName().startsWith("set") + && !"set".equals(method.getName()) + && Modifier.isPublic(method.getModifiers()) + && method.getParameterCount() == 1 + && ClassUtils.isPrimitive(method.getParameterTypes()[0]); + } + + public static boolean isGetter(Method method) { + String name = method.getName(); + return (name.startsWith("get") || name.startsWith("is")) + && !"get".equals(name) && !"is".equals(name) + && !"getClass".equals(name) && !"getObject".equals(name) + && Modifier.isPublic(method.getModifiers()) + && method.getParameterTypes().length == 0 + && ClassUtils.isPrimitive(method.getReturnType()); + } +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PojoUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PojoUtils.java index 18998dc6239..37aa5ddaa68 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PojoUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PojoUtils.java @@ -380,7 +380,7 @@ private static Object realize0(Object pojo, Class type, Type genericType, fin Object className = ((Map) pojo).get("class"); if (className instanceof String) { try { - type = ClassHelper.forName((String) className); + type = ClassUtils.forName((String) className); } catch (ClassNotFoundException e) { // ignore } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.java index 20e091acc45..ccec6875ca8 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.java @@ -665,7 +665,7 @@ public static Class forName(ClassLoader cl, String name) { * @return Class instance. */ public static Class name2class(String name) throws ClassNotFoundException { - return name2class(ClassHelper.getClassLoader(), name); + return name2class(ClassUtils.getClassLoader(), name); } /** @@ -734,7 +734,7 @@ private static Class name2class(ClassLoader cl, String name) throws ClassNotF } if (cl == null) { - cl = ClassHelper.getClassLoader(); + cl = ClassUtils.getClassLoader(); } Class clazz = NAME_CLASS_CACHE.get(name); if (clazz == null) { @@ -754,7 +754,7 @@ private static Class name2class(ClassLoader cl, String name) throws ClassNotF * @throws ClassNotFoundException */ public static Class desc2class(String desc) throws ClassNotFoundException { - return desc2class(ClassHelper.getClassLoader(), desc); + return desc2class(ClassUtils.getClassLoader(), desc); } /** @@ -798,7 +798,7 @@ private static Class desc2class(ClassLoader cl, String desc) throws ClassNotF } if (cl == null) { - cl = ClassHelper.getClassLoader(); + cl = ClassUtils.getClassLoader(); } Class clazz = DESC_CLASS_CACHE.get(desc); if (clazz == null) { @@ -816,7 +816,7 @@ private static Class desc2class(ClassLoader cl, String desc) throws ClassNotF * @throws ClassNotFoundException */ public static Class[] desc2classArray(String desc) throws ClassNotFoundException { - Class[] ret = desc2classArray(ClassHelper.getClassLoader(), desc); + Class[] ret = desc2classArray(ClassUtils.getClassLoader(), desc); return ret; } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ClassHelperTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ClassHelperTest.java deleted file mode 100644 index 470e58709a1..00000000000 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ClassHelperTest.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.dubbo.common.utils; - -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - -import static org.apache.dubbo.common.utils.ClassHelper.forName; -import static org.apache.dubbo.common.utils.ClassHelper.getCallerClassLoader; -import static org.apache.dubbo.common.utils.ClassHelper.getClassLoader; -import static org.apache.dubbo.common.utils.ClassHelper.resolvePrimitiveClassName; -import static org.apache.dubbo.common.utils.ClassHelper.toShortString; -import static org.apache.dubbo.common.utils.ClassHelper.convertPrimitive; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.sameInstance; -import static org.hamcrest.Matchers.startsWith; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.Mockito.verify; - -public class ClassHelperTest { - @Test - public void testForNameWithThreadContextClassLoader() throws Exception { - ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); - try { - ClassLoader classLoader = Mockito.mock(ClassLoader.class); - Thread.currentThread().setContextClassLoader(classLoader); - ClassHelper.forNameWithThreadContextClassLoader("a.b.c.D"); - verify(classLoader).loadClass("a.b.c.D"); - } finally { - Thread.currentThread().setContextClassLoader(oldClassLoader); - } - } - - @Test - public void tetForNameWithCallerClassLoader() throws Exception { - Class c = ClassHelper.forNameWithCallerClassLoader(ClassHelper.class.getName(), ClassHelperTest.class); - assertThat(c == ClassHelper.class, is(true)); - } - - @Test - public void testGetCallerClassLoader() throws Exception { - assertThat(getCallerClassLoader(ClassHelperTest.class), sameInstance(ClassHelperTest.class.getClassLoader())); - } - - @Test - public void testGetClassLoader1() throws Exception { - ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); - try { - assertThat(getClassLoader(ClassHelperTest.class), sameInstance(oldClassLoader)); - Thread.currentThread().setContextClassLoader(null); - assertThat(getClassLoader(ClassHelperTest.class), sameInstance(ClassHelperTest.class.getClassLoader())); - } finally { - Thread.currentThread().setContextClassLoader(oldClassLoader); - } - } - - @Test - public void testGetClassLoader2() throws Exception { - assertThat(getClassLoader(), sameInstance(ClassHelper.class.getClassLoader())); - } - - @Test - public void testForName1() throws Exception { - assertThat(forName(ClassHelperTest.class.getName()) == ClassHelperTest.class, is(true)); - } - - @Test - public void testForName2() throws Exception { - assertThat(forName("byte") == byte.class, is(true)); - assertThat(forName("java.lang.String[]") == String[].class, is(true)); - assertThat(forName("[Ljava.lang.String;") == String[].class, is(true)); - } - - @Test - public void testForName3() throws Exception { - ClassLoader classLoader = Mockito.mock(ClassLoader.class); - forName("a.b.c.D", classLoader); - verify(classLoader).loadClass("a.b.c.D"); - } - - @Test - public void testResolvePrimitiveClassName() throws Exception { - assertThat(resolvePrimitiveClassName("boolean") == boolean.class, is(true)); - assertThat(resolvePrimitiveClassName("byte") == byte.class, is(true)); - assertThat(resolvePrimitiveClassName("char") == char.class, is(true)); - assertThat(resolvePrimitiveClassName("double") == double.class, is(true)); - assertThat(resolvePrimitiveClassName("float") == float.class, is(true)); - assertThat(resolvePrimitiveClassName("int") == int.class, is(true)); - assertThat(resolvePrimitiveClassName("long") == long.class, is(true)); - assertThat(resolvePrimitiveClassName("short") == short.class, is(true)); - assertThat(resolvePrimitiveClassName("[Z") == boolean[].class, is(true)); - assertThat(resolvePrimitiveClassName("[B") == byte[].class, is(true)); - assertThat(resolvePrimitiveClassName("[C") == char[].class, is(true)); - assertThat(resolvePrimitiveClassName("[D") == double[].class, is(true)); - assertThat(resolvePrimitiveClassName("[F") == float[].class, is(true)); - assertThat(resolvePrimitiveClassName("[I") == int[].class, is(true)); - assertThat(resolvePrimitiveClassName("[J") == long[].class, is(true)); - assertThat(resolvePrimitiveClassName("[S") == short[].class, is(true)); - } - - @Test - public void testToShortString() throws Exception { - assertThat(toShortString(null), equalTo("null")); - assertThat(toShortString(new ClassHelperTest()), startsWith("ClassHelperTest@")); - } - - @Test - public void testConvertPrimitive() throws Exception { - - assertThat(convertPrimitive(char.class, ""), equalTo('\0')); - assertThat(convertPrimitive(char.class, null), equalTo(null)); - assertThat(convertPrimitive(char.class, "6"), equalTo('6')); - - assertThat(convertPrimitive(boolean.class, ""), equalTo(Boolean.FALSE)); - assertThat(convertPrimitive(boolean.class, null), equalTo(null)); - assertThat(convertPrimitive(boolean.class, "true"), equalTo(Boolean.TRUE)); - - - assertThat(convertPrimitive(byte.class, ""), equalTo(null)); - assertThat(convertPrimitive(byte.class, null), equalTo(null)); - assertThat(convertPrimitive(byte.class, "127"), equalTo(Byte.MAX_VALUE)); - - - assertThat(convertPrimitive(short.class, ""), equalTo(null)); - assertThat(convertPrimitive(short.class, null), equalTo(null)); - assertThat(convertPrimitive(short.class, "32767"), equalTo(Short.MAX_VALUE)); - - assertThat(convertPrimitive(int.class, ""), equalTo(null)); - assertThat(convertPrimitive(int.class, null), equalTo(null)); - assertThat(convertPrimitive(int.class, "6"), equalTo(6)); - - assertThat(convertPrimitive(long.class, ""), equalTo(null)); - assertThat(convertPrimitive(long.class, null), equalTo(null)); - assertThat(convertPrimitive(long.class, "6"), equalTo(new Long(6))); - - assertThat(convertPrimitive(float.class, ""), equalTo(null)); - assertThat(convertPrimitive(float.class, null), equalTo(null)); - assertThat(convertPrimitive(float.class, "1.1"), equalTo(new Float(1.1))); - - assertThat(convertPrimitive(double.class, ""), equalTo(null)); - assertThat(convertPrimitive(double.class, null), equalTo(null)); - assertThat(convertPrimitive(double.class, "10.1"), equalTo(new Double(10.1))); - } - -} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ClassUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ClassUtilsTest.java new file mode 100644 index 00000000000..211e6f4d09c --- /dev/null +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ClassUtilsTest.java @@ -0,0 +1,155 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.common.utils; + +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.sameInstance; +import static org.hamcrest.Matchers.startsWith; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.Mockito.verify; + +public class ClassUtilsTest { + @Test + public void testForNameWithThreadContextClassLoader() throws Exception { + ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); + try { + ClassLoader classLoader = Mockito.mock(ClassLoader.class); + Thread.currentThread().setContextClassLoader(classLoader); + ClassUtils.forNameWithThreadContextClassLoader("a.b.c.D"); + verify(classLoader).loadClass("a.b.c.D"); + } finally { + Thread.currentThread().setContextClassLoader(oldClassLoader); + } + } + + @Test + public void tetForNameWithCallerClassLoader() throws Exception { + Class c = ClassUtils.forNameWithCallerClassLoader(ClassUtils.class.getName(), ClassUtilsTest.class); + assertThat(c == ClassUtils.class, is(true)); + } + + @Test + public void testGetCallerClassLoader() throws Exception { + assertThat(ClassUtils.getCallerClassLoader(ClassUtilsTest.class), sameInstance(ClassUtilsTest.class.getClassLoader())); + } + + @Test + public void testGetClassLoader1() throws Exception { + ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); + try { + assertThat(ClassUtils.getClassLoader(ClassUtilsTest.class), sameInstance(oldClassLoader)); + Thread.currentThread().setContextClassLoader(null); + assertThat(ClassUtils.getClassLoader(ClassUtilsTest.class), sameInstance(ClassUtilsTest.class.getClassLoader())); + } finally { + Thread.currentThread().setContextClassLoader(oldClassLoader); + } + } + + @Test + public void testGetClassLoader2() throws Exception { + assertThat(ClassUtils.getClassLoader(), sameInstance(ClassUtils.class.getClassLoader())); + } + + @Test + public void testForName1() throws Exception { + assertThat(ClassUtils.forName(ClassUtilsTest.class.getName()) == ClassUtilsTest.class, is(true)); + } + + @Test + public void testForName2() throws Exception { + assertThat(ClassUtils.forName("byte") == byte.class, is(true)); + assertThat(ClassUtils.forName("java.lang.String[]") == String[].class, is(true)); + assertThat(ClassUtils.forName("[Ljava.lang.String;") == String[].class, is(true)); + } + + @Test + public void testForName3() throws Exception { + ClassLoader classLoader = Mockito.mock(ClassLoader.class); + ClassUtils.forName("a.b.c.D", classLoader); + verify(classLoader).loadClass("a.b.c.D"); + } + + @Test + public void testResolvePrimitiveClassName() throws Exception { + assertThat(ClassUtils.resolvePrimitiveClassName("boolean") == boolean.class, is(true)); + assertThat(ClassUtils.resolvePrimitiveClassName("byte") == byte.class, is(true)); + assertThat(ClassUtils.resolvePrimitiveClassName("char") == char.class, is(true)); + assertThat(ClassUtils.resolvePrimitiveClassName("double") == double.class, is(true)); + assertThat(ClassUtils.resolvePrimitiveClassName("float") == float.class, is(true)); + assertThat(ClassUtils.resolvePrimitiveClassName("int") == int.class, is(true)); + assertThat(ClassUtils.resolvePrimitiveClassName("long") == long.class, is(true)); + assertThat(ClassUtils.resolvePrimitiveClassName("short") == short.class, is(true)); + assertThat(ClassUtils.resolvePrimitiveClassName("[Z") == boolean[].class, is(true)); + assertThat(ClassUtils.resolvePrimitiveClassName("[B") == byte[].class, is(true)); + assertThat(ClassUtils.resolvePrimitiveClassName("[C") == char[].class, is(true)); + assertThat(ClassUtils.resolvePrimitiveClassName("[D") == double[].class, is(true)); + assertThat(ClassUtils.resolvePrimitiveClassName("[F") == float[].class, is(true)); + assertThat(ClassUtils.resolvePrimitiveClassName("[I") == int[].class, is(true)); + assertThat(ClassUtils.resolvePrimitiveClassName("[J") == long[].class, is(true)); + assertThat(ClassUtils.resolvePrimitiveClassName("[S") == short[].class, is(true)); + } + + @Test + public void testToShortString() throws Exception { + assertThat(ClassUtils.toShortString(null), equalTo("null")); + assertThat(ClassUtils.toShortString(new ClassUtilsTest()), startsWith("ClassUtilsTest@")); + } + + @Test + public void testConvertPrimitive() throws Exception { + + assertThat(ClassUtils.convertPrimitive(char.class, ""), equalTo('\0')); + assertThat(ClassUtils.convertPrimitive(char.class, null), equalTo(null)); + assertThat(ClassUtils.convertPrimitive(char.class, "6"), equalTo('6')); + + assertThat(ClassUtils.convertPrimitive(boolean.class, ""), equalTo(Boolean.FALSE)); + assertThat(ClassUtils.convertPrimitive(boolean.class, null), equalTo(null)); + assertThat(ClassUtils.convertPrimitive(boolean.class, "true"), equalTo(Boolean.TRUE)); + + + assertThat(ClassUtils.convertPrimitive(byte.class, ""), equalTo(null)); + assertThat(ClassUtils.convertPrimitive(byte.class, null), equalTo(null)); + assertThat(ClassUtils.convertPrimitive(byte.class, "127"), equalTo(Byte.MAX_VALUE)); + + + assertThat(ClassUtils.convertPrimitive(short.class, ""), equalTo(null)); + assertThat(ClassUtils.convertPrimitive(short.class, null), equalTo(null)); + assertThat(ClassUtils.convertPrimitive(short.class, "32767"), equalTo(Short.MAX_VALUE)); + + assertThat(ClassUtils.convertPrimitive(int.class, ""), equalTo(null)); + assertThat(ClassUtils.convertPrimitive(int.class, null), equalTo(null)); + assertThat(ClassUtils.convertPrimitive(int.class, "6"), equalTo(6)); + + assertThat(ClassUtils.convertPrimitive(long.class, ""), equalTo(null)); + assertThat(ClassUtils.convertPrimitive(long.class, null), equalTo(null)); + assertThat(ClassUtils.convertPrimitive(long.class, "6"), equalTo(new Long(6))); + + assertThat(ClassUtils.convertPrimitive(float.class, ""), equalTo(null)); + assertThat(ClassUtils.convertPrimitive(float.class, null), equalTo(null)); + assertThat(ClassUtils.convertPrimitive(float.class, "1.1"), equalTo(new Float(1.1))); + + assertThat(ClassUtils.convertPrimitive(double.class, ""), equalTo(null)); + assertThat(ClassUtils.convertPrimitive(double.class, null), equalTo(null)); + assertThat(ClassUtils.convertPrimitive(double.class, "10.1"), equalTo(new Double(10.1))); + } + +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MethodUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MethodUtilsTest.java new file mode 100644 index 00000000000..cc15d111690 --- /dev/null +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MethodUtilsTest.java @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.utils; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Method; + +public class MethodUtilsTest { + + @Test + public void testGetMethod() { + Method getMethod = null; + for (Method method : MethodTestClazz.class.getMethods()) { + if (MethodUtils.isGetter(method)) { + getMethod = method; + } + } + Assertions.assertNotNull(getMethod); + Assertions.assertTrue(getMethod.getName().equals("getValue")); + } + + @Test + public void testSetMethod() { + Method setMethod = null; + for (Method method : MethodTestClazz.class.getMethods()) { + if (MethodUtils.isSetter(method)) { + setMethod = method; + } + } + Assertions.assertNotNull(setMethod); + Assertions.assertTrue(setMethod.getName().equals("setValue")); + } + + public class MethodTestClazz { + private String value; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + } + +} diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractConfig.java index 61d05c56702..30b3f50daf5 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractConfig.java @@ -24,8 +24,9 @@ import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.ClassHelper; +import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.CollectionUtils; +import org.apache.dubbo.common.utils.MethodUtils; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.support.Parameter; @@ -156,7 +157,7 @@ protected static void appendParameters(Map parameters, Object co for (Method method : methods) { try { String name = method.getName(); - if (ClassHelper.isGetter(method)) { + if (MethodUtils.isGetter(method)) { Parameter parameter = method.getAnnotation(Parameter.class); if (method.getReturnType() == Object.class || parameter != null && parameter.excluded()) { continue; @@ -224,7 +225,7 @@ protected static void appendAttributes(Map parameters, Object co continue; } String name = method.getName(); - if (ClassHelper.isGetter(method)) { + if (MethodUtils.isGetter(method)) { String key; if (parameter.key().length() > 0) { key = parameter.key(); @@ -555,12 +556,12 @@ public void refresh() { // loop methods, get override value and set the new value back to method Method[] methods = getClass().getMethods(); for (Method method : methods) { - if (ClassHelper.isSetter(method)) { + if (MethodUtils.isSetter(method)) { try { String value = StringUtils.trim(compositeConfiguration.getString(extractPropertyName(getClass(), method))); // isTypeMatch() is called to avoid duplicate and incorrect update, for example, we have two 'setGeneric' methods in ReferenceConfig. - if (StringUtils.isNotEmpty(value) && ClassHelper.isTypeMatch(method.getParameterTypes()[0], value)) { - method.invoke(this, ClassHelper.convertPrimitive(method.getParameterTypes()[0], value)); + if (StringUtils.isNotEmpty(value) && ClassUtils.isTypeMatch(method.getParameterTypes()[0], value)) { + method.invoke(this, ClassUtils.convertPrimitive(method.getParameterTypes()[0], value)); } } catch (NoSuchMethodException e) { logger.info("Failed to override the property " + method.getName() + " in " + @@ -583,7 +584,7 @@ public String toString() { Method[] methods = getClass().getMethods(); for (Method method : methods) { try { - if (ClassHelper.isGetter(method)) { + if (MethodUtils.isGetter(method)) { String name = method.getName(); String key = calculateAttributeFromGetter(name); Object value = method.invoke(this); @@ -632,7 +633,7 @@ private boolean isMetaMethod(Method method) { if (method.getParameterTypes().length != 0) { return false; } - if (!ClassHelper.isPrimitive(method.getReturnType())) { + if (!ClassUtils.isPrimitive(method.getReturnType())) { return false; } return true; @@ -646,7 +647,7 @@ public boolean equals(Object obj) { Method[] methods = this.getClass().getMethods(); for (Method method1 : methods) { - if (ClassHelper.isGetter(method1) && ClassHelper.isPrimitive(method1.getReturnType())) { + if (MethodUtils.isGetter(method1) && ClassUtils.isPrimitive(method1.getReturnType())) { Parameter parameter = method1.getAnnotation(Parameter.class); if (parameter != null && parameter.excluded()) { continue; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java index fe0f43a1865..e1df3193c13 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java @@ -21,7 +21,7 @@ import org.apache.dubbo.common.Version; import org.apache.dubbo.common.bytecode.Wrapper; import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.utils.ClassHelper; +import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.NetUtils; @@ -108,7 +108,7 @@ public class ReferenceConfig extends AbstractReferenceConfig { * The interface class of the reference service */ private Class interfaceClass; - + /** * client type */ @@ -328,6 +328,7 @@ private ConsumerModel buildConsumerModel(String serviceKey, Map } return new ConsumerModel(serviceKey, serviceInterface, ref, methods, attributes); } + @SuppressWarnings({"unchecked", "rawtypes", "deprecation"}) private T createProxy(Map map) { if (shouldJvmRefer(map)) { @@ -439,7 +440,7 @@ protected boolean shouldJvmRefer(Map map) { protected boolean shouldCheck() { Boolean shouldCheck = isCheck(); - if (shouldCheck == null && getConsumer()!= null) { + if (shouldCheck == null && getConsumer() != null) { shouldCheck = getConsumer().isCheck(); } if (shouldCheck == null) { @@ -515,7 +516,7 @@ public Class getInterfaceClass() { } try { if (interfaceName != null && interfaceName.length() > 0) { - this.interfaceClass = Class.forName(interfaceName, true, ClassHelper.getClassLoader()); + this.interfaceClass = Class.forName(interfaceName, true, ClassUtils.getClassLoader()); } } catch (ClassNotFoundException t) { throw new IllegalStateException(t.getMessage(), t); diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index 602b5d4f467..2fbb85a8db5 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -23,7 +23,7 @@ import org.apache.dubbo.common.bytecode.Wrapper; import org.apache.dubbo.common.config.Environment; import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.utils.ClassHelper; +import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.NamedThreadFactory; @@ -301,7 +301,7 @@ public void checkAndUpdateSubConfigs() { } Class localClass; try { - localClass = ClassHelper.forNameWithThreadContextClassLoader(local); + localClass = ClassUtils.forNameWithThreadContextClassLoader(local); } catch (ClassNotFoundException e) { throw new IllegalStateException(e.getMessage(), e); } @@ -315,7 +315,7 @@ public void checkAndUpdateSubConfigs() { } Class stubClass; try { - stubClass = ClassHelper.forNameWithThreadContextClassLoader(stub); + stubClass = ClassUtils.forNameWithThreadContextClassLoader(stub); } catch (ClassNotFoundException e) { throw new IllegalStateException(e.getMessage(), e); } diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java index 58058f4f64f..ceef6ccf774 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java @@ -18,7 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.utils.ClassHelper; +import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Codec2; import org.apache.dubbo.remoting.buffer.ChannelBuffer; @@ -199,7 +199,7 @@ private Object decode(TProtocol protocol) if (clazz == null) { try { - clazz = ClassHelper.forNameWithThreadContextClassLoader(argsClassName); + clazz = ClassUtils.forNameWithThreadContextClassLoader(argsClassName); cachedClass.putIfAbsent(argsClassName, clazz); @@ -313,7 +313,7 @@ private Object decode(TProtocol protocol) try { - clazz = ClassHelper.forNameWithThreadContextClassLoader(resultClassName); + clazz = ClassUtils.forNameWithThreadContextClassLoader(resultClassName); cachedClass.putIfAbsent(resultClassName, clazz); @@ -429,7 +429,7 @@ private void encodeRequest(Channel channel, ChannelBuffer buffer, Request reques try { - clazz = ClassHelper.forNameWithThreadContextClassLoader(methodArgs); + clazz = ClassUtils.forNameWithThreadContextClassLoader(methodArgs); cachedClass.putIfAbsent(methodArgs, clazz); @@ -555,7 +555,7 @@ private void encodeResponse(Channel channel, ChannelBuffer buffer, Response resp if (clazz == null) { try { - clazz = ClassHelper.forNameWithThreadContextClassLoader(resultClassName); + clazz = ClassUtils.forNameWithThreadContextClassLoader(resultClassName); cachedClass.putIfAbsent(resultClassName, clazz); } catch (ClassNotFoundException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/CompactedObjectInputStream.java b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/CompactedObjectInputStream.java index 2ed71f814ec..e8817746a64 100644 --- a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/CompactedObjectInputStream.java +++ b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/CompactedObjectInputStream.java @@ -16,7 +16,8 @@ */ package org.apache.dubbo.common.serialize.java; -import org.apache.dubbo.common.utils.ClassHelper; + +import org.apache.dubbo.common.utils.ClassUtils; import java.io.EOFException; import java.io.IOException; @@ -37,7 +38,7 @@ public CompactedObjectInputStream(InputStream in) throws IOException { public CompactedObjectInputStream(InputStream in, ClassLoader cl) throws IOException { super(in); - mClassLoader = cl == null ? ClassHelper.getClassLoader() : cl; + mClassLoader = cl == null ? ClassUtils.getClassLoader() : cl; } @Override From e2f3346d9d1dff2bf6bf3ac2802e83d46b9923c0 Mon Sep 17 00:00:00 2001 From: huaifeng Date: Tue, 30 Apr 2019 15:52:50 +0800 Subject: [PATCH 015/115] fixed provider set delay NullPointerException (#3957) * fixed provider set delay NullPointerException * add getActualDelay method * simple --- .../src/main/java/org/apache/dubbo/config/ServiceConfig.java | 1 + 1 file changed, 1 insertion(+) diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index 2fbb85a8db5..e540dc0b6e2 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -360,6 +360,7 @@ private boolean shouldDelay() { if (delay == null && provider != null) { delay = provider.getDelay(); } + this.delay = delay; return delay != null && delay > 0; } From 78c75093f588b3ec3659fd426da774c392e5b10b Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Tue, 30 Apr 2019 16:47:30 +0800 Subject: [PATCH 016/115] #3952: Dubbo 2.7.1 delay export function doesn't work, a follow up for #3957 (#3959) --- .../apache/dubbo/config/ServiceConfig.java | 26 +++++++++---------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index e540dc0b6e2..0c38b2f135c 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -335,35 +335,33 @@ public synchronized void export() { } if (shouldDelay()) { - delayExportExecutor.schedule(this::doExport, delay, TimeUnit.MILLISECONDS); + delayExportExecutor.schedule(this::doExport, getDelay(), TimeUnit.MILLISECONDS); } else { doExport(); } } private boolean shouldExport() { - Boolean shouldExport = getExport(); - if (shouldExport == null && provider != null) { - shouldExport = provider.getExport(); - } - + Boolean export = getExport(); // default value is true - if (shouldExport == null) { - return true; - } + return export == null ? true : export; + } - return shouldExport; + @Override + public Boolean getExport() { + return (export == null && provider != null) ? provider.getExport() : export; } private boolean shouldDelay() { Integer delay = getDelay(); - if (delay == null && provider != null) { - delay = provider.getDelay(); - } - this.delay = delay; return delay != null && delay > 0; } + @Override + public Integer getDelay() { + return (delay == null && provider != null) ? provider.getDelay() : delay; + } + protected synchronized void doExport() { if (unexported) { throw new IllegalStateException("The service " + interfaceClass.getName() + " has already unexported!"); From 667f2271b3c93f0c4f321368e32eb37a62d1fe0c Mon Sep 17 00:00:00 2001 From: Geng Zhang Date: Thu, 2 May 2019 10:07:05 +0800 Subject: [PATCH 017/115] [Dubbo-3886] Integrate with SOFARegistry. (#3886) * Integrate with SOFARegistry. --- dubbo-all/pom.xml | 8 + dubbo-bom/pom.xml | 5 + dubbo-dependencies-bom/pom.xml | 15 +- dubbo-distribution/pom.xml | 5 + dubbo-registry/dubbo-registry-sofa/pom.xml | 141 +++++++++ .../dubbo/registry/sofa/SofaRegistry.java | 292 ++++++++++++++++++ .../registry/sofa/SofaRegistryConstants.java | 43 +++ .../registry/sofa/SofaRegistryFactory.java | 41 +++ .../org.apache.dubbo.registry.RegistryFactory | 1 + .../dubbo/registry/sofa/HelloService.java | 24 ++ .../dubbo/registry/sofa/HelloServiceImpl.java | 44 +++ .../dubbo/registry/sofa/SofaRegistryTest.java | 148 +++++++++ .../src/test/resources/log4j.properties | 7 + dubbo-registry/pom.xml | 1 + .../rpc/protocol/thrift/ThriftCodec.java | 3 +- 15 files changed, 775 insertions(+), 3 deletions(-) create mode 100644 dubbo-registry/dubbo-registry-sofa/pom.xml create mode 100644 dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistry.java create mode 100644 dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistryConstants.java create mode 100644 dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistryFactory.java create mode 100644 dubbo-registry/dubbo-registry-sofa/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory create mode 100644 dubbo-registry/dubbo-registry-sofa/src/test/java/org/apache/dubbo/registry/sofa/HelloService.java create mode 100644 dubbo-registry/dubbo-registry-sofa/src/test/java/org/apache/dubbo/registry/sofa/HelloServiceImpl.java create mode 100644 dubbo-registry/dubbo-registry-sofa/src/test/java/org/apache/dubbo/registry/sofa/SofaRegistryTest.java create mode 100644 dubbo-registry/dubbo-registry-sofa/src/test/resources/log4j.properties diff --git a/dubbo-all/pom.xml b/dubbo-all/pom.xml index e0e2366bd44..08621e41394 100644 --- a/dubbo-all/pom.xml +++ b/dubbo-all/pom.xml @@ -254,6 +254,13 @@ compile true + + org.apache.dubbo + dubbo-registry-sofa + ${project.version} + compile + true + org.apache.dubbo dubbo-monitor-api @@ -530,6 +537,7 @@ org.apache.dubbo:dubbo-registry-redis org.apache.dubbo:dubbo-registry-consul org.apache.dubbo:dubbo-registry-etcd3 + org.apache.dubbo:dubbo-registry-sofa org.apache.dubbo:dubbo-monitor-api org.apache.dubbo:dubbo-monitor-default org.apache.dubbo:dubbo-config-api diff --git a/dubbo-bom/pom.xml b/dubbo-bom/pom.xml index e894f8b0619..148b49aebdc 100644 --- a/dubbo-bom/pom.xml +++ b/dubbo-bom/pom.xml @@ -252,6 +252,11 @@ dubbo-registry-consul ${project.version} + + org.apache.dubbo + dubbo-registry-sofa + ${project.version} + org.apache.dubbo dubbo-monitor-api diff --git a/dubbo-dependencies-bom/pom.xml b/dubbo-dependencies-bom/pom.xml index 2d8be674495..6d68457125b 100644 --- a/dubbo-dependencies-bom/pom.xml +++ b/dubbo-dependencies-bom/pom.xml @@ -145,6 +145,7 @@ 4.3.16.RELEASE 2.0.1 + 5.2.0 2.8.5 1.2.0 2.0 @@ -458,7 +459,6 @@ ${commons_lang3_version} - javax.xml.bind @@ -519,6 +519,19 @@ metrics-rest ${metrics_version} + + + + com.alipay.sofa + registry-client-all + ${sofa_registry_version} + + + com.alipay.sofa + registry-test + ${sofa_registry_version} + test + diff --git a/dubbo-distribution/pom.xml b/dubbo-distribution/pom.xml index 50fd85532cc..e92363db722 100644 --- a/dubbo-distribution/pom.xml +++ b/dubbo-distribution/pom.xml @@ -180,6 +180,11 @@ dubbo-registry-redis ${project.version} + + org.apache.dubbo + dubbo-registry-sofa + ${project.version} + org.apache.dubbo dubbo-monitor-api diff --git a/dubbo-registry/dubbo-registry-sofa/pom.xml b/dubbo-registry/dubbo-registry-sofa/pom.xml new file mode 100644 index 00000000000..7a2415fc216 --- /dev/null +++ b/dubbo-registry/dubbo-registry-sofa/pom.xml @@ -0,0 +1,141 @@ + + + + org.apache.dubbo + dubbo-registry + ${revision} + ../pom.xml + + 4.0.0 + + dubbo-registry-sofa + ${project.artifactId} + The SOFARegistry module of Dubbo project + + + 2.1 + -Dnetwork_interface_denylist=docker0 + + + + + org.apache.dubbo + dubbo-registry-api + ${project.version} + true + + + + org.apache.dubbo + dubbo-common + ${project.version} + true + + + + com.alipay.sofa + registry-client-all + + + com.alipay.sofa + sofa-common-tools + + + + + + + org.apache.dubbo + dubbo-config-api + ${project.version} + test + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.version} + test + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.version} + test + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.version} + test + + + ch.qos.logback + logback-classic + test + + + + + com.alipay.sofa + registry-test + test + + + log4j-over-slf4j + org.slf4j + + + log4j-jcl + org.apache.logging.log4j + + + log4j-core + org.apache.logging.log4j + + + log4j-api + org.apache.logging.log4j + + + + + + org.jboss.resteasy + resteasy-jaxrs + test + + + org.jboss.resteasy + resteasy-netty4 + test + + + javax.ws.rs + javax.ws.rs-api + ${javax.ws.rs.version} + test + + + javax.xml.bind + jaxb-api + test + + + + \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistry.java b/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistry.java new file mode 100644 index 00000000000..a514d7a2517 --- /dev/null +++ b/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistry.java @@ -0,0 +1,292 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.registry.sofa; + +import com.alipay.sofa.registry.client.api.RegistryClient; +import com.alipay.sofa.registry.client.api.RegistryClientConfig; +import com.alipay.sofa.registry.client.api.Subscriber; +import com.alipay.sofa.registry.client.api.model.RegistryType; +import com.alipay.sofa.registry.client.api.model.UserData; +import com.alipay.sofa.registry.client.api.registration.PublisherRegistration; +import com.alipay.sofa.registry.client.api.registration.SubscriberRegistration; +import com.alipay.sofa.registry.client.provider.DefaultRegistryClient; +import com.alipay.sofa.registry.client.provider.DefaultRegistryClientConfigBuilder; +import com.alipay.sofa.registry.core.model.ScopeEnum; +import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.common.utils.ConfigUtils; +import org.apache.dubbo.common.utils.StringUtils; +import org.apache.dubbo.registry.NotifyListener; +import org.apache.dubbo.registry.support.FailbackRegistry; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import static org.apache.dubbo.registry.sofa.SofaRegistryConstants.ADDRESS_WAIT_TIME_KEY; +import static org.apache.dubbo.registry.sofa.SofaRegistryConstants.DEFAULT_GROUP; +import static org.apache.dubbo.registry.sofa.SofaRegistryConstants.LOCAL_DATA_CENTER; +import static org.apache.dubbo.registry.sofa.SofaRegistryConstants.LOCAL_REGION; + +/** + * The Sofa registry. + * + * @since 2.7.2 + */ +public class SofaRegistry extends FailbackRegistry { + + private static final Logger LOGGER = LoggerFactory.getLogger(SofaRegistry.class); + + /** + * Cache subscriber by dataId + */ + private final Map subscribers = new ConcurrentHashMap<>(); + + /** + * Direct registry client + */ + private RegistryClient registryClient; + /** + * wait address from registry + */ + private int waitAddressTimeout; + + /** + * Instantiates a new Sofa registry. + * + * @param url the url + */ + public SofaRegistry(URL url) { + super(url); + if (LOGGER.isInfoEnabled()) { + LOGGER.info("Build sofa registry by url:" + url); + } + this.registryClient = buildClient(url); + this.waitAddressTimeout = Integer.parseInt(ConfigUtils.getProperty(ADDRESS_WAIT_TIME_KEY, "5000")); + } + + /** + * Build client registry client. + * + * @param url the url + * @return the registry client + */ + protected RegistryClient buildClient(URL url) { + RegistryClientConfig config = DefaultRegistryClientConfigBuilder.start() + .setDataCenter(LOCAL_DATA_CENTER) + .setZone(LOCAL_REGION) + .setRegistryEndpoint(url.getHost()) + .setRegistryEndpointPort(url.getPort()).build(); + + DefaultRegistryClient registryClient = new DefaultRegistryClient(config); + registryClient.init(); + return registryClient; + } + + @Override + public boolean isAvailable() { + return true; + } + + @Override + public void doRegister(URL url) { + if (!url.getParameter(Constants.REGISTER_KEY, true) + || Constants.CONSUMER_PROTOCOL.equals(url.getProtocol())) { + return; + } + + String serviceName = buildServiceName(url); + String serviceData = url.toFullString(); + + PublisherRegistration registration = new PublisherRegistration(serviceName); + addAttributesForPub(registration); + + registryClient.register(registration, serviceData); + } + + /** + * Add attributes for pub. + * + * @param publisherRegistration the publisher registration + */ + protected void addAttributesForPub(PublisherRegistration publisherRegistration) { + publisherRegistration.setGroup(DEFAULT_GROUP); + } + + @Override + public void doUnregister(URL url) { + if (!url.getParameter(Constants.REGISTER_KEY, true) + || Constants.CONSUMER_PROTOCOL.equals(url.getProtocol())) { + return; + } + String serviceName = buildServiceName(url); + registryClient.unregister(serviceName, DEFAULT_GROUP, RegistryType.PUBLISHER); + } + + @Override + public void doSubscribe(URL url, final NotifyListener listener) { + if (!url.getParameter(Constants.SUBSCRIBE_KEY, true) + || Constants.PROVIDER_PROTOCOL.equals(url.getProtocol())) { + return; + } + + String serviceName = buildServiceName(url); + // com.alipay.test.TestService:1.0:group@dubbo + Subscriber listSubscriber = subscribers.get(serviceName); + + if (listSubscriber != null) { + LOGGER.warn("Service name [" + serviceName + "] have bean registered in SOFARegistry."); + + CountDownLatch countDownLatch = new CountDownLatch(1); + handleRegistryData(listSubscriber.peekData(), listener, countDownLatch); + waitAddress(serviceName, countDownLatch); + return; + } + + final CountDownLatch latch = new CountDownLatch(1); + SubscriberRegistration subscriberRegistration = new SubscriberRegistration(serviceName, + (dataId, data) -> { + //record change + printAddressData(dataId, data); + handleRegistryData(data, listener, latch); + }); + + addAttributesForSub(subscriberRegistration); + listSubscriber = registryClient.register(subscriberRegistration); + + subscribers.put(serviceName, listSubscriber); + + waitAddress(serviceName, latch); + } + + private void waitAddress(String serviceName, CountDownLatch countDownLatch) { + try { + if (!countDownLatch.await(waitAddressTimeout, TimeUnit.MILLISECONDS)) { + LOGGER.warn("Subscribe data failed by dataId " + serviceName); + } + } catch (Exception e) { + LOGGER.error("Error when wait Address!", e); + } + } + + @Override + public void doUnsubscribe(URL url, NotifyListener listener) { + if (!url.getParameter(Constants.SUBSCRIBE_KEY, true) + || Constants.PROVIDER_PROTOCOL.equals(url.getProtocol())) { + return; + } + String serviceName = buildServiceName(url); + + registryClient.unregister(serviceName, DEFAULT_GROUP, RegistryType.SUBSCRIBER); + } + + private void handleRegistryData(UserData data, NotifyListener notifyListener, + CountDownLatch latch) { + try { + List urls = new ArrayList<>(); + if (null != data) { + + List datas = flatUserData(data); + for (String serviceUrl : datas) { + URL url = URL.valueOf(serviceUrl); + String serverApplication = url.getParameter(Constants.APPLICATION_KEY); + if (StringUtils.isNotEmpty(serverApplication)) { + url = url.addParameter("dstApp", serverApplication); + } + urls.add(url); + } + } + notifyListener.notify(urls); + } finally { + latch.countDown(); + } + } + + private String buildServiceName(URL url) { + // return url.getServiceKey(); + StringBuilder buf = new StringBuilder(); + buf.append(url.getServiceInterface()); + String version = url.getParameter(Constants.VERSION_KEY); + if (StringUtils.isNotEmpty(version)) { + buf.append(":").append(version); + } + String group = url.getParameter(Constants.GROUP_KEY); + if (StringUtils.isNotEmpty(group)) { + buf.append(":").append(group); + } + buf.append("@").append(Constants.DUBBO); + return buf.toString(); + } + + /** + * Print address data. + * + * @param dataId the data id + * @param userData the user data + */ + protected void printAddressData(String dataId, UserData userData) { + + List datas; + if (userData == null) { + datas = new ArrayList<>(0); + } else { + datas = flatUserData(userData); + } + + StringBuilder sb = new StringBuilder(); + for (String provider : datas) { + sb.append(" >>> ").append(provider).append("\n"); + } + if (LOGGER.isInfoEnabled()) { + LOGGER.info("Receive updated RPC service addresses: service[" + dataId + + "]\n .Available target addresses size [" + datas.size() + "]\n" + + sb.toString()); + } + } + + /** + * Add attributes for sub. + * + * @param subscriberRegistration the subscriber registration + */ + protected void addAttributesForSub(SubscriberRegistration subscriberRegistration) { + subscriberRegistration.setGroup(DEFAULT_GROUP); + subscriberRegistration.setScopeEnum(ScopeEnum.global); + } + + /** + * Flat user data list. + * + * @param userData the user data + * @return the list + */ + protected List flatUserData(UserData userData) { + List result = new ArrayList<>(); + Map> zoneData = userData.getZoneData(); + + for (Map.Entry> entry : zoneData.entrySet()) { + result.addAll(entry.getValue()); + } + + return result; + } +} diff --git a/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistryConstants.java b/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistryConstants.java new file mode 100644 index 00000000000..f832e802f60 --- /dev/null +++ b/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistryConstants.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.registry.sofa; + +/** + * @since 2.7.2 + */ +public class SofaRegistryConstants { + + /** + * Default data center + */ + public static final String LOCAL_DATA_CENTER = "DefaultDataCenter"; + + /** + * Default region + */ + public static final String LOCAL_REGION = "DEFAULT_ZONE"; + + /** + * Default group + */ + public static final String DEFAULT_GROUP = "SOFA"; + + /** + * parameter for address.wait.time of rpc reference + */ + public static final String ADDRESS_WAIT_TIME_KEY = "rpc.reference.address.wait.time"; +} diff --git a/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistryFactory.java b/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistryFactory.java new file mode 100644 index 00000000000..18a7809ea58 --- /dev/null +++ b/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistryFactory.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.registry.sofa; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.registry.Registry; +import org.apache.dubbo.registry.support.AbstractRegistryFactory; + +/** + * @since 2.7.2 + */ +public class SofaRegistryFactory extends AbstractRegistryFactory { + + @Override + protected Registry createRegistry(URL url) { + initEnvironment(url); + return new SofaRegistry(url); + } + + /** + * For extension, such as load zone/accessKey/secretKey/... + * + * @param url URL + */ + protected void initEnvironment(URL url) { + } +} diff --git a/dubbo-registry/dubbo-registry-sofa/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory b/dubbo-registry/dubbo-registry-sofa/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory new file mode 100644 index 00000000000..dff4cbb8c52 --- /dev/null +++ b/dubbo-registry/dubbo-registry-sofa/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory @@ -0,0 +1 @@ +sofa=org.apache.dubbo.registry.sofa.SofaRegistryFactory \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-sofa/src/test/java/org/apache/dubbo/registry/sofa/HelloService.java b/dubbo-registry/dubbo-registry-sofa/src/test/java/org/apache/dubbo/registry/sofa/HelloService.java new file mode 100644 index 00000000000..cc66a5ede58 --- /dev/null +++ b/dubbo-registry/dubbo-registry-sofa/src/test/java/org/apache/dubbo/registry/sofa/HelloService.java @@ -0,0 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.registry.sofa; + +/** + */ +public interface HelloService { + + String sayHello(String name); +} diff --git a/dubbo-registry/dubbo-registry-sofa/src/test/java/org/apache/dubbo/registry/sofa/HelloServiceImpl.java b/dubbo-registry/dubbo-registry-sofa/src/test/java/org/apache/dubbo/registry/sofa/HelloServiceImpl.java new file mode 100644 index 00000000000..a9fb0ca7075 --- /dev/null +++ b/dubbo-registry/dubbo-registry-sofa/src/test/java/org/apache/dubbo/registry/sofa/HelloServiceImpl.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.registry.sofa; + +import com.alipay.sofa.registry.server.test.TestRegistryMain; + +/** + */ +public class HelloServiceImpl implements HelloService { + + private final String result; + + public HelloServiceImpl(String result) { + this.result = result; + } + + @Override + public String sayHello(String name) { + return result != null ? result : "hello, " + name + "!"; + } + + public static void main(String[] args) { + TestRegistryMain registryMain = new TestRegistryMain(); + try { + registryMain.startRegistry(); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/dubbo-registry/dubbo-registry-sofa/src/test/java/org/apache/dubbo/registry/sofa/SofaRegistryTest.java b/dubbo-registry/dubbo-registry-sofa/src/test/java/org/apache/dubbo/registry/sofa/SofaRegistryTest.java new file mode 100644 index 00000000000..4d67b7465e3 --- /dev/null +++ b/dubbo-registry/dubbo-registry-sofa/src/test/java/org/apache/dubbo/registry/sofa/SofaRegistryTest.java @@ -0,0 +1,148 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.registry.sofa; + +import com.alipay.sofa.registry.server.test.TestRegistryMain; +import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.config.ApplicationConfig; +import org.apache.dubbo.config.ProtocolConfig; +import org.apache.dubbo.config.ReferenceConfig; +import org.apache.dubbo.config.RegistryConfig; +import org.apache.dubbo.config.ServiceConfig; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +/** + */ +public class SofaRegistryTest { + + public static final Logger LOGGER = LoggerFactory.getLogger(SofaRegistryTest.class); + + private static TestRegistryMain registryMain; + + private static ApplicationConfig applicationConfig = new ApplicationConfig("test-sofa-registry"); + + private static ProtocolConfig protocolConfig1; + + private static ProtocolConfig protocolConfig2; + + private static RegistryConfig registryConfig; + + @BeforeAll + public static void beforeClass() { + + protocolConfig1 = new ProtocolConfig(); + protocolConfig1.setName("dubbo"); + protocolConfig1.setPort(20890); + + protocolConfig2 = new ProtocolConfig(); + protocolConfig2.setName("dubbo"); + protocolConfig2.setPort(20891); + + registryConfig = new RegistryConfig(); + registryConfig.setAddress("sofa://127.0.0.1:9603"); + registryConfig.setProtocol("sofa"); + + registryMain = new TestRegistryMain(); + try { + registryMain.startRegistry(); + } catch (Exception e) { + LOGGER.error("start test sofa registry error!", e); + } + } + + @Test + public void testPubAndSub() throws InterruptedException { + + ServiceConfig serviceConfig1 = new ServiceConfig<>(); + serviceConfig1.setInterface(HelloService.class); + serviceConfig1.setRef(new HelloServiceImpl("rrr11")); + serviceConfig1.setProtocol(protocolConfig1); + serviceConfig1.setRegistry(registryConfig); + serviceConfig1.setGroup("g1"); + serviceConfig1.setApplication(applicationConfig); + serviceConfig1.export(); + + ServiceConfig serviceConfig2 = new ServiceConfig<>(); + serviceConfig2.setInterface(HelloService.class); + serviceConfig2.setRef(new HelloServiceImpl("rrr22")); + serviceConfig2.setProtocol(protocolConfig1); + serviceConfig2.setRegistry(registryConfig); + serviceConfig2.setGroup("g2"); + serviceConfig2.setApplication(applicationConfig); + serviceConfig2.setRegister(false); + serviceConfig2.export(); + + Thread.sleep(1000); + + // do refer + ReferenceConfig referenceConfig1 = new ReferenceConfig<>(); + referenceConfig1.setInterface(HelloService.class); + referenceConfig1.setProtocol("dubbo"); + referenceConfig1.setInjvm(false); + referenceConfig1.setGroup("g1"); + referenceConfig1.setRegistry(registryConfig); + referenceConfig1.setApplication(applicationConfig); + HelloService service = referenceConfig1.get(); + Assertions.assertEquals("rrr11", service.sayHello("xxx")); + + // do refer duplicated + ReferenceConfig referenceConfig2 = new ReferenceConfig<>(); + referenceConfig2.setInterface(HelloService.class); + referenceConfig2.setProtocol("dubbo"); + referenceConfig2.setInjvm(false); + referenceConfig2.setGroup("g1"); + referenceConfig2.setRegistry(registryConfig); + referenceConfig2.setApplication(applicationConfig); + HelloService service2 = referenceConfig2.get(); + Assertions.assertEquals("rrr11", service2.sayHello("xxx")); + + // export one service + ServiceConfig serviceConfig3 = new ServiceConfig<>(); + serviceConfig3.setInterface(HelloService.class); + serviceConfig3.setRef(new HelloServiceImpl("rrr12")); + serviceConfig3.setProtocol(protocolConfig2); + serviceConfig3.setRegistry(registryConfig); + serviceConfig3.setGroup("g1"); + serviceConfig3.setApplication(applicationConfig); + serviceConfig3.export(); + Assertions.assertTrue(service2.sayHello("xxx").startsWith("rrr1")); + + // unrefer + referenceConfig1.destroy(); + Assertions.assertTrue(service2.sayHello("xxx").startsWith("rrr1")); + + // unexport one service + serviceConfig1.unexport(); + Thread.sleep(2000); + Assertions.assertTrue(service2.sayHello("xxx").startsWith("rrr1")); + } + + @AfterAll + public static void afterClass() { + try { + registryMain.stopRegistry(); + protocolConfig1.destroy(); + } catch (Exception e) { + LOGGER.error("Stop test sofa registry error!", e); + } + } + +} \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-sofa/src/test/resources/log4j.properties b/dubbo-registry/dubbo-registry-sofa/src/test/resources/log4j.properties new file mode 100644 index 00000000000..15a0900f0d2 --- /dev/null +++ b/dubbo-registry/dubbo-registry-sofa/src/test/resources/log4j.properties @@ -0,0 +1,7 @@ +###set log levels### +log4j.rootLogger=info, stdout +###output to the console### +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d{dd/MM/yy HH:mm:ss:SSS z}] %t %5p %c{2}: %m%n \ No newline at end of file diff --git a/dubbo-registry/pom.xml b/dubbo-registry/pom.xml index c9c3441ca25..962148b354a 100644 --- a/dubbo-registry/pom.xml +++ b/dubbo-registry/pom.xml @@ -37,5 +37,6 @@ dubbo-registry-consul dubbo-registry-etcd3 dubbo-registry-nacos + dubbo-registry-sofa diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java index ceef6ccf774..564505a5837 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java @@ -19,6 +19,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.ClassUtils; +import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Codec2; import org.apache.dubbo.remoting.buffer.ChannelBuffer; @@ -29,8 +30,6 @@ import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.protocol.thrift.io.RandomAccessByteArrayOutputStream; - -import org.apache.commons.lang.StringUtils; import org.apache.thrift.TApplicationException; import org.apache.thrift.TBase; import org.apache.thrift.TException; From 70edcf80e95f73390ece1527e982e1e9fa04037b Mon Sep 17 00:00:00 2001 From: jimin Date: Sun, 5 May 2019 14:01:35 +0800 Subject: [PATCH 018/115] optimize constant naming style (#3970) --- .../rpc/cluster/merger/MergerFactory.java | 12 ++++----- .../apache/dubbo/common/bytecode/Proxy.java | 12 ++++----- .../threadlocal/InternalThreadLocal.java | 10 +++---- .../threadlocal/InternalThreadLocalMap.java | 8 +++--- .../common/utils/AtomicPositiveInteger.java | 26 +++++++++---------- .../dubbo/common/utils/ExecutorUtil.java | 4 +-- .../apache/dubbo/common/utils/NetUtils.java | 6 ++--- .../apache/dubbo/config/AbstractConfig.java | 18 ++++++------- .../dubbo/config/DubboShutdownHook.java | 4 +-- .../apache/dubbo/config/ReferenceConfig.java | 20 +++++++------- .../dubbo/config/context/ConfigManager.java | 4 +-- .../config/utils/ReferenceConfigCache.java | 8 +++--- .../utils/ReferenceConfigCacheTest.java | 2 +- .../extension/SpringExtensionFactory.java | 18 ++++++------- .../integration/RegistryDirectory.java | 18 ++++++------- .../remoting/http/servlet/ServletManager.java | 4 +-- .../remoting/transport/mina/MinaClient.java | 6 ++--- .../transport/netty/NettyChannel.java | 8 +++--- .../remoting/transport/netty/NettyClient.java | 4 +-- .../transport/netty4/NettyChannel.java | 8 +++--- .../curator/CuratorZookeeperClient.java | 12 ++++----- .../dubbo/rpc/filter/AccessLogFilter.java | 12 ++++----- .../dubbo/rpc/model/ApplicationModel.java | 20 +++++++------- .../protocol/dubbo/CallbackServiceCodec.java | 6 ++--- .../protocol/http/HttpRemoteInvocation.java | 6 ++--- .../rpc/protocol/thrift/ThriftCodec.java | 24 ++++++++--------- .../dubbo/rpc/protocol/thrift/ThriftType.java | 6 ++--- .../rpc/protocol/thrift/ThriftCodecTest.java | 4 +-- .../support/SerializableClassRegistry.java | 6 ++--- 29 files changed, 148 insertions(+), 148 deletions(-) diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/MergerFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/MergerFactory.java index 845d21a6cd0..74789bbe911 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/MergerFactory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/MergerFactory.java @@ -27,7 +27,7 @@ public class MergerFactory { - private static final ConcurrentMap, Merger> mergerCache = + private static final ConcurrentMap, Merger> MERGER_CACHE = new ConcurrentHashMap, Merger>(); /** @@ -46,19 +46,19 @@ public static Merger getMerger(Class returnType) { Merger result; if (returnType.isArray()) { Class type = returnType.getComponentType(); - result = mergerCache.get(type); + result = MERGER_CACHE.get(type); if (result == null) { loadMergers(); - result = mergerCache.get(type); + result = MERGER_CACHE.get(type); } if (result == null && !type.isPrimitive()) { result = ArrayMerger.INSTANCE; } } else { - result = mergerCache.get(returnType); + result = MERGER_CACHE.get(returnType); if (result == null) { loadMergers(); - result = mergerCache.get(returnType); + result = MERGER_CACHE.get(returnType); } } return result; @@ -69,7 +69,7 @@ static void loadMergers() { .getSupportedExtensions(); for (String name : names) { Merger m = ExtensionLoader.getExtensionLoader(Merger.class).getExtension(name); - mergerCache.putIfAbsent(ReflectUtils.getGenericClass(m.getClass()), m); + MERGER_CACHE.putIfAbsent(ReflectUtils.getGenericClass(m.getClass()), m); } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Proxy.java b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Proxy.java index 8381bd20ca0..8486e94b34e 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Proxy.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Proxy.java @@ -48,9 +48,9 @@ public Object invoke(Object proxy, Method method, Object[] args) { }; private static final AtomicLong PROXY_CLASS_COUNTER = new AtomicLong(0); private static final String PACKAGE_NAME = Proxy.class.getPackage().getName(); - private static final Map> ProxyCacheMap = new WeakHashMap>(); + private static final Map> PROXY_CACHE_MAP = new WeakHashMap>(); - private static final Object PendingGenerationMarker = new Object(); + private static final Object PENDING_GENERATION_MARKER = new Object(); protected Proxy() { } @@ -102,8 +102,8 @@ public static Proxy getProxy(ClassLoader cl, Class... ics) { // get cache by class loader. Map cache; - synchronized (ProxyCacheMap) { - cache = ProxyCacheMap.computeIfAbsent(cl, k -> new HashMap<>()); + synchronized (PROXY_CACHE_MAP) { + cache = PROXY_CACHE_MAP.computeIfAbsent(cl, k -> new HashMap<>()); } Proxy proxy = null; @@ -117,13 +117,13 @@ public static Proxy getProxy(ClassLoader cl, Class... ics) { } } - if (value == PendingGenerationMarker) { + if (value == PENDING_GENERATION_MARKER) { try { cache.wait(); } catch (InterruptedException e) { } } else { - cache.put(key, PendingGenerationMarker); + cache.put(key, PENDING_GENERATION_MARKER); break; } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalThreadLocal.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalThreadLocal.java index ac887e45305..8820f12cc2f 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalThreadLocal.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalThreadLocal.java @@ -33,7 +33,7 @@ */ public class InternalThreadLocal { - private static final int variablesToRemoveIndex = InternalThreadLocalMap.nextVariableIndex(); + private static final int VARIABLES_TO_REMOVE_INDEX = InternalThreadLocalMap.nextVariableIndex(); private final int index; @@ -54,7 +54,7 @@ public static void removeAll() { } try { - Object v = threadLocalMap.indexedVariable(variablesToRemoveIndex); + Object v = threadLocalMap.indexedVariable(VARIABLES_TO_REMOVE_INDEX); if (v != null && v != InternalThreadLocalMap.UNSET) { Set> variablesToRemove = (Set>) v; InternalThreadLocal[] variablesToRemoveArray = @@ -86,11 +86,11 @@ public static void destroy() { @SuppressWarnings("unchecked") private static void addToVariablesToRemove(InternalThreadLocalMap threadLocalMap, InternalThreadLocal variable) { - Object v = threadLocalMap.indexedVariable(variablesToRemoveIndex); + Object v = threadLocalMap.indexedVariable(VARIABLES_TO_REMOVE_INDEX); Set> variablesToRemove; if (v == InternalThreadLocalMap.UNSET || v == null) { variablesToRemove = Collections.newSetFromMap(new IdentityHashMap, Boolean>()); - threadLocalMap.setIndexedVariable(variablesToRemoveIndex, variablesToRemove); + threadLocalMap.setIndexedVariable(VARIABLES_TO_REMOVE_INDEX, variablesToRemove); } else { variablesToRemove = (Set>) v; } @@ -101,7 +101,7 @@ private static void addToVariablesToRemove(InternalThreadLocalMap threadLocalMap @SuppressWarnings("unchecked") private static void removeFromVariablesToRemove(InternalThreadLocalMap threadLocalMap, InternalThreadLocal variable) { - Object v = threadLocalMap.indexedVariable(variablesToRemoveIndex); + Object v = threadLocalMap.indexedVariable(VARIABLES_TO_REMOVE_INDEX); if (v == InternalThreadLocalMap.UNSET || v == null) { return; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalThreadLocalMap.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalThreadLocalMap.java index 46d9ec48054..9b38eb484fe 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalThreadLocalMap.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalThreadLocalMap.java @@ -30,7 +30,7 @@ public final class InternalThreadLocalMap { private static ThreadLocal slowThreadLocalMap = new ThreadLocal(); - private static final AtomicInteger nextIndex = new AtomicInteger(); + private static final AtomicInteger NEXT_INDEX = new AtomicInteger(); public static final Object UNSET = new Object(); @@ -64,16 +64,16 @@ public static void destroy() { } public static int nextVariableIndex() { - int index = nextIndex.getAndIncrement(); + int index = NEXT_INDEX.getAndIncrement(); if (index < 0) { - nextIndex.decrementAndGet(); + NEXT_INDEX.decrementAndGet(); throw new IllegalStateException("Too many thread-local indexed variables"); } return index; } public static int lastVariableIndex() { - return nextIndex.get() - 1; + return NEXT_INDEX.get() - 1; } private InternalThreadLocalMap() { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/AtomicPositiveInteger.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/AtomicPositiveInteger.java index 4a13c6c4acd..63b9ab8d119 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/AtomicPositiveInteger.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/AtomicPositiveInteger.java @@ -22,7 +22,7 @@ public class AtomicPositiveInteger extends Number { private static final long serialVersionUID = -3038533876489105940L; - private static final AtomicIntegerFieldUpdater indexUpdater = + private static final AtomicIntegerFieldUpdater INDEX_UPDATER = AtomicIntegerFieldUpdater.newUpdater(AtomicPositiveInteger.class, "index"); @SuppressWarnings("unused") @@ -32,69 +32,69 @@ public AtomicPositiveInteger() { } public AtomicPositiveInteger(int initialValue) { - indexUpdater.set(this, initialValue); + INDEX_UPDATER.set(this, initialValue); } public final int getAndIncrement() { - return indexUpdater.getAndIncrement(this) & Integer.MAX_VALUE; + return INDEX_UPDATER.getAndIncrement(this) & Integer.MAX_VALUE; } public final int getAndDecrement() { - return indexUpdater.getAndDecrement(this) & Integer.MAX_VALUE; + return INDEX_UPDATER.getAndDecrement(this) & Integer.MAX_VALUE; } public final int incrementAndGet() { - return indexUpdater.incrementAndGet(this) & Integer.MAX_VALUE; + return INDEX_UPDATER.incrementAndGet(this) & Integer.MAX_VALUE; } public final int decrementAndGet() { - return indexUpdater.decrementAndGet(this) & Integer.MAX_VALUE; + return INDEX_UPDATER.decrementAndGet(this) & Integer.MAX_VALUE; } public final int get() { - return indexUpdater.get(this) & Integer.MAX_VALUE; + return INDEX_UPDATER.get(this) & Integer.MAX_VALUE; } public final void set(int newValue) { if (newValue < 0) { throw new IllegalArgumentException("new value " + newValue + " < 0"); } - indexUpdater.set(this, newValue); + INDEX_UPDATER.set(this, newValue); } public final int getAndSet(int newValue) { if (newValue < 0) { throw new IllegalArgumentException("new value " + newValue + " < 0"); } - return indexUpdater.getAndSet(this, newValue) & Integer.MAX_VALUE; + return INDEX_UPDATER.getAndSet(this, newValue) & Integer.MAX_VALUE; } public final int getAndAdd(int delta) { if (delta < 0) { throw new IllegalArgumentException("delta " + delta + " < 0"); } - return indexUpdater.getAndAdd(this, delta) & Integer.MAX_VALUE; + return INDEX_UPDATER.getAndAdd(this, delta) & Integer.MAX_VALUE; } public final int addAndGet(int delta) { if (delta < 0) { throw new IllegalArgumentException("delta " + delta + " < 0"); } - return indexUpdater.addAndGet(this, delta) & Integer.MAX_VALUE; + return INDEX_UPDATER.addAndGet(this, delta) & Integer.MAX_VALUE; } public final boolean compareAndSet(int expect, int update) { if (update < 0) { throw new IllegalArgumentException("update value " + update + " < 0"); } - return indexUpdater.compareAndSet(this, expect, update); + return INDEX_UPDATER.compareAndSet(this, expect, update); } public final boolean weakCompareAndSet(int expect, int update) { if (update < 0) { throw new IllegalArgumentException("update value " + update + " < 0"); } - return indexUpdater.weakCompareAndSet(this, expect, update); + return INDEX_UPDATER.weakCompareAndSet(this, expect, update); } @Override diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ExecutorUtil.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ExecutorUtil.java index 14408dacf64..c342ed2e713 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ExecutorUtil.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ExecutorUtil.java @@ -30,7 +30,7 @@ public class ExecutorUtil { private static final Logger logger = LoggerFactory.getLogger(ExecutorUtil.class); - private static final ThreadPoolExecutor shutdownExecutor = new ThreadPoolExecutor(0, 1, + private static final ThreadPoolExecutor SHUTDOWN_EXECUTOR = new ThreadPoolExecutor(0, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(100), new NamedThreadFactory("Close-ExecutorService-Timer", true)); @@ -102,7 +102,7 @@ public static void shutdownNow(Executor executor, final int timeout) { private static void newThreadToCloseExecutor(final ExecutorService es) { if (!isTerminated(es)) { - shutdownExecutor.execute(new Runnable() { + SHUTDOWN_EXECUTOR.execute(new Runnable() { @Override public void run() { try { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java index f03d91a0d5a..3119e5c189a 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java @@ -55,7 +55,7 @@ public class NetUtils { private static final Pattern LOCAL_IP_PATTERN = Pattern.compile("127(\\.\\d{1,3}){3}$"); private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$"); - private static final Map hostNameCache = new LRUCache<>(1000); + private static final Map HOST_NAME_CACHE = new LRUCache<>(1000); private static volatile InetAddress LOCAL_ADDRESS = null; private static final String SPLIT_IPV4_CHARECTER = "\\."; @@ -291,14 +291,14 @@ public static String getHostName(String address) { if (i > -1) { address = address.substring(0, i); } - String hostname = hostNameCache.get(address); + String hostname = HOST_NAME_CACHE.get(address); if (hostname != null && hostname.length() > 0) { return hostname; } InetAddress inetAddress = InetAddress.getByName(address); if (inetAddress != null) { hostname = inetAddress.getHostName(); - hostNameCache.put(address, hostname); + HOST_NAME_CACHE.put(address, hostname); return hostname; } } catch (Throwable e) { diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractConfig.java index 30b3f50daf5..50fb55ed0ab 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractConfig.java @@ -95,7 +95,7 @@ public abstract class AbstractConfig implements Serializable { /** * The legacy properties container */ - private static final Map legacyProperties = new HashMap(); + private static final Map LEGACY_PROPERTIES = new HashMap(); /** * The suffix container @@ -103,14 +103,14 @@ public abstract class AbstractConfig implements Serializable { private static final String[] SUFFIXES = new String[]{"Config", "Bean"}; static { - legacyProperties.put("dubbo.protocol.name", "dubbo.service.protocol"); - legacyProperties.put("dubbo.protocol.host", "dubbo.service.server.host"); - legacyProperties.put("dubbo.protocol.port", "dubbo.service.server.port"); - legacyProperties.put("dubbo.protocol.threads", "dubbo.service.max.thread.pool.size"); - legacyProperties.put("dubbo.consumer.timeout", "dubbo.service.invoke.timeout"); - legacyProperties.put("dubbo.consumer.retries", "dubbo.service.max.retry.providers"); - legacyProperties.put("dubbo.consumer.check", "dubbo.service.allow.no.provider"); - legacyProperties.put("dubbo.service.url", "dubbo.service.address"); + LEGACY_PROPERTIES.put("dubbo.protocol.name", "dubbo.service.protocol"); + LEGACY_PROPERTIES.put("dubbo.protocol.host", "dubbo.service.server.host"); + LEGACY_PROPERTIES.put("dubbo.protocol.port", "dubbo.service.server.port"); + LEGACY_PROPERTIES.put("dubbo.protocol.threads", "dubbo.service.max.thread.pool.size"); + LEGACY_PROPERTIES.put("dubbo.consumer.timeout", "dubbo.service.invoke.timeout"); + LEGACY_PROPERTIES.put("dubbo.consumer.retries", "dubbo.service.max.retry.providers"); + LEGACY_PROPERTIES.put("dubbo.consumer.check", "dubbo.service.allow.no.provider"); + LEGACY_PROPERTIES.put("dubbo.service.url", "dubbo.service.address"); // this is only for compatibility DubboShutdownHook.getDubboShutdownHook().register(); diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/DubboShutdownHook.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/DubboShutdownHook.java index 22d50dd05d4..47c035e293c 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/DubboShutdownHook.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/DubboShutdownHook.java @@ -34,7 +34,7 @@ public class DubboShutdownHook extends Thread { private static final Logger logger = LoggerFactory.getLogger(DubboShutdownHook.class); - private static final DubboShutdownHook dubboShutdownHook = new DubboShutdownHook("DubboShutdownHook"); + private static final DubboShutdownHook DUBBO_SHUTDOWN_HOOK = new DubboShutdownHook("DubboShutdownHook"); /** * Has it already been registered or not? */ @@ -49,7 +49,7 @@ private DubboShutdownHook(String name) { } public static DubboShutdownHook getDubboShutdownHook() { - return dubboShutdownHook; + return DUBBO_SHUTDOWN_HOOK; } @Override diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java index e1df3193c13..4c379375b6e 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java @@ -80,19 +80,19 @@ public class ReferenceConfig extends AbstractReferenceConfig { * Actually,when the {@link ExtensionLoader} init the {@link Protocol} instants,it will automatically wraps two * layers, and eventually will get a ProtocolFilterWrapper or ProtocolListenerWrapper */ - private static final Protocol refprotocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); + private static final Protocol REF_PROTOCOL = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); /** * The {@link Cluster}'s implementation with adaptive functionality, and actually it will get a {@link Cluster}'s * specific implementation who is wrapped with MockClusterInvoker */ - private static final Cluster cluster = ExtensionLoader.getExtensionLoader(Cluster.class).getAdaptiveExtension(); + private static final Cluster CLUSTER = ExtensionLoader.getExtensionLoader(Cluster.class).getAdaptiveExtension(); /** * A {@link ProxyFactory} implementation that will generate a reference service's proxy,the JavassistProxyFactory is * its default implementation */ - private static final ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + private static final ProxyFactory PROXY_FACTORY = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); /** * The url of the reference service @@ -333,7 +333,7 @@ private ConsumerModel buildConsumerModel(String serviceKey, Map private T createProxy(Map map) { if (shouldJvmRefer(map)) { URL url = new URL(Constants.LOCAL_PROTOCOL, Constants.LOCALHOST_VALUE, 0, interfaceClass.getName()).addParameters(map); - invoker = refprotocol.refer(interfaceClass, url); + invoker = REF_PROTOCOL.refer(interfaceClass, url); if (logger.isInfoEnabled()) { logger.info("Using injvm service " + interfaceClass.getName()); } @@ -371,23 +371,23 @@ private T createProxy(Map map) { } if (urls.size() == 1) { - invoker = refprotocol.refer(interfaceClass, urls.get(0)); + invoker = REF_PROTOCOL.refer(interfaceClass, urls.get(0)); } else { List> invokers = new ArrayList>(); URL registryURL = null; for (URL url : urls) { - invokers.add(refprotocol.refer(interfaceClass, url)); + invokers.add(REF_PROTOCOL.refer(interfaceClass, url)); if (Constants.REGISTRY_PROTOCOL.equals(url.getProtocol())) { registryURL = url; // use last registry url } } if (registryURL != null) { // registry url is available - // use RegistryAwareCluster only when register's cluster is available + // use RegistryAwareCluster only when register's CLUSTER is available URL u = registryURL.addParameter(Constants.CLUSTER_KEY, RegistryAwareCluster.NAME); // The invoker wrap relation would be: RegistryAwareClusterInvoker(StaticDirectory) -> FailoverClusterInvoker(RegistryDirectory, will execute route) -> Invoker - invoker = cluster.join(new StaticDirectory(u, invokers)); + invoker = CLUSTER.join(new StaticDirectory(u, invokers)); } else { // not a registry url, must be direct invoke. - invoker = cluster.join(new StaticDirectory(invokers)); + invoker = CLUSTER.join(new StaticDirectory(invokers)); } } } @@ -410,7 +410,7 @@ private T createProxy(Map map) { metadataReportService.publishConsumer(consumerURL); } // create service proxy - return (T) proxyFactory.getProxy(invoker); + return (T) PROXY_FACTORY.getProxy(invoker); } /** diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/context/ConfigManager.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/context/ConfigManager.java index ae16ef961a2..808fd9cdc57 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/context/ConfigManager.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/context/ConfigManager.java @@ -73,7 +73,7 @@ */ public class ConfigManager { private static final Logger logger = LoggerFactory.getLogger(ConfigManager.class); - private static final ConfigManager configManager = new ConfigManager(); + private static final ConfigManager CONFIG_MANAGER = new ConfigManager(); private ApplicationConfig application; private MonitorConfig monitor; @@ -86,7 +86,7 @@ public class ConfigManager { private Map consumers = new ConcurrentHashMap<>(); public static ConfigManager getInstance() { - return configManager; + return CONFIG_MANAGER; } private ConfigManager() { diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/ReferenceConfigCache.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/ReferenceConfigCache.java index 09f12dadeca..0891a767aba 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/ReferenceConfigCache.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/ReferenceConfigCache.java @@ -59,7 +59,7 @@ public class ReferenceConfigCache { } return ret.toString(); }; - static final ConcurrentMap cacheHolder = new ConcurrentHashMap(); + static final ConcurrentMap CACHE_HOLDER = new ConcurrentHashMap(); private final String name; private final KeyGenerator generator; ConcurrentMap> cache = new ConcurrentHashMap>(); @@ -90,12 +90,12 @@ public static ReferenceConfigCache getCache(String name) { * Create cache if not existed yet. */ public static ReferenceConfigCache getCache(String name, KeyGenerator keyGenerator) { - ReferenceConfigCache cache = cacheHolder.get(name); + ReferenceConfigCache cache = CACHE_HOLDER.get(name); if (cache != null) { return cache; } - cacheHolder.putIfAbsent(name, new ReferenceConfigCache(name, keyGenerator)); - return cacheHolder.get(name); + CACHE_HOLDER.putIfAbsent(name, new ReferenceConfigCache(name, keyGenerator)); + return CACHE_HOLDER.get(name); } @SuppressWarnings("unchecked") diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/ReferenceConfigCacheTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/ReferenceConfigCacheTest.java index 2af6da720ec..656d2af382d 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/ReferenceConfigCacheTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/ReferenceConfigCacheTest.java @@ -27,7 +27,7 @@ public class ReferenceConfigCacheTest { @BeforeEach public void setUp() throws Exception { MockReferenceConfig.setCounter(0); - ReferenceConfigCache.cacheHolder.clear(); + ReferenceConfigCache.CACHE_HOLDER.clear(); } @Test diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/extension/SpringExtensionFactory.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/extension/SpringExtensionFactory.java index 6aa80e860a3..d61db85fd4d 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/extension/SpringExtensionFactory.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/extension/SpringExtensionFactory.java @@ -40,29 +40,29 @@ public class SpringExtensionFactory implements ExtensionFactory { private static final Logger logger = LoggerFactory.getLogger(SpringExtensionFactory.class); - private static final Set contexts = new ConcurrentHashSet(); - private static final ApplicationListener shutdownHookListener = new ShutdownHookListener(); + private static final Set CONTEXTS = new ConcurrentHashSet(); + private static final ApplicationListener SHUTDOWN_HOOK_LISTENER = new ShutdownHookListener(); public static void addApplicationContext(ApplicationContext context) { - contexts.add(context); + CONTEXTS.add(context); if (context instanceof ConfigurableApplicationContext) { ((ConfigurableApplicationContext) context).registerShutdownHook(); DubboShutdownHook.getDubboShutdownHook().unregister(); } - BeanFactoryUtils.addApplicationListener(context, shutdownHookListener); + BeanFactoryUtils.addApplicationListener(context, SHUTDOWN_HOOK_LISTENER); } public static void removeApplicationContext(ApplicationContext context) { - contexts.remove(context); + CONTEXTS.remove(context); } public static Set getContexts() { - return contexts; + return CONTEXTS; } // currently for test purpose public static void clearContexts() { - contexts.clear(); + CONTEXTS.clear(); } @Override @@ -74,7 +74,7 @@ public T getExtension(Class type, String name) { return null; } - for (ApplicationContext context : contexts) { + for (ApplicationContext context : CONTEXTS) { if (context.containsBean(name)) { Object bean = context.getBean(name); if (type.isInstance(bean)) { @@ -89,7 +89,7 @@ public T getExtension(Class type, String name) { return null; } - for (ApplicationContext context : contexts) { + for (ApplicationContext context : CONTEXTS) { try { return context.getBean(type); } catch (NoUniqueBeanDefinitionException multiBeanExe) { diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java index 2593b2e081c..54bb0068a3e 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java @@ -75,9 +75,9 @@ public class RegistryDirectory extends AbstractDirectory implements Notify private static final Logger logger = LoggerFactory.getLogger(RegistryDirectory.class); - private static final Cluster cluster = ExtensionLoader.getExtensionLoader(Cluster.class).getAdaptiveExtension(); + private static final Cluster CLUSTER = ExtensionLoader.getExtensionLoader(Cluster.class).getAdaptiveExtension(); - private static final RouterFactory routerFactory = ExtensionLoader.getExtensionLoader(RouterFactory.class) + private static final RouterFactory ROUTER_FACTORY = ExtensionLoader.getExtensionLoader(RouterFactory.class) .getAdaptiveExtension(); private final String serviceKey; // Initialization at construction time, assertion not null @@ -108,7 +108,7 @@ public class RegistryDirectory extends AbstractDirectory implements Notify // Set cache invokeUrls to invokers mapping. private volatile Set cachedInvokerUrls; // The initial value is null and the midway may be assigned to null, please use the local variable reference - private static final ConsumerConfigurationListener consumerConfigurationListener = new ConsumerConfigurationListener(); + private static final ConsumerConfigurationListener CONSUMER_CONFIGURATION_LISTENER = new ConsumerConfigurationListener(); private ReferenceConfigurationListener serviceConfigurationListener; @@ -152,7 +152,7 @@ public void setRegistry(Registry registry) { public void subscribe(URL url) { setConsumerUrl(url); - consumerConfigurationListener.addNotifyListener(this); + CONSUMER_CONFIGURATION_LISTENER.addNotifyListener(this); serviceConfigurationListener = new ReferenceConfigurationListener(this, url); registry.subscribe(url, this); } @@ -178,7 +178,7 @@ public void destroy() { registry.unsubscribe(getConsumerUrl(), this); } DynamicConfiguration.getDynamicConfiguration() - .removeListener(ApplicationModel.getApplication(), consumerConfigurationListener); + .removeListener(ApplicationModel.getApplication(), CONSUMER_CONFIGURATION_LISTENER); } catch (Throwable t) { logger.warn("unexpected error when unsubscribe service " + serviceKey + "from registry" + registry.getUrl(), t); } @@ -308,7 +308,7 @@ private List> toMergeInvokerList(List> invokers) { for (List> groupList : groupMap.values()) { StaticDirectory staticDirectory = new StaticDirectory<>(groupList); staticDirectory.buildRouterChain(); - mergedInvokers.add(cluster.join(staticDirectory)); + mergedInvokers.add(CLUSTER.join(staticDirectory)); } } else { mergedInvokers = invokers; @@ -336,7 +336,7 @@ private Optional> toRouters(List urls) { url = url.setProtocol(routerType); } try { - Router router = routerFactory.getRouter(url); + Router router = ROUTER_FACTORY.getRouter(url); if (!routers.contains(router)) { routers.add(router); } @@ -461,7 +461,7 @@ private URL overrideWithConfigurator(URL providerUrl) { providerUrl = overrideWithConfigurators(this.configurators, providerUrl); // override url with configurator from configurator from "app-name.configurators" - providerUrl = overrideWithConfigurators(consumerConfigurationListener.getConfigurators(), providerUrl); + providerUrl = overrideWithConfigurators(CONSUMER_CONFIGURATION_LISTENER.getConfigurators(), providerUrl); // override url with configurator from configurators from "service-name.configurators" if (serviceConfigurationListener != null) { @@ -655,7 +655,7 @@ private void overrideDirectoryUrl() { this.overrideDirectoryUrl = directoryUrl; List localConfigurators = this.configurators; // local reference doOverrideUrl(localConfigurators); - List localAppDynamicConfigurators = consumerConfigurationListener.getConfigurators(); // local reference + List localAppDynamicConfigurators = CONSUMER_CONFIGURATION_LISTENER.getConfigurators(); // local reference doOverrideUrl(localAppDynamicConfigurators); if (serviceConfigurationListener != null) { List localDynamicConfigurators = serviceConfigurationListener.getConfigurators(); // local reference diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletManager.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletManager.java index 0b227704192..243c5541df0 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletManager.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletManager.java @@ -28,12 +28,12 @@ public class ServletManager { public static final int EXTERNAL_SERVER_PORT = -1234; - private static final ServletManager instance = new ServletManager(); + private static final ServletManager INSTANCE = new ServletManager(); private final Map contextMap = new ConcurrentHashMap(); public static ServletManager getInstance() { - return instance; + return INSTANCE; } public void addServletContext(int port, ServletContext servletContext) { diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaClient.java b/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaClient.java index 23296f71ce0..b5e9c8426d1 100644 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaClient.java +++ b/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaClient.java @@ -51,7 +51,7 @@ public class MinaClient extends AbstractClient { private static final Logger logger = LoggerFactory.getLogger(MinaClient.class); - private static final Map connectors = new ConcurrentHashMap(); + private static final Map CONNECTORS = new ConcurrentHashMap(); private String connectorKey; @@ -66,7 +66,7 @@ public MinaClient(final URL url, final ChannelHandler handler) throws RemotingEx @Override protected void doOpen() throws Throwable { connectorKey = getUrl().toFullString(); - SocketConnector c = connectors.get(connectorKey); + SocketConnector c = CONNECTORS.get(connectorKey); if (c != null) { connector = c; } else { @@ -82,7 +82,7 @@ protected void doOpen() throws Throwable { cfg.setConnectTimeout(timeout < 1000 ? 1 : timeout / 1000); // set codec. connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MinaCodecAdapter(getCodec(), getUrl(), this))); - connectors.put(connectorKey, connector); + CONNECTORS.put(connectorKey, connector); } } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyChannel.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyChannel.java index 9a0e107c84f..f5e02131a36 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyChannel.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyChannel.java @@ -38,7 +38,7 @@ final class NettyChannel extends AbstractChannel { private static final Logger logger = LoggerFactory.getLogger(NettyChannel.class); - private static final ConcurrentMap channelMap = new ConcurrentHashMap(); + private static final ConcurrentMap CHANNEL_MAP = new ConcurrentHashMap(); private final org.jboss.netty.channel.Channel channel; @@ -56,11 +56,11 @@ static NettyChannel getOrAddChannel(org.jboss.netty.channel.Channel ch, URL url, if (ch == null) { return null; } - NettyChannel ret = channelMap.get(ch); + NettyChannel ret = CHANNEL_MAP.get(ch); if (ret == null) { NettyChannel nc = new NettyChannel(ch, url, handler); if (ch.isConnected()) { - ret = channelMap.putIfAbsent(ch, nc); + ret = CHANNEL_MAP.putIfAbsent(ch, nc); } if (ret == null) { ret = nc; @@ -71,7 +71,7 @@ static NettyChannel getOrAddChannel(org.jboss.netty.channel.Channel ch, URL url, static void removeChannelIfDisconnected(org.jboss.netty.channel.Channel ch) { if (ch != null && !ch.isConnected()) { - channelMap.remove(ch); + CHANNEL_MAP.remove(ch); } } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyClient.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyClient.java index 434fd2a03b0..e9912985ebc 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyClient.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyClient.java @@ -48,7 +48,7 @@ public class NettyClient extends AbstractClient { // ChannelFactory's closure has a DirectMemory leak, using static to avoid // https://issues.jboss.org/browse/NETTY-424 - private static final ChannelFactory channelFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(new NamedThreadFactory("NettyClientBoss", true)), + private static final ChannelFactory CHANNEL_FACTORY = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(new NamedThreadFactory("NettyClientBoss", true)), Executors.newCachedThreadPool(new NamedThreadFactory("NettyClientWorker", true)), Constants.DEFAULT_IO_THREADS); private ClientBootstrap bootstrap; @@ -62,7 +62,7 @@ public NettyClient(final URL url, final ChannelHandler handler) throws RemotingE @Override protected void doOpen() throws Throwable { NettyHelper.setNettyLoggerFactory(); - bootstrap = new ClientBootstrap(channelFactory); + bootstrap = new ClientBootstrap(CHANNEL_FACTORY); // config // @see org.jboss.netty.channel.socket.SocketChannelConfig bootstrap.setOption("keepAlive", true); diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java index db69a29f24c..21bf2419487 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java @@ -39,7 +39,7 @@ final class NettyChannel extends AbstractChannel { private static final Logger logger = LoggerFactory.getLogger(NettyChannel.class); - private static final ConcurrentMap channelMap = new ConcurrentHashMap(); + private static final ConcurrentMap CHANNEL_MAP = new ConcurrentHashMap(); private final Channel channel; @@ -57,11 +57,11 @@ static NettyChannel getOrAddChannel(Channel ch, URL url, ChannelHandler handler) if (ch == null) { return null; } - NettyChannel ret = channelMap.get(ch); + NettyChannel ret = CHANNEL_MAP.get(ch); if (ret == null) { NettyChannel nettyChannel = new NettyChannel(ch, url, handler); if (ch.isActive()) { - ret = channelMap.putIfAbsent(ch, nettyChannel); + ret = CHANNEL_MAP.putIfAbsent(ch, nettyChannel); } if (ret == null) { ret = nettyChannel; @@ -72,7 +72,7 @@ static NettyChannel getOrAddChannel(Channel ch, URL url, ChannelHandler handler) static void removeChannelIfDisconnected(Channel ch) { if (ch != null && !ch.isActive()) { - channelMap.remove(ch); + CHANNEL_MAP.remove(ch); } } diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java index 4bf7b6d3bf5..a97eb7e5f22 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java @@ -48,7 +48,7 @@ public class CuratorZookeeperClient extends AbstractZookeeperClient { - static final Charset charset = Charset.forName("UTF-8"); + static final Charset CHARSET = Charset.forName("UTF-8"); private final CuratorFramework client; private Map treeCacheMap = new ConcurrentHashMap<>(); @@ -106,7 +106,7 @@ public void createEphemeral(String path) { @Override protected void createPersistent(String path, String data) { - byte[] dataBytes = data.getBytes(charset); + byte[] dataBytes = data.getBytes(CHARSET); try { client.create().forPath(path, dataBytes); } catch (NodeExistsException e) { @@ -122,7 +122,7 @@ protected void createPersistent(String path, String data) { @Override protected void createEphemeral(String path, String data) { - byte[] dataBytes = data.getBytes(charset); + byte[] dataBytes = data.getBytes(CHARSET); try { client.create().withMode(CreateMode.EPHEMERAL).forPath(path, dataBytes); } catch (NodeExistsException e) { @@ -177,7 +177,7 @@ public boolean isConnected() { public String doGetContent(String path) { try { byte[] dataBytes = client.getData().forPath(path); - return (dataBytes == null || dataBytes.length == 0) ? null : new String(dataBytes, charset); + return (dataBytes == null || dataBytes.length == 0) ? null : new String(dataBytes, CHARSET); } catch (NoNodeException e) { // ignore NoNode Exception. } catch (Exception e) { @@ -295,12 +295,12 @@ public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exc case NODE_ADDED: eventType = EventType.NodeCreated; path = event.getData().getPath(); - content = new String(event.getData().getData(), charset); + content = new String(event.getData().getData(), CHARSET); break; case NODE_UPDATED: eventType = EventType.NodeDataChanged; path = event.getData().getPath(); - content = new String(event.getData().getData(), charset); + content = new String(event.getData().getData(), CHARSET); break; case NODE_REMOVED: path = event.getData().getPath(); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java index f1bffc2a30b..23fa1ea52cb 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java @@ -75,16 +75,16 @@ public class AccessLogFilter implements Filter { // It's safe to declare it as singleton since it runs on single thread only private static final DateFormat FILE_NAME_FORMATTER = new SimpleDateFormat(FILE_DATE_FORMAT); - private static final Map> logEntries = new ConcurrentHashMap>(); + private static final Map> LOG_ENTRIES = new ConcurrentHashMap>(); - private static final ScheduledExecutorService logScheduled = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Dubbo-Access-Log", true)); + private static final ScheduledExecutorService LOG_SCHEDULED = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Dubbo-Access-Log", true)); /** * Default constructor initialize demon thread for writing into access log file with names with access log key * defined in url accesslog */ public AccessLogFilter() { - logScheduled.scheduleWithFixedDelay(this::writeLogToFile, LOG_OUTPUT_INTERVAL, LOG_OUTPUT_INTERVAL, TimeUnit.MILLISECONDS); + LOG_SCHEDULED.scheduleWithFixedDelay(this::writeLogToFile, LOG_OUTPUT_INTERVAL, LOG_OUTPUT_INTERVAL, TimeUnit.MILLISECONDS); } /** @@ -110,7 +110,7 @@ public Result invoke(Invoker invoker, Invocation inv) throws RpcException { } private void log(String accessLog, AccessLogData accessLogData) { - Set logSet = logEntries.computeIfAbsent(accessLog, k -> new ConcurrentHashSet<>()); + Set logSet = LOG_ENTRIES.computeIfAbsent(accessLog, k -> new ConcurrentHashSet<>()); if (logSet.size() < LOG_MAX_BUFFER) { logSet.add(accessLogData); @@ -121,8 +121,8 @@ private void log(String accessLog, AccessLogData accessLogData) { } private void writeLogToFile() { - if (!logEntries.isEmpty()) { - for (Map.Entry> entry : logEntries.entrySet()) { + if (!LOG_ENTRIES.isEmpty()) { + for (Map.Entry> entry : LOG_ENTRIES.entrySet()) { try { String accessLog = entry.getKey(); Set logSet = entry.getValue(); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java index cfad21c02ba..33dcc908e1b 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java @@ -39,38 +39,38 @@ public class ApplicationModel { /** * full qualified class name -> provided service */ - private static final ConcurrentMap providedServices = new ConcurrentHashMap<>(); + private static final ConcurrentMap PROVIDED_SERVICES = new ConcurrentHashMap<>(); /** * full qualified class name -> subscribe service */ - private static final ConcurrentMap consumedServices = new ConcurrentHashMap<>(); + private static final ConcurrentMap CONSUMED_SERVICES = new ConcurrentHashMap<>(); private static String application; public static Collection allConsumerModels() { - return consumedServices.values(); + return CONSUMED_SERVICES.values(); } public static Collection allProviderModels() { - return providedServices.values(); + return PROVIDED_SERVICES.values(); } public static ProviderModel getProviderModel(String serviceName) { - return providedServices.get(serviceName); + return PROVIDED_SERVICES.get(serviceName); } public static ConsumerModel getConsumerModel(String serviceName) { - return consumedServices.get(serviceName); + return CONSUMED_SERVICES.get(serviceName); } public static void initConsumerModel(String serviceName, ConsumerModel consumerModel) { - if (consumedServices.putIfAbsent(serviceName, consumerModel) != null) { + if (CONSUMED_SERVICES.putIfAbsent(serviceName, consumerModel) != null) { LOGGER.warn("Already register the same consumer:" + serviceName); } } public static void initProviderModel(String serviceName, ProviderModel providerModel) { - if (providedServices.putIfAbsent(serviceName, providerModel) != null) { + if (PROVIDED_SERVICES.putIfAbsent(serviceName, providerModel) != null) { LOGGER.warn("Already register the same:" + serviceName); } } @@ -87,7 +87,7 @@ public static void setApplication(String application) { * For unit test */ public static void reset() { - providedServices.clear(); - consumedServices.clear(); + PROVIDED_SERVICES.clear(); + CONSUMED_SERVICES.clear(); } } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java index 4d2f3c6756b..5eb4dd9205f 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java @@ -43,7 +43,7 @@ class CallbackServiceCodec { private static final Logger logger = LoggerFactory.getLogger(CallbackServiceCodec.class); - private static final ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + private static final ProxyFactory PROXY_FACTORY = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); private static final DubboProtocol protocol = DubboProtocol.getDubboProtocol(); private static final byte CALLBACK_NONE = 0x0; private static final byte CALLBACK_CREATE = 0x1; @@ -105,7 +105,7 @@ private static String exportOrUnexportCallbackService(Channel channel, URL url, // one channel can have multiple callback instances, no need to re-export for different instance. if (!channel.hasAttribute(cacheKey)) { if (!isInstancesOverLimit(channel, url, clazz.getName(), instid, false)) { - Invoker invoker = proxyFactory.getInvoker(inst, clazz, exportUrl); + Invoker invoker = PROXY_FACTORY.getInvoker(inst, clazz, exportUrl); // should destroy resource? Exporter exporter = protocol.export(invoker); // this is used for tracing if instid has published service or not. @@ -144,7 +144,7 @@ private static Object referOrDestroyCallbackService(Channel channel, URL url, Cl if (!isInstancesOverLimit(channel, referurl, clazz.getName(), instid, true)) { @SuppressWarnings("rawtypes") Invoker invoker = new ChannelWrappedInvoker(clazz, channel, referurl, String.valueOf(instid)); - proxy = proxyFactory.getProxy(invoker); + proxy = PROXY_FACTORY.getProxy(invoker); channel.setAttribute(proxyCacheKey, proxy); channel.setAttribute(invokerCacheKey, invoker); increaseInstanceCount(channel, countkey); diff --git a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpRemoteInvocation.java b/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpRemoteInvocation.java index c2cf48ac5f0..b4617396c21 100644 --- a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpRemoteInvocation.java +++ b/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpRemoteInvocation.java @@ -31,18 +31,18 @@ public class HttpRemoteInvocation extends RemoteInvocation { private static final long serialVersionUID = 1L; - private static final String dubboAttachmentsAttrName = "dubbo.attachments"; + private static final String DUBBO_ATTACHMENTS_ATTR_NAME = "dubbo.attachments"; public HttpRemoteInvocation(MethodInvocation methodInvocation) { super(methodInvocation); - addAttribute(dubboAttachmentsAttrName, new HashMap(RpcContext.getContext().getAttachments())); + addAttribute(DUBBO_ATTACHMENTS_ATTR_NAME, new HashMap(RpcContext.getContext().getAttachments())); } @Override public Object invoke(Object targetObject) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { RpcContext context = RpcContext.getContext(); - context.setAttachments((Map) getAttribute(dubboAttachmentsAttrName)); + context.setAttachments((Map) getAttribute(DUBBO_ATTACHMENTS_ATTR_NAME)); String generic = (String) getAttribute(Constants.GENERIC_KEY); if (StringUtils.isNotEmpty(generic)) { diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java index 564505a5837..b40996c8124 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java @@ -84,10 +84,10 @@ public class ThriftCodec implements Codec2 { public static final String PARAMETER_CLASS_NAME_GENERATOR = "class.name.generator"; public static final byte VERSION = (byte) 1; public static final short MAGIC = (short) 0xdabc; - static final ConcurrentMap cachedRequest = + static final ConcurrentMap CACHED_REQUEST = new ConcurrentHashMap(); private static final AtomicInteger THRIFT_SEQ_ID = new AtomicInteger(0); - private static final ConcurrentMap> cachedClass = + private static final ConcurrentMap> CACHED_CLASS = new ConcurrentHashMap>(); private static int nextSeqId() { @@ -193,14 +193,14 @@ private Object decode(TProtocol protocol) "The specified interface name incorrect."); } - Class clazz = cachedClass.get(argsClassName); + Class clazz = CACHED_CLASS.get(argsClassName); if (clazz == null) { try { clazz = ClassUtils.forNameWithThreadContextClassLoader(argsClassName); - cachedClass.putIfAbsent(argsClassName, clazz); + CACHED_CLASS.putIfAbsent(argsClassName, clazz); } catch (ClassNotFoundException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); @@ -268,7 +268,7 @@ private Object decode(TProtocol protocol) Request request = new Request(id); request.setData(result); - cachedRequest.putIfAbsent(id, + CACHED_REQUEST.putIfAbsent(id, RequestData.create(message.seqid, serviceName, message.name)); return request; @@ -306,7 +306,7 @@ private Object decode(TProtocol protocol) + serviceName + ", the service name you specified may not generated by thrift idl compiler"); } - Class clazz = cachedClass.get(resultClassName); + Class clazz = CACHED_CLASS.get(resultClassName); if (clazz == null) { @@ -314,7 +314,7 @@ private Object decode(TProtocol protocol) clazz = ClassUtils.forNameWithThreadContextClassLoader(resultClassName); - cachedClass.putIfAbsent(resultClassName, clazz); + CACHED_CLASS.putIfAbsent(resultClassName, clazz); } catch (ClassNotFoundException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); @@ -422,7 +422,7 @@ private void encodeRequest(Channel channel, ChannelBuffer buffer, Request reques "Could not encode request, the specified interface may be incorrect."); } - Class clazz = cachedClass.get(methodArgs); + Class clazz = CACHED_CLASS.get(methodArgs); if (clazz == null) { @@ -430,7 +430,7 @@ private void encodeRequest(Channel channel, ChannelBuffer buffer, Request reques clazz = ClassUtils.forNameWithThreadContextClassLoader(methodArgs); - cachedClass.putIfAbsent(methodArgs, clazz); + CACHED_CLASS.putIfAbsent(methodArgs, clazz); } catch (ClassNotFoundException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); @@ -538,7 +538,7 @@ private void encodeResponse(Channel channel, ChannelBuffer buffer, Response resp RpcResult result = (RpcResult) response.getResult(); - RequestData rd = cachedRequest.get(response.getId()); + RequestData rd = CACHED_REQUEST.get(response.getId()); String resultClassName = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class).getExtension( channel.getUrl().getParameter(ThriftConstants.CLASS_NAME_GENERATOR_KEY, ThriftClassNameGenerator.NAME)) @@ -549,13 +549,13 @@ private void encodeResponse(Channel channel, ChannelBuffer buffer, Response resp "Could not encode response, the specified interface may be incorrect."); } - Class clazz = cachedClass.get(resultClassName); + Class clazz = CACHED_CLASS.get(resultClassName); if (clazz == null) { try { clazz = ClassUtils.forNameWithThreadContextClassLoader(resultClassName); - cachedClass.putIfAbsent(resultClassName, clazz); + CACHED_CLASS.putIfAbsent(resultClassName, clazz); } catch (ClassNotFoundException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftType.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftType.java index 3d8d3b387cf..85ede895488 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftType.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftType.java @@ -26,7 +26,7 @@ public enum ThriftType { BOOL, BYTE, I16, I32, I64, DOUBLE, STRING; - private static final Map, ThriftType> types = + private static final Map, ThriftType> TYPES = new HashMap, ThriftType>(); static { @@ -39,13 +39,13 @@ public enum ThriftType { public static ThriftType get(Class key) { if (key != null) { - return types.get(key); + return TYPES.get(key); } throw new NullPointerException("key == null"); } private static void put(Class key, ThriftType value) { - types.put(key, value); + TYPES.put(key, value); } } diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodecTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodecTest.java index c2277f7fba5..2b0b1db9bfb 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodecTest.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodecTest.java @@ -286,7 +286,7 @@ public void testEncodeReplyResponse() throws Exception { ThriftCodec.RequestData rd = ThriftCodec.RequestData.create( ThriftCodec.getSeqId(), Demo.Iface.class.getName(), "echoString"); - ThriftCodec.cachedRequest.putIfAbsent(request.getId(), rd); + ThriftCodec.CACHED_REQUEST.putIfAbsent(request.getId(), rd); codec.encode(channel, bos, response); byte[] buf = new byte[bos.writerIndex() - 4]; @@ -345,7 +345,7 @@ public void testEncodeExceptionResponse() throws Exception { ThriftCodec.RequestData rd = ThriftCodec.RequestData.create( ThriftCodec.getSeqId(), Demo.Iface.class.getName(), "echoString"); - ThriftCodec.cachedRequest.put(request.getId(), rd); + ThriftCodec.CACHED_REQUEST.put(request.getId(), rd); codec.encode(channel, bos, response); byte[] buf = new byte[bos.writerIndex() - 4]; diff --git a/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/support/SerializableClassRegistry.java b/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/support/SerializableClassRegistry.java index 22de45d5c74..1a8fb69dbd6 100644 --- a/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/support/SerializableClassRegistry.java +++ b/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/support/SerializableClassRegistry.java @@ -28,7 +28,7 @@ public abstract class SerializableClassRegistry { - private static final Map registrations = new LinkedHashMap<>(); + private static final Map REGISTRATIONS = new LinkedHashMap<>(); /** * only supposed to be called at startup time @@ -49,7 +49,7 @@ public static void registerClass(Class clazz, Serializer serializer) { if (clazz == null) { throw new IllegalArgumentException("Class registered to kryo cannot be null!"); } - registrations.put(clazz, serializer); + REGISTRATIONS.put(clazz, serializer); } /** @@ -58,6 +58,6 @@ public static void registerClass(Class clazz, Serializer serializer) { * @return class serializer * */ public static Map getRegisteredClasses() { - return registrations; + return REGISTRATIONS; } } From 5ce7ed3535b42b62b278ce132e8a5cc81065f7bf Mon Sep 17 00:00:00 2001 From: Huang YunKun Date: Sun, 5 May 2019 14:09:15 +0800 Subject: [PATCH 019/115] include nacos in dubbo-all (#3968) --- dubbo-all/pom.xml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/dubbo-all/pom.xml b/dubbo-all/pom.xml index 08621e41394..f1ed0943300 100644 --- a/dubbo-all/pom.xml +++ b/dubbo-all/pom.xml @@ -254,6 +254,13 @@ compile true + + org.apache.dubbo + dubbo-registry-nacos + ${project.version} + compile + true + org.apache.dubbo dubbo-registry-sofa @@ -537,6 +544,7 @@ org.apache.dubbo:dubbo-registry-redis org.apache.dubbo:dubbo-registry-consul org.apache.dubbo:dubbo-registry-etcd3 + org.apache.dubbo:dubbo-registry-nacos org.apache.dubbo:dubbo-registry-sofa org.apache.dubbo:dubbo-monitor-api org.apache.dubbo:dubbo-monitor-default From ff50a292a04eb174464600012257db541730ef2a Mon Sep 17 00:00:00 2001 From: myPrecious Date: Sun, 5 May 2019 14:49:07 +0800 Subject: [PATCH 020/115] consul enhancement (#3963) * revert to use http ttl check for consul * clean code --- .../dubbo/registry/consul/ConsulRegistry.java | 41 ++++++++++++++----- 1 file changed, 30 insertions(+), 11 deletions(-) diff --git a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java b/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java index 888faa47ca5..7bcd6b00afb 100644 --- a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java +++ b/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java @@ -40,9 +40,12 @@ import java.util.ArrayList; import java.util.Map; import java.util.Objects; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.Executors; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; +import java.util.concurrent.ScheduledExecutorService; import java.util.stream.Collectors; import static java.util.concurrent.Executors.newCachedThreadPool; @@ -57,31 +60,34 @@ public class ConsulRegistry extends FailbackRegistry { private static final String SERVICE_TAG = "dubbo"; private static final String URL_META_KEY = "url"; private static final String WATCH_TIMEOUT = "consul-watch-timeout"; - private static final String CHECK_INTERVAL = "consul-check-interval"; - private static final String CHECK_TIMEOUT = "consul-check-timeout"; + private static final String CHECK_PASS_INTERVAL = "consul-check-pass-interval"; private static final String DEREGISTER_AFTER = "consul-deregister-critical-service-after"; private static final int DEFAULT_PORT = 8500; // default watch timeout in millisecond private static final int DEFAULT_WATCH_TIMEOUT = 60 * 1000; - // default tcp check interval - private static final String DEFAULT_CHECK_INTERVAL = "10s"; - // default tcp check timeout - private static final String DEFAULT_CHECK_TIMEOUT = "1s"; + // default time-to-live in millisecond + private static final long DEFAULT_CHECK_PASS_INTERVAL = 16000L; // default deregister critical server after private static final String DEFAULT_DEREGISTER_TIME = "20s"; private ConsulClient client; - + private long checkPassInterval; private ExecutorService notifierExecutor = newCachedThreadPool( new NamedThreadFactory("dubbo-consul-notifier", true)); private ConcurrentMap notifiers = new ConcurrentHashMap<>(); + private ScheduledExecutorService ttlConsulCheckExecutor; + public ConsulRegistry(URL url) { super(url); String host = url.getHost(); int port = url.getPort() != 0 ? url.getPort() : DEFAULT_PORT; client = new ConsulClient(host, port); + checkPassInterval = url.getParameter(CHECK_PASS_INTERVAL, DEFAULT_CHECK_PASS_INTERVAL); + ttlConsulCheckExecutor = Executors.newSingleThreadScheduledExecutor(); + ttlConsulCheckExecutor.scheduleAtFixedRate(this::checkPass, checkPassInterval / 8, + checkPassInterval / 8, TimeUnit.MILLISECONDS); } @Override @@ -164,7 +170,7 @@ public List lookup(URL url) { } try { String service = url.getServiceKey(); - Response> result = client.getHealthServices(service, HealthServicesRequest.newBuilder().setTag(SERVICE_TAG).build()); + Response> result = getHealthServices(service, -1, buildWatchTimeout(url)); if (result == null || result.getValue() == null || result.getValue().isEmpty()) { return new ArrayList<>(); } else { @@ -184,6 +190,21 @@ public boolean isAvailable() { public void destroy() { super.destroy(); notifierExecutor.shutdown(); + ttlConsulCheckExecutor.shutdown(); + } + + private void checkPass() { + for (URL url : getRegistered()) { + String checkId = buildId(url); + try { + client.agentCheckPass("service:" + checkId); + if (logger.isDebugEnabled()) { + logger.debug("check pass for url: " + url + " with check id: " + checkId); + } + } catch (Throwable t) { + logger.warn("fail to check pass for url: " + url + ", check id is: " + checkId); + } + } } private Response> getHealthServices(String service, long index, int watchTimeout) { @@ -258,9 +279,7 @@ private String buildId(URL url) { private NewService.Check buildCheck(URL url) { NewService.Check check = new NewService.Check(); - check.setTcp(url.getAddress()); - check.setInterval(url.getParameter(CHECK_INTERVAL, DEFAULT_CHECK_INTERVAL)); - check.setTimeout(url.getParameter(CHECK_TIMEOUT, DEFAULT_CHECK_TIMEOUT)); + check.setTtl((checkPassInterval / 1000) + "s"); check.setDeregisterCriticalServiceAfter(url.getParameter(DEREGISTER_AFTER, DEFAULT_DEREGISTER_TIME)); return check; } From 74a491ba4304c5ea07bd0016ab6c135b80abd651 Mon Sep 17 00:00:00 2001 From: xujingfeng Date: Sun, 5 May 2019 15:00:40 +0800 Subject: [PATCH 021/115] improve NetUtils (#3953) * 1. filter network interface in NetUtils 2. remove the useless attribute in ApplicationConfig * add reachable check for ipv4 * move the reachable check to outside * rename isValidV6Address to isPreferIPV6Address --- .../apache/dubbo/common/utils/NetUtils.java | 26 +++++++++++-------- .../dubbo/common/utils/NetUtilsTest.java | 2 +- .../dubbo/config/ApplicationConfig.java | 11 -------- .../dubbo/demo/provider/Application.java | 3 ++- 4 files changed, 18 insertions(+), 24 deletions(-) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java index 3119e5c189a..e5b85ecd577 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java @@ -128,28 +128,23 @@ static boolean isValidV4Address(InetAddress address) { return false; } String name = address.getHostAddress(); - return (name != null + boolean result = (name != null && IP_PATTERN.matcher(name).matches() && !Constants.ANYHOST_VALUE.equals(name) && !Constants.LOCALHOST_VALUE.equals(name)); + return result; } /** - * Check if an ipv6 address is reachable. + * Check if an ipv6 address * - * @param address the given address * @return true if it is reachable */ - static boolean isValidV6Address(Inet6Address address) { + static boolean isPreferIPV6Address() { boolean preferIpv6 = Boolean.getBoolean("java.net.preferIPv6Addresses"); if (!preferIpv6) { return false; } - try { - return address.isReachable(100); - } catch (IOException e) { - // ignore - } return false; } @@ -234,7 +229,7 @@ public static InetAddress getLocalAddress() { private static Optional toValidAddress(InetAddress address) { if (address instanceof Inet6Address) { Inet6Address v6Address = (Inet6Address) address; - if (isValidV6Address(v6Address)) { + if (isPreferIPV6Address()) { return Optional.ofNullable(normalizeV6Address(v6Address)); } } @@ -264,12 +259,21 @@ private static InetAddress getLocalAddress0() { while (interfaces.hasMoreElements()) { try { NetworkInterface network = interfaces.nextElement(); + if (network.isLoopback() || network.isVirtual() || !network.isUp()) { + continue; + } Enumeration addresses = network.getInetAddresses(); while (addresses.hasMoreElements()) { try { Optional addressOp = toValidAddress(addresses.nextElement()); if (addressOp.isPresent()) { - return addressOp.get(); + try { + if(addressOp.get().isReachable(100)){ + return addressOp.get(); + } + } catch (IOException e) { + // ignore + } } } catch (Throwable e) { logger.warn(e); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/NetUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/NetUtilsTest.java index 797f2b42b15..5def6c7fd8a 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/NetUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/NetUtilsTest.java @@ -191,7 +191,7 @@ public void testIsValidV6Address() { System.setProperty("java.net.preferIPv6Addresses", "true"); InetAddress address = NetUtils.getLocalAddress(); if (address instanceof Inet6Address) { - assertThat(NetUtils.isValidV6Address((Inet6Address) address), equalTo(true)); + assertThat(NetUtils.isPreferIPV6Address(), equalTo(true)); } System.setProperty("java.net.preferIPv6Addresses", saved); } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java index 984733f293f..2775d0de514 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java @@ -123,10 +123,6 @@ public class ApplicationConfig extends AbstractConfig { */ private String shutwait; - - private Boolean preferPublicIp; - - public ApplicationConfig() { } @@ -331,11 +327,4 @@ public boolean isValid() { return !StringUtils.isEmpty(name); } - public Boolean getPreferPublicIp() { - return preferPublicIp; - } - - public void setPreferPublicIp(Boolean preferPublicIp) { - this.preferPublicIp = preferPublicIp; - } } \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/src/main/java/org/apache/dubbo/demo/provider/Application.java b/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/src/main/java/org/apache/dubbo/demo/provider/Application.java index 857e03f1169..c453d1b5543 100644 --- a/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/src/main/java/org/apache/dubbo/demo/provider/Application.java +++ b/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/src/main/java/org/apache/dubbo/demo/provider/Application.java @@ -29,9 +29,10 @@ public class Application { * launch the application */ public static void main(String[] args) throws Exception { + System.setProperty("DUBBO_IP_TO_REGISTRY", "4.3.2.1"); ServiceConfig service = new ServiceConfig<>(); service.setApplication(new ApplicationConfig("dubbo-demo-api-provider")); - service.setRegistry(new RegistryConfig("multicast://224.5.6.7:1234")); + service.setRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181")); service.setInterface(DemoService.class); service.setRef(new DemoServiceImpl()); service.export(); From a206dde6cd65d4273adfd6c84dd3be711c3b5a5d Mon Sep 17 00:00:00 2001 From: Huxing Zhang Date: Sun, 5 May 2019 15:13:45 +0800 Subject: [PATCH 022/115] [Dubbo-3653] Enable etcd to support metadata center (#3943) * Support etcd as metadata center * Fix key format error for consul/redis and UT failure * Fix UT failure * Fix UT failure * Fix UT failure --- dubbo-all/pom.xml | 7 + dubbo-bom/pom.xml | 5 + .../etcd/EtcdDynamicConfigurationTest.java | 1 - dubbo-distribution/pom.xml | 50 +++++++ .../identifier/MetadataIdentifier.java | 6 +- .../dubbo/metadata/store/MetadataReport.java | 3 - .../support/AbstractMetadataReport.java | 15 +- .../identifier/MetadataIdentifierTest.java | 14 +- .../store/test/JTestMetadataReport4Test.java | 2 +- .../store/consul/ConsulMetadataReport.java | 2 +- .../dubbo-metadata-report-etcd/pom.xml | 53 +++++++ .../store/etcd/EtcdMetadataReport.java | 98 +++++++++++++ .../store/etcd/EtcdMetadataReportFactory.java | 50 +++++++ ...dubbo.metadata.store.MetadataReportFactory | 1 + .../store/etcd/EtcdMetadata4TstService.java | 28 ++++ .../store/etcd/EtcdMetadataReportTest.java | 132 ++++++++++++++++++ .../store/redis/RedisMetadataReport.java | 2 +- .../store/redis/RedisMetadataReportTest.java | 9 +- .../zookeeper/ZookeeperMetadataReport.java | 18 +-- .../ZookeeperMetadataReportTest.java | 3 +- dubbo-metadata-report/pom.xml | 1 + 21 files changed, 452 insertions(+), 48 deletions(-) create mode 100644 dubbo-metadata-report/dubbo-metadata-report-etcd/pom.xml create mode 100644 dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReport.java create mode 100644 dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportFactory.java create mode 100644 dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory create mode 100644 dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadata4TstService.java create mode 100644 dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java diff --git a/dubbo-all/pom.xml b/dubbo-all/pom.xml index f1ed0943300..a5e674a1edd 100644 --- a/dubbo-all/pom.xml +++ b/dubbo-all/pom.xml @@ -450,6 +450,13 @@ compile true + + org.apache.dubbo + dubbo-metadata-report-etcd + ${project.version} + compile + true + diff --git a/dubbo-bom/pom.xml b/dubbo-bom/pom.xml index 148b49aebdc..2a6ef723e0d 100644 --- a/dubbo-bom/pom.xml +++ b/dubbo-bom/pom.xml @@ -357,6 +357,11 @@ dubbo-metadata-report-consul ${project.version} + + org.apache.dubbo + dubbo-metadata-report-etcd + ${project.version} + org.apache.dubbo dubbo-configcenter-api diff --git a/dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java index 4e305eaf01e..0f07cab99d9 100644 --- a/dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java +++ b/dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java @@ -120,7 +120,6 @@ public String getValue() { private void put(String key, String value) { try { - client.getKVClient().put(ByteSequence.from(key, UTF_8), ByteSequence.from(value, UTF_8)).get(); } catch (Exception e) { System.out.println("Error put value to etcd."); diff --git a/dubbo-distribution/pom.xml b/dubbo-distribution/pom.xml index e92363db722..76e73a3df67 100644 --- a/dubbo-distribution/pom.xml +++ b/dubbo-distribution/pom.xml @@ -185,6 +185,56 @@ dubbo-registry-sofa ${project.version} + + org.apache.dubbo + dubbo-configcenter-api + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-apollo + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-consul + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-etcd + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-api + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-redis + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-consul + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-etcd + ${project.version} + org.apache.dubbo dubbo-monitor-api diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/identifier/MetadataIdentifier.java b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/identifier/MetadataIdentifier.java index fca21bfbc99..457b3b6092b 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/identifier/MetadataIdentifier.java +++ b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/identifier/MetadataIdentifier.java @@ -23,8 +23,10 @@ * 2018/10/25 */ public class MetadataIdentifier { + public static final String SEPARATOR = ":"; final static String DEFAULT_PATH_TAG = "metadata"; + final static String META_DATA_STORE_TAG = ".metaData"; private String serviceInterface; private String version; @@ -53,9 +55,9 @@ public MetadataIdentifier(URL url) { public String getUniqueKey(KeyTypeEnum keyType) { if (keyType == KeyTypeEnum.PATH) { - return getFilePathKey(); + return getFilePathKey() + Constants.PATH_SEPARATOR + DEFAULT_PATH_TAG; } - return getIdentifierKey(); + return getIdentifierKey() + META_DATA_STORE_TAG; } public String getIdentifierKey() { diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/store/MetadataReport.java b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/store/MetadataReport.java index 922f97cbeb3..1afcc83438b 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/store/MetadataReport.java +++ b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/store/MetadataReport.java @@ -26,9 +26,6 @@ */ public interface MetadataReport { - public static final String META_DATA_STORE_TAG = ".metaData"; - - void storeProviderMetadata(MetadataIdentifier providerMetadataIdentifier, FullServiceDefinition serviceDefinition); void storeConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, Map serviceParameterMap); diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java index 95b44f44927..16daa2eeb50 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java +++ b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java @@ -56,6 +56,7 @@ */ public abstract class AbstractMetadataReport implements MetadataReport { + protected final static String DEFAULT_ROOT = "dubbo"; private static final int ONE_DAY_IN_MIll = 60 * 24 * 60 * 1000; private static final int FOUR_HOURS_IN_MIll = 60 * 4 * 60 * 1000; @@ -216,12 +217,7 @@ public void storeProviderMetadata(MetadataIdentifier providerMetadataIdentifier, if (syncReport) { storeProviderMetadataTask(providerMetadataIdentifier, serviceDefinition); } else { - reportCacheExecutor.execute(new Runnable() { - @Override - public void run() { - storeProviderMetadataTask(providerMetadataIdentifier, serviceDefinition); - } - }); + reportCacheExecutor.execute(() -> storeProviderMetadataTask(providerMetadataIdentifier, serviceDefinition)); } } @@ -249,12 +245,7 @@ public void storeConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, if (syncReport) { storeConsumerMetadataTask(consumerMetadataIdentifier, serviceParameterMap); } else { - reportCacheExecutor.execute(new Runnable() { - @Override - public void run() { - storeConsumerMetadataTask(consumerMetadataIdentifier, serviceParameterMap); - } - }); + reportCacheExecutor.execute(() -> storeConsumerMetadataTask(consumerMetadataIdentifier, serviceParameterMap)); } } diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/identifier/MetadataIdentifierTest.java b/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/identifier/MetadataIdentifierTest.java index 40fab45c4c8..ca415b46457 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/identifier/MetadataIdentifierTest.java +++ b/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/identifier/MetadataIdentifierTest.java @@ -21,6 +21,8 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import static org.apache.dubbo.metadata.identifier.MetadataIdentifier.META_DATA_STORE_TAG; + /** * 2019/1/7 */ @@ -34,10 +36,16 @@ public void testGetUniqueKey() { String application = "vic.zk.md"; MetadataIdentifier providerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, Constants.PROVIDER_SIDE, application); System.out.println(providerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.PATH)); - Assertions.assertEquals(providerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.PATH), "metadata" + Constants.PATH_SEPARATOR + interfaceName + Constants.PATH_SEPARATOR + (version == null ? "" : (version + Constants.PATH_SEPARATOR)) - + (group == null ? "" : (group + Constants.PATH_SEPARATOR)) + Constants.PROVIDER_SIDE + Constants.PATH_SEPARATOR + application); + Assertions.assertEquals(providerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.PATH), + "metadata" + Constants.PATH_SEPARATOR + interfaceName + Constants.PATH_SEPARATOR + + (version == null ? "" : (version + Constants.PATH_SEPARATOR)) + + (group == null ? "" : (group + Constants.PATH_SEPARATOR)) + Constants.PROVIDER_SIDE + + Constants.PATH_SEPARATOR + application + Constants.PATH_SEPARATOR + "metadata"); System.out.println(providerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY)); Assertions.assertEquals(providerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY), - interfaceName + MetadataIdentifier.SEPARATOR + (version == null ? "" : version + MetadataIdentifier.SEPARATOR) + (group == null ? "" : group + MetadataIdentifier.SEPARATOR) + Constants.PROVIDER_SIDE + MetadataIdentifier.SEPARATOR + application); + interfaceName + MetadataIdentifier.SEPARATOR + + (version == null ? "" : version + MetadataIdentifier.SEPARATOR) + + (group == null ? "" : group + MetadataIdentifier.SEPARATOR) + + Constants.PROVIDER_SIDE + MetadataIdentifier.SEPARATOR + application + META_DATA_STORE_TAG); } } diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store/test/JTestMetadataReport4Test.java b/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store/test/JTestMetadataReport4Test.java index 76778cee339..f5c129692e1 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store/test/JTestMetadataReport4Test.java +++ b/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store/test/JTestMetadataReport4Test.java @@ -54,7 +54,7 @@ protected void doStoreProviderMetadata(MetadataIdentifier providerMetadataIdenti @Override protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, String serviceParameterString) { - store.put(consumerMetadataIdentifier.getIdentifierKey(), serviceParameterString); + store.put(consumerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY), serviceParameterString); } public static String getProviderKey(URL url) { diff --git a/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReport.java b/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReport.java index 7bc6e7ee644..42a2f600f63 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReport.java +++ b/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReport.java @@ -55,7 +55,7 @@ protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdenti private void storeMetadata(MetadataIdentifier identifier, String v) { try { - client.setKVValue(identifier.getIdentifierKey() + META_DATA_STORE_TAG, v); + client.setKVValue(identifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY), v); } catch (Throwable t) { logger.error("Failed to put " + identifier + " to consul " + v + ", cause: " + t.getMessage(), t); throw new RpcException("Failed to put " + identifier + " to consul " + v + ", cause: " + t.getMessage(), t); diff --git a/dubbo-metadata-report/dubbo-metadata-report-etcd/pom.xml b/dubbo-metadata-report/dubbo-metadata-report-etcd/pom.xml new file mode 100644 index 00000000000..6ab0c1e6d93 --- /dev/null +++ b/dubbo-metadata-report/dubbo-metadata-report-etcd/pom.xml @@ -0,0 +1,53 @@ + + + + + + dubbo-metadata-report + org.apache.dubbo + 2.7.2-SNAPSHOT + + 4.0.0 + + dubbo-metadata-report-etcd + + + + org.apache.dubbo + dubbo-metadata-report-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-remoting-etcd3 + ${project.parent.version} + + + io.etcd + jetcd-launcher + test + + + org.testcontainers + testcontainers + test + + + \ No newline at end of file diff --git a/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReport.java b/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReport.java new file mode 100644 index 00000000000..0a472f55a78 --- /dev/null +++ b/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReport.java @@ -0,0 +1,98 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.metadata.store.etcd; + +import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.metadata.identifier.MetadataIdentifier; +import org.apache.dubbo.metadata.support.AbstractMetadataReport; +import org.apache.dubbo.remoting.etcd.jetcd.JEtcdClient; + +/** + * Report Metadata to Etcd + */ +public class EtcdMetadataReport extends AbstractMetadataReport { + + private final static Logger logger = LoggerFactory.getLogger(EtcdMetadataReport.class); + + private final String root; + + /** + * The etcd client + */ + private final JEtcdClient etcdClient; + + public EtcdMetadataReport(URL url) { + super(url); + if (url.isAnyHost()) { + throw new IllegalStateException("registry address == null"); + } + String group = url.getParameter(Constants.GROUP_KEY, DEFAULT_ROOT); + if (!group.startsWith(Constants.PATH_SEPARATOR)) { + group = Constants.PATH_SEPARATOR + group; + } + this.root = group; + etcdClient = new JEtcdClient(url); + } + + @Override + protected void doStoreProviderMetadata(MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions) { + storeMetadata(providerMetadataIdentifier, serviceDefinitions); + } + + @Override + protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, String value) { + storeMetadata(consumerMetadataIdentifier, value); + } + + private void storeMetadata(MetadataIdentifier identifier, String v) { + String key = getNodeKey(identifier); + if (!etcdClient.put(key, v)) { + logger.error("Failed to put " + identifier + " to etcd, value: " + v); + } + } + + String getNodeKey(MetadataIdentifier identifier) { + return toRootDir() + identifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.PATH); + } + + String toRootDir() { + if (root.equals(Constants.PATH_SEPARATOR)) { + return root; + } + return root + Constants.PATH_SEPARATOR; + } +} diff --git a/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportFactory.java b/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportFactory.java new file mode 100644 index 00000000000..f0572b64482 --- /dev/null +++ b/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportFactory.java @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.metadata.store.etcd; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.metadata.store.MetadataReport; +import org.apache.dubbo.metadata.support.AbstractMetadataReportFactory; + +/** + * MetadataReportFactory to create an Etcd based {@link MetadataReport}. + */ +public class EtcdMetadataReportFactory extends AbstractMetadataReportFactory { + + @Override + public MetadataReport createMetadataReport(URL url) { + return new EtcdMetadataReport(url); + } + +} diff --git a/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory b/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory new file mode 100644 index 00000000000..9a3c98c82a5 --- /dev/null +++ b/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory @@ -0,0 +1 @@ +etcd=org.apache.dubbo.metadata.store.etcd.EtcdMetadataReportFactory diff --git a/dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadata4TstService.java b/dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadata4TstService.java new file mode 100644 index 00000000000..1de21ce5652 --- /dev/null +++ b/dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadata4TstService.java @@ -0,0 +1,28 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.metadata.store.etcd; + +/** + * Test interface for Etcd metadata report + */ +public interface EtcdMetadata4TstService { + + int getCounter(); + + void printResult(String var); +} diff --git a/dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java b/dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java new file mode 100644 index 00000000000..e6f6b02c522 --- /dev/null +++ b/dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java @@ -0,0 +1,132 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.metadata.store.etcd; + +import com.google.gson.Gson; +import io.etcd.jetcd.ByteSequence; +import io.etcd.jetcd.Client; +import io.etcd.jetcd.kv.GetResponse; +import io.etcd.jetcd.launcher.EtcdCluster; +import io.etcd.jetcd.launcher.EtcdClusterFactory; +import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.utils.NetUtils; +import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder; +import org.apache.dubbo.metadata.definition.model.FullServiceDefinition; +import org.apache.dubbo.metadata.identifier.MetadataIdentifier; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; + +/** + * Unit test for etcd metadata report + */ +public class EtcdMetadataReportTest { + + private static final String TEST_SERVICE = "org.apache.dubbo.metadata.store.etcd.EtcdMetadata4TstService"; + + private EtcdCluster etcdCluster = EtcdClusterFactory.buildCluster(getClass().getSimpleName(), 1, false, false); + private Client etcdClientForTest; + private EtcdMetadataReport etcdMetadataReport; + private URL registryUrl; + private EtcdMetadataReportFactory etcdMetadataReportFactory; + + @BeforeEach + public void setUp() { + etcdCluster.start(); + etcdClientForTest = Client.builder().endpoints(etcdCluster.getClientEndpoints()).build(); + List clientEndPoints = etcdCluster.getClientEndpoints(); + this.registryUrl = URL.valueOf("etcd://" + clientEndPoints.get(0).getHost() + ":" + clientEndPoints.get(0).getPort()); + etcdMetadataReportFactory = new EtcdMetadataReportFactory(); + this.etcdMetadataReport = (EtcdMetadataReport) etcdMetadataReportFactory.createMetadataReport(registryUrl); + } + + @AfterEach + public void tearDown() throws Exception { + etcdCluster.close(); + } + + @Test + public void testStoreProvider() throws Exception { + String version = "1.0.0"; + String group = null; + String application = "etcd-metdata-report-test"; + MetadataIdentifier providerIdentifier = + storeProvider(etcdMetadataReport, TEST_SERVICE, version, group, application); + + CompletableFuture response = etcdClientForTest.getKVClient().get(ByteSequence.from( + etcdMetadataReport.getNodeKey(providerIdentifier), StandardCharsets.UTF_8)); + String fileContent = response.get().getKvs().get(0).getValue().toString(StandardCharsets.UTF_8); + Assertions.assertNotNull(fileContent); + + Gson gson = new Gson(); + FullServiceDefinition fullServiceDefinition = gson.fromJson(fileContent, FullServiceDefinition.class); + Assertions.assertEquals(fullServiceDefinition.getParameters().get("paramTest"), "etcdTest"); + } + + @Test + public void testStoreConsumer() throws Exception { + String version = "1.0.0"; + String group = null; + String application = "etc-metadata-report-consumer-test"; + MetadataIdentifier consumerIdentifier = storeConsumer(etcdMetadataReport, TEST_SERVICE, version, group, application); + + CompletableFuture response = etcdClientForTest.getKVClient().get(ByteSequence.from( + etcdMetadataReport.getNodeKey(consumerIdentifier), StandardCharsets.UTF_8)); + String fileContent = response.get().getKvs().get(0).getValue().toString(StandardCharsets.UTF_8); + Assertions.assertNotNull(fileContent); + Assertions.assertEquals(fileContent, "{\"paramConsumerTest\":\"etcdConsumer\"}"); + } + + private MetadataIdentifier storeProvider(EtcdMetadataReport etcdMetadataReport, String interfaceName, String version, + String group, String application) + throws ClassNotFoundException, InterruptedException { + URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + + "?paramTest=etcdTest&version=" + version + "&application=" + + application + (group == null ? "" : "&group=" + group)); + + MetadataIdentifier providerMetadataIdentifier = + new MetadataIdentifier(interfaceName, version, group, Constants.PROVIDER_SIDE, application); + Class interfaceClass = Class.forName(interfaceName); + FullServiceDefinition fullServiceDefinition = + ServiceDefinitionBuilder.buildFullDefinition(interfaceClass, url.getParameters()); + + etcdMetadataReport.storeProviderMetadata(providerMetadataIdentifier, fullServiceDefinition); + Thread.sleep(1000); + return providerMetadataIdentifier; + } + + private MetadataIdentifier storeConsumer(EtcdMetadataReport etcdMetadataReport, String interfaceName, + String version, String group, String application) throws InterruptedException { + + MetadataIdentifier consumerIdentifier = new MetadataIdentifier(interfaceName, version, group, Constants.CONSUMER_SIDE, application); + Map tmp = new HashMap<>(); + tmp.put("paramConsumerTest", "etcdConsumer"); + etcdMetadataReport.storeConsumerMetadata(consumerIdentifier, tmp); + Thread.sleep(1000); + return consumerIdentifier; + } +} diff --git a/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java b/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java index 42d88802e5b..b00295c3bdf 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java +++ b/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java @@ -54,7 +54,7 @@ protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdenti private void storeMetadata(MetadataIdentifier metadataIdentifier, String v) { try (Jedis jedis = pool.getResource()) { - jedis.set(metadataIdentifier.getIdentifierKey() + META_DATA_STORE_TAG, v); + jedis.set(metadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY), v); } catch (Throwable e) { logger.error("Failed to put " + metadataIdentifier + " to redis " + v + ", cause: " + e.getMessage(), e); throw new RpcException("Failed to put " + metadataIdentifier + " to redis " + v + ", cause: " + e.getMessage(), e); diff --git a/dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java b/dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java index 4984bde5b19..5a6d4f5fcf1 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java +++ b/dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java @@ -39,7 +39,6 @@ import java.util.Map; import static org.apache.dubbo.common.Constants.SYNC_REPORT_KEY; -import static org.apache.dubbo.metadata.store.MetadataReport.META_DATA_STORE_TAG; /** * 2018/10/9 @@ -93,7 +92,7 @@ private void testStoreProvider(RedisMetadataReport redisMetadataReport, String v Jedis jedis = null; try { jedis = redisMetadataReport.pool.getResource(); - String keyTmp = providerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY) + META_DATA_STORE_TAG; + String keyTmp = providerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY); String value = jedis.get(keyTmp); if (value == null) { Thread.sleep(moreTime); @@ -109,7 +108,7 @@ private void testStoreProvider(RedisMetadataReport redisMetadataReport, String v throw new RpcException("Failed to put to redis . cause: " + e.getMessage(), e); } finally { if (jedis != null) { - jedis.del(providerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY) + META_DATA_STORE_TAG); + jedis.del(providerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY)); } redisMetadataReport.pool.close(); } @@ -133,7 +132,7 @@ private void testStoreConsumer(RedisMetadataReport redisMetadataReport, String v Jedis jedis = null; try { jedis = redisMetadataReport.pool.getResource(); - String keyTmp = consumerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY) + META_DATA_STORE_TAG; + String keyTmp = consumerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY); String value = jedis.get(keyTmp); if (value == null) { Thread.sleep(moreTime); @@ -144,7 +143,7 @@ private void testStoreConsumer(RedisMetadataReport redisMetadataReport, String v throw new RpcException("Failed to put to redis . cause: " + e.getMessage(), e); } finally { if (jedis != null) { - jedis.del(consumerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY) + META_DATA_STORE_TAG); + jedis.del(consumerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY)); } redisMetadataReport.pool.close(); } diff --git a/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java b/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java index 8194e1ae446..de26faf7c2a 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java +++ b/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java @@ -20,14 +20,11 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.metadata.identifier.MetadataIdentifier; import org.apache.dubbo.metadata.support.AbstractMetadataReport; import org.apache.dubbo.remoting.zookeeper.ZookeeperClient; import org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter; -import java.util.List; - /** * ZookeeperMetadataReport */ @@ -35,9 +32,6 @@ public class ZookeeperMetadataReport extends AbstractMetadataReport { private final static Logger logger = LoggerFactory.getLogger(ZookeeperMetadataReport.class); - private final static String DEFAULT_ROOT = "dubbo"; - private final static String METADATA_NODE_NAME = "service.data"; - private final String root; final ZookeeperClient zkClient; @@ -55,16 +49,6 @@ public ZookeeperMetadataReport(URL url, ZookeeperTransporter zookeeperTransporte zkClient = zookeeperTransporter.connect(url); } - void deletePath(String category) { - List urlStrs = zkClient.getChildren(category); - if (CollectionUtils.isEmpty(urlStrs)) { - return; - } - for (String urlStr : urlStrs) { - zkClient.delete(category + Constants.PATH_SEPARATOR + urlStr); - } - } - String toRootDir() { if (root.equals(Constants.PATH_SEPARATOR)) { return root; @@ -87,7 +71,7 @@ private void storeMetadata(MetadataIdentifier metadataIdentifier, String v) { } String getNodePath(MetadataIdentifier metadataIdentifier) { - return toRootDir() + metadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.PATH) + Constants.PATH_SEPARATOR + METADATA_NODE_NAME; + return toRootDir() + metadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.PATH); } diff --git a/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportTest.java b/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportTest.java index c9ed9cfa9bb..da1e87b8945 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportTest.java +++ b/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportTest.java @@ -29,7 +29,6 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.util.HashMap; @@ -62,7 +61,7 @@ public void tearDown() throws Exception { private void deletePath(MetadataIdentifier metadataIdentifier, ZookeeperMetadataReport zookeeperMetadataReport) { String category = zookeeperMetadataReport.toRootDir() + metadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.PATH); - zookeeperMetadataReport.deletePath(category); + zookeeperMetadataReport.zkClient.delete(category); } @Test diff --git a/dubbo-metadata-report/pom.xml b/dubbo-metadata-report/pom.xml index 6d47af47374..3cb254afb96 100644 --- a/dubbo-metadata-report/pom.xml +++ b/dubbo-metadata-report/pom.xml @@ -30,6 +30,7 @@ dubbo-metadata-report-redis dubbo-metadata-definition dubbo-metadata-report-consul + dubbo-metadata-report-etcd From 89f6d6d262ec7c26f85988405c7a9a464202a461 Mon Sep 17 00:00:00 2001 From: huazhongming Date: Sun, 5 May 2019 15:45:56 +0800 Subject: [PATCH 023/115] Fix ContentTypeId conflict (#3967) * fix ContentTypeId conflict * modify * modify avro id --- .../java/org/apache/dubbo/common/Constants.java | 14 ++++++++++++++ .../dubbo/remoting/transport/CodecSupport.java | 3 ++- .../common/serialize/avro/AvroSerialization.java | 3 ++- .../serialize/fastjson/FastJsonSerialization.java | 3 ++- .../common/serialize/fst/FstSerialization.java | 3 ++- .../common/serialize/gson/GsonSerialization.java | 3 ++- .../serialize/hessian2/Hessian2Serialization.java | 5 ++--- .../serialize/java/CompactedJavaSerialization.java | 3 ++- .../common/serialize/java/JavaSerialization.java | 3 ++- .../nativejava/NativeJavaSerialization.java | 4 ++-- .../common/serialize/kryo/KryoSerialization.java | 3 ++- .../protostuff/ProtostuffSerialization.java | 3 ++- .../serialize/avro/AvroSerializationTest.java | 3 ++- 13 files changed, 38 insertions(+), 15 deletions(-) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java index 596d91c5928..c89a31421fa 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java @@ -875,4 +875,18 @@ public class Constants { public static final String METRICS_PROTOCOL = "metrics.protocol"; + /** + * Serizlization ContentTypeId + */ + public static final byte HESSIAN2_SERIALIZATION_ID = 2; + public static final byte JAVA_SERIALIZATION_ID = 3; + public static final byte COMPACTED_JAVA_SERIALIZATION_ID = 4; + public static final byte FASTJSON_SERIALIZATION_ID = 6; + public static final byte NATIVE_JAVA_SERIALIZATION_ID = 7; + public static final byte KRYO_SERIALIZATION_ID = 8; + public static final byte FST_SERIALIZATION_ID = 9; + public static final byte PROTOSTUFF_SERIALIZATION_ID = 10; + public static final byte AVRO_SERIALIZATION_ID = 11; + public static final byte GSON_SERIALIZATION_ID = 16; + } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java index 07da9a38823..9125f8479ac 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java @@ -71,7 +71,8 @@ public static Serialization getSerialization(URL url, Byte id) throws IOExceptio String serializationName = url.getParameter(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION); // Check if "serialization id" passed from network matches the id on this side(only take effect for JDK serialization), for security purpose. if (serialization == null - || ((id == 3 || id == 7 || id == 4) && !(serializationName.equals(ID_SERIALIZATIONNAME_MAP.get(id))))) { + || ((id == Constants.JAVA_SERIALIZATION_ID || id == Constants.NATIVE_JAVA_SERIALIZATION_ID || id == Constants.COMPACTED_JAVA_SERIALIZATION_ID) + && !(serializationName.equals(ID_SERIALIZATIONNAME_MAP.get(id))))) { throw new IOException("Unexpected serialization id:" + id + " received from network, please check if the peer send the right id."); } return serialization; diff --git a/dubbo-serialization/dubbo-serialization-avro/src/main/java/org/apache/dubbo/common/serialize/avro/AvroSerialization.java b/dubbo-serialization/dubbo-serialization-avro/src/main/java/org/apache/dubbo/common/serialize/avro/AvroSerialization.java index 8c546623551..37eb320f19b 100644 --- a/dubbo-serialization/dubbo-serialization-avro/src/main/java/org/apache/dubbo/common/serialize/avro/AvroSerialization.java +++ b/dubbo-serialization/dubbo-serialization-avro/src/main/java/org/apache/dubbo/common/serialize/avro/AvroSerialization.java @@ -16,6 +16,7 @@ */ package org.apache.dubbo.common.serialize.avro; +import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -29,7 +30,7 @@ public class AvroSerialization implements Serialization { @Override public byte getContentTypeId() { - return 10; + return Constants.AVRO_SERIALIZATION_ID; } @Override diff --git a/dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonSerialization.java b/dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonSerialization.java index 097587132c7..d1d804e14d0 100644 --- a/dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonSerialization.java +++ b/dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonSerialization.java @@ -16,6 +16,7 @@ */ package org.apache.dubbo.common.serialize.fastjson; +import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -36,7 +37,7 @@ public class FastJsonSerialization implements Serialization { @Override public byte getContentTypeId() { - return 6; + return Constants.FASTJSON_SERIALIZATION_ID; } @Override diff --git a/dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstSerialization.java b/dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstSerialization.java index e8b984c8bba..c9201d22a3d 100644 --- a/dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstSerialization.java +++ b/dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstSerialization.java @@ -16,6 +16,7 @@ */ package org.apache.dubbo.common.serialize.fst; +import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -36,7 +37,7 @@ public class FstSerialization implements Serialization { @Override public byte getContentTypeId() { - return 9; + return Constants.FST_SERIALIZATION_ID; } @Override diff --git a/dubbo-serialization/dubbo-serialization-gson/src/main/java/org/apache/dubbo/common/serialize/gson/GsonSerialization.java b/dubbo-serialization/dubbo-serialization-gson/src/main/java/org/apache/dubbo/common/serialize/gson/GsonSerialization.java index eaa8f37ddd1..cb4c2f9b088 100644 --- a/dubbo-serialization/dubbo-serialization-gson/src/main/java/org/apache/dubbo/common/serialize/gson/GsonSerialization.java +++ b/dubbo-serialization/dubbo-serialization-gson/src/main/java/org/apache/dubbo/common/serialize/gson/GsonSerialization.java @@ -17,6 +17,7 @@ package org.apache.dubbo.common.serialize.gson; +import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -31,7 +32,7 @@ public class GsonSerialization implements Serialization { @Override public byte getContentTypeId() { - return 16; + return Constants.GSON_SERIALIZATION_ID; } @Override diff --git a/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2Serialization.java b/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2Serialization.java index 225df10908a..2c46c5b1933 100644 --- a/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2Serialization.java +++ b/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2Serialization.java @@ -16,6 +16,7 @@ */ package org.apache.dubbo.common.serialize.hessian2; +import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -34,11 +35,9 @@ */ public class Hessian2Serialization implements Serialization { - public static final byte ID = 2; - @Override public byte getContentTypeId() { - return ID; + return Constants.HESSIAN2_SERIALIZATION_ID; } @Override diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/CompactedJavaSerialization.java b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/CompactedJavaSerialization.java index 8222ac45091..e1b75abf0a1 100644 --- a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/CompactedJavaSerialization.java +++ b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/CompactedJavaSerialization.java @@ -16,6 +16,7 @@ */ package org.apache.dubbo.common.serialize.java; +import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -36,7 +37,7 @@ public class CompactedJavaSerialization implements Serialization { @Override public byte getContentTypeId() { - return 4; + return Constants.COMPACTED_JAVA_SERIALIZATION_ID; } @Override diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaSerialization.java b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaSerialization.java index bf98818fd43..01d29ee7c04 100644 --- a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaSerialization.java +++ b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaSerialization.java @@ -16,6 +16,7 @@ */ package org.apache.dubbo.common.serialize.java; +import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -36,7 +37,7 @@ public class JavaSerialization implements Serialization { @Override public byte getContentTypeId() { - return 3; + return Constants.JAVA_SERIALIZATION_ID; } @Override diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/nativejava/NativeJavaSerialization.java b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/nativejava/NativeJavaSerialization.java index 55198690607..2d89161ead9 100644 --- a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/nativejava/NativeJavaSerialization.java +++ b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/nativejava/NativeJavaSerialization.java @@ -17,6 +17,7 @@ package org.apache.dubbo.common.serialize.nativejava; +import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -35,11 +36,10 @@ */ public class NativeJavaSerialization implements Serialization { - public static final String NAME = "nativejava"; @Override public byte getContentTypeId() { - return 7; + return Constants.NATIVE_JAVA_SERIALIZATION_ID; } @Override diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/KryoSerialization.java b/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/KryoSerialization.java index aa10df4af90..4f903ff707b 100644 --- a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/KryoSerialization.java +++ b/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/KryoSerialization.java @@ -16,6 +16,7 @@ */ package org.apache.dubbo.common.serialize.kryo; +import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -36,7 +37,7 @@ public class KryoSerialization implements Serialization { @Override public byte getContentTypeId() { - return 8; + return Constants.KRYO_SERIALIZATION_ID; } @Override diff --git a/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffSerialization.java b/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffSerialization.java index acdeaeaff4c..66b6833ba41 100644 --- a/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffSerialization.java +++ b/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffSerialization.java @@ -17,6 +17,7 @@ package org.apache.dubbo.common.serialize.protostuff; +import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -36,7 +37,7 @@ public class ProtostuffSerialization implements Serialization { @Override public byte getContentTypeId() { - return 10; + return Constants.PROTOSTUFF_SERIALIZATION_ID; } @Override diff --git a/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/avro/AvroSerializationTest.java b/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/avro/AvroSerializationTest.java index 79e42bdeeb6..ee591cba4af 100644 --- a/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/avro/AvroSerializationTest.java +++ b/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/avro/AvroSerializationTest.java @@ -16,6 +16,7 @@ */ package org.apache.dubbo.common.serialize.avro; +import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; import org.hamcrest.Matchers; @@ -46,7 +47,7 @@ public void testContentType() { @Test public void testContentTypeId() { - assertThat(avroSerialization.getContentTypeId(), is((byte) 10)); + assertThat(avroSerialization.getContentTypeId(), is(Constants.AVRO_SERIALIZATION_ID)); } @Test From 4007cd4a0239823951624cf559f7df7666dcedd2 Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Sun, 5 May 2019 16:34:59 +0800 Subject: [PATCH 024/115] dubbo-registry-nacos module is not bundled into Apache Dubbo 2.7.1 (#3976) Fixes #3797: --- dubbo-all/pom.xml | 1 + dubbo-dependencies-bom/pom.xml | 8 +++++++- dubbo-distribution/pom.xml | 15 +++++++++++++++ dubbo-registry/dubbo-registry-nacos/pom.xml | 7 +------ 4 files changed, 24 insertions(+), 7 deletions(-) diff --git a/dubbo-all/pom.xml b/dubbo-all/pom.xml index a5e674a1edd..cceac62cc82 100644 --- a/dubbo-all/pom.xml +++ b/dubbo-all/pom.xml @@ -582,6 +582,7 @@ org.apache.dubbo:dubbo-metadata-report-redis org.apache.dubbo:dubbo-metadata-report-zookeeper org.apache.dubbo:dubbo-metadata-report-consul + org.apache.dubbo:dubbo-metadata-report-etcd diff --git a/dubbo-dependencies-bom/pom.xml b/dubbo-dependencies-bom/pom.xml index 6d68457125b..0acf4773111 100644 --- a/dubbo-dependencies-bom/pom.xml +++ b/dubbo-dependencies-bom/pom.xml @@ -127,6 +127,7 @@ 3.0.19.Final 8.5.31 0.3.0 + 1.0.0 1.7.25 1.2 @@ -519,7 +520,7 @@ metrics-rest ${metrics_version} - + com.alipay.sofa @@ -584,6 +585,11 @@ testcontainers ${test_container_version} + + com.alibaba.nacos + nacos-client + ${nacos_version} + diff --git a/dubbo-distribution/pom.xml b/dubbo-distribution/pom.xml index 76e73a3df67..f830aa4379c 100644 --- a/dubbo-distribution/pom.xml +++ b/dubbo-distribution/pom.xml @@ -180,6 +180,21 @@ dubbo-registry-redis ${project.version} + + org.apache.dubbo + dubbo-registry-consul + ${project.version} + + + org.apache.dubbo + dubbo-registry-nacos + ${project.version} + + + org.apache.dubbo + dubbo-registry-etcd3 + ${project.version} + org.apache.dubbo dubbo-registry-sofa diff --git a/dubbo-registry/dubbo-registry-nacos/pom.xml b/dubbo-registry/dubbo-registry-nacos/pom.xml index e2a9d02e149..b8c952d267b 100644 --- a/dubbo-registry/dubbo-registry-nacos/pom.xml +++ b/dubbo-registry/dubbo-registry-nacos/pom.xml @@ -27,10 +27,6 @@ ${project.artifactId} The Nacos registry module of Dubbo project - - 1.0.0-RC3 - - @@ -50,7 +46,6 @@ com.alibaba.nacos nacos-client - ${nacos.version} true @@ -147,4 +142,4 @@ - \ No newline at end of file + From b30bddb464344bdefad4034d06ed1ddba5d00aef Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Sun, 5 May 2019 17:07:30 +0800 Subject: [PATCH 025/115] switch from CopyOnWriteArrayList to regular list in order to avoid potential UnsupportedOperationException (#3978) Fixes #3242 --- .../main/java/org/apache/dubbo/rpc/cluster/RouterChain.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterChain.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterChain.java index a690d73f1c9..7586afed779 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterChain.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterChain.java @@ -22,9 +22,9 @@ import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; +import java.util.ArrayList; import java.util.Collections; import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Collectors; /** @@ -63,7 +63,7 @@ private RouterChain(URL url) { */ public void initWithRouters(List builtinRouters) { this.builtinRouters = builtinRouters; - this.routers = new CopyOnWriteArrayList<>(builtinRouters); + this.routers = new ArrayList<>(builtinRouters); this.sort(); } @@ -76,7 +76,7 @@ public void initWithRouters(List builtinRouters) { * @param routers routers from 'router://' rules in 2.6.x or before. */ public void addRouters(List routers) { - List newRouters = new CopyOnWriteArrayList<>(); + List newRouters = new ArrayList<>(); newRouters.addAll(builtinRouters); newRouters.addAll(routers); CollectionUtils.sort(routers); From c98abb2f95d90bffb3ee40690c2a290f62905c63 Mon Sep 17 00:00:00 2001 From: zhaixiaoxiang Date: Sun, 5 May 2019 18:32:34 +0800 Subject: [PATCH 026/115] use revision in pom.xml (#3980) --- dubbo-metadata-report/dubbo-metadata-report-etcd/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dubbo-metadata-report/dubbo-metadata-report-etcd/pom.xml b/dubbo-metadata-report/dubbo-metadata-report-etcd/pom.xml index 6ab0c1e6d93..45a1413e464 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-etcd/pom.xml +++ b/dubbo-metadata-report/dubbo-metadata-report-etcd/pom.xml @@ -22,7 +22,7 @@ dubbo-metadata-report org.apache.dubbo - 2.7.2-SNAPSHOT + ${revision} 4.0.0 From 77df9d7bd23f6fdeb41f8e4f81ce13a95abe5ed7 Mon Sep 17 00:00:00 2001 From: huaifeng Date: Mon, 6 May 2019 10:26:31 +0800 Subject: [PATCH 027/115] native hessian merge (#3966) * Merge serialization-native-hessian-for-apache-dubbo into incubator-dubbo * test success * test success * Merge serialization-native-hessian-for-apache-dubbo into incubator-dubbo * change maven install * add apache license * remove @Generated * optimize import * remove thrift * merge master * distribution pom add native hessian --- dubbo-all/pom.xml | 8 + dubbo-bom/pom.xml | 5 + dubbo-distribution/pom.xml | 5 + .../pom.xml | 42 +++++ .../hessian/Hessian2ObjectInput.java | 98 ++++++++++++ .../hessian/Hessian2ObjectOutput.java | 95 +++++++++++ .../hessian/Hessian2Serialization.java | 51 ++++++ .../hessian/Hessian2SerializerFactory.java | 42 +++++ .../hessian/Java8SerializerFactory.java | 88 ++++++++++ .../serializer/java8/DurationHandle.java | 53 +++++++ .../serializer/java8/InstantHandle.java | 54 +++++++ .../serializer/java8/Java8TimeSerializer.java | 57 +++++++ .../serializer/java8/LocalDateHandle.java | 55 +++++++ .../serializer/java8/LocalDateTimeHandle.java | 55 +++++++ .../serializer/java8/LocalTimeHandle.java | 57 +++++++ .../serializer/java8/MonthDayHandle.java | 53 +++++++ .../java8/OffsetDateTimeHandle.java | 55 +++++++ .../serializer/java8/OffsetTimeHandle.java | 55 +++++++ .../serializer/java8/PeriodHandle.java | 56 +++++++ .../hessian/serializer/java8/YearHandle.java | 52 ++++++ .../serializer/java8/YearMonthHandle.java | 53 +++++++ .../serializer/java8/ZoneIdHandle.java | 52 ++++++ .../serializer/java8/ZoneIdSerializer.java | 43 +++++ .../serializer/java8/ZoneOffsetHandle.java | 51 ++++++ .../serializer/java8/ZonedDateTimeHandle.java | 62 ++++++++ ...pache.dubbo.common.serialize.Serialization | 1 + .../hessian/Java8TimeSerializerTest.java | 150 ++++++++++++++++++ dubbo-serialization/pom.xml | 1 + 28 files changed, 1449 insertions(+) create mode 100644 dubbo-serialization/dubbo-serialization-native-hession/pom.xml create mode 100644 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2ObjectInput.java create mode 100644 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2ObjectOutput.java create mode 100644 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2Serialization.java create mode 100644 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2SerializerFactory.java create mode 100644 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Java8SerializerFactory.java create mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/DurationHandle.java create mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/InstantHandle.java create mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/Java8TimeSerializer.java create mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/LocalDateHandle.java create mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/LocalDateTimeHandle.java create mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/LocalTimeHandle.java create mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/MonthDayHandle.java create mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/OffsetDateTimeHandle.java create mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/OffsetTimeHandle.java create mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/PeriodHandle.java create mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/YearHandle.java create mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/YearMonthHandle.java create mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZoneIdHandle.java create mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZoneIdSerializer.java create mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZoneOffsetHandle.java create mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZonedDateTimeHandle.java create mode 100644 dubbo-serialization/dubbo-serialization-native-hession/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization create mode 100644 dubbo-serialization/dubbo-serialization-native-hession/src/test/java/org/apache/dubbo/serialize/hessian/Java8TimeSerializerTest.java diff --git a/dubbo-all/pom.xml b/dubbo-all/pom.xml index cceac62cc82..816dfa75077 100644 --- a/dubbo-all/pom.xml +++ b/dubbo-all/pom.xml @@ -338,6 +338,13 @@ compile true + + org.apache.dubbo + dubbo-serialization-native-hession + ${project.version} + compile + true + org.apache.dubbo dubbo-serialization-jdk @@ -583,6 +590,7 @@ org.apache.dubbo:dubbo-metadata-report-zookeeper org.apache.dubbo:dubbo-metadata-report-consul org.apache.dubbo:dubbo-metadata-report-etcd + org.apache.dubbo:dubbo-serialization-native-hession diff --git a/dubbo-bom/pom.xml b/dubbo-bom/pom.xml index 2a6ef723e0d..fb28b65bc42 100644 --- a/dubbo-bom/pom.xml +++ b/dubbo-bom/pom.xml @@ -307,6 +307,11 @@ dubbo-serialization-hessian2 ${project.version} + + org.apache.dubbo + dubbo-serialization-native-hession + ${project.version} + org.apache.dubbo dubbo-serialization-jdk diff --git a/dubbo-distribution/pom.xml b/dubbo-distribution/pom.xml index f830aa4379c..ef24feb3568 100644 --- a/dubbo-distribution/pom.xml +++ b/dubbo-distribution/pom.xml @@ -300,6 +300,11 @@ dubbo-serialization-hessian2 ${project.version} + + org.apache.dubbo + dubbo-serialization-native-hession + ${project.version} + org.apache.dubbo dubbo-serialization-jdk diff --git a/dubbo-serialization/dubbo-serialization-native-hession/pom.xml b/dubbo-serialization/dubbo-serialization-native-hession/pom.xml new file mode 100644 index 00000000000..8d641db13cc --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-native-hession/pom.xml @@ -0,0 +1,42 @@ + + + + + dubbo-serialization + org.apache.dubbo + ${revision} + + 4.0.0 + + dubbo-serialization-native-hession + jar + ${project.artifactId} + The native-hession serialization module of dubbo project + + + + org.apache.dubbo + dubbo-serialization-api + ${project.parent.version} + + + com.caucho + hessian + + + \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2ObjectInput.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2ObjectInput.java new file mode 100644 index 00000000000..4bbb13fc97e --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2ObjectInput.java @@ -0,0 +1,98 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.serialize.hessian; + +import com.caucho.hessian.io.Hessian2Input; +import org.apache.dubbo.common.serialize.ObjectInput; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Type; + +/** + * Hessian2 Object input. + */ +public class Hessian2ObjectInput implements ObjectInput { + private final Hessian2Input input; + + public Hessian2ObjectInput(InputStream is) { + input = new Hessian2Input(is); + input.setSerializerFactory(Hessian2SerializerFactory.INSTANCE); + } + + @Override + public boolean readBool() throws IOException { + return input.readBoolean(); + } + + @Override + public byte readByte() throws IOException { + return (byte) input.readInt(); + } + + @Override + public short readShort() throws IOException { + return (short) input.readInt(); + } + + @Override + public int readInt() throws IOException { + return input.readInt(); + } + + @Override + public long readLong() throws IOException { + return input.readLong(); + } + + @Override + public float readFloat() throws IOException { + return (float) input.readDouble(); + } + + @Override + public double readDouble() throws IOException { + return input.readDouble(); + } + + @Override + public byte[] readBytes() throws IOException { + return input.readBytes(); + } + + @Override + public String readUTF() throws IOException { + return input.readString(); + } + + @Override + public Object readObject() throws IOException { + return input.readObject(); + } + + @Override + @SuppressWarnings("unchecked") + public T readObject(Class cls) throws IOException { + return (T) input.readObject(cls); + } + + @Override + public T readObject(Class cls, Type type) throws IOException { + return readObject(cls); + } + +} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2ObjectOutput.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2ObjectOutput.java new file mode 100644 index 00000000000..e3f5fa2661c --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2ObjectOutput.java @@ -0,0 +1,95 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.serialize.hessian; + +import com.caucho.hessian.io.Hessian2Output; +import org.apache.dubbo.common.serialize.ObjectOutput; + +import java.io.IOException; +import java.io.OutputStream; + +/** + * Hessian2 Object output. + */ +public class Hessian2ObjectOutput implements ObjectOutput { + private final Hessian2Output output; + + public Hessian2ObjectOutput(OutputStream os) { + output = new Hessian2Output(os); + output.setSerializerFactory(Hessian2SerializerFactory.INSTANCE); + } + + @Override + public void writeBool(boolean v) throws IOException { + output.writeBoolean(v); + } + + @Override + public void writeByte(byte v) throws IOException { + output.writeInt(v); + } + + @Override + public void writeShort(short v) throws IOException { + output.writeInt(v); + } + + @Override + public void writeInt(int v) throws IOException { + output.writeInt(v); + } + + @Override + public void writeLong(long v) throws IOException { + output.writeLong(v); + } + + @Override + public void writeFloat(float v) throws IOException { + output.writeDouble(v); + } + + @Override + public void writeDouble(double v) throws IOException { + output.writeDouble(v); + } + + @Override + public void writeBytes(byte[] b) throws IOException { + output.writeBytes(b); + } + + @Override + public void writeBytes(byte[] b, int off, int len) throws IOException { + output.writeBytes(b, off, len); + } + + @Override + public void writeUTF(String v) throws IOException { + output.writeString(v); + } + + @Override + public void writeObject(Object obj) throws IOException { + output.writeObject(obj); + } + + @Override + public void flushBuffer() throws IOException { + output.flushBuffer(); + } +} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2Serialization.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2Serialization.java new file mode 100644 index 00000000000..aeda121d015 --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2Serialization.java @@ -0,0 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.serialize.hessian; + + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.serialize.ObjectInput; +import org.apache.dubbo.common.serialize.ObjectOutput; +import org.apache.dubbo.common.serialize.Serialization; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +public class Hessian2Serialization implements Serialization { + + @Override + public byte getContentTypeId() { + return 10; + } + + @Override + public String getContentType() { + return "x-application/native-hessian"; + } + + @Override + public ObjectOutput serialize(URL url, OutputStream out) throws IOException { + return new Hessian2ObjectOutput(out); + } + + @Override + public ObjectInput deserialize(URL url, InputStream is) throws IOException { + return new Hessian2ObjectInput(is); + } + +} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2SerializerFactory.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2SerializerFactory.java new file mode 100644 index 00000000000..2e87375c5f5 --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2SerializerFactory.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.serialize.hessian; + +import com.caucho.hessian.io.Deserializer; +import com.caucho.hessian.io.HessianProtocolException; +import com.caucho.hessian.io.Serializer; +import com.caucho.hessian.io.SerializerFactory; + +public class Hessian2SerializerFactory extends SerializerFactory { + public static final SerializerFactory INSTANCE = new Hessian2SerializerFactory(); + + private Hessian2SerializerFactory() { + super(); + } + + @Override + protected Serializer loadSerializer(Class cl) throws HessianProtocolException { + Serializer serializer = Java8SerializerFactory.INSTANCE.getSerializer(cl); + return serializer != null ? serializer : super.loadSerializer(cl); + } + + @Override + protected Deserializer loadDeserializer(Class cl) throws HessianProtocolException { + Deserializer deserializer = Java8SerializerFactory.INSTANCE.getDeserializer(cl); + return deserializer != null ? deserializer : super.loadDeserializer(cl); + } +} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Java8SerializerFactory.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Java8SerializerFactory.java new file mode 100644 index 00000000000..6280023315b --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Java8SerializerFactory.java @@ -0,0 +1,88 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.serialize.hessian; + + +import com.caucho.hessian.io.AbstractSerializerFactory; +import com.caucho.hessian.io.ExtSerializerFactory; +import com.caucho.hessian.io.HessianProtocolException; +import com.caucho.hessian.io.Serializer; +import org.apache.dubbo.serialize.hessian.serializer.java8.DurationHandle; +import org.apache.dubbo.serialize.hessian.serializer.java8.InstantHandle; +import org.apache.dubbo.serialize.hessian.serializer.java8.LocalDateHandle; +import org.apache.dubbo.serialize.hessian.serializer.java8.LocalDateTimeHandle; +import org.apache.dubbo.serialize.hessian.serializer.java8.LocalTimeHandle; +import org.apache.dubbo.serialize.hessian.serializer.java8.MonthDayHandle; +import org.apache.dubbo.serialize.hessian.serializer.java8.OffsetDateTimeHandle; +import org.apache.dubbo.serialize.hessian.serializer.java8.OffsetTimeHandle; +import org.apache.dubbo.serialize.hessian.serializer.java8.PeriodHandle; +import org.apache.dubbo.serialize.hessian.serializer.java8.YearHandle; +import org.apache.dubbo.serialize.hessian.serializer.java8.YearMonthHandle; +import org.apache.dubbo.serialize.hessian.serializer.java8.ZoneIdSerializer; +import org.apache.dubbo.serialize.hessian.serializer.java8.ZoneOffsetHandle; +import org.apache.dubbo.serialize.hessian.serializer.java8.ZonedDateTimeHandle; + +import static org.apache.dubbo.serialize.hessian.serializer.java8.Java8TimeSerializer.create; + + +public class Java8SerializerFactory extends ExtSerializerFactory { + public static final AbstractSerializerFactory INSTANCE = new Java8SerializerFactory(); + + private Java8SerializerFactory() { + if (isJava8()) { + try { + this.addSerializer(Class.forName("java.time.LocalTime"), create(LocalTimeHandle.class)); + this.addSerializer(Class.forName("java.time.LocalDate"), create(LocalDateHandle.class)); + this.addSerializer(Class.forName("java.time.LocalDateTime"), create(LocalDateTimeHandle.class)); + + this.addSerializer(Class.forName("java.time.Instant"), create(InstantHandle.class)); + this.addSerializer(Class.forName("java.time.Duration"), create(DurationHandle.class)); + this.addSerializer(Class.forName("java.time.Period"), create(PeriodHandle.class)); + + this.addSerializer(Class.forName("java.time.Year"), create(YearHandle.class)); + this.addSerializer(Class.forName("java.time.YearMonth"), create(YearMonthHandle.class)); + this.addSerializer(Class.forName("java.time.MonthDay"), create(MonthDayHandle.class)); + + this.addSerializer(Class.forName("java.time.OffsetDateTime"), create(OffsetDateTimeHandle.class)); + this.addSerializer(Class.forName("java.time.ZoneOffset"), create(ZoneOffsetHandle.class)); + this.addSerializer(Class.forName("java.time.OffsetTime"), create(OffsetTimeHandle.class)); + this.addSerializer(Class.forName("java.time.ZonedDateTime"), create(ZonedDateTimeHandle.class)); + } catch (ClassNotFoundException e) { + // ignore + } + } + } + + @Override + public Serializer getSerializer(Class cl) throws HessianProtocolException { + return isZoneId(cl) ? ZoneIdSerializer.getInstance() : super.getSerializer(cl); + } + + private static boolean isZoneId(Class cl) { + try { + return isJava8() && Class.forName("java.time.ZoneId").isAssignableFrom(cl); + } catch (ClassNotFoundException e) { + // ignore + } + return false; + } + + private static boolean isJava8() { + String javaVersion = System.getProperty("java.specification.version"); + return Double.valueOf(javaVersion) >= 1.8; + } +} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/DurationHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/DurationHandle.java new file mode 100755 index 00000000000..67615f3d866 --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/DurationHandle.java @@ -0,0 +1,53 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.serialize.hessian.serializer.java8; + + +import com.caucho.hessian.io.HessianHandle; + +import java.io.Serializable; +import java.time.Duration; + +public class DurationHandle implements HessianHandle, Serializable { + private static final long serialVersionUID = -4367309317780077156L; + + private long seconds; + private int nanos; + + public DurationHandle() { + } + + public DurationHandle(Object o) { + try { + Duration duration = (Duration) o; + this.seconds = duration.getSeconds(); + this.nanos = duration.getNano(); + } catch (Throwable t) { + // ignore + } + } + + private Object readResolve() { + try { + return Duration.ofSeconds(seconds, nanos); + } catch (Throwable t) { + // ignore + } + return null; + } +} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/InstantHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/InstantHandle.java new file mode 100755 index 00000000000..6b9a1a8d9bf --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/InstantHandle.java @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.serialize.hessian.serializer.java8; + + +import com.caucho.hessian.io.HessianHandle; + +import java.io.Serializable; +import java.time.Instant; + +public class InstantHandle implements HessianHandle, Serializable { + private static final long serialVersionUID = -4367309317780077156L; + + private long seconds; + private int nanos; + + public InstantHandle() { + } + + public InstantHandle(Object o) { + try { + Instant instant = (Instant) o; + this.seconds = instant.getEpochSecond(); + this.nanos = instant.getNano(); + } catch (Throwable t) { + // ignore + } + } + + + private Object readResolve() { + try { + return Instant.ofEpochSecond(seconds, nanos); + } catch (Throwable t) { + // ignore + } + return null; + } +} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/Java8TimeSerializer.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/Java8TimeSerializer.java new file mode 100755 index 00000000000..4b4494db527 --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/Java8TimeSerializer.java @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.serialize.hessian.serializer.java8; + + +import com.caucho.hessian.io.AbstractHessianOutput; +import com.caucho.hessian.io.AbstractSerializer; + +import java.io.IOException; +import java.lang.reflect.Constructor; + +public class Java8TimeSerializer extends AbstractSerializer { + + // Type of handle + private Class handleType; + + private Java8TimeSerializer(Class handleType) { + this.handleType = handleType; + } + + public static Java8TimeSerializer create(Class handleType) { + return new Java8TimeSerializer(handleType); + } + + @Override + public void writeObject(Object obj, AbstractHessianOutput out) throws IOException { + if (obj == null) { + out.writeNull(); + return; + } + + T handle = null; + try { + Constructor constructor = handleType.getConstructor(Object.class); + handle = constructor.newInstance(obj); + } catch (Exception e) { + throw new RuntimeException("the class :" + handleType.getName() + " construct failed:" + e.getMessage(), e); + } + + out.writeObject(handle); + } +} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/LocalDateHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/LocalDateHandle.java new file mode 100755 index 00000000000..f994bc4c2da --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/LocalDateHandle.java @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.serialize.hessian.serializer.java8; + + +import com.caucho.hessian.io.HessianHandle; + +import java.io.Serializable; +import java.time.LocalDate; + +public class LocalDateHandle implements HessianHandle, Serializable { + private static final long serialVersionUID = 166018689500019951L; + + private int year; + private int month; + private int day; + + public LocalDateHandle() { + } + + public LocalDateHandle(Object o) { + try { + LocalDate localDate = (LocalDate) o; + this.year = localDate.getYear(); + this.month = localDate.getMonthValue(); + this.day = localDate.getDayOfMonth(); + } catch (Throwable t) { + // ignore + } + } + + public Object readResolve() { + try { + return LocalDate.of(year, month, day); + } catch (Throwable t) { + // ignore + } + return null; + } +} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/LocalDateTimeHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/LocalDateTimeHandle.java new file mode 100755 index 00000000000..094ced53c4c --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/LocalDateTimeHandle.java @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.serialize.hessian.serializer.java8; + + +import com.caucho.hessian.io.HessianHandle; + +import java.io.Serializable; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; + +public class LocalDateTimeHandle implements HessianHandle, Serializable { + private static final long serialVersionUID = 7563825215275989361L; + + private LocalDate date; + private LocalTime time; + + public LocalDateTimeHandle() { + } + + public LocalDateTimeHandle(Object o) { + try { + LocalDateTime localDateTime = (LocalDateTime) o; + date = localDateTime.toLocalDate(); + time = localDateTime.toLocalTime(); + } catch (Throwable t) { + // ignore + } + } + + private Object readResolve() { + try { + return LocalDateTime.of(date, time); + } catch (Throwable t) { + // ignore + } + return null; + } +} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/LocalTimeHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/LocalTimeHandle.java new file mode 100755 index 00000000000..b0d96199013 --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/LocalTimeHandle.java @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.serialize.hessian.serializer.java8; + + +import com.caucho.hessian.io.HessianHandle; + +import java.io.Serializable; +import java.time.LocalTime; + +public class LocalTimeHandle implements HessianHandle, Serializable { + private static final long serialVersionUID = -5892919085390462315L; + + private int hour; + private int minute; + private int second; + private int nano; + + public LocalTimeHandle() { + } + + public LocalTimeHandle(Object o) { + try { + LocalTime localTime = (LocalTime) o; + this.hour = localTime.getHour(); + this.minute = localTime.getMinute(); + this.second = localTime.getSecond(); + this.nano = localTime.getNano(); + } catch (Throwable t) { + // ignore + } + } + + private Object readResolve() { + try { + return LocalTime.of(hour, minute, second, nano); + } catch (Throwable t) { + // ignore + } + return null; + } +} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/MonthDayHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/MonthDayHandle.java new file mode 100755 index 00000000000..8c19273c109 --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/MonthDayHandle.java @@ -0,0 +1,53 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.serialize.hessian.serializer.java8; + + +import com.caucho.hessian.io.HessianHandle; + +import java.io.Serializable; +import java.time.MonthDay; + +public class MonthDayHandle implements HessianHandle, Serializable { + private static final long serialVersionUID = 5288238558666577745L; + + private int month; + private int day; + + public MonthDayHandle() { + } + + public MonthDayHandle(Object o) { + try { + MonthDay monthDay = (MonthDay) o; + this.month = monthDay.getMonthValue(); + this.day = monthDay.getDayOfMonth(); + } catch (Throwable t) { + // ignore + } + } + + private Object readResolve() { + try { + return MonthDay.of(month, day); + } catch (Throwable t) { + // ignore + } + return null; + } +} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/OffsetDateTimeHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/OffsetDateTimeHandle.java new file mode 100755 index 00000000000..b785266ef26 --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/OffsetDateTimeHandle.java @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.serialize.hessian.serializer.java8; + + +import com.caucho.hessian.io.HessianHandle; + +import java.io.Serializable; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; + +public class OffsetDateTimeHandle implements HessianHandle, Serializable { + private static final long serialVersionUID = -7823900532640515312L; + + private LocalDateTime dateTime; + private ZoneOffset offset; + + public OffsetDateTimeHandle() { + } + + public OffsetDateTimeHandle(Object o) { + try { + OffsetDateTime offsetDateTime = (OffsetDateTime) o; + this.dateTime = offsetDateTime.toLocalDateTime(); + this.offset = offsetDateTime.getOffset(); + } catch (Throwable t) { + // ignore + } + } + + private Object readResolve() { + try { + return OffsetDateTime.of(dateTime, offset); + } catch (Throwable t) { + // ignore + } + return null; + } +} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/OffsetTimeHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/OffsetTimeHandle.java new file mode 100755 index 00000000000..5a5730054f7 --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/OffsetTimeHandle.java @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.serialize.hessian.serializer.java8; + + +import com.caucho.hessian.io.HessianHandle; + +import java.io.Serializable; +import java.time.LocalTime; +import java.time.OffsetTime; +import java.time.ZoneOffset; + +public class OffsetTimeHandle implements HessianHandle, Serializable { + private static final long serialVersionUID = -3269846941421652860L; + + private LocalTime localTime; + private ZoneOffset zoneOffset; + + public OffsetTimeHandle() { + } + + public OffsetTimeHandle(Object o) { + try { + OffsetTime offsetTime = (OffsetTime) o; + this.zoneOffset = offsetTime.getOffset(); + this.localTime = offsetTime.toLocalTime(); + } catch (Throwable t) { + // ignore + } + } + + private Object readResolve() { + try { + return OffsetTime.of(localTime, zoneOffset); + } catch (Throwable t) { + // ignore + } + return null; + } +} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/PeriodHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/PeriodHandle.java new file mode 100755 index 00000000000..d29b39f7711 --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/PeriodHandle.java @@ -0,0 +1,56 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.serialize.hessian.serializer.java8; + + +import com.caucho.hessian.io.HessianHandle; + +import java.io.Serializable; +import java.time.Period; + + +public class PeriodHandle implements HessianHandle, Serializable { + private static final long serialVersionUID = 4399720381283781186L; + + private int years; + private int months; + private int days; + + public PeriodHandle() { + } + + public PeriodHandle(Object o) { + try { + Period period = (Period) o; + this.years = period.getYears(); + this.months = period.getMonths(); + this.days = period.getDays(); + } catch (Throwable t) { + // ignore + } + } + + private Object readResolve() { + try { + return Period.of(years, months, days); + } catch (Throwable t) { + // ignore + } + return null; + } +} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/YearHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/YearHandle.java new file mode 100755 index 00000000000..6560c0d8396 --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/YearHandle.java @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.serialize.hessian.serializer.java8; + + +import com.caucho.hessian.io.HessianHandle; + +import java.io.Serializable; +import java.time.Year; + +public class YearHandle implements HessianHandle, Serializable { + private static final long serialVersionUID = -6299552890287487926L; + + private int year; + + public YearHandle() { + } + + public YearHandle(Object o) { + try { + Year y = (Year) o; + this.year = y.getValue(); + } catch (Throwable t) { + // ignore + } + + } + + private Object readResolve() { + try { + return Year.of(year); + } catch (Throwable t) { + // ignore + } + return null; + } +} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/YearMonthHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/YearMonthHandle.java new file mode 100755 index 00000000000..5f67c2ef754 --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/YearMonthHandle.java @@ -0,0 +1,53 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.serialize.hessian.serializer.java8; + + +import com.caucho.hessian.io.HessianHandle; + +import java.io.Serializable; +import java.time.YearMonth; + +public class YearMonthHandle implements HessianHandle, Serializable { + private static final long serialVersionUID = -4150786187896925314L; + + private int year; + private int month; + + public YearMonthHandle() { + } + + public YearMonthHandle(Object o) { + try { + YearMonth yearMonth = (YearMonth) o; + this.year = yearMonth.getYear(); + this.month = yearMonth.getMonthValue(); + } catch (Throwable t) { + // ignore + } + } + + private Object readResolve() { + try { + return YearMonth.of(year, month); + } catch (Throwable t) { + // ignore + } + return null; + } +} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZoneIdHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZoneIdHandle.java new file mode 100755 index 00000000000..f1254690d77 --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZoneIdHandle.java @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.serialize.hessian.serializer.java8; + + +import com.caucho.hessian.io.HessianHandle; + +import java.io.Serializable; +import java.time.ZoneId; + +public class ZoneIdHandle implements HessianHandle, Serializable { + + private static final long serialVersionUID = 8789182864066905552L; + + private String zoneId; + + public ZoneIdHandle() { + } + + public ZoneIdHandle(Object o) { + try { + ZoneId zoneId = (ZoneId) o; + this.zoneId = zoneId.getId(); + } catch (Throwable t) { + // ignore + } + } + + private Object readResolve() { + try { + return ZoneId.of(this.zoneId); + } catch (Throwable t) { + // ignore + } + return null; + } +} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZoneIdSerializer.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZoneIdSerializer.java new file mode 100755 index 00000000000..71046702963 --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZoneIdSerializer.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.serialize.hessian.serializer.java8; + + +import com.caucho.hessian.io.AbstractHessianOutput; +import com.caucho.hessian.io.AbstractSerializer; + +import java.io.IOException; + +public class ZoneIdSerializer extends AbstractSerializer { + + private static final ZoneIdSerializer SERIALIZER = new ZoneIdSerializer(); + + public static ZoneIdSerializer getInstance() { + return SERIALIZER; + } + + @Override + public void writeObject(Object obj, AbstractHessianOutput out) throws IOException { + if (obj == null) { + out.writeNull(); + } else { + out.writeObject(new ZoneIdHandle(obj)); + } + } + +} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZoneOffsetHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZoneOffsetHandle.java new file mode 100755 index 00000000000..f7e622a73cf --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZoneOffsetHandle.java @@ -0,0 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.serialize.hessian.serializer.java8; + + +import com.caucho.hessian.io.HessianHandle; + +import java.io.Serializable; +import java.time.ZoneOffset; + +public class ZoneOffsetHandle implements HessianHandle, Serializable { + private static final long serialVersionUID = 8841589723587858789L; + + private int seconds; + + public ZoneOffsetHandle() { + } + + public ZoneOffsetHandle(Object o) { + try { + ZoneOffset zoneOffset = (ZoneOffset) o; + this.seconds = zoneOffset.getTotalSeconds(); + } catch (Throwable t) { + // ignore + } + } + + private Object readResolve() { + try { + return ZoneOffset.ofTotalSeconds(seconds); + } catch (Throwable t) { + // ignore + } + return null; + } +} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZonedDateTimeHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZonedDateTimeHandle.java new file mode 100755 index 00000000000..44b3ff536ce --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZonedDateTimeHandle.java @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.serialize.hessian.serializer.java8; + + +import com.caucho.hessian.io.HessianHandle; + +import java.io.Serializable; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; + +public class ZonedDateTimeHandle implements HessianHandle, Serializable { + private static final long serialVersionUID = -6933460123278647569L; + + private LocalDateTime dateTime; + private ZoneOffset offset; + private String zoneId; + + + public ZonedDateTimeHandle() { + } + + public ZonedDateTimeHandle(Object o) { + try { + ZonedDateTime zonedDateTime = (ZonedDateTime) o; + this.dateTime = zonedDateTime.toLocalDateTime(); + this.offset = zonedDateTime.getOffset(); + ZoneId zone = zonedDateTime.getZone(); + if (zone != null) { + this.zoneId = zone.getId(); + } + } catch (Throwable t) { + // ignore + } + } + + private Object readResolve() { + try { + return ZonedDateTime.ofLocal(dateTime, ZoneId.of(zoneId), offset); + } catch (Throwable t) { + // ignore + } + return null; + } +} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization b/dubbo-serialization/dubbo-serialization-native-hession/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization new file mode 100644 index 00000000000..ad6601604ed --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-native-hession/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization @@ -0,0 +1 @@ +native-hessian=org.apache.dubbo.serialize.hessian.Hessian2Serialization \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/test/java/org/apache/dubbo/serialize/hessian/Java8TimeSerializerTest.java b/dubbo-serialization/dubbo-serialization-native-hession/src/test/java/org/apache/dubbo/serialize/hessian/Java8TimeSerializerTest.java new file mode 100644 index 00000000000..a481dc0cca5 --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-native-hession/src/test/java/org/apache/dubbo/serialize/hessian/Java8TimeSerializerTest.java @@ -0,0 +1,150 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.serialize.hessian; + +import com.caucho.hessian.io.Hessian2Input; +import com.caucho.hessian.io.Hessian2Output; +import com.caucho.hessian.io.SerializerFactory; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.time.Duration; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.MonthDay; +import java.time.OffsetDateTime; +import java.time.OffsetTime; +import java.time.Period; +import java.time.Year; +import java.time.YearMonth; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.Calendar; + +/** + * Test Java8TimeSerializer class + */ +public class Java8TimeSerializerTest { + + private static SerializerFactory factory = Hessian2SerializerFactory.INSTANCE; + private static ByteArrayOutputStream os = new ByteArrayOutputStream(); + + @Test + public void testNull() throws IOException { + testJava8Time(null); + } + + @Test + public void testInstant() throws Exception { + Instant.now(); + testJava8Time(Instant.now()); + } + + @Test + public void testDuration() throws Exception { + testJava8Time(Duration.ofDays(2)); + } + + @Test + public void testLocalDate() throws Exception { + testJava8Time(LocalDate.now()); + } + + @Test + public void testLocalDateTime() throws Exception { + testJava8Time(LocalDateTime.now()); + } + + @Test + public void testLocalTime() throws Exception { + testJava8Time(LocalTime.now()); + } + + @Test + public void testYear() throws Exception { + testJava8Time(Year.now()); + } + + @Test + public void testYearMonth() throws Exception { + testJava8Time(YearMonth.now()); + } + + @Test + public void testMonthDay() throws Exception { + testJava8Time(MonthDay.now()); + } + + @Test + public void testPeriod() throws Exception { + testJava8Time(Period.ofDays(3)); + } + + @Test + public void testOffsetTime() throws Exception { + testJava8Time(OffsetTime.now()); + } + + @Test + public void testZoneOffset() throws Exception { + testJava8Time(ZoneOffset.ofHours(8)); + } + + @Test + public void testOffsetDateTime() throws Throwable { + testJava8Time(OffsetDateTime.now()); + } + + @Test + public void testZonedDateTime() throws Exception { + testJava8Time(ZonedDateTime.now()); + } + + @Test + public void testZoneId() throws Exception { + testJava8Time(ZoneId.of("America/New_York")); + } + + + @Test + public void testCalendar() throws IOException { + testJava8Time(Calendar.getInstance()); + } + + private void testJava8Time(Object expected) throws IOException { + os.reset(); + + Hessian2Output output = new Hessian2Output(os); + output.setSerializerFactory(factory); + output.writeObject(expected); + output.flush(); + + ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); + Hessian2Input input = new Hessian2Input(is); + input.setSerializerFactory(factory); + Object actual = input.readObject(); + + Assertions.assertEquals(expected, actual); + } +} diff --git a/dubbo-serialization/pom.xml b/dubbo-serialization/pom.xml index 97b986d1b85..b6b4b5c5cef 100644 --- a/dubbo-serialization/pom.xml +++ b/dubbo-serialization/pom.xml @@ -39,5 +39,6 @@ dubbo-serialization-avro dubbo-serialization-test dubbo-serialization-gson + dubbo-serialization-native-hession From ceb930e00f9458941ce1c658b323659aee94dbdc Mon Sep 17 00:00:00 2001 From: huaifeng Date: Mon, 6 May 2019 14:21:24 +0800 Subject: [PATCH 028/115] merge thrift (#3977) * merge thrift * thrift version update * test * test success * test success * thrift and native thrift * Restore thrift compatibility issues --- dubbo-all/pom.xml | 8 + dubbo-bom/pom.xml | 5 + dubbo-dependencies-bom/pom.xml | 2 +- dubbo-distribution/pom.xml | 5 + dubbo-rpc/dubbo-rpc-native-thrift/pom.xml | 49 + .../protocol/nativethrift/ThriftProtocol.java | 179 + .../internal/org.apache.dubbo.rpc.Protocol | 1 + .../src/test/idls/DemoService.thrift | 17 + .../src/test/idls/UserService.thrift | 6 + .../protocol/nativethrift/DemoService.java | 5141 +++++++++++++++++ .../nativethrift/DemoServiceImpl.java | 78 + .../nativethrift/ThriftProtocolTest.java | 81 + .../protocol/nativethrift/UserService.java | 952 +++ .../nativethrift/UserServiceImpl.java | 24 + .../rpc/protocol/thrift/ThriftCodec.java | 2 +- .../protocol/thrift/ThriftNativeCodec.java | 1 - .../thrift/ext/MultiServiceProcessor.java | 1 - .../test/java/$__ClassNameTestDubboStub.java | 9 +- .../src/test/java/ClassNameTest.java | 1 - .../src/test/java/ClassNameTestThrift.java | 9 +- .../dubbo/rpc/gen/dubbo/$__DemoStub.java | 63 +- .../org/apache/dubbo/rpc/gen/thrift/Demo.java | 75 +- .../rpc/protocol/thrift/AbstractTest.java | 1 - .../protocol/thrift/ServerExceptionTest.java | 1 - .../thrift/ServiceMethodNotFoundTest.java | 1 - .../rpc/protocol/thrift/ThriftCodecTest.java | 3 +- .../protocol/thrift/ThriftProtocolTest.java | 1 - .../rpc/protocol/thrift/ThriftUtilsTest.java | 1 - .../thrift/examples/DubboDemoConsumer.java | 1 - dubbo-rpc/pom.xml | 1 + 30 files changed, 6668 insertions(+), 51 deletions(-) create mode 100644 dubbo-rpc/dubbo-rpc-native-thrift/pom.xml create mode 100644 dubbo-rpc/dubbo-rpc-native-thrift/src/main/java/org/apache/dubbo/rpc/protocol/nativethrift/ThriftProtocol.java create mode 100644 dubbo-rpc/dubbo-rpc-native-thrift/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol create mode 100644 dubbo-rpc/dubbo-rpc-native-thrift/src/test/idls/DemoService.thrift create mode 100644 dubbo-rpc/dubbo-rpc-native-thrift/src/test/idls/UserService.thrift create mode 100644 dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/DemoService.java create mode 100644 dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/DemoServiceImpl.java create mode 100644 dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/ThriftProtocolTest.java create mode 100644 dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/UserService.java create mode 100644 dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/UserServiceImpl.java diff --git a/dubbo-all/pom.xml b/dubbo-all/pom.xml index 816dfa75077..c38263aa7b9 100644 --- a/dubbo-all/pom.xml +++ b/dubbo-all/pom.xml @@ -184,6 +184,13 @@ compile true + + org.apache.dubbo + dubbo-rpc-native-thrift + ${project.version} + compile + true + org.apache.dubbo dubbo-rpc-memcached @@ -591,6 +598,7 @@ org.apache.dubbo:dubbo-metadata-report-consul org.apache.dubbo:dubbo-metadata-report-etcd org.apache.dubbo:dubbo-serialization-native-hession + org.apache.dubbo:dubbo-rpc-native-thrift diff --git a/dubbo-bom/pom.xml b/dubbo-bom/pom.xml index fb28b65bc42..56568646232 100644 --- a/dubbo-bom/pom.xml +++ b/dubbo-bom/pom.xml @@ -202,6 +202,11 @@ dubbo-rpc-thrift ${project.version} + + org.apache.dubbo + dubbo-rpc-native-thrift + ${project.version} + org.apache.dubbo dubbo-rpc-memcached diff --git a/dubbo-dependencies-bom/pom.xml b/dubbo-dependencies-bom/pom.xml index 0acf4773111..fa5434c964f 100644 --- a/dubbo-dependencies-bom/pom.xml +++ b/dubbo-dependencies-bom/pom.xml @@ -106,7 +106,7 @@ 2.0.0 1.3.6 3.1.15 - 0.8.0 + 0.12.0 4.0.38 3.1.0 9.4.11.v20180605 diff --git a/dubbo-distribution/pom.xml b/dubbo-distribution/pom.xml index ef24feb3568..07fdf356d4f 100644 --- a/dubbo-distribution/pom.xml +++ b/dubbo-distribution/pom.xml @@ -140,6 +140,11 @@ dubbo-rpc-thrift ${project.version} + + org.apache.dubbo + dubbo-rpc-native-thrift + ${project.version} + org.apache.dubbo dubbo-rpc-memcached diff --git a/dubbo-rpc/dubbo-rpc-native-thrift/pom.xml b/dubbo-rpc/dubbo-rpc-native-thrift/pom.xml new file mode 100644 index 00000000000..524cd1a706b --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-native-thrift/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + + org.apache.dubbo + dubbo-rpc + ${revision} + + dubbo-rpc-native-thrift + jar + ${project.artifactId} + The thrift rpc module of dubbo project + + false + + + + + org.apache.dubbo + dubbo-rpc-api + ${project.parent.version} + + + org.apache.thrift + libthrift + + + org.apache.dubbo + dubbo-serialization-jdk + ${revision} + test + + + \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-native-thrift/src/main/java/org/apache/dubbo/rpc/protocol/nativethrift/ThriftProtocol.java b/dubbo-rpc/dubbo-rpc-native-thrift/src/main/java/org/apache/dubbo/rpc/protocol/nativethrift/ThriftProtocol.java new file mode 100644 index 00000000000..c869c60337b --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-native-thrift/src/main/java/org/apache/dubbo/rpc/protocol/nativethrift/ThriftProtocol.java @@ -0,0 +1,179 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.rpc.protocol.nativethrift; + + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.rpc.RpcException; +import org.apache.dubbo.rpc.protocol.AbstractProxyProtocol; +import org.apache.thrift.TException; +import org.apache.thrift.TMultiplexedProcessor; +import org.apache.thrift.TProcessor; +import org.apache.thrift.protocol.TCompactProtocol; +import org.apache.thrift.protocol.TMultiplexedProtocol; +import org.apache.thrift.protocol.TProtocol; +import org.apache.thrift.server.TServer; +import org.apache.thrift.server.TThreadedSelectorServer; +import org.apache.thrift.transport.TFramedTransport; +import org.apache.thrift.transport.TNonblockingServerSocket; +import org.apache.thrift.transport.TSocket; +import org.apache.thrift.transport.TTransport; + +import java.lang.reflect.Constructor; +import java.net.InetSocketAddress; +import java.util.HashMap; +import java.util.Map; + +/** + * native thrift protocol + */ +public class ThriftProtocol extends AbstractProxyProtocol { + + public static final int DEFAULT_PORT = 40880; + + public static final String NAME = "native-thrift"; + public static final String THRIFT_IFACE = "$Iface"; + public static final String THRIFT_PROCESSOR = "$Processor"; + public static final String THRIFT_CLIENT = "$Client"; + + private static final Map serverMap = new HashMap<>(); + private TMultiplexedProcessor processor = new TMultiplexedProcessor(); + + @Override + public int getDefaultPort() { + return DEFAULT_PORT; + } + + public ThriftProtocol() { + super(TException.class, RpcException.class); + } + + @Override + protected Runnable doExport(T impl, Class type, URL url) throws RpcException { + return exportThreadedSelectorServer(impl, type, url); + } + + @Override + protected T doRefer(Class type, URL url) throws RpcException { + return doReferFrameAndCompact(type, url); + } + + public ThriftProtocol(Class... exceptions) { + super(exceptions); + } + + private Runnable exportThreadedSelectorServer(T impl, Class type, URL url) throws RpcException { + + TThreadedSelectorServer.Args tArgs = null; + String typeName = type.getName(); + + TServer tserver = null; + if (typeName.endsWith(THRIFT_IFACE)) { + String processorClsName = typeName.substring(0, typeName.indexOf(THRIFT_IFACE)) + THRIFT_PROCESSOR; + try { + Class clazz = Class.forName(processorClsName); + Constructor constructor = clazz.getConstructor(type); + try { + TProcessor tprocessor = (TProcessor) constructor.newInstance(impl); + processor.registerProcessor(typeName,tprocessor); + + tserver = serverMap.get(url.getAddress()); + if(tserver == null) { + + /**Solve the problem of only 50 of the default number of concurrent connections*/ + TNonblockingServerSocket.NonblockingAbstractServerSocketArgs args = new TNonblockingServerSocket.NonblockingAbstractServerSocketArgs(); + /**1000 connections*/ + args.backlog(1000); + args.bindAddr(new InetSocketAddress(url.getHost(), url.getPort())); + /**timeout: 10s */ + args.clientTimeout(10000); + + TNonblockingServerSocket transport = new TNonblockingServerSocket(args); + + tArgs = new TThreadedSelectorServer.Args(transport); + tArgs.workerThreads(200); + tArgs.selectorThreads(4); + tArgs.acceptQueueSizePerThread(256); + tArgs.processor(processor); + tArgs.transportFactory(new TFramedTransport.Factory()); + tArgs.protocolFactory(new TCompactProtocol.Factory()); + }else{ + return null; // if server is starting, return and do nothing here + } + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new RpcException("Fail to create nativethrift server(" + url + ") : " + e.getMessage(), e); + } + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new RpcException("Fail to create nativethrift server(" + url + ") : " + e.getMessage(), e); + } + } + + if (tserver == null && tArgs == null) { + logger.error("Fail to create nativethrift server(" + url + ") due to null args"); + throw new RpcException("Fail to create nativethrift server(" + url + ") due to null args"); + } + final TServer thriftServer = new TThreadedSelectorServer(tArgs); + serverMap.put(url.getAddress(),thriftServer); + + new Thread(() -> { + logger.info("Start Thrift ThreadedSelectorServer"); + thriftServer.serve(); + logger.info("Thrift ThreadedSelectorServer started."); + }).start(); + + return () -> { + try { + logger.info("Close Thrift NonblockingServer"); + thriftServer.stop(); + } catch (Throwable e) { + logger.warn(e.getMessage(), e); + } + }; + } + + private T doReferFrameAndCompact(Class type, URL url) throws RpcException { + + try { + T thriftClient = null; + String typeName = type.getName(); + if (typeName.endsWith(THRIFT_IFACE)) { + String clientClsName = typeName.substring(0, typeName.indexOf(THRIFT_IFACE)) + THRIFT_CLIENT; + Class clazz = Class.forName(clientClsName); + Constructor constructor = clazz.getConstructor(TProtocol.class); + try { + TSocket tSocket = new TSocket(url.getHost(), url.getPort()); + TTransport transport = new TFramedTransport(tSocket); + TProtocol tprotocol = new TCompactProtocol(transport); + TMultiplexedProtocol protocol = new TMultiplexedProtocol(tprotocol,typeName); + thriftClient = (T) constructor.newInstance(protocol); + transport.open(); + logger.info("nativethrift client opened for service(" + url + ")"); + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new RpcException("Fail to create remote client:" + e.getMessage(), e); + } + } + return thriftClient; + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new RpcException("Fail to create remote client for service(" + url + "): " + e.getMessage(), e); + } + } + +} diff --git a/dubbo-rpc/dubbo-rpc-native-thrift/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol b/dubbo-rpc/dubbo-rpc-native-thrift/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol new file mode 100644 index 00000000000..d3b91406aa3 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-native-thrift/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol @@ -0,0 +1 @@ +native-thrift=org.apache.dubbo.rpc.protocol.nativethrift.ThriftProtocol \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-native-thrift/src/test/idls/DemoService.thrift b/dubbo-rpc/dubbo-rpc-native-thrift/src/test/idls/DemoService.thrift new file mode 100644 index 00000000000..a39d590747b --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-native-thrift/src/test/idls/DemoService.thrift @@ -0,0 +1,17 @@ +namespace java org.apache.dubbo.rpc.protocol.nativethrift +namespace go demo +/*Demo service define file,can be generated to inteface files*/ +/*Here test the 7 kind of data type*/ +service DemoService { + string sayHello(1:required string name); + + bool hasName( 1:required bool hasName); + + string sayHelloTimes(1:required string name, 2:required i32 times); + + void timeOut(1:required i32 millis); + + string customException(); + + string context(1:required string name); +} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-native-thrift/src/test/idls/UserService.thrift b/dubbo-rpc/dubbo-rpc-native-thrift/src/test/idls/UserService.thrift new file mode 100644 index 00000000000..c2f18e429a8 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-native-thrift/src/test/idls/UserService.thrift @@ -0,0 +1,6 @@ +namespace java org.apache.dubbo.rpc.protocol.nativethrift +namespace go demo + +service UserService { + string find(1:required i32 id); +} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/DemoService.java b/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/DemoService.java new file mode 100644 index 00000000000..e6a39c5feb6 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/DemoService.java @@ -0,0 +1,5141 @@ + +/** + * Autogenerated by Thrift Compiler (0.11.0) + * + * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING + * @generated + */ +package org.apache.dubbo.rpc.protocol.nativethrift; + +@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"}) +public class DemoService { + + public interface Iface { + + public String sayHello(String name) throws org.apache.thrift.TException; + + public boolean hasName(boolean hasName) throws org.apache.thrift.TException; + + public String sayHelloTimes(String name, int times) throws org.apache.thrift.TException; + + public void timeOut(int millis) throws org.apache.thrift.TException; + + public String customException() throws org.apache.thrift.TException; + + public String context(String name) throws org.apache.thrift.TException; + + } + + public interface AsyncIface { + + public void sayHello(String name, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; + + public void hasName(boolean hasName, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; + + public void sayHelloTimes(String name, int times, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; + + public void timeOut(int millis, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; + + public void customException(org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; + + public void context(String name, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; + + } + + public static class Client extends org.apache.thrift.TServiceClient implements Iface { + public static class Factory implements org.apache.thrift.TServiceClientFactory { + public Factory() {} + public Client getClient(org.apache.thrift.protocol.TProtocol prot) { + return new Client(prot); + } + public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { + return new Client(iprot, oprot); + } + } + + public Client(org.apache.thrift.protocol.TProtocol prot) + { + super(prot, prot); + } + + public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { + super(iprot, oprot); + } + + public String sayHello(String name) throws org.apache.thrift.TException + { + send_sayHello(name); + return recv_sayHello(); + } + + public void send_sayHello(String name) throws org.apache.thrift.TException + { + sayHello_args args = new sayHello_args(); + args.setName(name); + sendBase("sayHello", args); + } + + public String recv_sayHello() throws org.apache.thrift.TException + { + sayHello_result result = new sayHello_result(); + receiveBase(result, "sayHello"); + if (result.isSetSuccess()) { + return result.success; + } + throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "sayHello failed: unknown result"); + } + + public boolean hasName(boolean hasName) throws org.apache.thrift.TException + { + send_hasName(hasName); + return recv_hasName(); + } + + public void send_hasName(boolean hasName) throws org.apache.thrift.TException + { + hasName_args args = new hasName_args(); + args.setHasName(hasName); + sendBase("hasName", args); + } + + public boolean recv_hasName() throws org.apache.thrift.TException + { + hasName_result result = new hasName_result(); + receiveBase(result, "hasName"); + if (result.isSetSuccess()) { + return result.success; + } + throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "hasName failed: unknown result"); + } + + public String sayHelloTimes(String name, int times) throws org.apache.thrift.TException + { + send_sayHelloTimes(name, times); + return recv_sayHelloTimes(); + } + + public void send_sayHelloTimes(String name, int times) throws org.apache.thrift.TException + { + sayHelloTimes_args args = new sayHelloTimes_args(); + args.setName(name); + args.setTimes(times); + sendBase("sayHelloTimes", args); + } + + public String recv_sayHelloTimes() throws org.apache.thrift.TException + { + sayHelloTimes_result result = new sayHelloTimes_result(); + receiveBase(result, "sayHelloTimes"); + if (result.isSetSuccess()) { + return result.success; + } + throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "sayHelloTimes failed: unknown result"); + } + + public void timeOut(int millis) throws org.apache.thrift.TException + { + send_timeOut(millis); + recv_timeOut(); + } + + public void send_timeOut(int millis) throws org.apache.thrift.TException + { + timeOut_args args = new timeOut_args(); + args.setMillis(millis); + sendBase("timeOut", args); + } + + public void recv_timeOut() throws org.apache.thrift.TException + { + timeOut_result result = new timeOut_result(); + receiveBase(result, "timeOut"); + return; + } + + public String customException() throws org.apache.thrift.TException + { + send_customException(); + return recv_customException(); + } + + public void send_customException() throws org.apache.thrift.TException + { + customException_args args = new customException_args(); + sendBase("customException", args); + } + + public String recv_customException() throws org.apache.thrift.TException + { + customException_result result = new customException_result(); + receiveBase(result, "customException"); + if (result.isSetSuccess()) { + return result.success; + } + throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "customException failed: unknown result"); + } + + public String context(String name) throws org.apache.thrift.TException + { + send_context(name); + return recv_context(); + } + + public void send_context(String name) throws org.apache.thrift.TException + { + context_args args = new context_args(); + args.setName(name); + sendBase("context", args); + } + + public String recv_context() throws org.apache.thrift.TException + { + context_result result = new context_result(); + receiveBase(result, "context"); + if (result.isSetSuccess()) { + return result.success; + } + throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "context failed: unknown result"); + } + + } + public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface { + public static class Factory implements org.apache.thrift.async.TAsyncClientFactory { + private org.apache.thrift.async.TAsyncClientManager clientManager; + private org.apache.thrift.protocol.TProtocolFactory protocolFactory; + public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) { + this.clientManager = clientManager; + this.protocolFactory = protocolFactory; + } + public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) { + return new AsyncClient(protocolFactory, clientManager, transport); + } + } + + public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) { + super(protocolFactory, clientManager, transport); + } + + public void sayHello(String name, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { + checkReady(); + sayHello_call method_call = new sayHello_call(name, resultHandler, this, ___protocolFactory, ___transport); + this.___currentMethod = method_call; + ___manager.call(method_call); + } + + public static class sayHello_call extends org.apache.thrift.async.TAsyncMethodCall { + private String name; + public sayHello_call(String name, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { + super(client, protocolFactory, transport, resultHandler, false); + this.name = name; + } + + public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { + prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("sayHello", org.apache.thrift.protocol.TMessageType.CALL, 0)); + sayHello_args args = new sayHello_args(); + args.setName(name); + args.write(prot); + prot.writeMessageEnd(); + } + + public String getResult() throws org.apache.thrift.TException { + if (getState() != State.RESPONSE_READ) { + throw new IllegalStateException("Method call not finished!"); + } + org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); + org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); + return (new Client(prot)).recv_sayHello(); + } + } + + public void hasName(boolean hasName, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { + checkReady(); + hasName_call method_call = new hasName_call(hasName, resultHandler, this, ___protocolFactory, ___transport); + this.___currentMethod = method_call; + ___manager.call(method_call); + } + + public static class hasName_call extends org.apache.thrift.async.TAsyncMethodCall { + private boolean hasName; + public hasName_call(boolean hasName, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { + super(client, protocolFactory, transport, resultHandler, false); + this.hasName = hasName; + } + + public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { + prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("hasName", org.apache.thrift.protocol.TMessageType.CALL, 0)); + hasName_args args = new hasName_args(); + args.setHasName(hasName); + args.write(prot); + prot.writeMessageEnd(); + } + + public Boolean getResult() throws org.apache.thrift.TException { + if (getState() != State.RESPONSE_READ) { + throw new IllegalStateException("Method call not finished!"); + } + org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); + org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); + return (new Client(prot)).recv_hasName(); + } + } + + public void sayHelloTimes(String name, int times, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { + checkReady(); + sayHelloTimes_call method_call = new sayHelloTimes_call(name, times, resultHandler, this, ___protocolFactory, ___transport); + this.___currentMethod = method_call; + ___manager.call(method_call); + } + + public static class sayHelloTimes_call extends org.apache.thrift.async.TAsyncMethodCall { + private String name; + private int times; + public sayHelloTimes_call(String name, int times, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { + super(client, protocolFactory, transport, resultHandler, false); + this.name = name; + this.times = times; + } + + public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { + prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("sayHelloTimes", org.apache.thrift.protocol.TMessageType.CALL, 0)); + sayHelloTimes_args args = new sayHelloTimes_args(); + args.setName(name); + args.setTimes(times); + args.write(prot); + prot.writeMessageEnd(); + } + + public String getResult() throws org.apache.thrift.TException { + if (getState() != State.RESPONSE_READ) { + throw new IllegalStateException("Method call not finished!"); + } + org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); + org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); + return (new Client(prot)).recv_sayHelloTimes(); + } + } + + public void timeOut(int millis, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { + checkReady(); + timeOut_call method_call = new timeOut_call(millis, resultHandler, this, ___protocolFactory, ___transport); + this.___currentMethod = method_call; + ___manager.call(method_call); + } + + public static class timeOut_call extends org.apache.thrift.async.TAsyncMethodCall { + private int millis; + public timeOut_call(int millis, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { + super(client, protocolFactory, transport, resultHandler, false); + this.millis = millis; + } + + public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { + prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("timeOut", org.apache.thrift.protocol.TMessageType.CALL, 0)); + timeOut_args args = new timeOut_args(); + args.setMillis(millis); + args.write(prot); + prot.writeMessageEnd(); + } + + public Void getResult() throws org.apache.thrift.TException { + if (getState() != State.RESPONSE_READ) { + throw new IllegalStateException("Method call not finished!"); + } + org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); + org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); + return null; + } + } + + public void customException(org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { + checkReady(); + customException_call method_call = new customException_call(resultHandler, this, ___protocolFactory, ___transport); + this.___currentMethod = method_call; + ___manager.call(method_call); + } + + public static class customException_call extends org.apache.thrift.async.TAsyncMethodCall { + public customException_call(org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { + super(client, protocolFactory, transport, resultHandler, false); + } + + public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { + prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("customException", org.apache.thrift.protocol.TMessageType.CALL, 0)); + customException_args args = new customException_args(); + args.write(prot); + prot.writeMessageEnd(); + } + + public String getResult() throws org.apache.thrift.TException { + if (getState() != State.RESPONSE_READ) { + throw new IllegalStateException("Method call not finished!"); + } + org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); + org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); + return (new Client(prot)).recv_customException(); + } + } + + public void context(String name, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { + checkReady(); + context_call method_call = new context_call(name, resultHandler, this, ___protocolFactory, ___transport); + this.___currentMethod = method_call; + ___manager.call(method_call); + } + + public static class context_call extends org.apache.thrift.async.TAsyncMethodCall { + private String name; + public context_call(String name, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { + super(client, protocolFactory, transport, resultHandler, false); + this.name = name; + } + + public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { + prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("context", org.apache.thrift.protocol.TMessageType.CALL, 0)); + context_args args = new context_args(); + args.setName(name); + args.write(prot); + prot.writeMessageEnd(); + } + + public String getResult() throws org.apache.thrift.TException { + if (getState() != State.RESPONSE_READ) { + throw new IllegalStateException("Method call not finished!"); + } + org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); + org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); + return (new Client(prot)).recv_context(); + } + } + + } + + public static class Processor extends org.apache.thrift.TBaseProcessor implements org.apache.thrift.TProcessor { + private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory.getLogger(Processor.class.getName()); + public Processor(I iface) { + super(iface, getProcessMap(new java.util.HashMap>())); + } + + protected Processor(I iface, java.util.Map> processMap) { + super(iface, getProcessMap(processMap)); + } + + private static java.util.Map> getProcessMap(java.util.Map> processMap) { + processMap.put("sayHello", new sayHello()); + processMap.put("hasName", new hasName()); + processMap.put("sayHelloTimes", new sayHelloTimes()); + processMap.put("timeOut", new timeOut()); + processMap.put("customException", new customException()); + processMap.put("context", new context()); + return processMap; + } + + public static class sayHello extends org.apache.thrift.ProcessFunction { + public sayHello() { + super("sayHello"); + } + + public sayHello_args getEmptyArgsInstance() { + return new sayHello_args(); + } + + protected boolean isOneway() { + return false; + } + + protected boolean handleRuntimeExceptions() { + return false; + } + + public sayHello_result getResult(I iface, sayHello_args args) throws org.apache.thrift.TException { + sayHello_result result = new sayHello_result(); + result.success = iface.sayHello(args.name); + return result; + } + } + + public static class hasName extends org.apache.thrift.ProcessFunction { + public hasName() { + super("hasName"); + } + + public hasName_args getEmptyArgsInstance() { + return new hasName_args(); + } + + protected boolean isOneway() { + return false; + } + + protected boolean handleRuntimeExceptions() { + return false; + } + + public hasName_result getResult(I iface, hasName_args args) throws org.apache.thrift.TException { + hasName_result result = new hasName_result(); + result.success = iface.hasName(args.hasName); + result.setSuccessIsSet(true); + return result; + } + } + + public static class sayHelloTimes extends org.apache.thrift.ProcessFunction { + public sayHelloTimes() { + super("sayHelloTimes"); + } + + public sayHelloTimes_args getEmptyArgsInstance() { + return new sayHelloTimes_args(); + } + + protected boolean isOneway() { + return false; + } + + protected boolean handleRuntimeExceptions() { + return false; + } + + public sayHelloTimes_result getResult(I iface, sayHelloTimes_args args) throws org.apache.thrift.TException { + sayHelloTimes_result result = new sayHelloTimes_result(); + result.success = iface.sayHelloTimes(args.name, args.times); + return result; + } + } + + public static class timeOut extends org.apache.thrift.ProcessFunction { + public timeOut() { + super("timeOut"); + } + + public timeOut_args getEmptyArgsInstance() { + return new timeOut_args(); + } + + protected boolean isOneway() { + return false; + } + + protected boolean handleRuntimeExceptions() { + return false; + } + + public timeOut_result getResult(I iface, timeOut_args args) throws org.apache.thrift.TException { + timeOut_result result = new timeOut_result(); + iface.timeOut(args.millis); + return result; + } + } + + public static class customException extends org.apache.thrift.ProcessFunction { + public customException() { + super("customException"); + } + + public customException_args getEmptyArgsInstance() { + return new customException_args(); + } + + protected boolean isOneway() { + return false; + } + + protected boolean handleRuntimeExceptions() { + return false; + } + + public customException_result getResult(I iface, customException_args args) throws org.apache.thrift.TException { + customException_result result = new customException_result(); + result.success = iface.customException(); + return result; + } + } + + public static class context extends org.apache.thrift.ProcessFunction { + public context() { + super("context"); + } + + public context_args getEmptyArgsInstance() { + return new context_args(); + } + + protected boolean isOneway() { + return false; + } + + protected boolean handleRuntimeExceptions() { + return false; + } + + public context_result getResult(I iface, context_args args) throws org.apache.thrift.TException { + context_result result = new context_result(); + result.success = iface.context(args.name); + return result; + } + } + + } + + public static class AsyncProcessor extends org.apache.thrift.TBaseAsyncProcessor { + private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory.getLogger(AsyncProcessor.class.getName()); + public AsyncProcessor(I iface) { + super(iface, getProcessMap(new java.util.HashMap<>())); + } + + protected AsyncProcessor(I iface, java.util.Map> processMap) { + super(iface, getProcessMap(processMap)); + } + + private static java.util.Map> getProcessMap(java.util.Map> processMap) { + processMap.put("sayHello", new sayHello()); + processMap.put("hasName", new hasName()); + processMap.put("sayHelloTimes", new sayHelloTimes()); + processMap.put("timeOut", new timeOut()); + processMap.put("customException", new customException()); + processMap.put("context", new context()); + return processMap; + } + + public static class sayHello extends org.apache.thrift.AsyncProcessFunction { + public sayHello() { + super("sayHello"); + } + + public sayHello_args getEmptyArgsInstance() { + return new sayHello_args(); + } + + public org.apache.thrift.async.AsyncMethodCallback getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) { + final org.apache.thrift.AsyncProcessFunction fcall = this; + return new org.apache.thrift.async.AsyncMethodCallback() { + public void onComplete(String o) { + sayHello_result result = new sayHello_result(); + result.success = o; + try { + fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); + } catch (org.apache.thrift.transport.TTransportException e) { + _LOGGER.error("TTransportException writing to internal frame buffer", e); + fb.close(); + } catch (Exception e) { + _LOGGER.error("Exception writing to internal frame buffer", e); + onError(e); + } + } + public void onError(Exception e) { + byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; + org.apache.thrift.TSerializable msg; + sayHello_result result = new sayHello_result(); + if (e instanceof org.apache.thrift.transport.TTransportException) { + _LOGGER.error("TTransportException inside handler", e); + fb.close(); + return; + } else if (e instanceof org.apache.thrift.TApplicationException) { + _LOGGER.error("TApplicationException inside handler", e); + msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; + msg = (org.apache.thrift.TApplicationException)e; + } else { + _LOGGER.error("Exception inside handler", e); + msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; + msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); + } + try { + fcall.sendResponse(fb,msg,msgType,seqid); + } catch (Exception ex) { + _LOGGER.error("Exception writing to internal frame buffer", ex); + fb.close(); + } + } + }; + } + + protected boolean isOneway() { + return false; + } + + public void start(I iface, sayHello_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { + iface.sayHello(args.name,resultHandler); + } + } + + public static class hasName extends org.apache.thrift.AsyncProcessFunction { + public hasName() { + super("hasName"); + } + + public hasName_args getEmptyArgsInstance() { + return new hasName_args(); + } + + public org.apache.thrift.async.AsyncMethodCallback getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) { + final org.apache.thrift.AsyncProcessFunction fcall = this; + return new org.apache.thrift.async.AsyncMethodCallback() { + public void onComplete(Boolean o) { + hasName_result result = new hasName_result(); + result.success = o; + result.setSuccessIsSet(true); + try { + fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); + } catch (org.apache.thrift.transport.TTransportException e) { + _LOGGER.error("TTransportException writing to internal frame buffer", e); + fb.close(); + } catch (Exception e) { + _LOGGER.error("Exception writing to internal frame buffer", e); + onError(e); + } + } + public void onError(Exception e) { + byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; + org.apache.thrift.TSerializable msg; + hasName_result result = new hasName_result(); + if (e instanceof org.apache.thrift.transport.TTransportException) { + _LOGGER.error("TTransportException inside handler", e); + fb.close(); + return; + } else if (e instanceof org.apache.thrift.TApplicationException) { + _LOGGER.error("TApplicationException inside handler", e); + msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; + msg = (org.apache.thrift.TApplicationException)e; + } else { + _LOGGER.error("Exception inside handler", e); + msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; + msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); + } + try { + fcall.sendResponse(fb,msg,msgType,seqid); + } catch (Exception ex) { + _LOGGER.error("Exception writing to internal frame buffer", ex); + fb.close(); + } + } + }; + } + + protected boolean isOneway() { + return false; + } + + public void start(I iface, hasName_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { + iface.hasName(args.hasName,resultHandler); + } + } + + public static class sayHelloTimes extends org.apache.thrift.AsyncProcessFunction { + public sayHelloTimes() { + super("sayHelloTimes"); + } + + public sayHelloTimes_args getEmptyArgsInstance() { + return new sayHelloTimes_args(); + } + + public org.apache.thrift.async.AsyncMethodCallback getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) { + final org.apache.thrift.AsyncProcessFunction fcall = this; + return new org.apache.thrift.async.AsyncMethodCallback() { + public void onComplete(String o) { + sayHelloTimes_result result = new sayHelloTimes_result(); + result.success = o; + try { + fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); + } catch (org.apache.thrift.transport.TTransportException e) { + _LOGGER.error("TTransportException writing to internal frame buffer", e); + fb.close(); + } catch (Exception e) { + _LOGGER.error("Exception writing to internal frame buffer", e); + onError(e); + } + } + public void onError(Exception e) { + byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; + org.apache.thrift.TSerializable msg; + sayHelloTimes_result result = new sayHelloTimes_result(); + if (e instanceof org.apache.thrift.transport.TTransportException) { + _LOGGER.error("TTransportException inside handler", e); + fb.close(); + return; + } else if (e instanceof org.apache.thrift.TApplicationException) { + _LOGGER.error("TApplicationException inside handler", e); + msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; + msg = (org.apache.thrift.TApplicationException)e; + } else { + _LOGGER.error("Exception inside handler", e); + msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; + msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); + } + try { + fcall.sendResponse(fb,msg,msgType,seqid); + } catch (Exception ex) { + _LOGGER.error("Exception writing to internal frame buffer", ex); + fb.close(); + } + } + }; + } + + protected boolean isOneway() { + return false; + } + + public void start(I iface, sayHelloTimes_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { + iface.sayHelloTimes(args.name, args.times,resultHandler); + } + } + + public static class timeOut extends org.apache.thrift.AsyncProcessFunction { + public timeOut() { + super("timeOut"); + } + + public timeOut_args getEmptyArgsInstance() { + return new timeOut_args(); + } + + public org.apache.thrift.async.AsyncMethodCallback getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) { + final org.apache.thrift.AsyncProcessFunction fcall = this; + return new org.apache.thrift.async.AsyncMethodCallback() { + public void onComplete(Void o) { + timeOut_result result = new timeOut_result(); + try { + fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); + } catch (org.apache.thrift.transport.TTransportException e) { + _LOGGER.error("TTransportException writing to internal frame buffer", e); + fb.close(); + } catch (Exception e) { + _LOGGER.error("Exception writing to internal frame buffer", e); + onError(e); + } + } + public void onError(Exception e) { + byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; + org.apache.thrift.TSerializable msg; + timeOut_result result = new timeOut_result(); + if (e instanceof org.apache.thrift.transport.TTransportException) { + _LOGGER.error("TTransportException inside handler", e); + fb.close(); + return; + } else if (e instanceof org.apache.thrift.TApplicationException) { + _LOGGER.error("TApplicationException inside handler", e); + msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; + msg = (org.apache.thrift.TApplicationException)e; + } else { + _LOGGER.error("Exception inside handler", e); + msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; + msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); + } + try { + fcall.sendResponse(fb,msg,msgType,seqid); + } catch (Exception ex) { + _LOGGER.error("Exception writing to internal frame buffer", ex); + fb.close(); + } + } + }; + } + + protected boolean isOneway() { + return false; + } + + public void start(I iface, timeOut_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { + iface.timeOut(args.millis,resultHandler); + } + } + + public static class customException extends org.apache.thrift.AsyncProcessFunction { + public customException() { + super("customException"); + } + + public customException_args getEmptyArgsInstance() { + return new customException_args(); + } + + public org.apache.thrift.async.AsyncMethodCallback getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) { + final org.apache.thrift.AsyncProcessFunction fcall = this; + return new org.apache.thrift.async.AsyncMethodCallback() { + public void onComplete(String o) { + customException_result result = new customException_result(); + result.success = o; + try { + fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); + } catch (org.apache.thrift.transport.TTransportException e) { + _LOGGER.error("TTransportException writing to internal frame buffer", e); + fb.close(); + } catch (Exception e) { + _LOGGER.error("Exception writing to internal frame buffer", e); + onError(e); + } + } + public void onError(Exception e) { + byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; + org.apache.thrift.TSerializable msg; + customException_result result = new customException_result(); + if (e instanceof org.apache.thrift.transport.TTransportException) { + _LOGGER.error("TTransportException inside handler", e); + fb.close(); + return; + } else if (e instanceof org.apache.thrift.TApplicationException) { + _LOGGER.error("TApplicationException inside handler", e); + msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; + msg = (org.apache.thrift.TApplicationException)e; + } else { + _LOGGER.error("Exception inside handler", e); + msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; + msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); + } + try { + fcall.sendResponse(fb,msg,msgType,seqid); + } catch (Exception ex) { + _LOGGER.error("Exception writing to internal frame buffer", ex); + fb.close(); + } + } + }; + } + + protected boolean isOneway() { + return false; + } + + public void start(I iface, customException_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { + iface.customException(resultHandler); + } + } + + public static class context extends org.apache.thrift.AsyncProcessFunction { + public context() { + super("context"); + } + + public context_args getEmptyArgsInstance() { + return new context_args(); + } + + public org.apache.thrift.async.AsyncMethodCallback getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) { + final org.apache.thrift.AsyncProcessFunction fcall = this; + return new org.apache.thrift.async.AsyncMethodCallback() { + public void onComplete(String o) { + context_result result = new context_result(); + result.success = o; + try { + fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); + } catch (org.apache.thrift.transport.TTransportException e) { + _LOGGER.error("TTransportException writing to internal frame buffer", e); + fb.close(); + } catch (Exception e) { + _LOGGER.error("Exception writing to internal frame buffer", e); + onError(e); + } + } + public void onError(Exception e) { + byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; + org.apache.thrift.TSerializable msg; + context_result result = new context_result(); + if (e instanceof org.apache.thrift.transport.TTransportException) { + _LOGGER.error("TTransportException inside handler", e); + fb.close(); + return; + } else if (e instanceof org.apache.thrift.TApplicationException) { + _LOGGER.error("TApplicationException inside handler", e); + msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; + msg = (org.apache.thrift.TApplicationException)e; + } else { + _LOGGER.error("Exception inside handler", e); + msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; + msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); + } + try { + fcall.sendResponse(fb,msg,msgType,seqid); + } catch (Exception ex) { + _LOGGER.error("Exception writing to internal frame buffer", ex); + fb.close(); + } + } + }; + } + + protected boolean isOneway() { + return false; + } + + public void start(I iface, context_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { + iface.context(args.name,resultHandler); + } + } + + } + + public static class sayHello_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { + private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("sayHello_args"); + + private static final org.apache.thrift.protocol.TField NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("name", org.apache.thrift.protocol.TType.STRING, (short)1); + + private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new sayHello_argsStandardSchemeFactory(); + private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new sayHello_argsTupleSchemeFactory(); + + public String name; // required + + /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ + public enum _Fields implements org.apache.thrift.TFieldIdEnum { + NAME((short)1, "name"); + + private static final java.util.Map byName = new java.util.HashMap(); + + static { + for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { + byName.put(field.getFieldName(), field); + } + } + + /** + * Find the _Fields constant that matches fieldId, or null if its not found. + */ + public static _Fields findByThriftId(int fieldId) { + switch(fieldId) { + case 1: // NAME + return NAME; + default: + return null; + } + } + + /** + * Find the _Fields constant that matches fieldId, throwing an exception + * if it is not found. + */ + public static _Fields findByThriftIdOrThrow(int fieldId) { + _Fields fields = findByThriftId(fieldId); + if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); + return fields; + } + + /** + * Find the _Fields constant that matches name, or null if its not found. + */ + public static _Fields findByName(String name) { + return byName.get(name); + } + + private final short _thriftId; + private final String _fieldName; + + _Fields(short thriftId, String fieldName) { + _thriftId = thriftId; + _fieldName = fieldName; + } + + public short getThriftFieldId() { + return _thriftId; + } + + public String getFieldName() { + return _fieldName; + } + } + + // isset id assignments + public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; + static { + java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); + tmpMap.put(_Fields.NAME, new org.apache.thrift.meta_data.FieldMetaData("name", org.apache.thrift.TFieldRequirementType.REQUIRED, + new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); + metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); + org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(sayHello_args.class, metaDataMap); + } + + public sayHello_args() { + } + + public sayHello_args( + String name) + { + this(); + this.name = name; + } + + /** + * Performs a deep copy on other. + */ + public sayHello_args(sayHello_args other) { + if (other.isSetName()) { + this.name = other.name; + } + } + + public sayHello_args deepCopy() { + return new sayHello_args(this); + } + + @Override + public void clear() { + this.name = null; + } + + public String getName() { + return this.name; + } + + public sayHello_args setName(String name) { + this.name = name; + return this; + } + + public void unsetName() { + this.name = null; + } + + /** Returns true if field name is set (has been assigned a value) and false otherwise */ + public boolean isSetName() { + return this.name != null; + } + + public void setNameIsSet(boolean value) { + if (!value) { + this.name = null; + } + } + + public void setFieldValue(_Fields field, Object value) { + switch (field) { + case NAME: + if (value == null) { + unsetName(); + } else { + setName((String)value); + } + break; + + } + } + + public Object getFieldValue(_Fields field) { + switch (field) { + case NAME: + return getName(); + + } + throw new IllegalStateException(); + } + + /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ + public boolean isSet(_Fields field) { + if (field == null) { + throw new IllegalArgumentException(); + } + + switch (field) { + case NAME: + return isSetName(); + } + throw new IllegalStateException(); + } + + @Override + public boolean equals(Object that) { + if (that == null) + return false; + if (that instanceof sayHello_args) + return this.equals((sayHello_args)that); + return false; + } + + public boolean equals(sayHello_args that) { + if (that == null) + return false; + if (this == that) + return true; + + boolean this_present_name = true && this.isSetName(); + boolean that_present_name = true && that.isSetName(); + if (this_present_name || that_present_name) { + if (!(this_present_name && that_present_name)) + return false; + if (!this.name.equals(that.name)) + return false; + } + + return true; + } + + @Override + public int hashCode() { + int hashCode = 1; + + hashCode = hashCode * 8191 + ((isSetName()) ? 131071 : 524287); + if (isSetName()) + hashCode = hashCode * 8191 + name.hashCode(); + + return hashCode; + } + + @Override + public int compareTo(sayHello_args other) { + if (!getClass().equals(other.getClass())) { + return getClass().getName().compareTo(other.getClass().getName()); + } + + int lastComparison = 0; + + lastComparison = Boolean.valueOf(isSetName()).compareTo(other.isSetName()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetName()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.name, other.name); + if (lastComparison != 0) { + return lastComparison; + } + } + return 0; + } + + public _Fields fieldForId(int fieldId) { + return _Fields.findByThriftId(fieldId); + } + + public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { + scheme(iprot).read(iprot, this); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { + scheme(oprot).write(oprot, this); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("sayHello_args("); + boolean first = true; + + sb.append("name:"); + if (this.name == null) { + sb.append("null"); + } else { + sb.append(this.name); + } + first = false; + sb.append(")"); + return sb.toString(); + } + + public void validate() throws org.apache.thrift.TException { + // check for required fields + if (name == null) { + throw new org.apache.thrift.protocol.TProtocolException("Required field 'name' was not present! Struct: " + toString()); + } + // check for sub-struct validity + } + + private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { + try { + write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { + try { + read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private static class sayHello_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public sayHello_argsStandardScheme getScheme() { + return new sayHello_argsStandardScheme(); + } + } + + private static class sayHello_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme { + + public void read(org.apache.thrift.protocol.TProtocol iprot, sayHello_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TField schemeField; + iprot.readStructBegin(); + while (true) + { + schemeField = iprot.readFieldBegin(); + if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { + break; + } + switch (schemeField.id) { + case 1: // NAME + if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { + struct.name = iprot.readString(); + struct.setNameIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + default: + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + iprot.readFieldEnd(); + } + iprot.readStructEnd(); + + // check for required fields of primitive type, which can't be checked in the validate method + struct.validate(); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot, sayHello_args struct) throws org.apache.thrift.TException { + struct.validate(); + + oprot.writeStructBegin(STRUCT_DESC); + if (struct.name != null) { + oprot.writeFieldBegin(NAME_FIELD_DESC); + oprot.writeString(struct.name); + oprot.writeFieldEnd(); + } + oprot.writeFieldStop(); + oprot.writeStructEnd(); + } + + } + + private static class sayHello_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public sayHello_argsTupleScheme getScheme() { + return new sayHello_argsTupleScheme(); + } + } + + private static class sayHello_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme { + + @Override + public void write(org.apache.thrift.protocol.TProtocol prot, sayHello_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + oprot.writeString(struct.name); + } + + @Override + public void read(org.apache.thrift.protocol.TProtocol prot, sayHello_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + struct.name = iprot.readString(); + struct.setNameIsSet(true); + } + } + + private static S scheme(org.apache.thrift.protocol.TProtocol proto) { + return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); + } + } + + public static class sayHello_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { + private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("sayHello_result"); + + private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRING, (short)0); + + private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new sayHello_resultStandardSchemeFactory(); + private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new sayHello_resultTupleSchemeFactory(); + + public String success; // required + + /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ + public enum _Fields implements org.apache.thrift.TFieldIdEnum { + SUCCESS((short)0, "success"); + + private static final java.util.Map byName = new java.util.HashMap(); + + static { + for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { + byName.put(field.getFieldName(), field); + } + } + + /** + * Find the _Fields constant that matches fieldId, or null if its not found. + */ + public static _Fields findByThriftId(int fieldId) { + switch(fieldId) { + case 0: // SUCCESS + return SUCCESS; + default: + return null; + } + } + + /** + * Find the _Fields constant that matches fieldId, throwing an exception + * if it is not found. + */ + public static _Fields findByThriftIdOrThrow(int fieldId) { + _Fields fields = findByThriftId(fieldId); + if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); + return fields; + } + + /** + * Find the _Fields constant that matches name, or null if its not found. + */ + public static _Fields findByName(String name) { + return byName.get(name); + } + + private final short _thriftId; + private final String _fieldName; + + _Fields(short thriftId, String fieldName) { + _thriftId = thriftId; + _fieldName = fieldName; + } + + public short getThriftFieldId() { + return _thriftId; + } + + public String getFieldName() { + return _fieldName; + } + } + + // isset id assignments + public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; + static { + java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); + tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, + new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); + metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); + org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(sayHello_result.class, metaDataMap); + } + + public sayHello_result() { + } + + public sayHello_result( + String success) + { + this(); + this.success = success; + } + + /** + * Performs a deep copy on other. + */ + public sayHello_result(sayHello_result other) { + if (other.isSetSuccess()) { + this.success = other.success; + } + } + + public sayHello_result deepCopy() { + return new sayHello_result(this); + } + + @Override + public void clear() { + this.success = null; + } + + public String getSuccess() { + return this.success; + } + + public sayHello_result setSuccess(String success) { + this.success = success; + return this; + } + + public void unsetSuccess() { + this.success = null; + } + + /** Returns true if field success is set (has been assigned a value) and false otherwise */ + public boolean isSetSuccess() { + return this.success != null; + } + + public void setSuccessIsSet(boolean value) { + if (!value) { + this.success = null; + } + } + + public void setFieldValue(_Fields field, Object value) { + switch (field) { + case SUCCESS: + if (value == null) { + unsetSuccess(); + } else { + setSuccess((String)value); + } + break; + + } + } + + public Object getFieldValue(_Fields field) { + switch (field) { + case SUCCESS: + return getSuccess(); + + } + throw new IllegalStateException(); + } + + /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ + public boolean isSet(_Fields field) { + if (field == null) { + throw new IllegalArgumentException(); + } + + switch (field) { + case SUCCESS: + return isSetSuccess(); + } + throw new IllegalStateException(); + } + + @Override + public boolean equals(Object that) { + if (that == null) + return false; + if (that instanceof sayHello_result) + return this.equals((sayHello_result)that); + return false; + } + + public boolean equals(sayHello_result that) { + if (that == null) + return false; + if (this == that) + return true; + + boolean this_present_success = true && this.isSetSuccess(); + boolean that_present_success = true && that.isSetSuccess(); + if (this_present_success || that_present_success) { + if (!(this_present_success && that_present_success)) + return false; + if (!this.success.equals(that.success)) + return false; + } + + return true; + } + + @Override + public int hashCode() { + int hashCode = 1; + + hashCode = hashCode * 8191 + ((isSetSuccess()) ? 131071 : 524287); + if (isSetSuccess()) + hashCode = hashCode * 8191 + success.hashCode(); + + return hashCode; + } + + @Override + public int compareTo(sayHello_result other) { + if (!getClass().equals(other.getClass())) { + return getClass().getName().compareTo(other.getClass().getName()); + } + + int lastComparison = 0; + + lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetSuccess()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); + if (lastComparison != 0) { + return lastComparison; + } + } + return 0; + } + + public _Fields fieldForId(int fieldId) { + return _Fields.findByThriftId(fieldId); + } + + public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { + scheme(iprot).read(iprot, this); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { + scheme(oprot).write(oprot, this); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("sayHello_result("); + boolean first = true; + + sb.append("success:"); + if (this.success == null) { + sb.append("null"); + } else { + sb.append(this.success); + } + first = false; + sb.append(")"); + return sb.toString(); + } + + public void validate() throws org.apache.thrift.TException { + // check for required fields + // check for sub-struct validity + } + + private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { + try { + write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { + try { + read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private static class sayHello_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public sayHello_resultStandardScheme getScheme() { + return new sayHello_resultStandardScheme(); + } + } + + private static class sayHello_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme { + + public void read(org.apache.thrift.protocol.TProtocol iprot, sayHello_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TField schemeField; + iprot.readStructBegin(); + while (true) + { + schemeField = iprot.readFieldBegin(); + if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { + break; + } + switch (schemeField.id) { + case 0: // SUCCESS + if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { + struct.success = iprot.readString(); + struct.setSuccessIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + default: + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + iprot.readFieldEnd(); + } + iprot.readStructEnd(); + + // check for required fields of primitive type, which can't be checked in the validate method + struct.validate(); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot, sayHello_result struct) throws org.apache.thrift.TException { + struct.validate(); + + oprot.writeStructBegin(STRUCT_DESC); + if (struct.success != null) { + oprot.writeFieldBegin(SUCCESS_FIELD_DESC); + oprot.writeString(struct.success); + oprot.writeFieldEnd(); + } + oprot.writeFieldStop(); + oprot.writeStructEnd(); + } + + } + + private static class sayHello_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public sayHello_resultTupleScheme getScheme() { + return new sayHello_resultTupleScheme(); + } + } + + private static class sayHello_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme { + + @Override + public void write(org.apache.thrift.protocol.TProtocol prot, sayHello_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet optionals = new java.util.BitSet(); + if (struct.isSetSuccess()) { + optionals.set(0); + } + oprot.writeBitSet(optionals, 1); + if (struct.isSetSuccess()) { + oprot.writeString(struct.success); + } + } + + @Override + public void read(org.apache.thrift.protocol.TProtocol prot, sayHello_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet incoming = iprot.readBitSet(1); + if (incoming.get(0)) { + struct.success = iprot.readString(); + struct.setSuccessIsSet(true); + } + } + } + + private static S scheme(org.apache.thrift.protocol.TProtocol proto) { + return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); + } + } + + public static class hasName_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { + private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("hasName_args"); + + private static final org.apache.thrift.protocol.TField HAS_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("hasName", org.apache.thrift.protocol.TType.BOOL, (short)1); + + private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new hasName_argsStandardSchemeFactory(); + private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new hasName_argsTupleSchemeFactory(); + + public boolean hasName; // required + + /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ + public enum _Fields implements org.apache.thrift.TFieldIdEnum { + HAS_NAME((short)1, "hasName"); + + private static final java.util.Map byName = new java.util.HashMap(); + + static { + for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { + byName.put(field.getFieldName(), field); + } + } + + /** + * Find the _Fields constant that matches fieldId, or null if its not found. + */ + public static _Fields findByThriftId(int fieldId) { + switch(fieldId) { + case 1: // HAS_NAME + return HAS_NAME; + default: + return null; + } + } + + /** + * Find the _Fields constant that matches fieldId, throwing an exception + * if it is not found. + */ + public static _Fields findByThriftIdOrThrow(int fieldId) { + _Fields fields = findByThriftId(fieldId); + if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); + return fields; + } + + /** + * Find the _Fields constant that matches name, or null if its not found. + */ + public static _Fields findByName(String name) { + return byName.get(name); + } + + private final short _thriftId; + private final String _fieldName; + + _Fields(short thriftId, String fieldName) { + _thriftId = thriftId; + _fieldName = fieldName; + } + + public short getThriftFieldId() { + return _thriftId; + } + + public String getFieldName() { + return _fieldName; + } + } + + // isset id assignments + private static final int __HASNAME_ISSET_ID = 0; + private byte __isset_bitfield = 0; + public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; + static { + java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); + tmpMap.put(_Fields.HAS_NAME, new org.apache.thrift.meta_data.FieldMetaData("hasName", org.apache.thrift.TFieldRequirementType.REQUIRED, + new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); + metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); + org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(hasName_args.class, metaDataMap); + } + + public hasName_args() { + } + + public hasName_args( + boolean hasName) + { + this(); + this.hasName = hasName; + setHasNameIsSet(true); + } + + /** + * Performs a deep copy on other. + */ + public hasName_args(hasName_args other) { + __isset_bitfield = other.__isset_bitfield; + this.hasName = other.hasName; + } + + public hasName_args deepCopy() { + return new hasName_args(this); + } + + @Override + public void clear() { + setHasNameIsSet(false); + this.hasName = false; + } + + public boolean isHasName() { + return this.hasName; + } + + public hasName_args setHasName(boolean hasName) { + this.hasName = hasName; + setHasNameIsSet(true); + return this; + } + + public void unsetHasName() { + __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __HASNAME_ISSET_ID); + } + + /** Returns true if field hasName is set (has been assigned a value) and false otherwise */ + public boolean isSetHasName() { + return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __HASNAME_ISSET_ID); + } + + public void setHasNameIsSet(boolean value) { + __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __HASNAME_ISSET_ID, value); + } + + public void setFieldValue(_Fields field, Object value) { + switch (field) { + case HAS_NAME: + if (value == null) { + unsetHasName(); + } else { + setHasName((Boolean)value); + } + break; + + } + } + + public Object getFieldValue(_Fields field) { + switch (field) { + case HAS_NAME: + return isHasName(); + + } + throw new IllegalStateException(); + } + + /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ + public boolean isSet(_Fields field) { + if (field == null) { + throw new IllegalArgumentException(); + } + + switch (field) { + case HAS_NAME: + return isSetHasName(); + } + throw new IllegalStateException(); + } + + @Override + public boolean equals(Object that) { + if (that == null) + return false; + if (that instanceof hasName_args) + return this.equals((hasName_args)that); + return false; + } + + public boolean equals(hasName_args that) { + if (that == null) + return false; + if (this == that) + return true; + + boolean this_present_hasName = true; + boolean that_present_hasName = true; + if (this_present_hasName || that_present_hasName) { + if (!(this_present_hasName && that_present_hasName)) + return false; + if (this.hasName != that.hasName) + return false; + } + + return true; + } + + @Override + public int hashCode() { + int hashCode = 1; + + hashCode = hashCode * 8191 + ((hasName) ? 131071 : 524287); + + return hashCode; + } + + @Override + public int compareTo(hasName_args other) { + if (!getClass().equals(other.getClass())) { + return getClass().getName().compareTo(other.getClass().getName()); + } + + int lastComparison = 0; + + lastComparison = Boolean.valueOf(isSetHasName()).compareTo(other.isSetHasName()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetHasName()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.hasName, other.hasName); + if (lastComparison != 0) { + return lastComparison; + } + } + return 0; + } + + public _Fields fieldForId(int fieldId) { + return _Fields.findByThriftId(fieldId); + } + + public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { + scheme(iprot).read(iprot, this); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { + scheme(oprot).write(oprot, this); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("hasName_args("); + boolean first = true; + + sb.append("hasName:"); + sb.append(this.hasName); + first = false; + sb.append(")"); + return sb.toString(); + } + + public void validate() throws org.apache.thrift.TException { + // check for required fields + // alas, we cannot check 'hasName' because it's a primitive and you chose the non-beans generator. + // check for sub-struct validity + } + + private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { + try { + write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { + try { + // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. + __isset_bitfield = 0; + read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private static class hasName_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public hasName_argsStandardScheme getScheme() { + return new hasName_argsStandardScheme(); + } + } + + private static class hasName_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme { + + public void read(org.apache.thrift.protocol.TProtocol iprot, hasName_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TField schemeField; + iprot.readStructBegin(); + while (true) + { + schemeField = iprot.readFieldBegin(); + if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { + break; + } + switch (schemeField.id) { + case 1: // HAS_NAME + if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { + struct.hasName = iprot.readBool(); + struct.setHasNameIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + default: + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + iprot.readFieldEnd(); + } + iprot.readStructEnd(); + + // check for required fields of primitive type, which can't be checked in the validate method + if (!struct.isSetHasName()) { + throw new org.apache.thrift.protocol.TProtocolException("Required field 'hasName' was not found in serialized data! Struct: " + toString()); + } + struct.validate(); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot, hasName_args struct) throws org.apache.thrift.TException { + struct.validate(); + + oprot.writeStructBegin(STRUCT_DESC); + oprot.writeFieldBegin(HAS_NAME_FIELD_DESC); + oprot.writeBool(struct.hasName); + oprot.writeFieldEnd(); + oprot.writeFieldStop(); + oprot.writeStructEnd(); + } + + } + + private static class hasName_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public hasName_argsTupleScheme getScheme() { + return new hasName_argsTupleScheme(); + } + } + + private static class hasName_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme { + + @Override + public void write(org.apache.thrift.protocol.TProtocol prot, hasName_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + oprot.writeBool(struct.hasName); + } + + @Override + public void read(org.apache.thrift.protocol.TProtocol prot, hasName_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + struct.hasName = iprot.readBool(); + struct.setHasNameIsSet(true); + } + } + + private static S scheme(org.apache.thrift.protocol.TProtocol proto) { + return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); + } + } + + public static class hasName_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { + private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("hasName_result"); + + private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.BOOL, (short)0); + + private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new hasName_resultStandardSchemeFactory(); + private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new hasName_resultTupleSchemeFactory(); + + public boolean success; // required + + /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ + public enum _Fields implements org.apache.thrift.TFieldIdEnum { + SUCCESS((short)0, "success"); + + private static final java.util.Map byName = new java.util.HashMap(); + + static { + for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { + byName.put(field.getFieldName(), field); + } + } + + /** + * Find the _Fields constant that matches fieldId, or null if its not found. + */ + public static _Fields findByThriftId(int fieldId) { + switch(fieldId) { + case 0: // SUCCESS + return SUCCESS; + default: + return null; + } + } + + /** + * Find the _Fields constant that matches fieldId, throwing an exception + * if it is not found. + */ + public static _Fields findByThriftIdOrThrow(int fieldId) { + _Fields fields = findByThriftId(fieldId); + if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); + return fields; + } + + /** + * Find the _Fields constant that matches name, or null if its not found. + */ + public static _Fields findByName(String name) { + return byName.get(name); + } + + private final short _thriftId; + private final String _fieldName; + + _Fields(short thriftId, String fieldName) { + _thriftId = thriftId; + _fieldName = fieldName; + } + + public short getThriftFieldId() { + return _thriftId; + } + + public String getFieldName() { + return _fieldName; + } + } + + // isset id assignments + private static final int __SUCCESS_ISSET_ID = 0; + private byte __isset_bitfield = 0; + public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; + static { + java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); + tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, + new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); + metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); + org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(hasName_result.class, metaDataMap); + } + + public hasName_result() { + } + + public hasName_result( + boolean success) + { + this(); + this.success = success; + setSuccessIsSet(true); + } + + /** + * Performs a deep copy on other. + */ + public hasName_result(hasName_result other) { + __isset_bitfield = other.__isset_bitfield; + this.success = other.success; + } + + public hasName_result deepCopy() { + return new hasName_result(this); + } + + @Override + public void clear() { + setSuccessIsSet(false); + this.success = false; + } + + public boolean isSuccess() { + return this.success; + } + + public hasName_result setSuccess(boolean success) { + this.success = success; + setSuccessIsSet(true); + return this; + } + + public void unsetSuccess() { + __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID); + } + + /** Returns true if field success is set (has been assigned a value) and false otherwise */ + public boolean isSetSuccess() { + return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID); + } + + public void setSuccessIsSet(boolean value) { + __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value); + } + + public void setFieldValue(_Fields field, Object value) { + switch (field) { + case SUCCESS: + if (value == null) { + unsetSuccess(); + } else { + setSuccess((Boolean)value); + } + break; + + } + } + + public Object getFieldValue(_Fields field) { + switch (field) { + case SUCCESS: + return isSuccess(); + + } + throw new IllegalStateException(); + } + + /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ + public boolean isSet(_Fields field) { + if (field == null) { + throw new IllegalArgumentException(); + } + + switch (field) { + case SUCCESS: + return isSetSuccess(); + } + throw new IllegalStateException(); + } + + @Override + public boolean equals(Object that) { + if (that == null) + return false; + if (that instanceof hasName_result) + return this.equals((hasName_result)that); + return false; + } + + public boolean equals(hasName_result that) { + if (that == null) + return false; + if (this == that) + return true; + + boolean this_present_success = true; + boolean that_present_success = true; + if (this_present_success || that_present_success) { + if (!(this_present_success && that_present_success)) + return false; + if (this.success != that.success) + return false; + } + + return true; + } + + @Override + public int hashCode() { + int hashCode = 1; + + hashCode = hashCode * 8191 + ((success) ? 131071 : 524287); + + return hashCode; + } + + @Override + public int compareTo(hasName_result other) { + if (!getClass().equals(other.getClass())) { + return getClass().getName().compareTo(other.getClass().getName()); + } + + int lastComparison = 0; + + lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetSuccess()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); + if (lastComparison != 0) { + return lastComparison; + } + } + return 0; + } + + public _Fields fieldForId(int fieldId) { + return _Fields.findByThriftId(fieldId); + } + + public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { + scheme(iprot).read(iprot, this); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { + scheme(oprot).write(oprot, this); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("hasName_result("); + boolean first = true; + + sb.append("success:"); + sb.append(this.success); + first = false; + sb.append(")"); + return sb.toString(); + } + + public void validate() throws org.apache.thrift.TException { + // check for required fields + // check for sub-struct validity + } + + private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { + try { + write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { + try { + // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. + __isset_bitfield = 0; + read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private static class hasName_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public hasName_resultStandardScheme getScheme() { + return new hasName_resultStandardScheme(); + } + } + + private static class hasName_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme { + + public void read(org.apache.thrift.protocol.TProtocol iprot, hasName_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TField schemeField; + iprot.readStructBegin(); + while (true) + { + schemeField = iprot.readFieldBegin(); + if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { + break; + } + switch (schemeField.id) { + case 0: // SUCCESS + if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { + struct.success = iprot.readBool(); + struct.setSuccessIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + default: + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + iprot.readFieldEnd(); + } + iprot.readStructEnd(); + + // check for required fields of primitive type, which can't be checked in the validate method + struct.validate(); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot, hasName_result struct) throws org.apache.thrift.TException { + struct.validate(); + + oprot.writeStructBegin(STRUCT_DESC); + if (struct.isSetSuccess()) { + oprot.writeFieldBegin(SUCCESS_FIELD_DESC); + oprot.writeBool(struct.success); + oprot.writeFieldEnd(); + } + oprot.writeFieldStop(); + oprot.writeStructEnd(); + } + + } + + private static class hasName_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public hasName_resultTupleScheme getScheme() { + return new hasName_resultTupleScheme(); + } + } + + private static class hasName_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme { + + @Override + public void write(org.apache.thrift.protocol.TProtocol prot, hasName_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet optionals = new java.util.BitSet(); + if (struct.isSetSuccess()) { + optionals.set(0); + } + oprot.writeBitSet(optionals, 1); + if (struct.isSetSuccess()) { + oprot.writeBool(struct.success); + } + } + + @Override + public void read(org.apache.thrift.protocol.TProtocol prot, hasName_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet incoming = iprot.readBitSet(1); + if (incoming.get(0)) { + struct.success = iprot.readBool(); + struct.setSuccessIsSet(true); + } + } + } + + private static S scheme(org.apache.thrift.protocol.TProtocol proto) { + return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); + } + } + + public static class sayHelloTimes_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { + private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("sayHelloTimes_args"); + + private static final org.apache.thrift.protocol.TField NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("name", org.apache.thrift.protocol.TType.STRING, (short)1); + private static final org.apache.thrift.protocol.TField TIMES_FIELD_DESC = new org.apache.thrift.protocol.TField("times", org.apache.thrift.protocol.TType.I32, (short)2); + + private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new sayHelloTimes_argsStandardSchemeFactory(); + private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new sayHelloTimes_argsTupleSchemeFactory(); + + public String name; // required + public int times; // required + + /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ + public enum _Fields implements org.apache.thrift.TFieldIdEnum { + NAME((short)1, "name"), + TIMES((short)2, "times"); + + private static final java.util.Map byName = new java.util.HashMap(); + + static { + for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { + byName.put(field.getFieldName(), field); + } + } + + /** + * Find the _Fields constant that matches fieldId, or null if its not found. + */ + public static _Fields findByThriftId(int fieldId) { + switch(fieldId) { + case 1: // NAME + return NAME; + case 2: // TIMES + return TIMES; + default: + return null; + } + } + + /** + * Find the _Fields constant that matches fieldId, throwing an exception + * if it is not found. + */ + public static _Fields findByThriftIdOrThrow(int fieldId) { + _Fields fields = findByThriftId(fieldId); + if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); + return fields; + } + + /** + * Find the _Fields constant that matches name, or null if its not found. + */ + public static _Fields findByName(String name) { + return byName.get(name); + } + + private final short _thriftId; + private final String _fieldName; + + _Fields(short thriftId, String fieldName) { + _thriftId = thriftId; + _fieldName = fieldName; + } + + public short getThriftFieldId() { + return _thriftId; + } + + public String getFieldName() { + return _fieldName; + } + } + + // isset id assignments + private static final int __TIMES_ISSET_ID = 0; + private byte __isset_bitfield = 0; + public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; + static { + java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); + tmpMap.put(_Fields.NAME, new org.apache.thrift.meta_data.FieldMetaData("name", org.apache.thrift.TFieldRequirementType.REQUIRED, + new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); + tmpMap.put(_Fields.TIMES, new org.apache.thrift.meta_data.FieldMetaData("times", org.apache.thrift.TFieldRequirementType.REQUIRED, + new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); + metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); + org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(sayHelloTimes_args.class, metaDataMap); + } + + public sayHelloTimes_args() { + } + + public sayHelloTimes_args( + String name, + int times) + { + this(); + this.name = name; + this.times = times; + setTimesIsSet(true); + } + + /** + * Performs a deep copy on other. + */ + public sayHelloTimes_args(sayHelloTimes_args other) { + __isset_bitfield = other.__isset_bitfield; + if (other.isSetName()) { + this.name = other.name; + } + this.times = other.times; + } + + public sayHelloTimes_args deepCopy() { + return new sayHelloTimes_args(this); + } + + @Override + public void clear() { + this.name = null; + setTimesIsSet(false); + this.times = 0; + } + + public String getName() { + return this.name; + } + + public sayHelloTimes_args setName(String name) { + this.name = name; + return this; + } + + public void unsetName() { + this.name = null; + } + + /** Returns true if field name is set (has been assigned a value) and false otherwise */ + public boolean isSetName() { + return this.name != null; + } + + public void setNameIsSet(boolean value) { + if (!value) { + this.name = null; + } + } + + public int getTimes() { + return this.times; + } + + public sayHelloTimes_args setTimes(int times) { + this.times = times; + setTimesIsSet(true); + return this; + } + + public void unsetTimes() { + __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __TIMES_ISSET_ID); + } + + /** Returns true if field times is set (has been assigned a value) and false otherwise */ + public boolean isSetTimes() { + return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __TIMES_ISSET_ID); + } + + public void setTimesIsSet(boolean value) { + __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __TIMES_ISSET_ID, value); + } + + public void setFieldValue(_Fields field, Object value) { + switch (field) { + case NAME: + if (value == null) { + unsetName(); + } else { + setName((String)value); + } + break; + + case TIMES: + if (value == null) { + unsetTimes(); + } else { + setTimes((Integer)value); + } + break; + + } + } + + public Object getFieldValue(_Fields field) { + switch (field) { + case NAME: + return getName(); + + case TIMES: + return getTimes(); + + } + throw new IllegalStateException(); + } + + /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ + public boolean isSet(_Fields field) { + if (field == null) { + throw new IllegalArgumentException(); + } + + switch (field) { + case NAME: + return isSetName(); + case TIMES: + return isSetTimes(); + } + throw new IllegalStateException(); + } + + @Override + public boolean equals(Object that) { + if (that == null) + return false; + if (that instanceof sayHelloTimes_args) + return this.equals((sayHelloTimes_args)that); + return false; + } + + public boolean equals(sayHelloTimes_args that) { + if (that == null) + return false; + if (this == that) + return true; + + boolean this_present_name = true && this.isSetName(); + boolean that_present_name = true && that.isSetName(); + if (this_present_name || that_present_name) { + if (!(this_present_name && that_present_name)) + return false; + if (!this.name.equals(that.name)) + return false; + } + + boolean this_present_times = true; + boolean that_present_times = true; + if (this_present_times || that_present_times) { + if (!(this_present_times && that_present_times)) + return false; + if (this.times != that.times) + return false; + } + + return true; + } + + @Override + public int hashCode() { + int hashCode = 1; + + hashCode = hashCode * 8191 + ((isSetName()) ? 131071 : 524287); + if (isSetName()) + hashCode = hashCode * 8191 + name.hashCode(); + + hashCode = hashCode * 8191 + times; + + return hashCode; + } + + @Override + public int compareTo(sayHelloTimes_args other) { + if (!getClass().equals(other.getClass())) { + return getClass().getName().compareTo(other.getClass().getName()); + } + + int lastComparison = 0; + + lastComparison = Boolean.valueOf(isSetName()).compareTo(other.isSetName()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetName()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.name, other.name); + if (lastComparison != 0) { + return lastComparison; + } + } + lastComparison = Boolean.valueOf(isSetTimes()).compareTo(other.isSetTimes()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetTimes()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.times, other.times); + if (lastComparison != 0) { + return lastComparison; + } + } + return 0; + } + + public _Fields fieldForId(int fieldId) { + return _Fields.findByThriftId(fieldId); + } + + public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { + scheme(iprot).read(iprot, this); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { + scheme(oprot).write(oprot, this); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("sayHelloTimes_args("); + boolean first = true; + + sb.append("name:"); + if (this.name == null) { + sb.append("null"); + } else { + sb.append(this.name); + } + first = false; + if (!first) sb.append(", "); + sb.append("times:"); + sb.append(this.times); + first = false; + sb.append(")"); + return sb.toString(); + } + + public void validate() throws org.apache.thrift.TException { + // check for required fields + if (name == null) { + throw new org.apache.thrift.protocol.TProtocolException("Required field 'name' was not present! Struct: " + toString()); + } + // alas, we cannot check 'times' because it's a primitive and you chose the non-beans generator. + // check for sub-struct validity + } + + private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { + try { + write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { + try { + // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. + __isset_bitfield = 0; + read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private static class sayHelloTimes_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public sayHelloTimes_argsStandardScheme getScheme() { + return new sayHelloTimes_argsStandardScheme(); + } + } + + private static class sayHelloTimes_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme { + + public void read(org.apache.thrift.protocol.TProtocol iprot, sayHelloTimes_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TField schemeField; + iprot.readStructBegin(); + while (true) + { + schemeField = iprot.readFieldBegin(); + if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { + break; + } + switch (schemeField.id) { + case 1: // NAME + if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { + struct.name = iprot.readString(); + struct.setNameIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + case 2: // TIMES + if (schemeField.type == org.apache.thrift.protocol.TType.I32) { + struct.times = iprot.readI32(); + struct.setTimesIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + default: + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + iprot.readFieldEnd(); + } + iprot.readStructEnd(); + + // check for required fields of primitive type, which can't be checked in the validate method + if (!struct.isSetTimes()) { + throw new org.apache.thrift.protocol.TProtocolException("Required field 'times' was not found in serialized data! Struct: " + toString()); + } + struct.validate(); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot, sayHelloTimes_args struct) throws org.apache.thrift.TException { + struct.validate(); + + oprot.writeStructBegin(STRUCT_DESC); + if (struct.name != null) { + oprot.writeFieldBegin(NAME_FIELD_DESC); + oprot.writeString(struct.name); + oprot.writeFieldEnd(); + } + oprot.writeFieldBegin(TIMES_FIELD_DESC); + oprot.writeI32(struct.times); + oprot.writeFieldEnd(); + oprot.writeFieldStop(); + oprot.writeStructEnd(); + } + + } + + private static class sayHelloTimes_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public sayHelloTimes_argsTupleScheme getScheme() { + return new sayHelloTimes_argsTupleScheme(); + } + } + + private static class sayHelloTimes_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme { + + @Override + public void write(org.apache.thrift.protocol.TProtocol prot, sayHelloTimes_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + oprot.writeString(struct.name); + oprot.writeI32(struct.times); + } + + @Override + public void read(org.apache.thrift.protocol.TProtocol prot, sayHelloTimes_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + struct.name = iprot.readString(); + struct.setNameIsSet(true); + struct.times = iprot.readI32(); + struct.setTimesIsSet(true); + } + } + + private static S scheme(org.apache.thrift.protocol.TProtocol proto) { + return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); + } + } + + public static class sayHelloTimes_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { + private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("sayHelloTimes_result"); + + private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRING, (short)0); + + private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new sayHelloTimes_resultStandardSchemeFactory(); + private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new sayHelloTimes_resultTupleSchemeFactory(); + + public String success; // required + + /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ + public enum _Fields implements org.apache.thrift.TFieldIdEnum { + SUCCESS((short)0, "success"); + + private static final java.util.Map byName = new java.util.HashMap(); + + static { + for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { + byName.put(field.getFieldName(), field); + } + } + + /** + * Find the _Fields constant that matches fieldId, or null if its not found. + */ + public static _Fields findByThriftId(int fieldId) { + switch(fieldId) { + case 0: // SUCCESS + return SUCCESS; + default: + return null; + } + } + + /** + * Find the _Fields constant that matches fieldId, throwing an exception + * if it is not found. + */ + public static _Fields findByThriftIdOrThrow(int fieldId) { + _Fields fields = findByThriftId(fieldId); + if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); + return fields; + } + + /** + * Find the _Fields constant that matches name, or null if its not found. + */ + public static _Fields findByName(String name) { + return byName.get(name); + } + + private final short _thriftId; + private final String _fieldName; + + _Fields(short thriftId, String fieldName) { + _thriftId = thriftId; + _fieldName = fieldName; + } + + public short getThriftFieldId() { + return _thriftId; + } + + public String getFieldName() { + return _fieldName; + } + } + + // isset id assignments + public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; + static { + java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); + tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, + new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); + metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); + org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(sayHelloTimes_result.class, metaDataMap); + } + + public sayHelloTimes_result() { + } + + public sayHelloTimes_result( + String success) + { + this(); + this.success = success; + } + + /** + * Performs a deep copy on other. + */ + public sayHelloTimes_result(sayHelloTimes_result other) { + if (other.isSetSuccess()) { + this.success = other.success; + } + } + + public sayHelloTimes_result deepCopy() { + return new sayHelloTimes_result(this); + } + + @Override + public void clear() { + this.success = null; + } + + public String getSuccess() { + return this.success; + } + + public sayHelloTimes_result setSuccess(String success) { + this.success = success; + return this; + } + + public void unsetSuccess() { + this.success = null; + } + + /** Returns true if field success is set (has been assigned a value) and false otherwise */ + public boolean isSetSuccess() { + return this.success != null; + } + + public void setSuccessIsSet(boolean value) { + if (!value) { + this.success = null; + } + } + + public void setFieldValue(_Fields field, Object value) { + switch (field) { + case SUCCESS: + if (value == null) { + unsetSuccess(); + } else { + setSuccess((String)value); + } + break; + + } + } + + public Object getFieldValue(_Fields field) { + switch (field) { + case SUCCESS: + return getSuccess(); + + } + throw new IllegalStateException(); + } + + /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ + public boolean isSet(_Fields field) { + if (field == null) { + throw new IllegalArgumentException(); + } + + switch (field) { + case SUCCESS: + return isSetSuccess(); + } + throw new IllegalStateException(); + } + + @Override + public boolean equals(Object that) { + if (that == null) + return false; + if (that instanceof sayHelloTimes_result) + return this.equals((sayHelloTimes_result)that); + return false; + } + + public boolean equals(sayHelloTimes_result that) { + if (that == null) + return false; + if (this == that) + return true; + + boolean this_present_success = true && this.isSetSuccess(); + boolean that_present_success = true && that.isSetSuccess(); + if (this_present_success || that_present_success) { + if (!(this_present_success && that_present_success)) + return false; + if (!this.success.equals(that.success)) + return false; + } + + return true; + } + + @Override + public int hashCode() { + int hashCode = 1; + + hashCode = hashCode * 8191 + ((isSetSuccess()) ? 131071 : 524287); + if (isSetSuccess()) + hashCode = hashCode * 8191 + success.hashCode(); + + return hashCode; + } + + @Override + public int compareTo(sayHelloTimes_result other) { + if (!getClass().equals(other.getClass())) { + return getClass().getName().compareTo(other.getClass().getName()); + } + + int lastComparison = 0; + + lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetSuccess()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); + if (lastComparison != 0) { + return lastComparison; + } + } + return 0; + } + + public _Fields fieldForId(int fieldId) { + return _Fields.findByThriftId(fieldId); + } + + public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { + scheme(iprot).read(iprot, this); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { + scheme(oprot).write(oprot, this); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("sayHelloTimes_result("); + boolean first = true; + + sb.append("success:"); + if (this.success == null) { + sb.append("null"); + } else { + sb.append(this.success); + } + first = false; + sb.append(")"); + return sb.toString(); + } + + public void validate() throws org.apache.thrift.TException { + // check for required fields + // check for sub-struct validity + } + + private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { + try { + write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { + try { + read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private static class sayHelloTimes_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public sayHelloTimes_resultStandardScheme getScheme() { + return new sayHelloTimes_resultStandardScheme(); + } + } + + private static class sayHelloTimes_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme { + + public void read(org.apache.thrift.protocol.TProtocol iprot, sayHelloTimes_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TField schemeField; + iprot.readStructBegin(); + while (true) + { + schemeField = iprot.readFieldBegin(); + if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { + break; + } + switch (schemeField.id) { + case 0: // SUCCESS + if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { + struct.success = iprot.readString(); + struct.setSuccessIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + default: + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + iprot.readFieldEnd(); + } + iprot.readStructEnd(); + + // check for required fields of primitive type, which can't be checked in the validate method + struct.validate(); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot, sayHelloTimes_result struct) throws org.apache.thrift.TException { + struct.validate(); + + oprot.writeStructBegin(STRUCT_DESC); + if (struct.success != null) { + oprot.writeFieldBegin(SUCCESS_FIELD_DESC); + oprot.writeString(struct.success); + oprot.writeFieldEnd(); + } + oprot.writeFieldStop(); + oprot.writeStructEnd(); + } + + } + + private static class sayHelloTimes_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public sayHelloTimes_resultTupleScheme getScheme() { + return new sayHelloTimes_resultTupleScheme(); + } + } + + private static class sayHelloTimes_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme { + + @Override + public void write(org.apache.thrift.protocol.TProtocol prot, sayHelloTimes_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet optionals = new java.util.BitSet(); + if (struct.isSetSuccess()) { + optionals.set(0); + } + oprot.writeBitSet(optionals, 1); + if (struct.isSetSuccess()) { + oprot.writeString(struct.success); + } + } + + @Override + public void read(org.apache.thrift.protocol.TProtocol prot, sayHelloTimes_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet incoming = iprot.readBitSet(1); + if (incoming.get(0)) { + struct.success = iprot.readString(); + struct.setSuccessIsSet(true); + } + } + } + + private static S scheme(org.apache.thrift.protocol.TProtocol proto) { + return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); + } + } + + public static class timeOut_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { + private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("timeOut_args"); + + private static final org.apache.thrift.protocol.TField MILLIS_FIELD_DESC = new org.apache.thrift.protocol.TField("millis", org.apache.thrift.protocol.TType.I32, (short)1); + + private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new timeOut_argsStandardSchemeFactory(); + private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new timeOut_argsTupleSchemeFactory(); + + public int millis; // required + + /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ + public enum _Fields implements org.apache.thrift.TFieldIdEnum { + MILLIS((short)1, "millis"); + + private static final java.util.Map byName = new java.util.HashMap(); + + static { + for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { + byName.put(field.getFieldName(), field); + } + } + + /** + * Find the _Fields constant that matches fieldId, or null if its not found. + */ + public static _Fields findByThriftId(int fieldId) { + switch(fieldId) { + case 1: // MILLIS + return MILLIS; + default: + return null; + } + } + + /** + * Find the _Fields constant that matches fieldId, throwing an exception + * if it is not found. + */ + public static _Fields findByThriftIdOrThrow(int fieldId) { + _Fields fields = findByThriftId(fieldId); + if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); + return fields; + } + + /** + * Find the _Fields constant that matches name, or null if its not found. + */ + public static _Fields findByName(String name) { + return byName.get(name); + } + + private final short _thriftId; + private final String _fieldName; + + _Fields(short thriftId, String fieldName) { + _thriftId = thriftId; + _fieldName = fieldName; + } + + public short getThriftFieldId() { + return _thriftId; + } + + public String getFieldName() { + return _fieldName; + } + } + + // isset id assignments + private static final int __MILLIS_ISSET_ID = 0; + private byte __isset_bitfield = 0; + public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; + static { + java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); + tmpMap.put(_Fields.MILLIS, new org.apache.thrift.meta_data.FieldMetaData("millis", org.apache.thrift.TFieldRequirementType.REQUIRED, + new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); + metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); + org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(timeOut_args.class, metaDataMap); + } + + public timeOut_args() { + } + + public timeOut_args( + int millis) + { + this(); + this.millis = millis; + setMillisIsSet(true); + } + + /** + * Performs a deep copy on other. + */ + public timeOut_args(timeOut_args other) { + __isset_bitfield = other.__isset_bitfield; + this.millis = other.millis; + } + + public timeOut_args deepCopy() { + return new timeOut_args(this); + } + + @Override + public void clear() { + setMillisIsSet(false); + this.millis = 0; + } + + public int getMillis() { + return this.millis; + } + + public timeOut_args setMillis(int millis) { + this.millis = millis; + setMillisIsSet(true); + return this; + } + + public void unsetMillis() { + __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __MILLIS_ISSET_ID); + } + + /** Returns true if field millis is set (has been assigned a value) and false otherwise */ + public boolean isSetMillis() { + return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __MILLIS_ISSET_ID); + } + + public void setMillisIsSet(boolean value) { + __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __MILLIS_ISSET_ID, value); + } + + public void setFieldValue(_Fields field, Object value) { + switch (field) { + case MILLIS: + if (value == null) { + unsetMillis(); + } else { + setMillis((Integer)value); + } + break; + + } + } + + public Object getFieldValue(_Fields field) { + switch (field) { + case MILLIS: + return getMillis(); + + } + throw new IllegalStateException(); + } + + /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ + public boolean isSet(_Fields field) { + if (field == null) { + throw new IllegalArgumentException(); + } + + switch (field) { + case MILLIS: + return isSetMillis(); + } + throw new IllegalStateException(); + } + + @Override + public boolean equals(Object that) { + if (that == null) + return false; + if (that instanceof timeOut_args) + return this.equals((timeOut_args)that); + return false; + } + + public boolean equals(timeOut_args that) { + if (that == null) + return false; + if (this == that) + return true; + + boolean this_present_millis = true; + boolean that_present_millis = true; + if (this_present_millis || that_present_millis) { + if (!(this_present_millis && that_present_millis)) + return false; + if (this.millis != that.millis) + return false; + } + + return true; + } + + @Override + public int hashCode() { + int hashCode = 1; + + hashCode = hashCode * 8191 + millis; + + return hashCode; + } + + @Override + public int compareTo(timeOut_args other) { + if (!getClass().equals(other.getClass())) { + return getClass().getName().compareTo(other.getClass().getName()); + } + + int lastComparison = 0; + + lastComparison = Boolean.valueOf(isSetMillis()).compareTo(other.isSetMillis()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetMillis()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.millis, other.millis); + if (lastComparison != 0) { + return lastComparison; + } + } + return 0; + } + + public _Fields fieldForId(int fieldId) { + return _Fields.findByThriftId(fieldId); + } + + public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { + scheme(iprot).read(iprot, this); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { + scheme(oprot).write(oprot, this); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("timeOut_args("); + boolean first = true; + + sb.append("millis:"); + sb.append(this.millis); + first = false; + sb.append(")"); + return sb.toString(); + } + + public void validate() throws org.apache.thrift.TException { + // check for required fields + // alas, we cannot check 'millis' because it's a primitive and you chose the non-beans generator. + // check for sub-struct validity + } + + private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { + try { + write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { + try { + // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. + __isset_bitfield = 0; + read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private static class timeOut_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public timeOut_argsStandardScheme getScheme() { + return new timeOut_argsStandardScheme(); + } + } + + private static class timeOut_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme { + + public void read(org.apache.thrift.protocol.TProtocol iprot, timeOut_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TField schemeField; + iprot.readStructBegin(); + while (true) + { + schemeField = iprot.readFieldBegin(); + if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { + break; + } + switch (schemeField.id) { + case 1: // MILLIS + if (schemeField.type == org.apache.thrift.protocol.TType.I32) { + struct.millis = iprot.readI32(); + struct.setMillisIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + default: + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + iprot.readFieldEnd(); + } + iprot.readStructEnd(); + + // check for required fields of primitive type, which can't be checked in the validate method + if (!struct.isSetMillis()) { + throw new org.apache.thrift.protocol.TProtocolException("Required field 'millis' was not found in serialized data! Struct: " + toString()); + } + struct.validate(); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot, timeOut_args struct) throws org.apache.thrift.TException { + struct.validate(); + + oprot.writeStructBegin(STRUCT_DESC); + oprot.writeFieldBegin(MILLIS_FIELD_DESC); + oprot.writeI32(struct.millis); + oprot.writeFieldEnd(); + oprot.writeFieldStop(); + oprot.writeStructEnd(); + } + + } + + private static class timeOut_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public timeOut_argsTupleScheme getScheme() { + return new timeOut_argsTupleScheme(); + } + } + + private static class timeOut_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme { + + @Override + public void write(org.apache.thrift.protocol.TProtocol prot, timeOut_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + oprot.writeI32(struct.millis); + } + + @Override + public void read(org.apache.thrift.protocol.TProtocol prot, timeOut_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + struct.millis = iprot.readI32(); + struct.setMillisIsSet(true); + } + } + + private static S scheme(org.apache.thrift.protocol.TProtocol proto) { + return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); + } + } + + public static class timeOut_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { + private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("timeOut_result"); + + + private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new timeOut_resultStandardSchemeFactory(); + private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new timeOut_resultTupleSchemeFactory(); + + + /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ + public enum _Fields implements org.apache.thrift.TFieldIdEnum { + ; + + private static final java.util.Map byName = new java.util.HashMap(); + + static { + for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { + byName.put(field.getFieldName(), field); + } + } + + /** + * Find the _Fields constant that matches fieldId, or null if its not found. + */ + public static _Fields findByThriftId(int fieldId) { + switch(fieldId) { + default: + return null; + } + } + + /** + * Find the _Fields constant that matches fieldId, throwing an exception + * if it is not found. + */ + public static _Fields findByThriftIdOrThrow(int fieldId) { + _Fields fields = findByThriftId(fieldId); + if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); + return fields; + } + + /** + * Find the _Fields constant that matches name, or null if its not found. + */ + public static _Fields findByName(String name) { + return byName.get(name); + } + + private final short _thriftId; + private final String _fieldName; + + _Fields(short thriftId, String fieldName) { + _thriftId = thriftId; + _fieldName = fieldName; + } + + public short getThriftFieldId() { + return _thriftId; + } + + public String getFieldName() { + return _fieldName; + } + } + public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; + static { + java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); + metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); + org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(timeOut_result.class, metaDataMap); + } + + public timeOut_result() { + } + + /** + * Performs a deep copy on other. + */ + public timeOut_result(timeOut_result other) { + } + + public timeOut_result deepCopy() { + return new timeOut_result(this); + } + + @Override + public void clear() { + } + + public void setFieldValue(_Fields field, Object value) { + switch (field) { + } + } + + public Object getFieldValue(_Fields field) { + switch (field) { + } + throw new IllegalStateException(); + } + + /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ + public boolean isSet(_Fields field) { + if (field == null) { + throw new IllegalArgumentException(); + } + + switch (field) { + } + throw new IllegalStateException(); + } + + @Override + public boolean equals(Object that) { + if (that == null) + return false; + if (that instanceof timeOut_result) + return this.equals((timeOut_result)that); + return false; + } + + public boolean equals(timeOut_result that) { + if (that == null) + return false; + if (this == that) + return true; + + return true; + } + + @Override + public int hashCode() { + int hashCode = 1; + + return hashCode; + } + + @Override + public int compareTo(timeOut_result other) { + if (!getClass().equals(other.getClass())) { + return getClass().getName().compareTo(other.getClass().getName()); + } + + int lastComparison = 0; + + return 0; + } + + public _Fields fieldForId(int fieldId) { + return _Fields.findByThriftId(fieldId); + } + + public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { + scheme(iprot).read(iprot, this); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { + scheme(oprot).write(oprot, this); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("timeOut_result("); + boolean first = true; + + sb.append(")"); + return sb.toString(); + } + + public void validate() throws org.apache.thrift.TException { + // check for required fields + // check for sub-struct validity + } + + private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { + try { + write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { + try { + read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private static class timeOut_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public timeOut_resultStandardScheme getScheme() { + return new timeOut_resultStandardScheme(); + } + } + + private static class timeOut_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme { + + public void read(org.apache.thrift.protocol.TProtocol iprot, timeOut_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TField schemeField; + iprot.readStructBegin(); + while (true) + { + schemeField = iprot.readFieldBegin(); + if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { + break; + } + switch (schemeField.id) { + default: + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + iprot.readFieldEnd(); + } + iprot.readStructEnd(); + + // check for required fields of primitive type, which can't be checked in the validate method + struct.validate(); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot, timeOut_result struct) throws org.apache.thrift.TException { + struct.validate(); + + oprot.writeStructBegin(STRUCT_DESC); + oprot.writeFieldStop(); + oprot.writeStructEnd(); + } + + } + + private static class timeOut_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public timeOut_resultTupleScheme getScheme() { + return new timeOut_resultTupleScheme(); + } + } + + private static class timeOut_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme { + + @Override + public void write(org.apache.thrift.protocol.TProtocol prot, timeOut_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + } + + @Override + public void read(org.apache.thrift.protocol.TProtocol prot, timeOut_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + } + } + + private static S scheme(org.apache.thrift.protocol.TProtocol proto) { + return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); + } + } + + public static class customException_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { + private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("customException_args"); + + + private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new customException_argsStandardSchemeFactory(); + private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new customException_argsTupleSchemeFactory(); + + + /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ + public enum _Fields implements org.apache.thrift.TFieldIdEnum { + ; + + private static final java.util.Map byName = new java.util.HashMap(); + + static { + for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { + byName.put(field.getFieldName(), field); + } + } + + /** + * Find the _Fields constant that matches fieldId, or null if its not found. + */ + public static _Fields findByThriftId(int fieldId) { + switch(fieldId) { + default: + return null; + } + } + + /** + * Find the _Fields constant that matches fieldId, throwing an exception + * if it is not found. + */ + public static _Fields findByThriftIdOrThrow(int fieldId) { + _Fields fields = findByThriftId(fieldId); + if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); + return fields; + } + + /** + * Find the _Fields constant that matches name, or null if its not found. + */ + public static _Fields findByName(String name) { + return byName.get(name); + } + + private final short _thriftId; + private final String _fieldName; + + _Fields(short thriftId, String fieldName) { + _thriftId = thriftId; + _fieldName = fieldName; + } + + public short getThriftFieldId() { + return _thriftId; + } + + public String getFieldName() { + return _fieldName; + } + } + public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; + static { + java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); + metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); + org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(customException_args.class, metaDataMap); + } + + public customException_args() { + } + + /** + * Performs a deep copy on other. + */ + public customException_args(customException_args other) { + } + + public customException_args deepCopy() { + return new customException_args(this); + } + + @Override + public void clear() { + } + + public void setFieldValue(_Fields field, Object value) { + switch (field) { + } + } + + public Object getFieldValue(_Fields field) { + switch (field) { + } + throw new IllegalStateException(); + } + + /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ + public boolean isSet(_Fields field) { + if (field == null) { + throw new IllegalArgumentException(); + } + + switch (field) { + } + throw new IllegalStateException(); + } + + @Override + public boolean equals(Object that) { + if (that == null) + return false; + if (that instanceof customException_args) + return this.equals((customException_args)that); + return false; + } + + public boolean equals(customException_args that) { + if (that == null) + return false; + if (this == that) + return true; + + return true; + } + + @Override + public int hashCode() { + int hashCode = 1; + + return hashCode; + } + + @Override + public int compareTo(customException_args other) { + if (!getClass().equals(other.getClass())) { + return getClass().getName().compareTo(other.getClass().getName()); + } + + int lastComparison = 0; + + return 0; + } + + public _Fields fieldForId(int fieldId) { + return _Fields.findByThriftId(fieldId); + } + + public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { + scheme(iprot).read(iprot, this); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { + scheme(oprot).write(oprot, this); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("customException_args("); + boolean first = true; + + sb.append(")"); + return sb.toString(); + } + + public void validate() throws org.apache.thrift.TException { + // check for required fields + // check for sub-struct validity + } + + private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { + try { + write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { + try { + read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private static class customException_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public customException_argsStandardScheme getScheme() { + return new customException_argsStandardScheme(); + } + } + + private static class customException_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme { + + public void read(org.apache.thrift.protocol.TProtocol iprot, customException_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TField schemeField; + iprot.readStructBegin(); + while (true) + { + schemeField = iprot.readFieldBegin(); + if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { + break; + } + switch (schemeField.id) { + default: + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + iprot.readFieldEnd(); + } + iprot.readStructEnd(); + + // check for required fields of primitive type, which can't be checked in the validate method + struct.validate(); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot, customException_args struct) throws org.apache.thrift.TException { + struct.validate(); + + oprot.writeStructBegin(STRUCT_DESC); + oprot.writeFieldStop(); + oprot.writeStructEnd(); + } + + } + + private static class customException_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public customException_argsTupleScheme getScheme() { + return new customException_argsTupleScheme(); + } + } + + private static class customException_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme { + + @Override + public void write(org.apache.thrift.protocol.TProtocol prot, customException_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + } + + @Override + public void read(org.apache.thrift.protocol.TProtocol prot, customException_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + } + } + + private static S scheme(org.apache.thrift.protocol.TProtocol proto) { + return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); + } + } + + public static class customException_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { + private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("customException_result"); + + private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRING, (short)0); + + private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new customException_resultStandardSchemeFactory(); + private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new customException_resultTupleSchemeFactory(); + + public String success; // required + + /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ + public enum _Fields implements org.apache.thrift.TFieldIdEnum { + SUCCESS((short)0, "success"); + + private static final java.util.Map byName = new java.util.HashMap(); + + static { + for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { + byName.put(field.getFieldName(), field); + } + } + + /** + * Find the _Fields constant that matches fieldId, or null if its not found. + */ + public static _Fields findByThriftId(int fieldId) { + switch(fieldId) { + case 0: // SUCCESS + return SUCCESS; + default: + return null; + } + } + + /** + * Find the _Fields constant that matches fieldId, throwing an exception + * if it is not found. + */ + public static _Fields findByThriftIdOrThrow(int fieldId) { + _Fields fields = findByThriftId(fieldId); + if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); + return fields; + } + + /** + * Find the _Fields constant that matches name, or null if its not found. + */ + public static _Fields findByName(String name) { + return byName.get(name); + } + + private final short _thriftId; + private final String _fieldName; + + _Fields(short thriftId, String fieldName) { + _thriftId = thriftId; + _fieldName = fieldName; + } + + public short getThriftFieldId() { + return _thriftId; + } + + public String getFieldName() { + return _fieldName; + } + } + + // isset id assignments + public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; + static { + java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); + tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, + new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); + metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); + org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(customException_result.class, metaDataMap); + } + + public customException_result() { + } + + public customException_result( + String success) + { + this(); + this.success = success; + } + + /** + * Performs a deep copy on other. + */ + public customException_result(customException_result other) { + if (other.isSetSuccess()) { + this.success = other.success; + } + } + + public customException_result deepCopy() { + return new customException_result(this); + } + + @Override + public void clear() { + this.success = null; + } + + public String getSuccess() { + return this.success; + } + + public customException_result setSuccess(String success) { + this.success = success; + return this; + } + + public void unsetSuccess() { + this.success = null; + } + + /** Returns true if field success is set (has been assigned a value) and false otherwise */ + public boolean isSetSuccess() { + return this.success != null; + } + + public void setSuccessIsSet(boolean value) { + if (!value) { + this.success = null; + } + } + + public void setFieldValue(_Fields field, Object value) { + switch (field) { + case SUCCESS: + if (value == null) { + unsetSuccess(); + } else { + setSuccess((String)value); + } + break; + + } + } + + public Object getFieldValue(_Fields field) { + switch (field) { + case SUCCESS: + return getSuccess(); + + } + throw new IllegalStateException(); + } + + /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ + public boolean isSet(_Fields field) { + if (field == null) { + throw new IllegalArgumentException(); + } + + switch (field) { + case SUCCESS: + return isSetSuccess(); + } + throw new IllegalStateException(); + } + + @Override + public boolean equals(Object that) { + if (that == null) + return false; + if (that instanceof customException_result) + return this.equals((customException_result)that); + return false; + } + + public boolean equals(customException_result that) { + if (that == null) + return false; + if (this == that) + return true; + + boolean this_present_success = true && this.isSetSuccess(); + boolean that_present_success = true && that.isSetSuccess(); + if (this_present_success || that_present_success) { + if (!(this_present_success && that_present_success)) + return false; + if (!this.success.equals(that.success)) + return false; + } + + return true; + } + + @Override + public int hashCode() { + int hashCode = 1; + + hashCode = hashCode * 8191 + ((isSetSuccess()) ? 131071 : 524287); + if (isSetSuccess()) + hashCode = hashCode * 8191 + success.hashCode(); + + return hashCode; + } + + @Override + public int compareTo(customException_result other) { + if (!getClass().equals(other.getClass())) { + return getClass().getName().compareTo(other.getClass().getName()); + } + + int lastComparison = 0; + + lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetSuccess()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); + if (lastComparison != 0) { + return lastComparison; + } + } + return 0; + } + + public _Fields fieldForId(int fieldId) { + return _Fields.findByThriftId(fieldId); + } + + public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { + scheme(iprot).read(iprot, this); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { + scheme(oprot).write(oprot, this); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("customException_result("); + boolean first = true; + + sb.append("success:"); + if (this.success == null) { + sb.append("null"); + } else { + sb.append(this.success); + } + first = false; + sb.append(")"); + return sb.toString(); + } + + public void validate() throws org.apache.thrift.TException { + // check for required fields + // check for sub-struct validity + } + + private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { + try { + write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { + try { + read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private static class customException_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public customException_resultStandardScheme getScheme() { + return new customException_resultStandardScheme(); + } + } + + private static class customException_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme { + + public void read(org.apache.thrift.protocol.TProtocol iprot, customException_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TField schemeField; + iprot.readStructBegin(); + while (true) + { + schemeField = iprot.readFieldBegin(); + if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { + break; + } + switch (schemeField.id) { + case 0: // SUCCESS + if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { + struct.success = iprot.readString(); + struct.setSuccessIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + default: + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + iprot.readFieldEnd(); + } + iprot.readStructEnd(); + + // check for required fields of primitive type, which can't be checked in the validate method + struct.validate(); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot, customException_result struct) throws org.apache.thrift.TException { + struct.validate(); + + oprot.writeStructBegin(STRUCT_DESC); + if (struct.success != null) { + oprot.writeFieldBegin(SUCCESS_FIELD_DESC); + oprot.writeString(struct.success); + oprot.writeFieldEnd(); + } + oprot.writeFieldStop(); + oprot.writeStructEnd(); + } + + } + + private static class customException_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public customException_resultTupleScheme getScheme() { + return new customException_resultTupleScheme(); + } + } + + private static class customException_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme { + + @Override + public void write(org.apache.thrift.protocol.TProtocol prot, customException_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet optionals = new java.util.BitSet(); + if (struct.isSetSuccess()) { + optionals.set(0); + } + oprot.writeBitSet(optionals, 1); + if (struct.isSetSuccess()) { + oprot.writeString(struct.success); + } + } + + @Override + public void read(org.apache.thrift.protocol.TProtocol prot, customException_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet incoming = iprot.readBitSet(1); + if (incoming.get(0)) { + struct.success = iprot.readString(); + struct.setSuccessIsSet(true); + } + } + } + + private static S scheme(org.apache.thrift.protocol.TProtocol proto) { + return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); + } + } + + public static class context_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { + private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("context_args"); + + private static final org.apache.thrift.protocol.TField NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("name", org.apache.thrift.protocol.TType.STRING, (short)1); + + private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new context_argsStandardSchemeFactory(); + private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new context_argsTupleSchemeFactory(); + + public String name; // required + + /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ + public enum _Fields implements org.apache.thrift.TFieldIdEnum { + NAME((short)1, "name"); + + private static final java.util.Map byName = new java.util.HashMap(); + + static { + for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { + byName.put(field.getFieldName(), field); + } + } + + /** + * Find the _Fields constant that matches fieldId, or null if its not found. + */ + public static _Fields findByThriftId(int fieldId) { + switch(fieldId) { + case 1: // NAME + return NAME; + default: + return null; + } + } + + /** + * Find the _Fields constant that matches fieldId, throwing an exception + * if it is not found. + */ + public static _Fields findByThriftIdOrThrow(int fieldId) { + _Fields fields = findByThriftId(fieldId); + if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); + return fields; + } + + /** + * Find the _Fields constant that matches name, or null if its not found. + */ + public static _Fields findByName(String name) { + return byName.get(name); + } + + private final short _thriftId; + private final String _fieldName; + + _Fields(short thriftId, String fieldName) { + _thriftId = thriftId; + _fieldName = fieldName; + } + + public short getThriftFieldId() { + return _thriftId; + } + + public String getFieldName() { + return _fieldName; + } + } + + // isset id assignments + public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; + static { + java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); + tmpMap.put(_Fields.NAME, new org.apache.thrift.meta_data.FieldMetaData("name", org.apache.thrift.TFieldRequirementType.REQUIRED, + new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); + metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); + org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(context_args.class, metaDataMap); + } + + public context_args() { + } + + public context_args( + String name) + { + this(); + this.name = name; + } + + /** + * Performs a deep copy on other. + */ + public context_args(context_args other) { + if (other.isSetName()) { + this.name = other.name; + } + } + + public context_args deepCopy() { + return new context_args(this); + } + + @Override + public void clear() { + this.name = null; + } + + public String getName() { + return this.name; + } + + public context_args setName(String name) { + this.name = name; + return this; + } + + public void unsetName() { + this.name = null; + } + + /** Returns true if field name is set (has been assigned a value) and false otherwise */ + public boolean isSetName() { + return this.name != null; + } + + public void setNameIsSet(boolean value) { + if (!value) { + this.name = null; + } + } + + public void setFieldValue(_Fields field, Object value) { + switch (field) { + case NAME: + if (value == null) { + unsetName(); + } else { + setName((String)value); + } + break; + + } + } + + public Object getFieldValue(_Fields field) { + switch (field) { + case NAME: + return getName(); + + } + throw new IllegalStateException(); + } + + /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ + public boolean isSet(_Fields field) { + if (field == null) { + throw new IllegalArgumentException(); + } + + switch (field) { + case NAME: + return isSetName(); + } + throw new IllegalStateException(); + } + + @Override + public boolean equals(Object that) { + if (that == null) + return false; + if (that instanceof context_args) + return this.equals((context_args)that); + return false; + } + + public boolean equals(context_args that) { + if (that == null) + return false; + if (this == that) + return true; + + boolean this_present_name = true && this.isSetName(); + boolean that_present_name = true && that.isSetName(); + if (this_present_name || that_present_name) { + if (!(this_present_name && that_present_name)) + return false; + if (!this.name.equals(that.name)) + return false; + } + + return true; + } + + @Override + public int hashCode() { + int hashCode = 1; + + hashCode = hashCode * 8191 + ((isSetName()) ? 131071 : 524287); + if (isSetName()) + hashCode = hashCode * 8191 + name.hashCode(); + + return hashCode; + } + + @Override + public int compareTo(context_args other) { + if (!getClass().equals(other.getClass())) { + return getClass().getName().compareTo(other.getClass().getName()); + } + + int lastComparison = 0; + + lastComparison = Boolean.valueOf(isSetName()).compareTo(other.isSetName()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetName()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.name, other.name); + if (lastComparison != 0) { + return lastComparison; + } + } + return 0; + } + + public _Fields fieldForId(int fieldId) { + return _Fields.findByThriftId(fieldId); + } + + public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { + scheme(iprot).read(iprot, this); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { + scheme(oprot).write(oprot, this); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("context_args("); + boolean first = true; + + sb.append("name:"); + if (this.name == null) { + sb.append("null"); + } else { + sb.append(this.name); + } + first = false; + sb.append(")"); + return sb.toString(); + } + + public void validate() throws org.apache.thrift.TException { + // check for required fields + if (name == null) { + throw new org.apache.thrift.protocol.TProtocolException("Required field 'name' was not present! Struct: " + toString()); + } + // check for sub-struct validity + } + + private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { + try { + write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { + try { + read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private static class context_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public context_argsStandardScheme getScheme() { + return new context_argsStandardScheme(); + } + } + + private static class context_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme { + + public void read(org.apache.thrift.protocol.TProtocol iprot, context_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TField schemeField; + iprot.readStructBegin(); + while (true) + { + schemeField = iprot.readFieldBegin(); + if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { + break; + } + switch (schemeField.id) { + case 1: // NAME + if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { + struct.name = iprot.readString(); + struct.setNameIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + default: + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + iprot.readFieldEnd(); + } + iprot.readStructEnd(); + + // check for required fields of primitive type, which can't be checked in the validate method + struct.validate(); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot, context_args struct) throws org.apache.thrift.TException { + struct.validate(); + + oprot.writeStructBegin(STRUCT_DESC); + if (struct.name != null) { + oprot.writeFieldBegin(NAME_FIELD_DESC); + oprot.writeString(struct.name); + oprot.writeFieldEnd(); + } + oprot.writeFieldStop(); + oprot.writeStructEnd(); + } + + } + + private static class context_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public context_argsTupleScheme getScheme() { + return new context_argsTupleScheme(); + } + } + + private static class context_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme { + + @Override + public void write(org.apache.thrift.protocol.TProtocol prot, context_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + oprot.writeString(struct.name); + } + + @Override + public void read(org.apache.thrift.protocol.TProtocol prot, context_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + struct.name = iprot.readString(); + struct.setNameIsSet(true); + } + } + + private static S scheme(org.apache.thrift.protocol.TProtocol proto) { + return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); + } + } + + public static class context_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { + private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("context_result"); + + private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRING, (short)0); + + private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new context_resultStandardSchemeFactory(); + private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new context_resultTupleSchemeFactory(); + + public String success; // required + + /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ + public enum _Fields implements org.apache.thrift.TFieldIdEnum { + SUCCESS((short)0, "success"); + + private static final java.util.Map byName = new java.util.HashMap(); + + static { + for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { + byName.put(field.getFieldName(), field); + } + } + + /** + * Find the _Fields constant that matches fieldId, or null if its not found. + */ + public static _Fields findByThriftId(int fieldId) { + switch(fieldId) { + case 0: // SUCCESS + return SUCCESS; + default: + return null; + } + } + + /** + * Find the _Fields constant that matches fieldId, throwing an exception + * if it is not found. + */ + public static _Fields findByThriftIdOrThrow(int fieldId) { + _Fields fields = findByThriftId(fieldId); + if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); + return fields; + } + + /** + * Find the _Fields constant that matches name, or null if its not found. + */ + public static _Fields findByName(String name) { + return byName.get(name); + } + + private final short _thriftId; + private final String _fieldName; + + _Fields(short thriftId, String fieldName) { + _thriftId = thriftId; + _fieldName = fieldName; + } + + public short getThriftFieldId() { + return _thriftId; + } + + public String getFieldName() { + return _fieldName; + } + } + + // isset id assignments + public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; + static { + java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); + tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, + new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); + metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); + org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(context_result.class, metaDataMap); + } + + public context_result() { + } + + public context_result( + String success) + { + this(); + this.success = success; + } + + /** + * Performs a deep copy on other. + */ + public context_result(context_result other) { + if (other.isSetSuccess()) { + this.success = other.success; + } + } + + public context_result deepCopy() { + return new context_result(this); + } + + @Override + public void clear() { + this.success = null; + } + + public String getSuccess() { + return this.success; + } + + public context_result setSuccess(String success) { + this.success = success; + return this; + } + + public void unsetSuccess() { + this.success = null; + } + + /** Returns true if field success is set (has been assigned a value) and false otherwise */ + public boolean isSetSuccess() { + return this.success != null; + } + + public void setSuccessIsSet(boolean value) { + if (!value) { + this.success = null; + } + } + + public void setFieldValue(_Fields field, Object value) { + switch (field) { + case SUCCESS: + if (value == null) { + unsetSuccess(); + } else { + setSuccess((String)value); + } + break; + + } + } + + public Object getFieldValue(_Fields field) { + switch (field) { + case SUCCESS: + return getSuccess(); + + } + throw new IllegalStateException(); + } + + /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ + public boolean isSet(_Fields field) { + if (field == null) { + throw new IllegalArgumentException(); + } + + switch (field) { + case SUCCESS: + return isSetSuccess(); + } + throw new IllegalStateException(); + } + + @Override + public boolean equals(Object that) { + if (that == null) + return false; + if (that instanceof context_result) + return this.equals((context_result)that); + return false; + } + + public boolean equals(context_result that) { + if (that == null) + return false; + if (this == that) + return true; + + boolean this_present_success = true && this.isSetSuccess(); + boolean that_present_success = true && that.isSetSuccess(); + if (this_present_success || that_present_success) { + if (!(this_present_success && that_present_success)) + return false; + if (!this.success.equals(that.success)) + return false; + } + + return true; + } + + @Override + public int hashCode() { + int hashCode = 1; + + hashCode = hashCode * 8191 + ((isSetSuccess()) ? 131071 : 524287); + if (isSetSuccess()) + hashCode = hashCode * 8191 + success.hashCode(); + + return hashCode; + } + + @Override + public int compareTo(context_result other) { + if (!getClass().equals(other.getClass())) { + return getClass().getName().compareTo(other.getClass().getName()); + } + + int lastComparison = 0; + + lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetSuccess()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); + if (lastComparison != 0) { + return lastComparison; + } + } + return 0; + } + + public _Fields fieldForId(int fieldId) { + return _Fields.findByThriftId(fieldId); + } + + public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { + scheme(iprot).read(iprot, this); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { + scheme(oprot).write(oprot, this); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("context_result("); + boolean first = true; + + sb.append("success:"); + if (this.success == null) { + sb.append("null"); + } else { + sb.append(this.success); + } + first = false; + sb.append(")"); + return sb.toString(); + } + + public void validate() throws org.apache.thrift.TException { + // check for required fields + // check for sub-struct validity + } + + private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { + try { + write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { + try { + read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private static class context_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public context_resultStandardScheme getScheme() { + return new context_resultStandardScheme(); + } + } + + private static class context_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme { + + public void read(org.apache.thrift.protocol.TProtocol iprot, context_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TField schemeField; + iprot.readStructBegin(); + while (true) + { + schemeField = iprot.readFieldBegin(); + if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { + break; + } + switch (schemeField.id) { + case 0: // SUCCESS + if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { + struct.success = iprot.readString(); + struct.setSuccessIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + default: + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + iprot.readFieldEnd(); + } + iprot.readStructEnd(); + + // check for required fields of primitive type, which can't be checked in the validate method + struct.validate(); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot, context_result struct) throws org.apache.thrift.TException { + struct.validate(); + + oprot.writeStructBegin(STRUCT_DESC); + if (struct.success != null) { + oprot.writeFieldBegin(SUCCESS_FIELD_DESC); + oprot.writeString(struct.success); + oprot.writeFieldEnd(); + } + oprot.writeFieldStop(); + oprot.writeStructEnd(); + } + + } + + private static class context_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public context_resultTupleScheme getScheme() { + return new context_resultTupleScheme(); + } + } + + private static class context_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme { + + @Override + public void write(org.apache.thrift.protocol.TProtocol prot, context_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet optionals = new java.util.BitSet(); + if (struct.isSetSuccess()) { + optionals.set(0); + } + oprot.writeBitSet(optionals, 1); + if (struct.isSetSuccess()) { + oprot.writeString(struct.success); + } + } + + @Override + public void read(org.apache.thrift.protocol.TProtocol prot, context_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet incoming = iprot.readBitSet(1); + if (incoming.get(0)) { + struct.success = iprot.readString(); + struct.setSuccessIsSet(true); + } + } + } + + private static S scheme(org.apache.thrift.protocol.TProtocol proto) { + return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); + } + } + +} diff --git a/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/DemoServiceImpl.java b/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/DemoServiceImpl.java new file mode 100644 index 00000000000..37876742c26 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/DemoServiceImpl.java @@ -0,0 +1,78 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.rpc.protocol.nativethrift; + + +import org.apache.dubbo.rpc.RpcContext; +import org.apache.thrift.TException; + +public class DemoServiceImpl implements DemoService.Iface { + private boolean called; + + public String sayHello(String name) { + called = true; + return "Hello, " + name; + } + + @Override + public boolean hasName(boolean hasName) throws TException { + return hasName; + } + + @Override + public String sayHelloTimes(String name, int times) throws TException { + return null; + } + + public String sayHello(String name, int times) { + called = true; + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < times; i++) { + sb.append("Hello, " + name + ". "); + } + return sb.toString(); + } + + public boolean isCalled() { + return called; + } + + public void timeOut(int millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + public String customException() { + throw new MyException("custom exception"); + } + + public String context(String name) { + return "Hello, " + name + " context, " + RpcContext.getContext().getAttachment("myContext"); + } + + static class MyException extends RuntimeException { + + private static final long serialVersionUID = -3051041116483629056L; + + public MyException(String message) { + super(message); + } + } +} diff --git a/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/ThriftProtocolTest.java b/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/ThriftProtocolTest.java new file mode 100644 index 00000000000..76cd1f39839 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/ThriftProtocolTest.java @@ -0,0 +1,81 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.rpc.protocol.nativethrift; + + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.extension.ExtensionLoader; +import org.apache.dubbo.rpc.Exporter; +import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.Protocol; +import org.apache.dubbo.rpc.ProxyFactory; +import org.apache.thrift.TException; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + + +/** + * ThriftProtocolTest + */ +public class ThriftProtocolTest { + + @Test + public void testThriftProtocol() throws TException{ + DemoServiceImpl server = new DemoServiceImpl(); + ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); + URL url = URL.valueOf(org.apache.dubbo.rpc.protocol.nativethrift.ThriftProtocol.NAME + "://127.0.0.1:5341/" + DemoService.Iface.class.getName() + "?version=1.0.0&nativethrift.overload.method=true"); + Exporter exporter = protocol.export(proxyFactory.getInvoker(server, DemoService.Iface.class, url)); + Invoker invoker = protocol.refer(DemoService.Iface.class, url); + DemoService.Iface client = proxyFactory.getProxy(invoker); + String result = client.sayHello("haha"); + Assertions.assertTrue(server.isCalled()); + Assertions.assertEquals("Hello, haha", result); + invoker.destroy(); + exporter.unexport(); + } + + @Test + public void testThriftProtocolMultipleServices() throws TException{ + + ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); + + DemoServiceImpl server1 = new DemoServiceImpl(); + URL url1 = URL.valueOf(org.apache.dubbo.rpc.protocol.nativethrift.ThriftProtocol.NAME + "://127.0.0.1:5342/" + DemoService.Iface.class.getName() + "?version=1.0.0&nativethrift.overload.method=true"); + Exporter exporter1 = protocol.export(proxyFactory.getInvoker(server1, DemoService.Iface.class, url1)); + Invoker invoker1 = protocol.refer(DemoService.Iface.class, url1); + DemoService.Iface client1 = proxyFactory.getProxy(invoker1); + String result1 = client1.sayHello("haha"); + Assertions.assertTrue(server1.isCalled()); + Assertions.assertEquals("Hello, haha", result1); + + UserServiceImpl server2 = new UserServiceImpl(); + URL url2 = URL.valueOf(org.apache.dubbo.rpc.protocol.nativethrift.ThriftProtocol.NAME + "://127.0.0.1:5342/" + UserService.Iface.class.getName() + "?version=1.0.0&nativethrift.overload.method=true"); + Exporter exporter2 = protocol.export(proxyFactory.getInvoker(server2, UserService.Iface.class, url2)); + Invoker invoker2 = protocol.refer(UserService.Iface.class, url2); + UserService.Iface client2 = proxyFactory.getProxy(invoker2); + String result2 = client2.find(2); + Assertions.assertEquals("KK2", result2); + + invoker1.destroy(); + exporter1.unexport(); + invoker2.destroy(); + exporter2.unexport(); + } + +} diff --git a/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/UserService.java b/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/UserService.java new file mode 100644 index 00000000000..3f87cb940e0 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/UserService.java @@ -0,0 +1,952 @@ +/** + * Autogenerated by Thrift Compiler (0.11.0) + * + * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING + * @generated + */ +package org.apache.dubbo.rpc.protocol.nativethrift; + +@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"}) +public class UserService { + + public interface Iface { + + public String find(int id) throws org.apache.thrift.TException; + + } + + public interface AsyncIface { + + public void find(int id, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; + + } + + public static class Client extends org.apache.thrift.TServiceClient implements Iface { + public static class Factory implements org.apache.thrift.TServiceClientFactory { + public Factory() {} + public Client getClient(org.apache.thrift.protocol.TProtocol prot) { + return new Client(prot); + } + public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { + return new Client(iprot, oprot); + } + } + + public Client(org.apache.thrift.protocol.TProtocol prot) + { + super(prot, prot); + } + + public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { + super(iprot, oprot); + } + + public String find(int id) throws org.apache.thrift.TException + { + send_find(id); + return recv_find(); + } + + public void send_find(int id) throws org.apache.thrift.TException + { + find_args args = new find_args(); + args.setId(id); + sendBase("find", args); + } + + public String recv_find() throws org.apache.thrift.TException + { + find_result result = new find_result(); + receiveBase(result, "find"); + if (result.isSetSuccess()) { + return result.success; + } + throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "find failed: unknown result"); + } + + } + public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface { + public static class Factory implements org.apache.thrift.async.TAsyncClientFactory { + private org.apache.thrift.async.TAsyncClientManager clientManager; + private org.apache.thrift.protocol.TProtocolFactory protocolFactory; + public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) { + this.clientManager = clientManager; + this.protocolFactory = protocolFactory; + } + public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) { + return new AsyncClient(protocolFactory, clientManager, transport); + } + } + + public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) { + super(protocolFactory, clientManager, transport); + } + + public void find(int id, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { + checkReady(); + find_call method_call = new find_call(id, resultHandler, this, ___protocolFactory, ___transport); + this.___currentMethod = method_call; + ___manager.call(method_call); + } + + public static class find_call extends org.apache.thrift.async.TAsyncMethodCall { + private int id; + public find_call(int id, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { + super(client, protocolFactory, transport, resultHandler, false); + this.id = id; + } + + public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { + prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("find", org.apache.thrift.protocol.TMessageType.CALL, 0)); + find_args args = new find_args(); + args.setId(id); + args.write(prot); + prot.writeMessageEnd(); + } + + public String getResult() throws org.apache.thrift.TException { + if (getState() != State.RESPONSE_READ) { + throw new IllegalStateException("Method call not finished!"); + } + org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); + org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); + return (new Client(prot)).recv_find(); + } + } + + } + + public static class Processor extends org.apache.thrift.TBaseProcessor implements org.apache.thrift.TProcessor { + private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory.getLogger(Processor.class.getName()); + public Processor(I iface) { + super(iface, getProcessMap(new java.util.HashMap>())); + } + + protected Processor(I iface, java.util.Map> processMap) { + super(iface, getProcessMap(processMap)); + } + + private static java.util.Map> getProcessMap(java.util.Map> processMap) { + processMap.put("find", new find()); + return processMap; + } + + public static class find extends org.apache.thrift.ProcessFunction { + public find() { + super("find"); + } + + public find_args getEmptyArgsInstance() { + return new find_args(); + } + + protected boolean isOneway() { + return false; + } + + protected boolean handleRuntimeExceptions() { + return false; + } + + public find_result getResult(I iface, find_args args) throws org.apache.thrift.TException { + find_result result = new find_result(); + result.success = iface.find(args.id); + return result; + } + } + + } + + public static class AsyncProcessor extends org.apache.thrift.TBaseAsyncProcessor { + private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory.getLogger(AsyncProcessor.class.getName()); + public AsyncProcessor(I iface) { + super(iface, getProcessMap(new java.util.HashMap>())); + } + + protected AsyncProcessor(I iface, java.util.Map> processMap) { + super(iface, getProcessMap(processMap)); + } + + private static java.util.Map> getProcessMap(java.util.Map> processMap) { + processMap.put("find", new find()); + return processMap; + } + + public static class find extends org.apache.thrift.AsyncProcessFunction { + public find() { + super("find"); + } + + public find_args getEmptyArgsInstance() { + return new find_args(); + } + + public org.apache.thrift.async.AsyncMethodCallback getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) { + final org.apache.thrift.AsyncProcessFunction fcall = this; + return new org.apache.thrift.async.AsyncMethodCallback() { + public void onComplete(String o) { + find_result result = new find_result(); + result.success = o; + try { + fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); + } catch (org.apache.thrift.transport.TTransportException e) { + _LOGGER.error("TTransportException writing to internal frame buffer", e); + fb.close(); + } catch (Exception e) { + _LOGGER.error("Exception writing to internal frame buffer", e); + onError(e); + } + } + public void onError(Exception e) { + byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; + org.apache.thrift.TSerializable msg; + find_result result = new find_result(); + if (e instanceof org.apache.thrift.transport.TTransportException) { + _LOGGER.error("TTransportException inside handler", e); + fb.close(); + return; + } else if (e instanceof org.apache.thrift.TApplicationException) { + _LOGGER.error("TApplicationException inside handler", e); + msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; + msg = (org.apache.thrift.TApplicationException)e; + } else { + _LOGGER.error("Exception inside handler", e); + msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; + msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); + } + try { + fcall.sendResponse(fb,msg,msgType,seqid); + } catch (Exception ex) { + _LOGGER.error("Exception writing to internal frame buffer", ex); + fb.close(); + } + } + }; + } + + protected boolean isOneway() { + return false; + } + + public void start(I iface, find_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { + iface.find(args.id,resultHandler); + } + } + + } + + public static class find_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { + private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("find_args"); + + private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.I32, (short)1); + + private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new find_argsStandardSchemeFactory(); + private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new find_argsTupleSchemeFactory(); + + public int id; // required + + /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ + public enum _Fields implements org.apache.thrift.TFieldIdEnum { + ID((short)1, "id"); + + private static final java.util.Map byName = new java.util.HashMap(); + + static { + for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { + byName.put(field.getFieldName(), field); + } + } + + /** + * Find the _Fields constant that matches fieldId, or null if its not found. + */ + public static _Fields findByThriftId(int fieldId) { + switch(fieldId) { + case 1: // ID + return ID; + default: + return null; + } + } + + /** + * Find the _Fields constant that matches fieldId, throwing an exception + * if it is not found. + */ + public static _Fields findByThriftIdOrThrow(int fieldId) { + _Fields fields = findByThriftId(fieldId); + if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); + return fields; + } + + /** + * Find the _Fields constant that matches name, or null if its not found. + */ + public static _Fields findByName(String name) { + return byName.get(name); + } + + private final short _thriftId; + private final String _fieldName; + + _Fields(short thriftId, String fieldName) { + _thriftId = thriftId; + _fieldName = fieldName; + } + + public short getThriftFieldId() { + return _thriftId; + } + + public String getFieldName() { + return _fieldName; + } + } + + // isset id assignments + private static final int __ID_ISSET_ID = 0; + private byte __isset_bitfield = 0; + public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; + static { + java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); + tmpMap.put(_Fields.ID, new org.apache.thrift.meta_data.FieldMetaData("id", org.apache.thrift.TFieldRequirementType.REQUIRED, + new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); + metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); + org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(find_args.class, metaDataMap); + } + + public find_args() { + } + + public find_args( + int id) + { + this(); + this.id = id; + setIdIsSet(true); + } + + /** + * Performs a deep copy on other. + */ + public find_args(find_args other) { + __isset_bitfield = other.__isset_bitfield; + this.id = other.id; + } + + public find_args deepCopy() { + return new find_args(this); + } + + @Override + public void clear() { + setIdIsSet(false); + this.id = 0; + } + + public int getId() { + return this.id; + } + + public find_args setId(int id) { + this.id = id; + setIdIsSet(true); + return this; + } + + public void unsetId() { + __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __ID_ISSET_ID); + } + + /** Returns true if field id is set (has been assigned a value) and false otherwise */ + public boolean isSetId() { + return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __ID_ISSET_ID); + } + + public void setIdIsSet(boolean value) { + __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __ID_ISSET_ID, value); + } + + public void setFieldValue(_Fields field, Object value) { + switch (field) { + case ID: + if (value == null) { + unsetId(); + } else { + setId((Integer)value); + } + break; + + } + } + + public Object getFieldValue(_Fields field) { + switch (field) { + case ID: + return getId(); + + } + throw new IllegalStateException(); + } + + /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ + public boolean isSet(_Fields field) { + if (field == null) { + throw new IllegalArgumentException(); + } + + switch (field) { + case ID: + return isSetId(); + } + throw new IllegalStateException(); + } + + @Override + public boolean equals(Object that) { + if (that == null) + return false; + if (that instanceof find_args) + return this.equals((find_args)that); + return false; + } + + public boolean equals(find_args that) { + if (that == null) + return false; + if (this == that) + return true; + + boolean this_present_id = true; + boolean that_present_id = true; + if (this_present_id || that_present_id) { + if (!(this_present_id && that_present_id)) + return false; + if (this.id != that.id) + return false; + } + + return true; + } + + @Override + public int hashCode() { + int hashCode = 1; + + hashCode = hashCode * 8191 + id; + + return hashCode; + } + + @Override + public int compareTo(find_args other) { + if (!getClass().equals(other.getClass())) { + return getClass().getName().compareTo(other.getClass().getName()); + } + + int lastComparison = 0; + + lastComparison = Boolean.valueOf(isSetId()).compareTo(other.isSetId()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetId()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.id, other.id); + if (lastComparison != 0) { + return lastComparison; + } + } + return 0; + } + + public _Fields fieldForId(int fieldId) { + return _Fields.findByThriftId(fieldId); + } + + public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { + scheme(iprot).read(iprot, this); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { + scheme(oprot).write(oprot, this); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("find_args("); + boolean first = true; + + sb.append("id:"); + sb.append(this.id); + first = false; + sb.append(")"); + return sb.toString(); + } + + public void validate() throws org.apache.thrift.TException { + // check for required fields + // alas, we cannot check 'id' because it's a primitive and you chose the non-beans generator. + // check for sub-struct validity + } + + private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { + try { + write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { + try { + // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. + __isset_bitfield = 0; + read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private static class find_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public find_argsStandardScheme getScheme() { + return new find_argsStandardScheme(); + } + } + + private static class find_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme { + + public void read(org.apache.thrift.protocol.TProtocol iprot, find_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TField schemeField; + iprot.readStructBegin(); + while (true) + { + schemeField = iprot.readFieldBegin(); + if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { + break; + } + switch (schemeField.id) { + case 1: // ID + if (schemeField.type == org.apache.thrift.protocol.TType.I32) { + struct.id = iprot.readI32(); + struct.setIdIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + default: + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + iprot.readFieldEnd(); + } + iprot.readStructEnd(); + + // check for required fields of primitive type, which can't be checked in the validate method + if (!struct.isSetId()) { + throw new org.apache.thrift.protocol.TProtocolException("Required field 'id' was not found in serialized data! Struct: " + toString()); + } + struct.validate(); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot, find_args struct) throws org.apache.thrift.TException { + struct.validate(); + + oprot.writeStructBegin(STRUCT_DESC); + oprot.writeFieldBegin(ID_FIELD_DESC); + oprot.writeI32(struct.id); + oprot.writeFieldEnd(); + oprot.writeFieldStop(); + oprot.writeStructEnd(); + } + + } + + private static class find_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public find_argsTupleScheme getScheme() { + return new find_argsTupleScheme(); + } + } + + private static class find_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme { + + @Override + public void write(org.apache.thrift.protocol.TProtocol prot, find_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + oprot.writeI32(struct.id); + } + + @Override + public void read(org.apache.thrift.protocol.TProtocol prot, find_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + struct.id = iprot.readI32(); + struct.setIdIsSet(true); + } + } + + private static S scheme(org.apache.thrift.protocol.TProtocol proto) { + return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); + } + } + + public static class find_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { + private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("find_result"); + + private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRING, (short)0); + + private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new find_resultStandardSchemeFactory(); + private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new find_resultTupleSchemeFactory(); + + public String success; // required + + /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ + public enum _Fields implements org.apache.thrift.TFieldIdEnum { + SUCCESS((short)0, "success"); + + private static final java.util.Map byName = new java.util.HashMap(); + + static { + for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { + byName.put(field.getFieldName(), field); + } + } + + /** + * Find the _Fields constant that matches fieldId, or null if its not found. + */ + public static _Fields findByThriftId(int fieldId) { + switch(fieldId) { + case 0: // SUCCESS + return SUCCESS; + default: + return null; + } + } + + /** + * Find the _Fields constant that matches fieldId, throwing an exception + * if it is not found. + */ + public static _Fields findByThriftIdOrThrow(int fieldId) { + _Fields fields = findByThriftId(fieldId); + if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); + return fields; + } + + /** + * Find the _Fields constant that matches name, or null if its not found. + */ + public static _Fields findByName(String name) { + return byName.get(name); + } + + private final short _thriftId; + private final String _fieldName; + + _Fields(short thriftId, String fieldName) { + _thriftId = thriftId; + _fieldName = fieldName; + } + + public short getThriftFieldId() { + return _thriftId; + } + + public String getFieldName() { + return _fieldName; + } + } + + // isset id assignments + public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; + static { + java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); + tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, + new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); + metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); + org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(find_result.class, metaDataMap); + } + + public find_result() { + } + + public find_result( + String success) + { + this(); + this.success = success; + } + + /** + * Performs a deep copy on other. + */ + public find_result(find_result other) { + if (other.isSetSuccess()) { + this.success = other.success; + } + } + + public find_result deepCopy() { + return new find_result(this); + } + + @Override + public void clear() { + this.success = null; + } + + public String getSuccess() { + return this.success; + } + + public find_result setSuccess(String success) { + this.success = success; + return this; + } + + public void unsetSuccess() { + this.success = null; + } + + /** Returns true if field success is set (has been assigned a value) and false otherwise */ + public boolean isSetSuccess() { + return this.success != null; + } + + public void setSuccessIsSet(boolean value) { + if (!value) { + this.success = null; + } + } + + public void setFieldValue(_Fields field, Object value) { + switch (field) { + case SUCCESS: + if (value == null) { + unsetSuccess(); + } else { + setSuccess((String)value); + } + break; + + } + } + + public Object getFieldValue(_Fields field) { + switch (field) { + case SUCCESS: + return getSuccess(); + + } + throw new IllegalStateException(); + } + + /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ + public boolean isSet(_Fields field) { + if (field == null) { + throw new IllegalArgumentException(); + } + + switch (field) { + case SUCCESS: + return isSetSuccess(); + } + throw new IllegalStateException(); + } + + @Override + public boolean equals(Object that) { + if (that == null) + return false; + if (that instanceof find_result) + return this.equals((find_result)that); + return false; + } + + public boolean equals(find_result that) { + if (that == null) + return false; + if (this == that) + return true; + + boolean this_present_success = true && this.isSetSuccess(); + boolean that_present_success = true && that.isSetSuccess(); + if (this_present_success || that_present_success) { + if (!(this_present_success && that_present_success)) + return false; + if (!this.success.equals(that.success)) + return false; + } + + return true; + } + + @Override + public int hashCode() { + int hashCode = 1; + + hashCode = hashCode * 8191 + ((isSetSuccess()) ? 131071 : 524287); + if (isSetSuccess()) + hashCode = hashCode * 8191 + success.hashCode(); + + return hashCode; + } + + @Override + public int compareTo(find_result other) { + if (!getClass().equals(other.getClass())) { + return getClass().getName().compareTo(other.getClass().getName()); + } + + int lastComparison = 0; + + lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetSuccess()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); + if (lastComparison != 0) { + return lastComparison; + } + } + return 0; + } + + public _Fields fieldForId(int fieldId) { + return _Fields.findByThriftId(fieldId); + } + + public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { + scheme(iprot).read(iprot, this); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { + scheme(oprot).write(oprot, this); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("find_result("); + boolean first = true; + + sb.append("success:"); + if (this.success == null) { + sb.append("null"); + } else { + sb.append(this.success); + } + first = false; + sb.append(")"); + return sb.toString(); + } + + public void validate() throws org.apache.thrift.TException { + // check for required fields + // check for sub-struct validity + } + + private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { + try { + write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { + try { + read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private static class find_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public find_resultStandardScheme getScheme() { + return new find_resultStandardScheme(); + } + } + + private static class find_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme { + + public void read(org.apache.thrift.protocol.TProtocol iprot, find_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TField schemeField; + iprot.readStructBegin(); + while (true) + { + schemeField = iprot.readFieldBegin(); + if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { + break; + } + switch (schemeField.id) { + case 0: // SUCCESS + if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { + struct.success = iprot.readString(); + struct.setSuccessIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + default: + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + iprot.readFieldEnd(); + } + iprot.readStructEnd(); + + // check for required fields of primitive type, which can't be checked in the validate method + struct.validate(); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot, find_result struct) throws org.apache.thrift.TException { + struct.validate(); + + oprot.writeStructBegin(STRUCT_DESC); + if (struct.success != null) { + oprot.writeFieldBegin(SUCCESS_FIELD_DESC); + oprot.writeString(struct.success); + oprot.writeFieldEnd(); + } + oprot.writeFieldStop(); + oprot.writeStructEnd(); + } + + } + + private static class find_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public find_resultTupleScheme getScheme() { + return new find_resultTupleScheme(); + } + } + + private static class find_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme { + + @Override + public void write(org.apache.thrift.protocol.TProtocol prot, find_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet optionals = new java.util.BitSet(); + if (struct.isSetSuccess()) { + optionals.set(0); + } + oprot.writeBitSet(optionals, 1); + if (struct.isSetSuccess()) { + oprot.writeString(struct.success); + } + } + + @Override + public void read(org.apache.thrift.protocol.TProtocol prot, find_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet incoming = iprot.readBitSet(1); + if (incoming.get(0)) { + struct.success = iprot.readString(); + struct.setSuccessIsSet(true); + } + } + } + + private static S scheme(org.apache.thrift.protocol.TProtocol proto) { + return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); + } + } + +} diff --git a/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/UserServiceImpl.java b/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/UserServiceImpl.java new file mode 100644 index 00000000000..3cd3c76cfb5 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/UserServiceImpl.java @@ -0,0 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.rpc.protocol.nativethrift; + +public class UserServiceImpl implements UserService.Iface { + + public String find(int id) throws org.apache.thrift.TException{ + return "KK"+id; + } +} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java index b40996c8124..93a5900d753 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java @@ -278,7 +278,7 @@ private Object decode(TProtocol protocol) TApplicationException exception; try { - exception = TApplicationException.read(protocol); + exception = TApplicationException.readFrom(protocol); protocol.readMessageEnd(); } catch (TException e) { throw new IOException(e.getMessage(), e); diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftNativeCodec.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftNativeCodec.java index e7e036aac34..612417752fc 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftNativeCodec.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftNativeCodec.java @@ -24,7 +24,6 @@ import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.rpc.Invocation; - import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TMessage; diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ext/MultiServiceProcessor.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ext/MultiServiceProcessor.java index e80efa4eb4b..bb3d8180492 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ext/MultiServiceProcessor.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ext/MultiServiceProcessor.java @@ -19,7 +19,6 @@ import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.protocol.thrift.ThriftCodec; - import org.apache.thrift.TException; import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TBinaryProtocol; diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/$__ClassNameTestDubboStub.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/$__ClassNameTestDubboStub.java index a60c7b60a11..c7f92d7b5e0 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/$__ClassNameTestDubboStub.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/$__ClassNameTestDubboStub.java @@ -60,11 +60,16 @@ public echo() { super("echo"); } - protected echo_args getEmptyArgsInstance() { + public echo_args getEmptyArgsInstance() { return new echo_args(); } - protected echo_result getResult(I iface, echo_args args) throws org.apache.thrift.TException { + @Override + protected boolean isOneway() { + return false; + } + + public echo_result getResult(I iface, echo_args args) throws org.apache.thrift.TException { echo_result result = new echo_result(); result.success = iface.echo(args.arg); return result; diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTest.java index c7d1050676c..eb2cc55655b 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTest.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTest.java @@ -16,7 +16,6 @@ */ import org.apache.dubbo.rpc.protocol.thrift.ThriftUtils; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTestThrift.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTestThrift.java index 51f04a20b51..21758837035 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTestThrift.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTestThrift.java @@ -146,11 +146,16 @@ public echo() { super("echo"); } - protected echo_args getEmptyArgsInstance() { + public echo_args getEmptyArgsInstance() { return new echo_args(); } - protected echo_result getResult(I iface, echo_args args) throws org.apache.thrift.TException { + @Override + protected boolean isOneway() { + return false; + } + + public echo_result getResult(I iface, echo_args args) throws org.apache.thrift.TException { echo_result result = new echo_result(); result.success = iface.echo(args.arg); return result; diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/gen/dubbo/$__DemoStub.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/gen/dubbo/$__DemoStub.java index da5c9a3a29a..04b6353d724 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/gen/dubbo/$__DemoStub.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/gen/dubbo/$__DemoStub.java @@ -80,11 +80,16 @@ public echoBool() { super("echoBool"); } - protected echoBool_args getEmptyArgsInstance() { + public echoBool_args getEmptyArgsInstance() { return new echoBool_args(); } - protected echoBool_result getResult(I iface, echoBool_args args) throws org.apache.thrift.TException { + @Override + protected boolean isOneway() { + return false; + } + + public echoBool_result getResult(I iface, echoBool_args args) throws org.apache.thrift.TException { echoBool_result result = new echoBool_result(); result.success = iface.echoBool(args.arg); result.setSuccessIsSet(true); @@ -97,11 +102,16 @@ public echoByte() { super("echoByte"); } - protected echoByte_args getEmptyArgsInstance() { + public echoByte_args getEmptyArgsInstance() { return new echoByte_args(); } - protected echoByte_result getResult(I iface, echoByte_args args) throws org.apache.thrift.TException { + @Override + protected boolean isOneway() { + return false; + } + + public echoByte_result getResult(I iface, echoByte_args args) throws org.apache.thrift.TException { echoByte_result result = new echoByte_result(); result.success = iface.echoByte(args.arg); result.setSuccessIsSet(true); @@ -114,11 +124,16 @@ public echoI16() { super("echoI16"); } - protected echoI16_args getEmptyArgsInstance() { + public echoI16_args getEmptyArgsInstance() { return new echoI16_args(); } - protected echoI16_result getResult(I iface, echoI16_args args) throws org.apache.thrift.TException { + @Override + protected boolean isOneway() { + return false; + } + + public echoI16_result getResult(I iface, echoI16_args args) throws org.apache.thrift.TException { echoI16_result result = new echoI16_result(); result.success = iface.echoI16(args.arg); result.setSuccessIsSet(true); @@ -131,11 +146,16 @@ public echoI32() { super("echoI32"); } - protected echoI32_args getEmptyArgsInstance() { + public echoI32_args getEmptyArgsInstance() { return new echoI32_args(); } - protected echoI32_result getResult(I iface, echoI32_args args) throws org.apache.thrift.TException { + @Override + protected boolean isOneway() { + return false; + } + + public echoI32_result getResult(I iface, echoI32_args args) throws org.apache.thrift.TException { echoI32_result result = new echoI32_result(); result.success = iface.echoI32(args.arg); result.setSuccessIsSet(true); @@ -148,11 +168,16 @@ public echoI64() { super("echoI64"); } - protected echoI64_args getEmptyArgsInstance() { + public echoI64_args getEmptyArgsInstance() { return new echoI64_args(); } - protected echoI64_result getResult(I iface, echoI64_args args) throws org.apache.thrift.TException { + @Override + protected boolean isOneway() { + return false; + } + + public echoI64_result getResult(I iface, echoI64_args args) throws org.apache.thrift.TException { echoI64_result result = new echoI64_result(); result.success = iface.echoI64(args.arg); result.setSuccessIsSet(true); @@ -165,11 +190,16 @@ public echoDouble() { super("echoDouble"); } - protected echoDouble_args getEmptyArgsInstance() { + public echoDouble_args getEmptyArgsInstance() { return new echoDouble_args(); } - protected echoDouble_result getResult(I iface, echoDouble_args args) throws org.apache.thrift.TException { + @Override + protected boolean isOneway() { + return false; + } + + public echoDouble_result getResult(I iface, echoDouble_args args) throws org.apache.thrift.TException { echoDouble_result result = new echoDouble_result(); result.success = iface.echoDouble(args.arg); result.setSuccessIsSet(true); @@ -182,11 +212,16 @@ public echoString() { super("echoString"); } - protected echoString_args getEmptyArgsInstance() { + public echoString_args getEmptyArgsInstance() { return new echoString_args(); } - protected echoString_result getResult(I iface, echoString_args args) throws org.apache.thrift.TException { + @Override + protected boolean isOneway() { + return false; + } + + public echoString_result getResult(I iface, echoString_args args) throws org.apache.thrift.TException { echoString_result result = new echoString_result(); result.success = iface.echoString(args.arg); return result; diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/gen/thrift/Demo.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/gen/thrift/Demo.java index 231ff9fc070..3c9312913f4 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/gen/thrift/Demo.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/gen/thrift/Demo.java @@ -301,7 +301,7 @@ public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apa prot.writeMessageEnd(); } - public boolean getResult() throws org.apache.thrift.TException { + public Object getResult() throws org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } @@ -327,7 +327,7 @@ public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apa prot.writeMessageEnd(); } - public byte getResult() throws org.apache.thrift.TException { + public Object getResult() throws org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } @@ -353,7 +353,7 @@ public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apa prot.writeMessageEnd(); } - public short getResult() throws org.apache.thrift.TException { + public Object getResult() throws org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } @@ -379,7 +379,7 @@ public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apa prot.writeMessageEnd(); } - public int getResult() throws org.apache.thrift.TException { + public Object getResult() throws org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } @@ -405,7 +405,7 @@ public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apa prot.writeMessageEnd(); } - public long getResult() throws org.apache.thrift.TException { + public Object getResult() throws org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } @@ -431,7 +431,7 @@ public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apa prot.writeMessageEnd(); } - public double getResult() throws org.apache.thrift.TException { + public Object getResult() throws org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } @@ -496,11 +496,16 @@ public echoBool() { super("echoBool"); } - protected echoBool_args getEmptyArgsInstance() { + public echoBool_args getEmptyArgsInstance() { return new echoBool_args(); } - protected echoBool_result getResult(I iface, echoBool_args args) throws org.apache.thrift.TException { + @Override + protected boolean isOneway() { + return false; + } + + public echoBool_result getResult(I iface, echoBool_args args) throws org.apache.thrift.TException { echoBool_result result = new echoBool_result(); result.success = iface.echoBool(args.arg); result.setSuccessIsSet(true); @@ -513,11 +518,16 @@ public echoByte() { super("echoByte"); } - protected echoByte_args getEmptyArgsInstance() { + public echoByte_args getEmptyArgsInstance() { return new echoByte_args(); } - protected echoByte_result getResult(I iface, echoByte_args args) throws org.apache.thrift.TException { + @Override + protected boolean isOneway() { + return false; + } + + public echoByte_result getResult(I iface, echoByte_args args) throws org.apache.thrift.TException { echoByte_result result = new echoByte_result(); result.success = iface.echoByte(args.arg); result.setSuccessIsSet(true); @@ -530,11 +540,16 @@ public echoI16() { super("echoI16"); } - protected echoI16_args getEmptyArgsInstance() { + public echoI16_args getEmptyArgsInstance() { return new echoI16_args(); } - protected echoI16_result getResult(I iface, echoI16_args args) throws org.apache.thrift.TException { + @Override + protected boolean isOneway() { + return false; + } + + public echoI16_result getResult(I iface, echoI16_args args) throws org.apache.thrift.TException { echoI16_result result = new echoI16_result(); result.success = iface.echoI16(args.arg); result.setSuccessIsSet(true); @@ -547,11 +562,16 @@ public echoI32() { super("echoI32"); } - protected echoI32_args getEmptyArgsInstance() { + public echoI32_args getEmptyArgsInstance() { return new echoI32_args(); } - protected echoI32_result getResult(I iface, echoI32_args args) throws org.apache.thrift.TException { + @Override + protected boolean isOneway() { + return false; + } + + public echoI32_result getResult(I iface, echoI32_args args) throws org.apache.thrift.TException { echoI32_result result = new echoI32_result(); result.success = iface.echoI32(args.arg); result.setSuccessIsSet(true); @@ -564,11 +584,16 @@ public echoI64() { super("echoI64"); } - protected echoI64_args getEmptyArgsInstance() { + public echoI64_args getEmptyArgsInstance() { return new echoI64_args(); } - protected echoI64_result getResult(I iface, echoI64_args args) throws org.apache.thrift.TException { + @Override + protected boolean isOneway() { + return false; + } + + public echoI64_result getResult(I iface, echoI64_args args) throws org.apache.thrift.TException { echoI64_result result = new echoI64_result(); result.success = iface.echoI64(args.arg); result.setSuccessIsSet(true); @@ -581,11 +606,16 @@ public echoDouble() { super("echoDouble"); } - protected echoDouble_args getEmptyArgsInstance() { + public echoDouble_args getEmptyArgsInstance() { return new echoDouble_args(); } - protected echoDouble_result getResult(I iface, echoDouble_args args) throws org.apache.thrift.TException { + @Override + protected boolean isOneway() { + return false; + } + + public echoDouble_result getResult(I iface, echoDouble_args args) throws org.apache.thrift.TException { echoDouble_result result = new echoDouble_result(); result.success = iface.echoDouble(args.arg); result.setSuccessIsSet(true); @@ -598,11 +628,16 @@ public echoString() { super("echoString"); } - protected echoString_args getEmptyArgsInstance() { + public echoString_args getEmptyArgsInstance() { return new echoString_args(); } - protected echoString_result getResult(I iface, echoString_args args) throws org.apache.thrift.TException { + @Override + protected boolean isOneway() { + return false; + } + + public echoString_result getResult(I iface, echoString_args args) throws org.apache.thrift.TException { echoString_result result = new echoString_result(); result.success = iface.echoString(args.arg); return result; diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/AbstractTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/AbstractTest.java index 234afa563a9..52a549f6096 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/AbstractTest.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/AbstractTest.java @@ -24,7 +24,6 @@ import org.apache.dubbo.rpc.gen.dubbo.$__DemoStub; import org.apache.dubbo.rpc.gen.dubbo.Demo; import org.apache.dubbo.rpc.protocol.thrift.ext.MultiServiceProcessor; - import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.server.TServer; diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ServerExceptionTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ServerExceptionTest.java index fc9c2a4975f..0b9be90b02e 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ServerExceptionTest.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ServerExceptionTest.java @@ -21,7 +21,6 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.gen.dubbo.$__DemoStub; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ServiceMethodNotFoundTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ServiceMethodNotFoundTest.java index fffe6c8322f..bb6857603ee 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ServiceMethodNotFoundTest.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ServiceMethodNotFoundTest.java @@ -20,7 +20,6 @@ import org.apache.dubbo.rpc.gen.dubbo.$__DemoStub; import org.apache.dubbo.rpc.gen.dubbo.Demo; import org.apache.dubbo.rpc.protocol.thrift.ext.MultiServiceProcessor; - import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.server.TThreadPoolServer; import org.apache.thrift.transport.TServerSocket; diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodecTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodecTest.java index 2b0b1db9bfb..a1d5daadea8 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodecTest.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodecTest.java @@ -29,7 +29,6 @@ import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.gen.thrift.Demo; import org.apache.dubbo.rpc.protocol.thrift.io.RandomAccessByteArrayOutputStream; - import org.apache.thrift.TApplicationException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TMessage; @@ -376,7 +375,7 @@ public void testEncodeExceptionResponse() throws Exception { Assertions.assertEquals("echoString", message.name); Assertions.assertEquals(TMessageType.EXCEPTION, message.type); Assertions.assertEquals(ThriftCodec.getSeqId(), message.seqid); - TApplicationException exception = TApplicationException.read(protocol); + TApplicationException exception = TApplicationException.readFrom(protocol); protocol.readMessageEnd(); Assertions.assertEquals(exceptionMessage, exception.getMessage()); diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocolTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocolTest.java index 364b31536a4..967b77abcdc 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocolTest.java @@ -20,7 +20,6 @@ import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.gen.dubbo.Demo; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftUtilsTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftUtilsTest.java index 1e60315b697..9a0e2b4cbe0 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftUtilsTest.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftUtilsTest.java @@ -18,7 +18,6 @@ import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.rpc.gen.dubbo.$__DemoStub; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/examples/DubboDemoConsumer.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/examples/DubboDemoConsumer.java index 15fb62a5f46..a631cdd59e5 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/examples/DubboDemoConsumer.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/examples/DubboDemoConsumer.java @@ -17,7 +17,6 @@ package org.apache.dubbo.rpc.protocol.thrift.examples; import org.apache.dubbo.rpc.gen.thrift.Demo; - import org.springframework.context.support.ClassPathXmlApplicationContext; public class DubboDemoConsumer { diff --git a/dubbo-rpc/pom.xml b/dubbo-rpc/pom.xml index 20e8e8d1321..ed95d9fca01 100644 --- a/dubbo-rpc/pom.xml +++ b/dubbo-rpc/pom.xml @@ -37,6 +37,7 @@ dubbo-rpc-hessian dubbo-rpc-http dubbo-rpc-webservice + dubbo-rpc-native-thrift dubbo-rpc-thrift dubbo-rpc-memcached dubbo-rpc-redis From d11f204592a3c130c0b86abb22da036b9f81aca1 Mon Sep 17 00:00:00 2001 From: huaifeng Date: Mon, 6 May 2019 14:25:31 +0800 Subject: [PATCH 029/115] fixed injvm export and refer (#3857) * fix injvm export and refer * Add default injvm protocol is only injvm protocol don't register * Multiple protocol registry filter injvm * isOnlyJvm --- .../apache/dubbo/config/ReferenceConfig.java | 25 +++---- .../apache/dubbo/config/ServiceConfig.java | 65 ++++++++++++------- 2 files changed, 55 insertions(+), 35 deletions(-) diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java index 4c379375b6e..5ecae9c0519 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java @@ -354,19 +354,22 @@ private T createProxy(Map map) { } } } else { // assemble URL from register center's configuration - checkRegistry(); - List us = loadRegistries(false); - if (CollectionUtils.isNotEmpty(us)) { - for (URL u : us) { - URL monitorUrl = loadMonitor(u); - if (monitorUrl != null) { - map.put(Constants.MONITOR_KEY, URL.encode(monitorUrl.toFullString())); + // if protocols not injvm checkRegistry + if (!Constants.LOCAL_PROTOCOL.equalsIgnoreCase(getProtocol())){ + checkRegistry(); + List us = loadRegistries(false); + if (CollectionUtils.isNotEmpty(us)) { + for (URL u : us) { + URL monitorUrl = loadMonitor(u); + if (monitorUrl != null) { + map.put(Constants.MONITOR_KEY, URL.encode(monitorUrl.toFullString())); + } + urls.add(u.addParameterAndEncoded(Constants.REFER_KEY, StringUtils.toQueryString(map))); } - urls.add(u.addParameterAndEncoded(Constants.REFER_KEY, StringUtils.toQueryString(map))); } - } - if (urls.isEmpty()) { - throw new IllegalStateException("No such any registry to reference " + interfaceName + " on the consumer " + NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion() + ", please config to your spring config."); + if (urls.isEmpty()) { + throw new IllegalStateException("No such any registry to reference " + interfaceName + " on the consumer " + NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion() + ", please config to your spring config."); + } } } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index 0c38b2f135c..86c5ed45f9a 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -269,9 +269,12 @@ public void checkAndUpdateSubConfigs() { // Config Center should always being started first. startConfigCenter(); checkDefault(); - checkApplication(); - checkRegistry(); checkProtocol(); + checkApplication(); + // if protocol is not injvm checkRegistry + if (!isOnlyInJvm()) { + checkRegistry(); + } this.refresh(); checkMetadataReport(); @@ -327,6 +330,15 @@ public void checkAndUpdateSubConfigs() { checkMock(interfaceClass); } + /** + * Determine if it is injvm + * + * @return + */ + private boolean isOnlyInJvm() { + return getProtocols().size() == 1 && Constants.LOCAL_PROTOCOL.equalsIgnoreCase(getProtocols().get(0).getName()); + } + public synchronized void export() { checkAndUpdateSubConfigs(); @@ -539,11 +551,15 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r } // export to remote if the config is not local (export to local only when config is local) if (!Constants.SCOPE_LOCAL.equalsIgnoreCase(scope)) { - if (logger.isInfoEnabled()) { + if (!isOnlyInJvm() && logger.isInfoEnabled()) { logger.info("Export dubbo service " + interfaceClass.getName() + " to url " + url); } if (CollectionUtils.isNotEmpty(registryURLs)) { for (URL registryURL : registryURLs) { + //if protocol is only injvm ,not register + if (Constants.LOCAL_PROTOCOL.equalsIgnoreCase(url.getProtocol())) { + continue; + } url = url.addParameterIfAbsent(Constants.DYNAMIC_KEY, registryURL.getParameter(Constants.DYNAMIC_KEY)); URL monitorUrl = loadMonitor(registryURL); if (monitorUrl != null) { @@ -586,18 +602,19 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r } @SuppressWarnings({"unchecked", "rawtypes"}) + /** + * always export injvm + */ private void exportLocal(URL url) { - if (!Constants.LOCAL_PROTOCOL.equalsIgnoreCase(url.getProtocol())) { - URL local = URLBuilder.from(url) - .setProtocol(Constants.LOCAL_PROTOCOL) - .setHost(LOCALHOST_VALUE) - .setPort(0) - .build(); - Exporter exporter = protocol.export( - proxyFactory.getInvoker(ref, (Class) interfaceClass, local)); - exporters.add(exporter); - logger.info("Export dubbo service " + interfaceClass.getName() + " to local registry"); - } + URL local = URLBuilder.from(url) + .setProtocol(Constants.LOCAL_PROTOCOL) + .setHost(LOCALHOST_VALUE) + .setPort(0) + .build(); + Exporter exporter = protocol.export( + proxyFactory.getInvoker(ref, (Class) interfaceClass, local)); + exporters.add(exporter); + logger.info("Export dubbo service " + interfaceClass.getName() + " to local registry url : " + local); } private Optional getContextPath(ProtocolConfig protocolConfig) { @@ -803,7 +820,7 @@ private void createProviderIfAbsent() { if (provider != null) { return; } - setProvider ( + setProvider( ConfigManager.getInstance() .getDefaultProvider() .orElseGet(() -> { @@ -834,15 +851,15 @@ private void convertProtocolIdsToProtocols() { if (StringUtils.isEmpty(protocolIds)) { if (CollectionUtils.isEmpty(protocols)) { - setProtocols( - ConfigManager.getInstance().getDefaultProtocols() - .filter(CollectionUtils::isNotEmpty) - .orElseGet(() -> { - ProtocolConfig protocolConfig = new ProtocolConfig(); - protocolConfig.refresh(); - return new ArrayList<>(Arrays.asList(protocolConfig)); - }) - ); + setProtocols( + ConfigManager.getInstance().getDefaultProtocols() + .filter(CollectionUtils::isNotEmpty) + .orElseGet(() -> { + ProtocolConfig protocolConfig = new ProtocolConfig(); + protocolConfig.refresh(); + return new ArrayList<>(Arrays.asList(protocolConfig)); + }) + ); } } else { String[] arr = Constants.COMMA_SPLIT_PATTERN.split(protocolIds); From 392fcbfd1a51418c92dce096b2d466c5890b9a17 Mon Sep 17 00:00:00 2001 From: Taosheng Wei Date: Tue, 7 May 2019 08:05:09 +0800 Subject: [PATCH 030/115] Sort added router list before set the 'routers' field of the RouterChain (#3969) --- .../src/main/java/org/apache/dubbo/rpc/cluster/RouterChain.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterChain.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterChain.java index 7586afed779..8ba22b1e8d5 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterChain.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterChain.java @@ -79,7 +79,7 @@ public void addRouters(List routers) { List newRouters = new ArrayList<>(); newRouters.addAll(builtinRouters); newRouters.addAll(routers); - CollectionUtils.sort(routers); + CollectionUtils.sort(newRouters); this.routers = newRouters; } From fbc0320e10246491be630041d1f6fd63eef4bccd Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Wed, 8 May 2019 10:28:22 +0800 Subject: [PATCH 031/115] remove useless module-dubbo-test-integration (#3989) Fixes #3573 --- PULL_REQUEST_TEMPLATE.md | 2 +- .../dubbo-test-spring3/pom.xml | 58 ----- .../dubbo/test/Spring3CompatibilityTest.java | 81 ------- .../test/consumer/ConsumerConfiguration.java | 46 ---- .../test/provider/DefaultDemoService.java | 40 --- .../test/provider/ProviderConfiguration.java | 33 --- .../META-INF/spring/dubbo-consumer.xml | 30 --- .../META-INF/spring/dubbo-provider.xml | 32 --- dubbo-test/dubbo-test-compatibility/pom.xml | 56 ----- dubbo-test/dubbo-test-integration/pom.xml | 46 ---- dubbo-test/pom.xml | 227 ------------------ 11 files changed, 1 insertion(+), 650 deletions(-) delete mode 100644 dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/pom.xml delete mode 100644 dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/src/main/java/org/apache/dubbo/test/Spring3CompatibilityTest.java delete mode 100644 dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/src/main/java/org/apache/dubbo/test/consumer/ConsumerConfiguration.java delete mode 100644 dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/src/main/java/org/apache/dubbo/test/provider/DefaultDemoService.java delete mode 100644 dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/src/main/java/org/apache/dubbo/test/provider/ProviderConfiguration.java delete mode 100644 dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/src/main/resources/META-INF/spring/dubbo-consumer.xml delete mode 100644 dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/src/main/resources/META-INF/spring/dubbo-provider.xml delete mode 100644 dubbo-test/dubbo-test-compatibility/pom.xml delete mode 100644 dubbo-test/dubbo-test-integration/pom.xml delete mode 100644 dubbo-test/pom.xml diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md index 8cb19f93455..17bc2b3ac33 100644 --- a/PULL_REQUEST_TEMPLATE.md +++ b/PULL_REQUEST_TEMPLATE.md @@ -15,6 +15,6 @@ Follow this checklist to help us incorporate your contribution quickly and easil - [x] Make sure there is a [GITHUB_issue](https://github.com/apache/incubator-dubbo/issues) field for the change (usually before you start working on it). Trivial changes like typos do not require a GITHUB issue. Your pull request should address just this issue, without pulling in other changes - one PR resolves one issue. - [ ] Format the pull request title like `[Dubbo-XXX] Fix UnknownException when host config not exist #XXX`. Each commit in the pull request should have a meaningful subject line and body. - [ ] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. -- [ ] Write necessary unit-test to verify your logic correction, more mock a little better when cross module dependency exist. If the new feature or significant change is committed, please remember to add integration-test in [test module](https://github.com/apache/incubator-dubbo/tree/master/dubbo-test). +- [ ] Write necessary unit-test to verify your logic correction, more mock a little better when cross module dependency exist. If the new feature or significant change is committed, please remember to add sample in [dubbo samples](https://github.com/apache/incubator-dubbo-samples) project. - [ ] Run `mvn clean install -DskipTests=false` & `mvn clean test-compile failsafe:integration-test` to make sure unit-test and integration-test pass. - [ ] If this contribution is large, please follow the [Software Donation Guide](https://github.com/apache/incubator-dubbo/wiki/Software-donation-guide). diff --git a/dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/pom.xml b/dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/pom.xml deleted file mode 100644 index 0295aaa3990..00000000000 --- a/dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/pom.xml +++ /dev/null @@ -1,58 +0,0 @@ - - - - - dubbo-test-compatibility - org.apache.dubbo - ${revision} - - 4.0.0 - - dubbo-test-spring3 - - - 3.2.18.RELEASE - - - - - - org.apache.dubbo - dubbo - - - org.springframework - spring-context - - - - - - org.apache.dubbo - dubbo-demo-interface - - - - org.springframework - spring-context - ${spring.version} - - - - - diff --git a/dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/src/main/java/org/apache/dubbo/test/Spring3CompatibilityTest.java b/dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/src/main/java/org/apache/dubbo/test/Spring3CompatibilityTest.java deleted file mode 100644 index 752be7fc31b..00000000000 --- a/dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/src/main/java/org/apache/dubbo/test/Spring3CompatibilityTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.test; - -import org.apache.dubbo.demo.DemoService; -import org.apache.dubbo.test.consumer.ConsumerConfiguration; -import org.apache.dubbo.test.provider.ProviderConfiguration; - -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.util.Assert; - -/** - * Dubbo compatibility test on Spring 3.2.x - * - * @since 2.5.8 - */ -public class Spring3CompatibilityTest { - - public static void main(String[] args) { - - ConfigurableApplicationContext provider = startupProvider(); - - ConfigurableApplicationContext consumer = startConsumer(); - - ConsumerConfiguration consumerConfiguration = consumer.getBean(ConsumerConfiguration.class); - - DemoService demoService = consumerConfiguration.getDemoService(); - - String value = demoService.sayHello("Mercy"); - - Assert.isTrue("DefaultDemoService - sayHell() : Mercy".equals(value), "Test is failed!"); - - System.out.println(value); - - provider.close(); - consumer.close(); - - } - - private static ConfigurableApplicationContext startupProvider() { - - ConfigurableApplicationContext context = startupApplicationContext(ProviderConfiguration.class); - - System.out.println("Startup Provider ..."); - - return context; - } - - private static ConfigurableApplicationContext startConsumer() { - - ConfigurableApplicationContext context = startupApplicationContext(ConsumerConfiguration.class); - - System.out.println("Startup Consumer ..."); - - return context; - - } - - private static ConfigurableApplicationContext startupApplicationContext(Class... annotatedClasses) { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - context.register(annotatedClasses); - context.refresh(); - return context; - } - -} diff --git a/dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/src/main/java/org/apache/dubbo/test/consumer/ConsumerConfiguration.java b/dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/src/main/java/org/apache/dubbo/test/consumer/ConsumerConfiguration.java deleted file mode 100644 index 7026ef33400..00000000000 --- a/dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/src/main/java/org/apache/dubbo/test/consumer/ConsumerConfiguration.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.test.consumer; - -import org.apache.dubbo.config.annotation.Reference; -import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan; -import org.apache.dubbo.demo.DemoService; - -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportResource; - -/** - * Consumer {@Link Configuration} - * - * @since 2.5.8 - */ -@Configuration -@ImportResource("META-INF/spring/dubbo-consumer.xml") -@DubboComponentScan -public class ConsumerConfiguration { - - @Reference(version = "2.5.8", url = "dubbo://127.0.0.1:12345") - private DemoService demoService; - - public DemoService getDemoService() { - return demoService; - } - - public void setDemoService(DemoService demoService) { - this.demoService = demoService; - } -} diff --git a/dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/src/main/java/org/apache/dubbo/test/provider/DefaultDemoService.java b/dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/src/main/java/org/apache/dubbo/test/provider/DefaultDemoService.java deleted file mode 100644 index 7c747717ef9..00000000000 --- a/dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/src/main/java/org/apache/dubbo/test/provider/DefaultDemoService.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.test.provider; - -import org.apache.dubbo.config.annotation.Service; -import org.apache.dubbo.demo.DemoService; - -/** - * Default {@link DemoService} implementation - * - * @since 2.5.8 - */ -@Service( - version = "2.5.8", - application = "dubbo-annotation-provider", - protocol = "dubbo", - registry = "my-registry" -) -public class DefaultDemoService implements DemoService { - - @Override - public String sayHello(String name) { - return "DefaultDemoService - sayHell() : " + name; - } - -} diff --git a/dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/src/main/java/org/apache/dubbo/test/provider/ProviderConfiguration.java b/dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/src/main/java/org/apache/dubbo/test/provider/ProviderConfiguration.java deleted file mode 100644 index d959e544516..00000000000 --- a/dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/src/main/java/org/apache/dubbo/test/provider/ProviderConfiguration.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.test.provider; - -import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan; - -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportResource; - -/** - * Provider {@Link Configuration} - * - * @since 2.5.8 - */ -@Configuration -@ImportResource("META-INF/spring/dubbo-provider.xml") -@DubboComponentScan -public class ProviderConfiguration { -} diff --git a/dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/src/main/resources/META-INF/spring/dubbo-consumer.xml b/dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/src/main/resources/META-INF/spring/dubbo-consumer.xml deleted file mode 100644 index 7a00ab3e00e..00000000000 --- a/dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/src/main/resources/META-INF/spring/dubbo-consumer.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/src/main/resources/META-INF/spring/dubbo-provider.xml b/dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/src/main/resources/META-INF/spring/dubbo-provider.xml deleted file mode 100644 index aa012e0aef2..00000000000 --- a/dubbo-test/dubbo-test-compatibility/dubbo-test-spring3/src/main/resources/META-INF/spring/dubbo-provider.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-compatibility/pom.xml b/dubbo-test/dubbo-test-compatibility/pom.xml deleted file mode 100644 index d3c178d0685..00000000000 --- a/dubbo-test/dubbo-test-compatibility/pom.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - 4.0.0 - - dubbo-test-spring3 - - - org.apache.dubbo - dubbo-test - ${revision} - - dubbo-test-compatibility - pom - ${project.artifactId} - The technology compatibility kit(TCK) test module of dubbo project - - - true - - - - - - - - org.apache.dubbo - dubbo - ${project.parent.version} - - - - - org.apache.dubbo - dubbo-demo-interface - ${project.parent.version} - - - - - - diff --git a/dubbo-test/dubbo-test-integration/pom.xml b/dubbo-test/dubbo-test-integration/pom.xml deleted file mode 100644 index f9e0794d290..00000000000 --- a/dubbo-test/dubbo-test-integration/pom.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - 4.0.0 - - org.apache.dubbo - dubbo-test - ${revision} - - dubbo-test-integration - jar - ${project.artifactId} - The showcase test module of dubbo project - - true - - - - - - ${basedir}/src/main/java - - **/*.java - - - - ${basedir}/src/main/resources - - - - - \ No newline at end of file diff --git a/dubbo-test/pom.xml b/dubbo-test/pom.xml deleted file mode 100644 index 4c8e19d9802..00000000000 --- a/dubbo-test/pom.xml +++ /dev/null @@ -1,227 +0,0 @@ - - - 4.0.0 - - org.apache.dubbo - dubbo-parent - ${revision} - - dubbo-test - pom - ${project.artifactId} - The test module of dubbo project - - true - - - dubbo-test-compatibility - dubbo-test-integration - - - - - - org.apache.dubbo - dubbo-bom - ${project.parent.version} - pom - import - - - - - - - org.apache.dubbo - dubbo-cluster - - - org.apache.dubbo - dubbo-common - - - org.apache.dubbo - dubbo-config-api - - - org.apache.dubbo - dubbo-config-spring - - - org.apache.dubbo - dubbo-filter-cache - - - org.apache.dubbo - dubbo-filter-validation - - - org.apache.dubbo - dubbo-remoting-netty - - - org.apache.dubbo - dubbo-remoting-netty4 - - - org.apache.dubbo - dubbo-remoting-mina - - - org.apache.dubbo - dubbo-remoting-grizzly - - - org.apache.dubbo - dubbo-remoting-p2p - - - org.apache.dubbo - dubbo-remoting-http - - - org.apache.dubbo - dubbo-rpc-jsonrpc - - - org.apache.dubbo - dubbo-rpc-dubbo - - - org.apache.dubbo - dubbo-rpc-injvm - - - org.apache.dubbo - dubbo-rpc-rmi - - - org.apache.dubbo - dubbo-rpc-hessian - - - org.apache.dubbo - dubbo-rpc-http - - - org.apache.dubbo - dubbo-rpc-webservice - - - org.apache.dubbo - dubbo-rpc-thrift - - - org.apache.dubbo - dubbo-rpc-memcached - - - org.apache.dubbo - dubbo-rpc-redis - - - org.apache.dubbo - dubbo-rpc-rest - - - org.apache.dubbo - dubbo-registry-default - - - org.apache.dubbo - dubbo-registry-multicast - - - org.apache.dubbo - dubbo-registry-zookeeper - - - org.apache.dubbo - dubbo-registry-redis - - - org.apache.dubbo - dubbo-monitor-api - - - org.apache.dubbo - dubbo-monitor-default - - - org.apache.dubbo - dubbo-container-spring - - - org.apache.dubbo - dubbo-container-log4j - - - org.apache.dubbo - dubbo-container-logback - - - org.apache.dubbo - dubbo-qos - - - com.alibaba - hessian-lite - - - org.apache.dubbo - dubbo-serialization-api - - - org.apache.dubbo - dubbo-serialization-hessian2 - - - org.apache.dubbo - dubbo-serialization-fst - - - org.apache.dubbo - dubbo-serialization-fastjson - - - org.apache.dubbo - dubbo-serialization-gson - - - org.apache.dubbo - dubbo-serialization-kryo - - - org.apache.dubbo - dubbo-serialization-avro - - - org.apache.dubbo - dubbo-serialization-jdk - 2.7.1-SNAPSHOT - - - org.hibernate - hibernate-validator - - - org.glassfish - javax.el - - - From f2bed88616b644d87f939f002be426c1fa3718bc Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Wed, 8 May 2019 10:51:05 +0800 Subject: [PATCH 032/115] provide more meaningful binary releases. (#3987) fixes #2491 --- dubbo-demo/README.md | 28 ++ .../dubbo-demo-annotation-consumer/pom.xml | 22 +- .../dubbo-demo-annotation-provider/pom.xml | 28 +- dubbo-demo/dubbo-demo-annotation/pom.xml | 18 +- .../dubbo-demo-api-consumer/pom.xml | 16 - .../dubbo-demo-api-provider/pom.xml | 26 +- .../dubbo/demo/provider/Application.java | 3 +- dubbo-demo/dubbo-demo-api/pom.xml | 20 +- .../dubbo-demo-xml-consumer/pom.xml | 20 +- .../dubbo-demo-xml-provider/pom.xml | 28 +- dubbo-demo/dubbo-demo-xml/pom.xml | 18 + dubbo-distribution/pom.xml | 313 +----------------- .../src/assembly/bin-release.xml | 13 +- 13 files changed, 131 insertions(+), 422 deletions(-) diff --git a/dubbo-demo/README.md b/dubbo-demo/README.md index de43542497e..4cb99b72a95 100644 --- a/dubbo-demo/README.md +++ b/dubbo-demo/README.md @@ -1 +1,29 @@ +# Dubbo Demo + This directory contains basic usages of Dubbo to help Dubbo developers for debugging and smoke test purpose. If you are looking for Dubbo samples for study purpose, you should look into [here](https://github.com/apache/incubator-dubbo-samples) where you will find comprehensive usages for how to use Dubbo in different scenarios with the different features. + +## How To Build + +To build all demo applications from the source code, simply step into '*dubbo-demo*' directory and use maven to build: + +```bash +mvn clean package +``` + +After build completes, a couple of fat jars are generated under '*target*' directory under each module directories, for example: '*dubbo-demo-api-provider-${project.version}.jar*' can be found under the directory '*dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/target*'. + +## How To Run + +Since the generated artifacts are fat jars backed by spring boot maven plugin, they can be executed directly with '*java -jar*', and since multicast is used for service registration, a necessary system property '**-Djava.net.preferIPv4Stack=true**' is required in order to registry and discover the demo service properly. + +Use '*dubbo-demo/dubbo-demo-api*' as an example, to start the provider '*dubbo-demo-api-provider*', execute the following command: + +```bash +java -Djava.net.preferIPv4Stack=true dubbo-demo-api-provider-${project.version}.jar +``` + +To run the consumer '*dubbo-demo-api-consumer*', execute the following command: + +```bash +java -Djava.net.preferIPv4Stack=true dubbo-demo-api-consumer-${project.version}.jar +``` diff --git a/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-consumer/pom.xml b/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-consumer/pom.xml index 7e38ba1b435..c13bc265bc2 100644 --- a/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-consumer/pom.xml +++ b/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-consumer/pom.xml @@ -38,14 +38,6 @@ dubbo-demo-interface ${project.parent.version} - - org.apache.dubbo - dubbo-config-spring - - - org.apache.dubbo - dubbo-registry-zookeeper - org.apache.dubbo dubbo-registry-multicast @@ -56,23 +48,15 @@ org.apache.dubbo - dubbo-remoting-netty4 - - - org.apache.dubbo - dubbo-serialization-hessian2 - - - org.apache.dubbo - dubbo-configcenter-zookeeper + dubbo-config-spring org.apache.dubbo - dubbo-metadata-report-redis + dubbo-remoting-netty4 org.apache.dubbo - dubbo-metadata-report-zookeeper + dubbo-serialization-hessian2 diff --git a/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-provider/pom.xml b/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-provider/pom.xml index 9e807ce5d48..4f164bce61e 100644 --- a/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-provider/pom.xml +++ b/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-provider/pom.xml @@ -30,6 +30,7 @@ true + 1.7.25 @@ -38,14 +39,6 @@ dubbo-demo-interface ${project.parent.version} - - org.apache.dubbo - dubbo-config-spring - - - org.apache.dubbo - dubbo-registry-zookeeper - org.apache.dubbo dubbo-registry-multicast @@ -56,27 +49,28 @@ org.apache.dubbo - dubbo-remoting-netty4 + dubbo-config-spring org.apache.dubbo - dubbo-serialization-hessian2 + dubbo-remoting-netty4 org.apache.dubbo - dubbo-configcenter-zookeeper + dubbo-serialization-hessian2 - org.apache.dubbo - dubbo-metadata-report-zookeeper + org.slf4j + slf4j-api - org.apache.dubbo - dubbo-metadata-report-redis + org.slf4j + slf4j-log4j12 + ${slf4j-log4j12.version} - org.apache.dubbo - dubbo-qos + log4j + log4j diff --git a/dubbo-demo/dubbo-demo-annotation/pom.xml b/dubbo-demo/dubbo-demo-annotation/pom.xml index df69c4c424b..81e7fbe8eae 100644 --- a/dubbo-demo/dubbo-demo-annotation/pom.xml +++ b/dubbo-demo/dubbo-demo-annotation/pom.xml @@ -30,6 +30,7 @@ true + 2.1.4.RELEASE @@ -37,5 +38,20 @@ dubbo-demo-annotation-consumer - + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} + + + + repackage + + + + + + diff --git a/dubbo-demo/dubbo-demo-api/dubbo-demo-api-consumer/pom.xml b/dubbo-demo/dubbo-demo-api/dubbo-demo-api-consumer/pom.xml index fd0f62631e4..f668a8540db 100644 --- a/dubbo-demo/dubbo-demo-api/dubbo-demo-api-consumer/pom.xml +++ b/dubbo-demo/dubbo-demo-api/dubbo-demo-api-consumer/pom.xml @@ -38,10 +38,6 @@ dubbo-demo-interface ${project.parent.version} - - org.apache.dubbo - dubbo-registry-zookeeper - org.apache.dubbo dubbo-registry-multicast @@ -58,18 +54,6 @@ org.apache.dubbo dubbo-serialization-hessian2 - - org.apache.dubbo - dubbo-configcenter-zookeeper - - - org.apache.dubbo - dubbo-metadata-report-redis - - - org.apache.dubbo - dubbo-metadata-report-zookeeper - diff --git a/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/pom.xml b/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/pom.xml index 095b43093fa..ff5d9ced5b7 100644 --- a/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/pom.xml +++ b/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/pom.xml @@ -18,7 +18,8 @@ ~ under the License. --> - + dubbo-demo-api org.apache.dubbo @@ -30,6 +31,7 @@ true + 1.7.25 @@ -38,10 +40,6 @@ dubbo-demo-interface ${project.parent.version} - - org.apache.dubbo - dubbo-registry-zookeeper - org.apache.dubbo dubbo-registry-multicast @@ -58,21 +56,19 @@ org.apache.dubbo dubbo-serialization-hessian2 + - org.apache.dubbo - dubbo-configcenter-zookeeper - - - org.apache.dubbo - dubbo-metadata-report-zookeeper + org.slf4j + slf4j-api - org.apache.dubbo - dubbo-metadata-report-redis + org.slf4j + slf4j-log4j12 + ${slf4j-log4j12.version} - org.apache.dubbo - dubbo-qos + log4j + log4j diff --git a/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/src/main/java/org/apache/dubbo/demo/provider/Application.java b/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/src/main/java/org/apache/dubbo/demo/provider/Application.java index c453d1b5543..857e03f1169 100644 --- a/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/src/main/java/org/apache/dubbo/demo/provider/Application.java +++ b/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/src/main/java/org/apache/dubbo/demo/provider/Application.java @@ -29,10 +29,9 @@ public class Application { * launch the application */ public static void main(String[] args) throws Exception { - System.setProperty("DUBBO_IP_TO_REGISTRY", "4.3.2.1"); ServiceConfig service = new ServiceConfig<>(); service.setApplication(new ApplicationConfig("dubbo-demo-api-provider")); - service.setRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181")); + service.setRegistry(new RegistryConfig("multicast://224.5.6.7:1234")); service.setInterface(DemoService.class); service.setRef(new DemoServiceImpl()); service.export(); diff --git a/dubbo-demo/dubbo-demo-api/pom.xml b/dubbo-demo/dubbo-demo-api/pom.xml index 944c76dd505..e78c2ca4e89 100644 --- a/dubbo-demo/dubbo-demo-api/pom.xml +++ b/dubbo-demo/dubbo-demo-api/pom.xml @@ -18,7 +18,8 @@ ~ under the License. --> - + dubbo-demo org.apache.dubbo @@ -34,9 +35,26 @@ true + 2.1.4.RELEASE dubbo-demo-api + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} + + + + repackage + + + + + + diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-consumer/pom.xml b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-consumer/pom.xml index 7eb47eef78e..4dfde790cfa 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-consumer/pom.xml +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-consumer/pom.xml @@ -36,15 +36,11 @@ org.apache.dubbo - dubbo-config-spring - - - org.apache.dubbo - dubbo-registry-zookeeper + dubbo-registry-multicast org.apache.dubbo - dubbo-registry-multicast + dubbo-config-spring org.apache.dubbo @@ -58,17 +54,5 @@ org.apache.dubbo dubbo-serialization-hessian2 - - org.apache.dubbo - dubbo-configcenter-zookeeper - - - org.apache.dubbo - dubbo-metadata-report-redis - - - org.apache.dubbo - dubbo-metadata-report-zookeeper - diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/pom.xml b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/pom.xml index 81cfe6c9d70..a93c41ccf00 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/pom.xml +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/pom.xml @@ -27,6 +27,7 @@ The demo provider module of dubbo project true + 1.7.25 @@ -35,14 +36,6 @@ dubbo-demo-interface ${project.parent.version} - - org.apache.dubbo - dubbo-config-spring - - - org.apache.dubbo - dubbo-registry-zookeeper - org.apache.dubbo dubbo-registry-multicast @@ -53,27 +46,28 @@ org.apache.dubbo - dubbo-remoting-netty4 + dubbo-config-spring org.apache.dubbo - dubbo-serialization-hessian2 + dubbo-remoting-netty4 org.apache.dubbo - dubbo-configcenter-zookeeper + dubbo-serialization-hessian2 - org.apache.dubbo - dubbo-metadata-report-zookeeper + org.slf4j + slf4j-api - org.apache.dubbo - dubbo-metadata-report-redis + org.slf4j + slf4j-log4j12 + ${slf4j-log4j12.version} - org.apache.dubbo - dubbo-qos + log4j + log4j diff --git a/dubbo-demo/dubbo-demo-xml/pom.xml b/dubbo-demo/dubbo-demo-xml/pom.xml index 97aa01023bf..f75b2eca752 100644 --- a/dubbo-demo/dubbo-demo-xml/pom.xml +++ b/dubbo-demo/dubbo-demo-xml/pom.xml @@ -31,6 +31,7 @@ true + 2.1.4.RELEASE @@ -38,4 +39,21 @@ dubbo-demo-xml-consumer + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} + + + + repackage + + + + + + + diff --git a/dubbo-distribution/pom.xml b/dubbo-distribution/pom.xml index 07fdf356d4f..1ab955cc3e9 100644 --- a/dubbo-distribution/pom.xml +++ b/dubbo-distribution/pom.xml @@ -32,323 +32,14 @@ org.apache.dubbo - dubbo-cluster + dubbo-demo-api-provider ${project.version} org.apache.dubbo - dubbo-common + dubbo-demo-api-consumer ${project.version} - - org.apache.dubbo - dubbo-config-api - ${project.version} - - - org.apache.dubbo - dubbo-config-spring - ${project.version} - - - org.apache.dubbo - dubbo-filter-cache - ${project.version} - - - org.apache.dubbo - dubbo-filter-validation - ${project.version} - - - org.apache.dubbo - dubbo-remoting-api - ${project.version} - - - org.apache.dubbo - dubbo-remoting-netty - ${project.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - - - org.apache.dubbo - dubbo-remoting-mina - ${project.version} - - - org.apache.dubbo - dubbo-remoting-grizzly - ${project.version} - - - org.apache.dubbo - dubbo-remoting-p2p - ${project.version} - - - org.apache.dubbo - dubbo-remoting-http - ${project.version} - - - org.apache.dubbo - dubbo-rpc-api - ${project.version} - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - - - org.apache.dubbo - dubbo-rpc-injvm - ${project.version} - - - org.apache.dubbo - dubbo-rpc-jsonrpc - ${project.version} - - - org.apache.dubbo - dubbo-rpc-rmi - ${project.version} - - - org.apache.dubbo - dubbo-rpc-hessian - ${project.version} - - - org.apache.dubbo - dubbo-rpc-http - ${project.version} - - - org.apache.dubbo - dubbo-rpc-webservice - ${project.version} - - - org.apache.dubbo - dubbo-rpc-thrift - ${project.version} - - - org.apache.dubbo - dubbo-rpc-native-thrift - ${project.version} - - - org.apache.dubbo - dubbo-rpc-memcached - ${project.version} - - - org.apache.dubbo - dubbo-rpc-redis - ${project.version} - - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - - - org.apache.dubbo - dubbo-registry-api - ${project.version} - - - org.apache.dubbo - dubbo-registry-default - ${project.version} - - - org.apache.dubbo - dubbo-registry-multicast - ${project.version} - - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-registry-redis - ${project.version} - - - org.apache.dubbo - dubbo-registry-consul - ${project.version} - - - org.apache.dubbo - dubbo-registry-nacos - ${project.version} - - - org.apache.dubbo - dubbo-registry-etcd3 - ${project.version} - - - org.apache.dubbo - dubbo-registry-sofa - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-api - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-apollo - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-consul - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-etcd - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-api - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-redis - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-consul - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-etcd - ${project.version} - - - org.apache.dubbo - dubbo-monitor-api - ${project.version} - - - org.apache.dubbo - dubbo-monitor-default - ${project.version} - - - org.apache.dubbo - dubbo-container-spring - ${project.version} - - - org.apache.dubbo - dubbo-container-log4j - ${project.version} - - - org.apache.dubbo - dubbo-container-logback - ${project.version} - - - org.apache.dubbo - dubbo-qos - ${project.version} - - - org.apache.dubbo - dubbo-serialization-api - ${project.version} - - - org.apache.dubbo - dubbo-serialization-fastjson - ${project.version} - - - org.apache.dubbo - dubbo-serialization-fst - ${project.version} - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-native-hession - ${project.version} - - - org.apache.dubbo - dubbo-serialization-jdk - ${project.version} - - - org.apache.dubbo - dubbo-serialization-kryo - ${project.version} - - - org.apache.dubbo - dubbo-serialization-protostuff - ${project.version} - - - org.apache.dubbo - dubbo-serialization-avro - ${project.version} - - - org.apache.dubbo - dubbo-serialization-gson - ${project.version} - - - org.apache.dubbo - dubbo - ${project.version} - - - org.apache.dubbo - dubbo-compatible - ${project.version} - - - com.alibaba - hessian-lite - diff --git a/dubbo-distribution/src/assembly/bin-release.xml b/dubbo-distribution/src/assembly/bin-release.xml index e0aef5cbca7..76409930e6d 100644 --- a/dubbo-distribution/src/assembly/bin-release.xml +++ b/dubbo-distribution/src/assembly/bin-release.xml @@ -31,20 +31,23 @@ LICENSE + + ../dubbo-demo + + README.md + + true false - /libs + /dubbo-demo runtime - org.apache.dubbo:* + org.apache.dubbo:dubbo-demo-api* - - com.alibaba:fastjson - From 455d29a224bbd0a21ee1fcd42ae48114de72883f Mon Sep 17 00:00:00 2001 From: violin Date: Wed, 8 May 2019 16:25:46 +0800 Subject: [PATCH 033/115] [Dubbo-3829] support google pb generic invocation (#3975) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * modify generic filter to support google pb service test. * save * save code * save genericFilter 改写完毕 * save * add Licensed * fix some problem after code review * change directory name after change module name --- dubbo-all/pom.xml | 8 + dubbo-bom/pom.xml | 5 + .../org/apache/dubbo/common/Constants.java | 2 + dubbo-dependencies-bom/pom.xml | 11 + .../dubbo/rpc/filter/GenericFilter.java | 39 +- .../dubbo/rpc/support/ProtocolUtils.java | 7 +- .../dubbo-serialization-protobuf-json/pom.xml | 46 + .../support/GenericProtobufObjectInput.java | 115 + .../support/GenericProtobufObjectOutput.java | 107 + .../support/GenericProtobufSerialization.java | 53 + .../protobuf/support/ProtobufUtils.java | 61 + ...pache.dubbo.common.serialize.Serialization | 1 + .../dubbo-serialization-test/pom.xml | 5 + .../GenericProtobufObjectOutputTest.java | 85 + .../GenericProtobufSerializationTest.java | 26 + .../protobuf/support/model/GooglePB.java | 3431 +++++++++++++++++ .../test/resources/protobuf/GooglePB.proto | 51 + dubbo-serialization/pom.xml | 1 + 18 files changed, 4051 insertions(+), 3 deletions(-) create mode 100644 dubbo-serialization/dubbo-serialization-protobuf-json/pom.xml create mode 100644 dubbo-serialization/dubbo-serialization-protobuf-json/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufObjectInput.java create mode 100644 dubbo-serialization/dubbo-serialization-protobuf-json/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufObjectOutput.java create mode 100644 dubbo-serialization/dubbo-serialization-protobuf-json/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufSerialization.java create mode 100644 dubbo-serialization/dubbo-serialization-protobuf-json/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/ProtobufUtils.java create mode 100644 dubbo-serialization/dubbo-serialization-protobuf-json/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization create mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufObjectOutputTest.java create mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufSerializationTest.java create mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protobuf/support/model/GooglePB.java create mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/resources/protobuf/GooglePB.proto diff --git a/dubbo-all/pom.xml b/dubbo-all/pom.xml index c38263aa7b9..c353874f88d 100644 --- a/dubbo-all/pom.xml +++ b/dubbo-all/pom.xml @@ -387,6 +387,13 @@ compile true + + org.apache.dubbo + dubbo-serialization-protobuf-json + ${project.version} + compile + true + org.apache.dubbo dubbo-configcenter-api @@ -585,6 +592,7 @@ org.apache.dubbo:dubbo-serialization-jdk org.apache.dubbo:dubbo-serialization-protostuff org.apache.dubbo:dubbo-serialization-gson + org.apache.dubbo:dubbo-serialization-googlePb org.apache.dubbo:dubbo-configcenter-api org.apache.dubbo:dubbo-configcenter-definition org.apache.dubbo:dubbo-configcenter-apollo diff --git a/dubbo-bom/pom.xml b/dubbo-bom/pom.xml index 56568646232..a7e44dcf6dc 100644 --- a/dubbo-bom/pom.xml +++ b/dubbo-bom/pom.xml @@ -342,6 +342,11 @@ dubbo-serialization-gson ${project.version} + + org.apache.dubbo + dubbo-serialization-protobuf-json + ${project.version} + org.apache.dubbo dubbo-compatible diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java index c89a31421fa..cc52e77d6f7 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java @@ -727,6 +727,8 @@ public class Constants { public static final String GENERIC_SERIALIZATION_BEAN = "bean"; + public static final String GENERIC_SERIALIZATION_PROTOBUF = "protobuf-json"; + public static final String DUBBO_IP_TO_REGISTRY = "DUBBO_IP_TO_REGISTRY"; public static final String DUBBO_PORT_TO_REGISTRY = "DUBBO_PORT_TO_REGISTRY"; diff --git a/dubbo-dependencies-bom/pom.xml b/dubbo-dependencies-bom/pom.xml index fa5434c964f..6fc9a88ebc0 100644 --- a/dubbo-dependencies-bom/pom.xml +++ b/dubbo-dependencies-bom/pom.xml @@ -108,6 +108,7 @@ 3.1.15 0.12.0 4.0.38 + 3.6.0 3.1.0 9.4.11.v20180605 1.1.0.Final @@ -271,6 +272,16 @@ hessian-lite ${hessian_lite_version} + + com.google.protobuf + protobuf-java + ${protobuf-java_version} + + + com.google.protobuf + protobuf-java-util + ${protobuf-java_version} + javax.servlet javax.servlet-api diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java index ae7b92c40f1..fdbfdef275e 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java @@ -76,7 +76,7 @@ public Result invoke(Invoker invoker, Invocation inv) throws RpcException { } else if (ProtocolUtils.isJavaGenericSerialization(generic)) { for (int i = 0; i < args.length; i++) { if (byte[].class == args[i].getClass()) { - try(UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream((byte[]) args[i])) { + try (UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream((byte[]) args[i])) { args[i] = ExtensionLoader.getExtensionLoader(Serialization.class) .getExtension(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA) .deserialize(null, is).readObject(); @@ -107,6 +107,26 @@ public Result invoke(Invoker invoker, Invocation inv) throws RpcException { args[i].getClass().getName()); } } + } else if (ProtocolUtils.isProtobufGenericSerialization(generic)) { + // as proto3 only accept one protobuf parameter + if (args.length == 1 && args[0] instanceof String) { + try (UnsafeByteArrayInputStream is = + new UnsafeByteArrayInputStream(((String) args[0]).getBytes())) { + args[0] = ExtensionLoader.getExtensionLoader(Serialization.class) + .getExtension("" + Constants.GENERIC_SERIALIZATION_PROTOBUF) + .deserialize(null, is).readObject(method.getParameterTypes()[0]); + } catch (Exception e) { + throw new RpcException("Deserialize argument failed.", e); + } + } else { + throw new RpcException( + "Generic serialization [" + + Constants.GENERIC_SERIALIZATION_PROTOBUF + + "] only support one" + String.class.getName() + + " argument and your message size is " + + args.length + " and type is" + + args[0].getClass().getName()); + } } Result result = invoker.invoke(new RpcInvocation(method, args, inv.getAttachments())); if (result.hasException() @@ -121,10 +141,25 @@ public Result invoke(Invoker invoker, Invocation inv) throws RpcException { .serialize(null, os).writeObject(result.getValue()); return new RpcResult(os.toByteArray()); } catch (IOException e) { - throw new RpcException("Serialize result failed.", e); + throw new RpcException( + "Generic serialization [" + + Constants.GENERIC_SERIALIZATION_NATIVE_JAVA + + "] serialize result failed.", e); } } else if (ProtocolUtils.isBeanGenericSerialization(generic)) { return new RpcResult(JavaBeanSerializeUtil.serialize(result.getValue(), JavaBeanAccessor.METHOD)); + } else if (ProtocolUtils.isProtobufGenericSerialization(generic)) { + try { + UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(512); + ExtensionLoader.getExtensionLoader(Serialization.class) + .getExtension(Constants.GENERIC_SERIALIZATION_PROTOBUF) + .serialize(null, os).writeObject(result.getValue()); + return new RpcResult(os.toString()); + } catch (IOException e) { + throw new RpcException("Generic serialization [" + + Constants.GENERIC_SERIALIZATION_PROTOBUF + + "] serialize result failed.", e); + } } else { return new RpcResult(PojoUtils.generalize(result.getValue())); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/ProtocolUtils.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/ProtocolUtils.java index ce5da6b51be..a64717c26c4 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/ProtocolUtils.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/ProtocolUtils.java @@ -51,7 +51,8 @@ public static boolean isGeneric(String generic) { && !"".equals(generic) && (Constants.GENERIC_SERIALIZATION_DEFAULT.equalsIgnoreCase(generic) /* Normal generalization cal */ || Constants.GENERIC_SERIALIZATION_NATIVE_JAVA.equalsIgnoreCase(generic) /* Streaming generalization call supporting jdk serialization */ - || Constants.GENERIC_SERIALIZATION_BEAN.equalsIgnoreCase(generic)); + || Constants.GENERIC_SERIALIZATION_BEAN.equalsIgnoreCase(generic) + || Constants.GENERIC_SERIALIZATION_PROTOBUF.equalsIgnoreCase(generic)); } public static boolean isDefaultGenericSerialization(String generic) { @@ -67,4 +68,8 @@ public static boolean isJavaGenericSerialization(String generic) { public static boolean isBeanGenericSerialization(String generic) { return isGeneric(generic) && Constants.GENERIC_SERIALIZATION_BEAN.equals(generic); } + + public static boolean isProtobufGenericSerialization(String generic) { + return isGeneric(generic) && Constants.GENERIC_SERIALIZATION_PROTOBUF.equals(generic); + } } diff --git a/dubbo-serialization/dubbo-serialization-protobuf-json/pom.xml b/dubbo-serialization/dubbo-serialization-protobuf-json/pom.xml new file mode 100644 index 00000000000..6580e8705a1 --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-protobuf-json/pom.xml @@ -0,0 +1,46 @@ + + + 4.0.0 + + dubbo-serialization + org.apache.dubbo + ${revision} + + dubbo-serialization-protobuf-json + jar + ${project.artifactId} + The protobuf serialization module of dubbo project + + false + + + + org.apache.dubbo + dubbo-serialization-api + ${project.parent.version} + + + com.google.protobuf + protobuf-java + + + com.google.protobuf + protobuf-java-util + + + \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-protobuf-json/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufObjectInput.java b/dubbo-serialization/dubbo-serialization-protobuf-json/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufObjectInput.java new file mode 100644 index 00000000000..a1c565037df --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-protobuf-json/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufObjectInput.java @@ -0,0 +1,115 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.serialize.protobuf.support; + +import org.apache.dubbo.common.serialize.ObjectInput; + +import java.io.BufferedReader; +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.lang.reflect.Type; + +/** + * GenericGoogleProtobuf object input implementation + */ +public class GenericProtobufObjectInput implements ObjectInput { + private final BufferedReader reader; + + public GenericProtobufObjectInput(InputStream in) { + this.reader = new BufferedReader(new InputStreamReader(in)); + } + + @Override + public boolean readBool() throws IOException { + return read(boolean.class); + } + + @Override + public byte readByte() throws IOException { + return read(byte.class); + } + + @Override + public short readShort() throws IOException { + return read(short.class); + } + + @Override + public int readInt() throws IOException { + return read(int.class); + } + + @Override + public long readLong() throws IOException { + return read(long.class); + } + + @Override + public float readFloat() throws IOException { + return read(float.class); + } + + @Override + public double readDouble() throws IOException { + return read(double.class); + } + + @Override + public String readUTF() throws IOException { + return read(String.class); + } + + @Override + public byte[] readBytes() throws IOException { + return readLine().getBytes(); + } + + @Override + public Object readObject() throws IOException { + return read(String.class); + } + + @Override + public T readObject(Class cls) throws IOException { + return read(cls); + } + + @Override + @SuppressWarnings("unchecked") + public T readObject(Class cls, Type type) throws IOException { + return readObject(cls); + } + + private String readLine() throws IOException { + String line = reader.readLine(); + if (line == null || line.trim().length() == 0) { + throw new EOFException(); + } + return line; + } + + private T read(Class cls) throws IOException { + if (!ProtobufUtils.isSupported(cls)) { + throw new IllegalArgumentException("This serialization only support google protobuf entity, the class is :" + cls.getName()); + } + + String json = readLine(); + return ProtobufUtils.deserialize(json, cls); + } +} diff --git a/dubbo-serialization/dubbo-serialization-protobuf-json/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufObjectOutput.java b/dubbo-serialization/dubbo-serialization-protobuf-json/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufObjectOutput.java new file mode 100644 index 00000000000..93b488edc73 --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-protobuf-json/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufObjectOutput.java @@ -0,0 +1,107 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.serialize.protobuf.support; + +import org.apache.dubbo.common.serialize.ObjectOutput; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; + +/** + * GenericGoogleProtobuf object output implementation + */ +public class GenericProtobufObjectOutput implements ObjectOutput { + + private final PrintWriter writer; + + public GenericProtobufObjectOutput(OutputStream out) { + this.writer = new PrintWriter(new OutputStreamWriter(out)); + } + + @Override + public void writeBool(boolean v) throws IOException { + writeObject(v); + } + + @Override + public void writeByte(byte v) throws IOException { + writeObject(v); + } + + @Override + public void writeShort(short v) throws IOException { + writeObject(v); + } + + @Override + public void writeInt(int v) throws IOException { + writeObject(v); + } + + @Override + public void writeLong(long v) throws IOException { + writeObject(v); + } + + @Override + public void writeFloat(float v) throws IOException { + writeObject(v); + } + + @Override + public void writeDouble(double v) throws IOException { + writeObject(v); + } + + @Override + public void writeUTF(String v) throws IOException { + writeObject(v); + } + + @Override + public void writeBytes(byte[] b) { + writer.println(new String(b)); + } + + @Override + public void writeBytes(byte[] b, int off, int len) { + writer.println(new String(b, off, len)); + } + + @Override + public void writeObject(Object obj) throws IOException { + if (obj == null) { + throw new IllegalArgumentException("This serialization only support google protobuf object, the object is : null"); + } + + if (!ProtobufUtils.isSupported(obj.getClass())) { + throw new IllegalArgumentException("This serialization only support google protobuf object, the object class is: " + obj.getClass().getName()); + } + + writer.write(ProtobufUtils.serialize(obj)); + writer.println(); + writer.flush(); + } + + @Override + public void flushBuffer() { + writer.flush(); + } + +} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-protobuf-json/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufSerialization.java b/dubbo-serialization/dubbo-serialization-protobuf-json/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufSerialization.java new file mode 100644 index 00000000000..8b9395c95b7 --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-protobuf-json/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufSerialization.java @@ -0,0 +1,53 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.serialize.protobuf.support; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.serialize.ObjectInput; +import org.apache.dubbo.common.serialize.ObjectOutput; +import org.apache.dubbo.common.serialize.Serialization; + +import java.io.InputStream; +import java.io.OutputStream; + +/** + * This serizalization is use for google protobuf generic reference. + * The entity be transported between client and server by json string. + * + */ +public class GenericProtobufSerialization implements Serialization { + + @Override + public byte getContentTypeId() { + return 21; + } + + @Override + public String getContentType() { + return "text/json"; + } + + @Override + public ObjectOutput serialize(URL url, OutputStream output) { + return new GenericProtobufObjectOutput(output); + } + + @Override + public ObjectInput deserialize(URL url, InputStream input) { + return new GenericProtobufObjectInput(input); + } +} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-protobuf-json/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/ProtobufUtils.java b/dubbo-serialization/dubbo-serialization-protobuf-json/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/ProtobufUtils.java new file mode 100644 index 00000000000..7a2eda8814c --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-protobuf-json/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/ProtobufUtils.java @@ -0,0 +1,61 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.serialize.protobuf.support; + +import com.google.protobuf.GeneratedMessageV3; +import com.google.protobuf.GeneratedMessageV3.Builder; +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.MessageOrBuilder; +import com.google.protobuf.util.JsonFormat; +import com.google.protobuf.util.JsonFormat.Printer; + +import java.lang.reflect.Method; + +public class ProtobufUtils { + + static boolean isSupported(Class clazz) { + if (clazz == null) { + return false; + } + + if (GeneratedMessageV3.class.isAssignableFrom(clazz)) { + return true; + } + return false; + } + + static T deserialize(String json, Class requestClass) throws InvalidProtocolBufferException { + Builder builder; + try { + builder = getMessageBuilder(requestClass); + } catch (Exception e) { + throw new IllegalArgumentException("Get google protobuf message builder from " + requestClass.getName() + "failed", e); + } + JsonFormat.parser().merge(json, builder); + return (T) builder.build(); + } + + static String serialize(Object value) throws InvalidProtocolBufferException { + Printer printer = JsonFormat.printer().omittingInsignificantWhitespace(); + return printer.print((MessageOrBuilder) value); + } + + private static Builder getMessageBuilder(Class requestType) throws Exception { + Method method = requestType.getMethod("newBuilder"); + return (Builder) method.invoke(null, null); + } +} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-protobuf-json/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization b/dubbo-serialization/dubbo-serialization-protobuf-json/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization new file mode 100644 index 00000000000..56d6b68bf05 --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-protobuf-json/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization @@ -0,0 +1 @@ +protobuf-json=org.apache.dubbo.common.serialize.protobuf.support.GenericProtobufSerialization \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-test/pom.xml b/dubbo-serialization/dubbo-serialization-test/pom.xml index 868b45bc82b..60d0c5ff0f1 100644 --- a/dubbo-serialization/dubbo-serialization-test/pom.xml +++ b/dubbo-serialization/dubbo-serialization-test/pom.xml @@ -77,5 +77,10 @@ dubbo-serialization-avro ${project.parent.version} + + org.apache.dubbo + dubbo-serialization-protobuf-json + ${project.parent.version} + diff --git a/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufObjectOutputTest.java b/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufObjectOutputTest.java new file mode 100644 index 00000000000..e420aec82ab --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufObjectOutputTest.java @@ -0,0 +1,85 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.serialize.protobuf.support; + +import org.apache.dubbo.common.serialize.protobuf.support.model.GooglePB; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + + +public class GenericProtobufObjectOutputTest { + private ByteArrayOutputStream byteArrayOutputStream; + private GenericProtobufObjectOutput genericProtobufObjectOutput; + private GenericProtobufObjectInput genericProtobufObjectInput; + private ByteArrayInputStream byteArrayInputStream; + + @BeforeEach + public void setUp() { + this.byteArrayOutputStream = new ByteArrayOutputStream(); + this.genericProtobufObjectOutput = new GenericProtobufObjectOutput(byteArrayOutputStream); + } + + @Test + public void testWriteObjectNull() throws IOException { + assertThrows(IllegalArgumentException.class, () -> { + this.genericProtobufObjectOutput.writeObject(null); + }); + } + + @Test + public void testWriteGooglePbObject() throws IOException { + Random random = new Random(); + final int bound = 100000; + List phoneNumberList = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + phoneNumberList.add(GooglePB.PhoneNumber.newBuilder().setNumber(random.nextInt(bound) + "").setType(GooglePB.PhoneType.forNumber(random.nextInt(GooglePB.PhoneType.values().length - 1))).build()); + } + + Map phoneNumberMap = new HashMap<>(); + for (int i = 0; i < 5; i++) { + phoneNumberMap.put("phoneNumber" + i, GooglePB.PhoneNumber.newBuilder().setNumber(random.nextInt(bound) + "").setType(GooglePB.PhoneType.forNumber(random.nextInt(GooglePB.PhoneType.values().length - 1))).build()); + } + GooglePB.PBRequestType request = GooglePB.PBRequestType.newBuilder() + .setAge(15).setCash(10).setMoney(16.0).setNum(100L) + .addAllPhone(phoneNumberList).putAllDoubleMap(phoneNumberMap).build(); + + this.genericProtobufObjectOutput.writeObject(request); + this.flushToInput(); + assertThat(genericProtobufObjectInput.readObject(GooglePB.PBRequestType.class), is(request)); + } + + private void flushToInput() { + this.genericProtobufObjectOutput.flushBuffer(); + this.byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); + this.genericProtobufObjectInput = new GenericProtobufObjectInput(byteArrayInputStream); + } +} + diff --git a/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufSerializationTest.java b/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufSerializationTest.java new file mode 100644 index 00000000000..6a7748edd6f --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufSerializationTest.java @@ -0,0 +1,26 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.serialize.protobuf.support; + +import org.apache.dubbo.common.serialize.base.AbstractSerializationTest; +import org.apache.dubbo.common.serialize.protostuff.ProtostuffSerialization; + +public class GenericProtobufSerializationTest extends AbstractSerializationTest { + { + serialization = new ProtostuffSerialization(); + } +} diff --git a/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protobuf/support/model/GooglePB.java b/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protobuf/support/model/GooglePB.java new file mode 100644 index 00000000000..257b37f91be --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protobuf/support/model/GooglePB.java @@ -0,0 +1,3431 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: GooglePB.proto + +package org.apache.dubbo.common.serialize.protobuf.support.model; + +public final class GooglePB { + private GooglePB() {} + public static void registerAllExtensions( + com.google.protobuf.ExtensionRegistryLite registry) { + } + + public static void registerAllExtensions( + com.google.protobuf.ExtensionRegistry registry) { + registerAllExtensions( + (com.google.protobuf.ExtensionRegistryLite) registry); + } + /** + * Protobuf enum {@code org.apache.dubbo.common.serialize.protobuf.model.PhoneType} + */ + public enum PhoneType + implements com.google.protobuf.ProtocolMessageEnum { + /** + * MOBILE = 0; + */ + MOBILE(0), + /** + * HOME = 1; + */ + HOME(1), + /** + * WORK = 2; + */ + WORK(2), + ; + + /** + * MOBILE = 0; + */ + public static final int MOBILE_VALUE = 0; + /** + * HOME = 1; + */ + public static final int HOME_VALUE = 1; + /** + * WORK = 2; + */ + public static final int WORK_VALUE = 2; + + + public final int getNumber() { + return value; + } + + /** + * @deprecated Use {@link #forNumber(int)} instead. + */ + @Deprecated + public static PhoneType valueOf(int value) { + return forNumber(value); + } + + public static PhoneType forNumber(int value) { + switch (value) { + case 0: return MOBILE; + case 1: return HOME; + case 2: return WORK; + default: return null; + } + } + + public static com.google.protobuf.Internal.EnumLiteMap + internalGetValueMap() { + return internalValueMap; + } + private static final com.google.protobuf.Internal.EnumLiteMap< + PhoneType> internalValueMap = + new com.google.protobuf.Internal.EnumLiteMap() { + public PhoneType findValueByNumber(int number) { + return PhoneType.forNumber(number); + } + }; + + public final com.google.protobuf.Descriptors.EnumValueDescriptor + getValueDescriptor() { + return getDescriptor().getValues().get(ordinal()); + } + public final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptorForType() { + return getDescriptor(); + } + public static final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptor() { + return GooglePB.getDescriptor().getEnumTypes().get(0); + } + + private static final PhoneType[] VALUES = values(); + + public static PhoneType valueOf( + com.google.protobuf.Descriptors.EnumValueDescriptor desc) { + if (desc.getType() != getDescriptor()) { + throw new IllegalArgumentException( + "EnumValueDescriptor is not for this type."); + } + return VALUES[desc.getIndex()]; + } + + private final int value; + + private PhoneType(int value) { + this.value = value; + } + + // @@protoc_insertion_point(enum_scope:org.apache.dubbo.common.serialize.protobuf.model.PhoneType) + } + + public interface PBRequestTypeOrBuilder extends + // @@protoc_insertion_point(interface_extends:org.apache.dubbo.common.serialize.protobuf.model.PBRequestType) + com.google.protobuf.MessageOrBuilder { + + /** + * optional double money = 1; + */ + boolean hasMoney(); + /** + * optional double money = 1; + */ + double getMoney(); + + /** + * optional float cash = 2; + */ + boolean hasCash(); + /** + * optional float cash = 2; + */ + float getCash(); + + /** + * optional int32 age = 3; + */ + boolean hasAge(); + /** + * optional int32 age = 3; + */ + int getAge(); + + /** + * optional int64 num = 4; + */ + boolean hasNum(); + /** + * optional int64 num = 4; + */ + long getNum(); + + /** + * optional bool sex = 5; + */ + boolean hasSex(); + /** + * optional bool sex = 5; + */ + boolean getSex(); + + /** + * optional string name = 6; + */ + boolean hasName(); + /** + * optional string name = 6; + */ + String getName(); + /** + * optional string name = 6; + */ + com.google.protobuf.ByteString + getNameBytes(); + + /** + * optional bytes msg = 7; + */ + boolean hasMsg(); + /** + * optional bytes msg = 7; + */ + com.google.protobuf.ByteString getMsg(); + + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + java.util.List + getPhoneList(); + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + GooglePB.PhoneNumber getPhone(int index); + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + int getPhoneCount(); + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + java.util.List + getPhoneOrBuilderList(); + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + GooglePB.PhoneNumberOrBuilder getPhoneOrBuilder( + int index); + + /** + * map<string, .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber> doubleMap = 9; + */ + int getDoubleMapCount(); + /** + * map<string, .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber> doubleMap = 9; + */ + boolean containsDoubleMap( + String key); + /** + * Use {@link #getDoubleMapMap()} instead. + */ + @Deprecated + java.util.Map + getDoubleMap(); + /** + * map<string, .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber> doubleMap = 9; + */ + java.util.Map + getDoubleMapMap(); + /** + * map<string, .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber> doubleMap = 9; + */ + + GooglePB.PhoneNumber getDoubleMapOrDefault( + String key, + GooglePB.PhoneNumber defaultValue); + /** + * map<string, .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber> doubleMap = 9; + */ + + GooglePB.PhoneNumber getDoubleMapOrThrow( + String key); + } + /** + * Protobuf type {@code org.apache.dubbo.common.serialize.protobuf.model.PBRequestType} + */ + public static final class PBRequestType extends + com.google.protobuf.GeneratedMessageV3 implements + // @@protoc_insertion_point(message_implements:org.apache.dubbo.common.serialize.protobuf.model.PBRequestType) + PBRequestTypeOrBuilder { + private static final long serialVersionUID = 0L; + // Use PBRequestType.newBuilder() to construct. + private PBRequestType(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + private PBRequestType() { + money_ = 0D; + cash_ = 0F; + age_ = 0; + num_ = 0L; + sex_ = false; + name_ = ""; + msg_ = com.google.protobuf.ByteString.EMPTY; + phone_ = java.util.Collections.emptyList(); + } + + @Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private PBRequestType( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownField( + input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 9: { + bitField0_ |= 0x00000001; + money_ = input.readDouble(); + break; + } + case 21: { + bitField0_ |= 0x00000002; + cash_ = input.readFloat(); + break; + } + case 24: { + bitField0_ |= 0x00000004; + age_ = input.readInt32(); + break; + } + case 32: { + bitField0_ |= 0x00000008; + num_ = input.readInt64(); + break; + } + case 40: { + bitField0_ |= 0x00000010; + sex_ = input.readBool(); + break; + } + case 50: { + com.google.protobuf.ByteString bs = input.readBytes(); + bitField0_ |= 0x00000020; + name_ = bs; + break; + } + case 58: { + bitField0_ |= 0x00000040; + msg_ = input.readBytes(); + break; + } + case 66: { + if (!((mutable_bitField0_ & 0x00000080) == 0x00000080)) { + phone_ = new java.util.ArrayList(); + mutable_bitField0_ |= 0x00000080; + } + phone_.add( + input.readMessage(GooglePB.PhoneNumber.PARSER, extensionRegistry)); + break; + } + case 74: { + if (!((mutable_bitField0_ & 0x00000100) == 0x00000100)) { + doubleMap_ = com.google.protobuf.MapField.newMapField( + DoubleMapDefaultEntryHolder.defaultEntry); + mutable_bitField0_ |= 0x00000100; + } + com.google.protobuf.MapEntry + doubleMap__ = input.readMessage( + DoubleMapDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); + doubleMap_.getMutableMap().put( + doubleMap__.getKey(), doubleMap__.getValue()); + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000080) == 0x00000080)) { + phone_ = java.util.Collections.unmodifiableList(phone_); + } + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return GooglePB.internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBRequestType_descriptor; + } + + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMapField( + int number) { + switch (number) { + case 9: + return internalGetDoubleMap(); + default: + throw new RuntimeException( + "Invalid map field number: " + number); + } + } + protected FieldAccessorTable + internalGetFieldAccessorTable() { + return GooglePB.internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBRequestType_fieldAccessorTable + .ensureFieldAccessorsInitialized( + GooglePB.PBRequestType.class, GooglePB.PBRequestType.Builder.class); + } + + private int bitField0_; + public static final int MONEY_FIELD_NUMBER = 1; + private double money_; + /** + * optional double money = 1; + */ + public boolean hasMoney() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + /** + * optional double money = 1; + */ + public double getMoney() { + return money_; + } + + public static final int CASH_FIELD_NUMBER = 2; + private float cash_; + /** + * optional float cash = 2; + */ + public boolean hasCash() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + /** + * optional float cash = 2; + */ + public float getCash() { + return cash_; + } + + public static final int AGE_FIELD_NUMBER = 3; + private int age_; + /** + * optional int32 age = 3; + */ + public boolean hasAge() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + /** + * optional int32 age = 3; + */ + public int getAge() { + return age_; + } + + public static final int NUM_FIELD_NUMBER = 4; + private long num_; + /** + * optional int64 num = 4; + */ + public boolean hasNum() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + /** + * optional int64 num = 4; + */ + public long getNum() { + return num_; + } + + public static final int SEX_FIELD_NUMBER = 5; + private boolean sex_; + /** + * optional bool sex = 5; + */ + public boolean hasSex() { + return ((bitField0_ & 0x00000010) == 0x00000010); + } + /** + * optional bool sex = 5; + */ + public boolean getSex() { + return sex_; + } + + public static final int NAME_FIELD_NUMBER = 6; + private volatile Object name_; + /** + * optional string name = 6; + */ + public boolean hasName() { + return ((bitField0_ & 0x00000020) == 0x00000020); + } + /** + * optional string name = 6; + */ + public String getName() { + Object ref = name_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (bs.isValidUtf8()) { + name_ = s; + } + return s; + } + } + /** + * optional string name = 6; + */ + public com.google.protobuf.ByteString + getNameBytes() { + Object ref = name_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (String) ref); + name_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int MSG_FIELD_NUMBER = 7; + private com.google.protobuf.ByteString msg_; + /** + * optional bytes msg = 7; + */ + public boolean hasMsg() { + return ((bitField0_ & 0x00000040) == 0x00000040); + } + /** + * optional bytes msg = 7; + */ + public com.google.protobuf.ByteString getMsg() { + return msg_; + } + + public static final int PHONE_FIELD_NUMBER = 8; + private java.util.List phone_; + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + public java.util.List getPhoneList() { + return phone_; + } + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + public java.util.List + getPhoneOrBuilderList() { + return phone_; + } + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + public int getPhoneCount() { + return phone_.size(); + } + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + public GooglePB.PhoneNumber getPhone(int index) { + return phone_.get(index); + } + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + public GooglePB.PhoneNumberOrBuilder getPhoneOrBuilder( + int index) { + return phone_.get(index); + } + + public static final int DOUBLEMAP_FIELD_NUMBER = 9; + private static final class DoubleMapDefaultEntryHolder { + static final com.google.protobuf.MapEntry< + String, PhoneNumber> defaultEntry = + com.google.protobuf.MapEntry + .newDefaultInstance( + GooglePB.internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBRequestType_DoubleMapEntry_descriptor, + com.google.protobuf.WireFormat.FieldType.STRING, + "", + com.google.protobuf.WireFormat.FieldType.MESSAGE, + GooglePB.PhoneNumber.getDefaultInstance()); + } + private com.google.protobuf.MapField< + String, PhoneNumber> doubleMap_; + private com.google.protobuf.MapField + internalGetDoubleMap() { + if (doubleMap_ == null) { + return com.google.protobuf.MapField.emptyMapField( + DoubleMapDefaultEntryHolder.defaultEntry); + } + return doubleMap_; + } + + public int getDoubleMapCount() { + return internalGetDoubleMap().getMap().size(); + } + /** + * map<string, .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber> doubleMap = 9; + */ + + public boolean containsDoubleMap( + String key) { + if (key == null) { throw new NullPointerException(); } + return internalGetDoubleMap().getMap().containsKey(key); + } + /** + * Use {@link #getDoubleMapMap()} instead. + */ + @Deprecated + public java.util.Map getDoubleMap() { + return getDoubleMapMap(); + } + /** + * map<string, .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber> doubleMap = 9; + */ + + public java.util.Map getDoubleMapMap() { + return internalGetDoubleMap().getMap(); + } + /** + * map<string, .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber> doubleMap = 9; + */ + + public GooglePB.PhoneNumber getDoubleMapOrDefault( + String key, + GooglePB.PhoneNumber defaultValue) { + if (key == null) { throw new NullPointerException(); } + java.util.Map map = + internalGetDoubleMap().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } + /** + * map<string, .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber> doubleMap = 9; + */ + + public GooglePB.PhoneNumber getDoubleMapOrThrow( + String key) { + if (key == null) { throw new NullPointerException(); } + java.util.Map map = + internalGetDoubleMap().getMap(); + if (!map.containsKey(key)) { + throw new IllegalArgumentException(); + } + return map.get(key); + } + + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + for (int i = 0; i < getPhoneCount(); i++) { + if (!getPhone(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + for (GooglePB.PhoneNumber item : getDoubleMapMap().values()) { + if (!item.isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeDouble(1, money_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeFloat(2, cash_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + output.writeInt32(3, age_); + } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + output.writeInt64(4, num_); + } + if (((bitField0_ & 0x00000010) == 0x00000010)) { + output.writeBool(5, sex_); + } + if (((bitField0_ & 0x00000020) == 0x00000020)) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 6, name_); + } + if (((bitField0_ & 0x00000040) == 0x00000040)) { + output.writeBytes(7, msg_); + } + for (int i = 0; i < phone_.size(); i++) { + output.writeMessage(8, phone_.get(i)); + } + com.google.protobuf.GeneratedMessageV3 + .serializeStringMapTo( + output, + internalGetDoubleMap(), + DoubleMapDefaultEntryHolder.defaultEntry, + 9); + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeDoubleSize(1, money_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeFloatSize(2, cash_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(3, age_); + } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + size += com.google.protobuf.CodedOutputStream + .computeInt64Size(4, num_); + } + if (((bitField0_ & 0x00000010) == 0x00000010)) { + size += com.google.protobuf.CodedOutputStream + .computeBoolSize(5, sex_); + } + if (((bitField0_ & 0x00000020) == 0x00000020)) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, name_); + } + if (((bitField0_ & 0x00000040) == 0x00000040)) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(7, msg_); + } + for (int i = 0; i < phone_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(8, phone_.get(i)); + } + for (java.util.Map.Entry entry + : internalGetDoubleMap().getMap().entrySet()) { + com.google.protobuf.MapEntry + doubleMap__ = DoubleMapDefaultEntryHolder.defaultEntry.newBuilderForType() + .setKey(entry.getKey()) + .setValue(entry.getValue()) + .build(); + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(9, doubleMap__); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @Override + public boolean equals(final Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof GooglePB.PBRequestType)) { + return super.equals(obj); + } + GooglePB.PBRequestType other = (GooglePB.PBRequestType) obj; + + boolean result = true; + result = result && (hasMoney() == other.hasMoney()); + if (hasMoney()) { + result = result && ( + Double.doubleToLongBits(getMoney()) + == Double.doubleToLongBits( + other.getMoney())); + } + result = result && (hasCash() == other.hasCash()); + if (hasCash()) { + result = result && ( + Float.floatToIntBits(getCash()) + == Float.floatToIntBits( + other.getCash())); + } + result = result && (hasAge() == other.hasAge()); + if (hasAge()) { + result = result && (getAge() + == other.getAge()); + } + result = result && (hasNum() == other.hasNum()); + if (hasNum()) { + result = result && (getNum() + == other.getNum()); + } + result = result && (hasSex() == other.hasSex()); + if (hasSex()) { + result = result && (getSex() + == other.getSex()); + } + result = result && (hasName() == other.hasName()); + if (hasName()) { + result = result && getName() + .equals(other.getName()); + } + result = result && (hasMsg() == other.hasMsg()); + if (hasMsg()) { + result = result && getMsg() + .equals(other.getMsg()); + } + result = result && getPhoneList() + .equals(other.getPhoneList()); + result = result && internalGetDoubleMap().equals( + other.internalGetDoubleMap()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + if (hasMoney()) { + hash = (37 * hash) + MONEY_FIELD_NUMBER; + hash = (53 * hash) + com.google.protobuf.Internal.hashLong( + Double.doubleToLongBits(getMoney())); + } + if (hasCash()) { + hash = (37 * hash) + CASH_FIELD_NUMBER; + hash = (53 * hash) + Float.floatToIntBits( + getCash()); + } + if (hasAge()) { + hash = (37 * hash) + AGE_FIELD_NUMBER; + hash = (53 * hash) + getAge(); + } + if (hasNum()) { + hash = (37 * hash) + NUM_FIELD_NUMBER; + hash = (53 * hash) + com.google.protobuf.Internal.hashLong( + getNum()); + } + if (hasSex()) { + hash = (37 * hash) + SEX_FIELD_NUMBER; + hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( + getSex()); + } + if (hasName()) { + hash = (37 * hash) + NAME_FIELD_NUMBER; + hash = (53 * hash) + getName().hashCode(); + } + if (hasMsg()) { + hash = (37 * hash) + MSG_FIELD_NUMBER; + hash = (53 * hash) + getMsg().hashCode(); + } + if (getPhoneCount() > 0) { + hash = (37 * hash) + PHONE_FIELD_NUMBER; + hash = (53 * hash) + getPhoneList().hashCode(); + } + if (!internalGetDoubleMap().getMap().isEmpty()) { + hash = (37 * hash) + DOUBLEMAP_FIELD_NUMBER; + hash = (53 * hash) + internalGetDoubleMap().hashCode(); + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static GooglePB.PBRequestType parseFrom( + java.nio.ByteBuffer data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static GooglePB.PBRequestType parseFrom( + java.nio.ByteBuffer data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static GooglePB.PBRequestType parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static GooglePB.PBRequestType parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static GooglePB.PBRequestType parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static GooglePB.PBRequestType parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static GooglePB.PBRequestType parseFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static GooglePB.PBRequestType parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + public static GooglePB.PBRequestType parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input); + } + public static GooglePB.PBRequestType parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + public static GooglePB.PBRequestType parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static GooglePB.PBRequestType parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + public static Builder newBuilder(GooglePB.PBRequestType prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { + return this == DEFAULT_INSTANCE + ? new Builder() : new Builder().mergeFrom(this); + } + + @Override + protected Builder newBuilderForType( + BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code org.apache.dubbo.common.serialize.protobuf.model.PBRequestType} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessageV3.Builder implements + // @@protoc_insertion_point(builder_implements:org.apache.dubbo.common.serialize.protobuf.model.PBRequestType) + GooglePB.PBRequestTypeOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return GooglePB.internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBRequestType_descriptor; + } + + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMapField( + int number) { + switch (number) { + case 9: + return internalGetDoubleMap(); + default: + throw new RuntimeException( + "Invalid map field number: " + number); + } + } + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMutableMapField( + int number) { + switch (number) { + case 9: + return internalGetMutableDoubleMap(); + default: + throw new RuntimeException( + "Invalid map field number: " + number); + } + } + protected FieldAccessorTable + internalGetFieldAccessorTable() { + return GooglePB.internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBRequestType_fieldAccessorTable + .ensureFieldAccessorsInitialized( + GooglePB.PBRequestType.class, GooglePB.PBRequestType.Builder.class); + } + + // Construct using org.apache.dubbo.common.serialize.protobuf.model.GooglePB.PBRequestType.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3 + .alwaysUseFieldBuilders) { + getPhoneFieldBuilder(); + } + } + public Builder clear() { + super.clear(); + money_ = 0D; + bitField0_ = (bitField0_ & ~0x00000001); + cash_ = 0F; + bitField0_ = (bitField0_ & ~0x00000002); + age_ = 0; + bitField0_ = (bitField0_ & ~0x00000004); + num_ = 0L; + bitField0_ = (bitField0_ & ~0x00000008); + sex_ = false; + bitField0_ = (bitField0_ & ~0x00000010); + name_ = ""; + bitField0_ = (bitField0_ & ~0x00000020); + msg_ = com.google.protobuf.ByteString.EMPTY; + bitField0_ = (bitField0_ & ~0x00000040); + if (phoneBuilder_ == null) { + phone_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000080); + } else { + phoneBuilder_.clear(); + } + internalGetMutableDoubleMap().clear(); + return this; + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return GooglePB.internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBRequestType_descriptor; + } + + public GooglePB.PBRequestType getDefaultInstanceForType() { + return GooglePB.PBRequestType.getDefaultInstance(); + } + + public GooglePB.PBRequestType build() { + GooglePB.PBRequestType result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public GooglePB.PBRequestType buildPartial() { + GooglePB.PBRequestType result = new GooglePB.PBRequestType(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.money_ = money_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.cash_ = cash_; + if (((from_bitField0_ & 0x00000004) == 0x00000004)) { + to_bitField0_ |= 0x00000004; + } + result.age_ = age_; + if (((from_bitField0_ & 0x00000008) == 0x00000008)) { + to_bitField0_ |= 0x00000008; + } + result.num_ = num_; + if (((from_bitField0_ & 0x00000010) == 0x00000010)) { + to_bitField0_ |= 0x00000010; + } + result.sex_ = sex_; + if (((from_bitField0_ & 0x00000020) == 0x00000020)) { + to_bitField0_ |= 0x00000020; + } + result.name_ = name_; + if (((from_bitField0_ & 0x00000040) == 0x00000040)) { + to_bitField0_ |= 0x00000040; + } + result.msg_ = msg_; + if (phoneBuilder_ == null) { + if (((bitField0_ & 0x00000080) == 0x00000080)) { + phone_ = java.util.Collections.unmodifiableList(phone_); + bitField0_ = (bitField0_ & ~0x00000080); + } + result.phone_ = phone_; + } else { + result.phone_ = phoneBuilder_.build(); + } + result.doubleMap_ = internalGetDoubleMap(); + result.doubleMap_.makeImmutable(); + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder clone() { + return (Builder) super.clone(); + } + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, + Object value) { + return (Builder) super.setField(field, value); + } + public Builder clearField( + com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } + public Builder clearOneof( + com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + int index, Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + Object value) { + return (Builder) super.addRepeatedField(field, value); + } + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof GooglePB.PBRequestType) { + return mergeFrom((GooglePB.PBRequestType)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(GooglePB.PBRequestType other) { + if (other == GooglePB.PBRequestType.getDefaultInstance()) return this; + if (other.hasMoney()) { + setMoney(other.getMoney()); + } + if (other.hasCash()) { + setCash(other.getCash()); + } + if (other.hasAge()) { + setAge(other.getAge()); + } + if (other.hasNum()) { + setNum(other.getNum()); + } + if (other.hasSex()) { + setSex(other.getSex()); + } + if (other.hasName()) { + bitField0_ |= 0x00000020; + name_ = other.name_; + onChanged(); + } + if (other.hasMsg()) { + setMsg(other.getMsg()); + } + if (phoneBuilder_ == null) { + if (!other.phone_.isEmpty()) { + if (phone_.isEmpty()) { + phone_ = other.phone_; + bitField0_ = (bitField0_ & ~0x00000080); + } else { + ensurePhoneIsMutable(); + phone_.addAll(other.phone_); + } + onChanged(); + } + } else { + if (!other.phone_.isEmpty()) { + if (phoneBuilder_.isEmpty()) { + phoneBuilder_.dispose(); + phoneBuilder_ = null; + phone_ = other.phone_; + bitField0_ = (bitField0_ & ~0x00000080); + phoneBuilder_ = + com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? + getPhoneFieldBuilder() : null; + } else { + phoneBuilder_.addAllMessages(other.phone_); + } + } + } + internalGetMutableDoubleMap().mergeFrom( + other.internalGetDoubleMap()); + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + public final boolean isInitialized() { + for (int i = 0; i < getPhoneCount(); i++) { + if (!getPhone(i).isInitialized()) { + return false; + } + } + for (GooglePB.PhoneNumber item : getDoubleMapMap().values()) { + if (!item.isInitialized()) { + return false; + } + } + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + GooglePB.PBRequestType parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (GooglePB.PBRequestType) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + private int bitField0_; + + private double money_ ; + /** + * optional double money = 1; + */ + public boolean hasMoney() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + /** + * optional double money = 1; + */ + public double getMoney() { + return money_; + } + /** + * optional double money = 1; + */ + public Builder setMoney(double value) { + bitField0_ |= 0x00000001; + money_ = value; + onChanged(); + return this; + } + /** + * optional double money = 1; + */ + public Builder clearMoney() { + bitField0_ = (bitField0_ & ~0x00000001); + money_ = 0D; + onChanged(); + return this; + } + + private float cash_ ; + /** + * optional float cash = 2; + */ + public boolean hasCash() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + /** + * optional float cash = 2; + */ + public float getCash() { + return cash_; + } + /** + * optional float cash = 2; + */ + public Builder setCash(float value) { + bitField0_ |= 0x00000002; + cash_ = value; + onChanged(); + return this; + } + /** + * optional float cash = 2; + */ + public Builder clearCash() { + bitField0_ = (bitField0_ & ~0x00000002); + cash_ = 0F; + onChanged(); + return this; + } + + private int age_ ; + /** + * optional int32 age = 3; + */ + public boolean hasAge() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + /** + * optional int32 age = 3; + */ + public int getAge() { + return age_; + } + /** + * optional int32 age = 3; + */ + public Builder setAge(int value) { + bitField0_ |= 0x00000004; + age_ = value; + onChanged(); + return this; + } + /** + * optional int32 age = 3; + */ + public Builder clearAge() { + bitField0_ = (bitField0_ & ~0x00000004); + age_ = 0; + onChanged(); + return this; + } + + private long num_ ; + /** + * optional int64 num = 4; + */ + public boolean hasNum() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + /** + * optional int64 num = 4; + */ + public long getNum() { + return num_; + } + /** + * optional int64 num = 4; + */ + public Builder setNum(long value) { + bitField0_ |= 0x00000008; + num_ = value; + onChanged(); + return this; + } + /** + * optional int64 num = 4; + */ + public Builder clearNum() { + bitField0_ = (bitField0_ & ~0x00000008); + num_ = 0L; + onChanged(); + return this; + } + + private boolean sex_ ; + /** + * optional bool sex = 5; + */ + public boolean hasSex() { + return ((bitField0_ & 0x00000010) == 0x00000010); + } + /** + * optional bool sex = 5; + */ + public boolean getSex() { + return sex_; + } + /** + * optional bool sex = 5; + */ + public Builder setSex(boolean value) { + bitField0_ |= 0x00000010; + sex_ = value; + onChanged(); + return this; + } + /** + * optional bool sex = 5; + */ + public Builder clearSex() { + bitField0_ = (bitField0_ & ~0x00000010); + sex_ = false; + onChanged(); + return this; + } + + private Object name_ = ""; + /** + * optional string name = 6; + */ + public boolean hasName() { + return ((bitField0_ & 0x00000020) == 0x00000020); + } + /** + * optional string name = 6; + */ + public String getName() { + Object ref = name_; + if (!(ref instanceof String)) { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (bs.isValidUtf8()) { + name_ = s; + } + return s; + } else { + return (String) ref; + } + } + /** + * optional string name = 6; + */ + public com.google.protobuf.ByteString + getNameBytes() { + Object ref = name_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (String) ref); + name_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + /** + * optional string name = 6; + */ + public Builder setName( + String value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000020; + name_ = value; + onChanged(); + return this; + } + /** + * optional string name = 6; + */ + public Builder clearName() { + bitField0_ = (bitField0_ & ~0x00000020); + name_ = getDefaultInstance().getName(); + onChanged(); + return this; + } + /** + * optional string name = 6; + */ + public Builder setNameBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000020; + name_ = value; + onChanged(); + return this; + } + + private com.google.protobuf.ByteString msg_ = com.google.protobuf.ByteString.EMPTY; + /** + * optional bytes msg = 7; + */ + public boolean hasMsg() { + return ((bitField0_ & 0x00000040) == 0x00000040); + } + /** + * optional bytes msg = 7; + */ + public com.google.protobuf.ByteString getMsg() { + return msg_; + } + /** + * optional bytes msg = 7; + */ + public Builder setMsg(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000040; + msg_ = value; + onChanged(); + return this; + } + /** + * optional bytes msg = 7; + */ + public Builder clearMsg() { + bitField0_ = (bitField0_ & ~0x00000040); + msg_ = getDefaultInstance().getMsg(); + onChanged(); + return this; + } + + private java.util.List phone_ = + java.util.Collections.emptyList(); + private void ensurePhoneIsMutable() { + if (!((bitField0_ & 0x00000080) == 0x00000080)) { + phone_ = new java.util.ArrayList(phone_); + bitField0_ |= 0x00000080; + } + } + + private com.google.protobuf.RepeatedFieldBuilderV3< + PhoneNumber, PhoneNumber.Builder, PhoneNumberOrBuilder> phoneBuilder_; + + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + public java.util.List getPhoneList() { + if (phoneBuilder_ == null) { + return java.util.Collections.unmodifiableList(phone_); + } else { + return phoneBuilder_.getMessageList(); + } + } + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + public int getPhoneCount() { + if (phoneBuilder_ == null) { + return phone_.size(); + } else { + return phoneBuilder_.getCount(); + } + } + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + public GooglePB.PhoneNumber getPhone(int index) { + if (phoneBuilder_ == null) { + return phone_.get(index); + } else { + return phoneBuilder_.getMessage(index); + } + } + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + public Builder setPhone( + int index, GooglePB.PhoneNumber value) { + if (phoneBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensurePhoneIsMutable(); + phone_.set(index, value); + onChanged(); + } else { + phoneBuilder_.setMessage(index, value); + } + return this; + } + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + public Builder setPhone( + int index, GooglePB.PhoneNumber.Builder builderForValue) { + if (phoneBuilder_ == null) { + ensurePhoneIsMutable(); + phone_.set(index, builderForValue.build()); + onChanged(); + } else { + phoneBuilder_.setMessage(index, builderForValue.build()); + } + return this; + } + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + public Builder addPhone(GooglePB.PhoneNumber value) { + if (phoneBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensurePhoneIsMutable(); + phone_.add(value); + onChanged(); + } else { + phoneBuilder_.addMessage(value); + } + return this; + } + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + public Builder addPhone( + int index, GooglePB.PhoneNumber value) { + if (phoneBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensurePhoneIsMutable(); + phone_.add(index, value); + onChanged(); + } else { + phoneBuilder_.addMessage(index, value); + } + return this; + } + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + public Builder addPhone( + GooglePB.PhoneNumber.Builder builderForValue) { + if (phoneBuilder_ == null) { + ensurePhoneIsMutable(); + phone_.add(builderForValue.build()); + onChanged(); + } else { + phoneBuilder_.addMessage(builderForValue.build()); + } + return this; + } + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + public Builder addPhone( + int index, GooglePB.PhoneNumber.Builder builderForValue) { + if (phoneBuilder_ == null) { + ensurePhoneIsMutable(); + phone_.add(index, builderForValue.build()); + onChanged(); + } else { + phoneBuilder_.addMessage(index, builderForValue.build()); + } + return this; + } + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + public Builder addAllPhone( + Iterable values) { + if (phoneBuilder_ == null) { + ensurePhoneIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll( + values, phone_); + onChanged(); + } else { + phoneBuilder_.addAllMessages(values); + } + return this; + } + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + public Builder clearPhone() { + if (phoneBuilder_ == null) { + phone_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000080); + onChanged(); + } else { + phoneBuilder_.clear(); + } + return this; + } + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + public Builder removePhone(int index) { + if (phoneBuilder_ == null) { + ensurePhoneIsMutable(); + phone_.remove(index); + onChanged(); + } else { + phoneBuilder_.remove(index); + } + return this; + } + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + public GooglePB.PhoneNumber.Builder getPhoneBuilder( + int index) { + return getPhoneFieldBuilder().getBuilder(index); + } + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + public GooglePB.PhoneNumberOrBuilder getPhoneOrBuilder( + int index) { + if (phoneBuilder_ == null) { + return phone_.get(index); } else { + return phoneBuilder_.getMessageOrBuilder(index); + } + } + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + public java.util.List + getPhoneOrBuilderList() { + if (phoneBuilder_ != null) { + return phoneBuilder_.getMessageOrBuilderList(); + } else { + return java.util.Collections.unmodifiableList(phone_); + } + } + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + public GooglePB.PhoneNumber.Builder addPhoneBuilder() { + return getPhoneFieldBuilder().addBuilder( + GooglePB.PhoneNumber.getDefaultInstance()); + } + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + public GooglePB.PhoneNumber.Builder addPhoneBuilder( + int index) { + return getPhoneFieldBuilder().addBuilder( + index, GooglePB.PhoneNumber.getDefaultInstance()); + } + /** + * repeated .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + */ + public java.util.List + getPhoneBuilderList() { + return getPhoneFieldBuilder().getBuilderList(); + } + private com.google.protobuf.RepeatedFieldBuilderV3< + PhoneNumber, PhoneNumber.Builder, PhoneNumberOrBuilder> + getPhoneFieldBuilder() { + if (phoneBuilder_ == null) { + phoneBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< + PhoneNumber, PhoneNumber.Builder, PhoneNumberOrBuilder>( + phone_, + ((bitField0_ & 0x00000080) == 0x00000080), + getParentForChildren(), + isClean()); + phone_ = null; + } + return phoneBuilder_; + } + + private com.google.protobuf.MapField< + String, PhoneNumber> doubleMap_; + private com.google.protobuf.MapField + internalGetDoubleMap() { + if (doubleMap_ == null) { + return com.google.protobuf.MapField.emptyMapField( + DoubleMapDefaultEntryHolder.defaultEntry); + } + return doubleMap_; + } + private com.google.protobuf.MapField + internalGetMutableDoubleMap() { + onChanged();; + if (doubleMap_ == null) { + doubleMap_ = com.google.protobuf.MapField.newMapField( + DoubleMapDefaultEntryHolder.defaultEntry); + } + if (!doubleMap_.isMutable()) { + doubleMap_ = doubleMap_.copy(); + } + return doubleMap_; + } + + public int getDoubleMapCount() { + return internalGetDoubleMap().getMap().size(); + } + /** + * map<string, .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber> doubleMap = 9; + */ + + public boolean containsDoubleMap( + String key) { + if (key == null) { throw new NullPointerException(); } + return internalGetDoubleMap().getMap().containsKey(key); + } + /** + * Use {@link #getDoubleMapMap()} instead. + */ + @Deprecated + public java.util.Map getDoubleMap() { + return getDoubleMapMap(); + } + /** + * map<string, .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber> doubleMap = 9; + */ + + public java.util.Map getDoubleMapMap() { + return internalGetDoubleMap().getMap(); + } + /** + * map<string, .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber> doubleMap = 9; + */ + + public GooglePB.PhoneNumber getDoubleMapOrDefault( + String key, + GooglePB.PhoneNumber defaultValue) { + if (key == null) { throw new NullPointerException(); } + java.util.Map map = + internalGetDoubleMap().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } + /** + * map<string, .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber> doubleMap = 9; + */ + + public GooglePB.PhoneNumber getDoubleMapOrThrow( + String key) { + if (key == null) { throw new NullPointerException(); } + java.util.Map map = + internalGetDoubleMap().getMap(); + if (!map.containsKey(key)) { + throw new IllegalArgumentException(); + } + return map.get(key); + } + + public Builder clearDoubleMap() { + internalGetMutableDoubleMap().getMutableMap() + .clear(); + return this; + } + /** + * map<string, .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber> doubleMap = 9; + */ + + public Builder removeDoubleMap( + String key) { + if (key == null) { throw new NullPointerException(); } + internalGetMutableDoubleMap().getMutableMap() + .remove(key); + return this; + } + /** + * Use alternate mutation accessors instead. + */ + @Deprecated + public java.util.Map + getMutableDoubleMap() { + return internalGetMutableDoubleMap().getMutableMap(); + } + /** + * map<string, .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber> doubleMap = 9; + */ + public Builder putDoubleMap( + String key, + GooglePB.PhoneNumber value) { + if (key == null) { throw new NullPointerException(); } + if (value == null) { throw new NullPointerException(); } + internalGetMutableDoubleMap().getMutableMap() + .put(key, value); + return this; + } + /** + * map<string, .org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber> doubleMap = 9; + */ + + public Builder putAllDoubleMap( + java.util.Map values) { + internalGetMutableDoubleMap().getMutableMap() + .putAll(values); + return this; + } + public final Builder setUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFields(unknownFields); + } + + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + + // @@protoc_insertion_point(builder_scope:org.apache.dubbo.common.serialize.protobuf.model.PBRequestType) + } + + // @@protoc_insertion_point(class_scope:org.apache.dubbo.common.serialize.protobuf.model.PBRequestType) + private static final GooglePB.PBRequestType DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new GooglePB.PBRequestType(); + } + + public static GooglePB.PBRequestType getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + @Deprecated public static final com.google.protobuf.Parser + PARSER = new com.google.protobuf.AbstractParser() { + public PBRequestType parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new PBRequestType(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public GooglePB.PBRequestType getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + } + + public interface PBResponseTypeOrBuilder extends + // @@protoc_insertion_point(interface_extends:org.apache.dubbo.common.serialize.protobuf.model.PBResponseType) + com.google.protobuf.MessageOrBuilder { + + /** + * optional string msg = 1; + */ + boolean hasMsg(); + /** + * optional string msg = 1; + */ + String getMsg(); + /** + * optional string msg = 1; + */ + com.google.protobuf.ByteString + getMsgBytes(); + + /** + * optional .org.apache.dubbo.common.serialize.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + boolean hasCDubboPBRequestType(); + /** + * optional .org.apache.dubbo.common.serialize.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + GooglePB.PBRequestType getCDubboPBRequestType(); + /** + * optional .org.apache.dubbo.common.serialize.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + GooglePB.PBRequestTypeOrBuilder getCDubboPBRequestTypeOrBuilder(); + } + /** + * Protobuf type {@code org.apache.dubbo.common.serialize.protobuf.model.PBResponseType} + */ + public static final class PBResponseType extends + com.google.protobuf.GeneratedMessageV3 implements + // @@protoc_insertion_point(message_implements:org.apache.dubbo.common.serialize.protobuf.model.PBResponseType) + PBResponseTypeOrBuilder { + private static final long serialVersionUID = 0L; + // Use PBResponseType.newBuilder() to construct. + private PBResponseType(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + private PBResponseType() { + msg_ = ""; + } + + @Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private PBResponseType( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownField( + input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: { + com.google.protobuf.ByteString bs = input.readBytes(); + bitField0_ |= 0x00000001; + msg_ = bs; + break; + } + case 26: { + GooglePB.PBRequestType.Builder subBuilder = null; + if (((bitField0_ & 0x00000002) == 0x00000002)) { + subBuilder = cDubboPBRequestType_.toBuilder(); + } + cDubboPBRequestType_ = input.readMessage(GooglePB.PBRequestType.PARSER, extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(cDubboPBRequestType_); + cDubboPBRequestType_ = subBuilder.buildPartial(); + } + bitField0_ |= 0x00000002; + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return GooglePB.internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBResponseType_descriptor; + } + + protected FieldAccessorTable + internalGetFieldAccessorTable() { + return GooglePB.internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBResponseType_fieldAccessorTable + .ensureFieldAccessorsInitialized( + GooglePB.PBResponseType.class, GooglePB.PBResponseType.Builder.class); + } + + private int bitField0_; + public static final int MSG_FIELD_NUMBER = 1; + private volatile Object msg_; + /** + * optional string msg = 1; + */ + public boolean hasMsg() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + /** + * optional string msg = 1; + */ + public String getMsg() { + Object ref = msg_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (bs.isValidUtf8()) { + msg_ = s; + } + return s; + } + } + /** + * optional string msg = 1; + */ + public com.google.protobuf.ByteString + getMsgBytes() { + Object ref = msg_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (String) ref); + msg_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int CDUBBOPBREQUESTTYPE_FIELD_NUMBER = 3; + private GooglePB.PBRequestType cDubboPBRequestType_; + /** + * optional .org.apache.dubbo.common.serialize.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + public boolean hasCDubboPBRequestType() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + /** + * optional .org.apache.dubbo.common.serialize.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + public GooglePB.PBRequestType getCDubboPBRequestType() { + return cDubboPBRequestType_ == null ? GooglePB.PBRequestType.getDefaultInstance() : cDubboPBRequestType_; + } + /** + * optional .org.apache.dubbo.common.serialize.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + public GooglePB.PBRequestTypeOrBuilder getCDubboPBRequestTypeOrBuilder() { + return cDubboPBRequestType_ == null ? GooglePB.PBRequestType.getDefaultInstance() : cDubboPBRequestType_; + } + + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + if (hasCDubboPBRequestType()) { + if (!getCDubboPBRequestType().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + if (((bitField0_ & 0x00000001) == 0x00000001)) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 1, msg_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeMessage(3, getCDubboPBRequestType()); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, msg_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(3, getCDubboPBRequestType()); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @Override + public boolean equals(final Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof GooglePB.PBResponseType)) { + return super.equals(obj); + } + GooglePB.PBResponseType other = (GooglePB.PBResponseType) obj; + + boolean result = true; + result = result && (hasMsg() == other.hasMsg()); + if (hasMsg()) { + result = result && getMsg() + .equals(other.getMsg()); + } + result = result && (hasCDubboPBRequestType() == other.hasCDubboPBRequestType()); + if (hasCDubboPBRequestType()) { + result = result && getCDubboPBRequestType() + .equals(other.getCDubboPBRequestType()); + } + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + if (hasMsg()) { + hash = (37 * hash) + MSG_FIELD_NUMBER; + hash = (53 * hash) + getMsg().hashCode(); + } + if (hasCDubboPBRequestType()) { + hash = (37 * hash) + CDUBBOPBREQUESTTYPE_FIELD_NUMBER; + hash = (53 * hash) + getCDubboPBRequestType().hashCode(); + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static GooglePB.PBResponseType parseFrom( + java.nio.ByteBuffer data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static GooglePB.PBResponseType parseFrom( + java.nio.ByteBuffer data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static GooglePB.PBResponseType parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static GooglePB.PBResponseType parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static GooglePB.PBResponseType parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static GooglePB.PBResponseType parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static GooglePB.PBResponseType parseFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static GooglePB.PBResponseType parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + public static GooglePB.PBResponseType parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input); + } + public static GooglePB.PBResponseType parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + public static GooglePB.PBResponseType parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static GooglePB.PBResponseType parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + public static Builder newBuilder(GooglePB.PBResponseType prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { + return this == DEFAULT_INSTANCE + ? new Builder() : new Builder().mergeFrom(this); + } + + @Override + protected Builder newBuilderForType( + BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code org.apache.dubbo.common.serialize.protobuf.model.PBResponseType} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessageV3.Builder implements + // @@protoc_insertion_point(builder_implements:org.apache.dubbo.common.serialize.protobuf.model.PBResponseType) + GooglePB.PBResponseTypeOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return GooglePB.internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBResponseType_descriptor; + } + + protected FieldAccessorTable + internalGetFieldAccessorTable() { + return GooglePB.internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBResponseType_fieldAccessorTable + .ensureFieldAccessorsInitialized( + GooglePB.PBResponseType.class, GooglePB.PBResponseType.Builder.class); + } + + // Construct using org.apache.dubbo.common.serialize.protobuf.model.GooglePB.PBResponseType.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3 + .alwaysUseFieldBuilders) { + getCDubboPBRequestTypeFieldBuilder(); + } + } + public Builder clear() { + super.clear(); + msg_ = ""; + bitField0_ = (bitField0_ & ~0x00000001); + if (cDubboPBRequestTypeBuilder_ == null) { + cDubboPBRequestType_ = null; + } else { + cDubboPBRequestTypeBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000002); + return this; + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return GooglePB.internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBResponseType_descriptor; + } + + public GooglePB.PBResponseType getDefaultInstanceForType() { + return GooglePB.PBResponseType.getDefaultInstance(); + } + + public GooglePB.PBResponseType build() { + GooglePB.PBResponseType result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public GooglePB.PBResponseType buildPartial() { + GooglePB.PBResponseType result = new GooglePB.PBResponseType(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.msg_ = msg_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + if (cDubboPBRequestTypeBuilder_ == null) { + result.cDubboPBRequestType_ = cDubboPBRequestType_; + } else { + result.cDubboPBRequestType_ = cDubboPBRequestTypeBuilder_.build(); + } + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder clone() { + return (Builder) super.clone(); + } + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, + Object value) { + return (Builder) super.setField(field, value); + } + public Builder clearField( + com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } + public Builder clearOneof( + com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + int index, Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + Object value) { + return (Builder) super.addRepeatedField(field, value); + } + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof GooglePB.PBResponseType) { + return mergeFrom((GooglePB.PBResponseType)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(GooglePB.PBResponseType other) { + if (other == GooglePB.PBResponseType.getDefaultInstance()) return this; + if (other.hasMsg()) { + bitField0_ |= 0x00000001; + msg_ = other.msg_; + onChanged(); + } + if (other.hasCDubboPBRequestType()) { + mergeCDubboPBRequestType(other.getCDubboPBRequestType()); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + public final boolean isInitialized() { + if (hasCDubboPBRequestType()) { + if (!getCDubboPBRequestType().isInitialized()) { + return false; + } + } + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + GooglePB.PBResponseType parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (GooglePB.PBResponseType) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + private int bitField0_; + + private Object msg_ = ""; + /** + * optional string msg = 1; + */ + public boolean hasMsg() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + /** + * optional string msg = 1; + */ + public String getMsg() { + Object ref = msg_; + if (!(ref instanceof String)) { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (bs.isValidUtf8()) { + msg_ = s; + } + return s; + } else { + return (String) ref; + } + } + /** + * optional string msg = 1; + */ + public com.google.protobuf.ByteString + getMsgBytes() { + Object ref = msg_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (String) ref); + msg_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + /** + * optional string msg = 1; + */ + public Builder setMsg( + String value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000001; + msg_ = value; + onChanged(); + return this; + } + /** + * optional string msg = 1; + */ + public Builder clearMsg() { + bitField0_ = (bitField0_ & ~0x00000001); + msg_ = getDefaultInstance().getMsg(); + onChanged(); + return this; + } + /** + * optional string msg = 1; + */ + public Builder setMsgBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000001; + msg_ = value; + onChanged(); + return this; + } + + private GooglePB.PBRequestType cDubboPBRequestType_ = null; + private com.google.protobuf.SingleFieldBuilderV3< + PBRequestType, PBRequestType.Builder, PBRequestTypeOrBuilder> cDubboPBRequestTypeBuilder_; + /** + * optional .org.apache.dubbo.common.serialize.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + public boolean hasCDubboPBRequestType() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + /** + * optional .org.apache.dubbo.common.serialize.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + public GooglePB.PBRequestType getCDubboPBRequestType() { + if (cDubboPBRequestTypeBuilder_ == null) { + return cDubboPBRequestType_ == null ? GooglePB.PBRequestType.getDefaultInstance() : cDubboPBRequestType_; + } else { + return cDubboPBRequestTypeBuilder_.getMessage(); + } + } + /** + * optional .org.apache.dubbo.common.serialize.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + public Builder setCDubboPBRequestType(GooglePB.PBRequestType value) { + if (cDubboPBRequestTypeBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + cDubboPBRequestType_ = value; + onChanged(); + } else { + cDubboPBRequestTypeBuilder_.setMessage(value); + } + bitField0_ |= 0x00000002; + return this; + } + /** + * optional .org.apache.dubbo.common.serialize.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + public Builder setCDubboPBRequestType( + GooglePB.PBRequestType.Builder builderForValue) { + if (cDubboPBRequestTypeBuilder_ == null) { + cDubboPBRequestType_ = builderForValue.build(); + onChanged(); + } else { + cDubboPBRequestTypeBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000002; + return this; + } + /** + * optional .org.apache.dubbo.common.serialize.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + public Builder mergeCDubboPBRequestType(GooglePB.PBRequestType value) { + if (cDubboPBRequestTypeBuilder_ == null) { + if (((bitField0_ & 0x00000002) == 0x00000002) && + cDubboPBRequestType_ != null && + cDubboPBRequestType_ != GooglePB.PBRequestType.getDefaultInstance()) { + cDubboPBRequestType_ = + GooglePB.PBRequestType.newBuilder(cDubboPBRequestType_).mergeFrom(value).buildPartial(); + } else { + cDubboPBRequestType_ = value; + } + onChanged(); + } else { + cDubboPBRequestTypeBuilder_.mergeFrom(value); + } + bitField0_ |= 0x00000002; + return this; + } + /** + * optional .org.apache.dubbo.common.serialize.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + public Builder clearCDubboPBRequestType() { + if (cDubboPBRequestTypeBuilder_ == null) { + cDubboPBRequestType_ = null; + onChanged(); + } else { + cDubboPBRequestTypeBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000002); + return this; + } + /** + * optional .org.apache.dubbo.common.serialize.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + public GooglePB.PBRequestType.Builder getCDubboPBRequestTypeBuilder() { + bitField0_ |= 0x00000002; + onChanged(); + return getCDubboPBRequestTypeFieldBuilder().getBuilder(); + } + /** + * optional .org.apache.dubbo.common.serialize.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + public GooglePB.PBRequestTypeOrBuilder getCDubboPBRequestTypeOrBuilder() { + if (cDubboPBRequestTypeBuilder_ != null) { + return cDubboPBRequestTypeBuilder_.getMessageOrBuilder(); + } else { + return cDubboPBRequestType_ == null ? + GooglePB.PBRequestType.getDefaultInstance() : cDubboPBRequestType_; + } + } + /** + * optional .org.apache.dubbo.common.serialize.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + private com.google.protobuf.SingleFieldBuilderV3< + PBRequestType, PBRequestType.Builder, PBRequestTypeOrBuilder> + getCDubboPBRequestTypeFieldBuilder() { + if (cDubboPBRequestTypeBuilder_ == null) { + cDubboPBRequestTypeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + PBRequestType, PBRequestType.Builder, PBRequestTypeOrBuilder>( + getCDubboPBRequestType(), + getParentForChildren(), + isClean()); + cDubboPBRequestType_ = null; + } + return cDubboPBRequestTypeBuilder_; + } + public final Builder setUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFields(unknownFields); + } + + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + + // @@protoc_insertion_point(builder_scope:org.apache.dubbo.common.serialize.protobuf.model.PBResponseType) + } + + // @@protoc_insertion_point(class_scope:org.apache.dubbo.common.serialize.protobuf.model.PBResponseType) + private static final GooglePB.PBResponseType DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new GooglePB.PBResponseType(); + } + + public static GooglePB.PBResponseType getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + @Deprecated public static final com.google.protobuf.Parser + PARSER = new com.google.protobuf.AbstractParser() { + public PBResponseType parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new PBResponseType(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public GooglePB.PBResponseType getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + } + + public interface PhoneNumberOrBuilder extends + // @@protoc_insertion_point(interface_extends:org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber) + com.google.protobuf.MessageOrBuilder { + + /** + * required string number = 1; + */ + boolean hasNumber(); + /** + * required string number = 1; + */ + String getNumber(); + /** + * required string number = 1; + */ + com.google.protobuf.ByteString + getNumberBytes(); + + /** + * optional .org.apache.dubbo.common.serialize.protobuf.model.PhoneType type = 2 [default = HOME]; + */ + boolean hasType(); + /** + * optional .org.apache.dubbo.common.serialize.protobuf.model.PhoneType type = 2 [default = HOME]; + */ + GooglePB.PhoneType getType(); + } + /** + * Protobuf type {@code org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber} + */ + public static final class PhoneNumber extends + com.google.protobuf.GeneratedMessageV3 implements + // @@protoc_insertion_point(message_implements:org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber) + PhoneNumberOrBuilder { + private static final long serialVersionUID = 0L; + // Use PhoneNumber.newBuilder() to construct. + private PhoneNumber(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + private PhoneNumber() { + number_ = ""; + type_ = 1; + } + + @Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private PhoneNumber( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownField( + input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: { + com.google.protobuf.ByteString bs = input.readBytes(); + bitField0_ |= 0x00000001; + number_ = bs; + break; + } + case 16: { + int rawValue = input.readEnum(); + GooglePB.PhoneType value = GooglePB.PhoneType.valueOf(rawValue); + if (value == null) { + unknownFields.mergeVarintField(2, rawValue); + } else { + bitField0_ |= 0x00000002; + type_ = rawValue; + } + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return GooglePB.internal_static_org_apache_dubbo_common_serialize_protobuf_model_PhoneNumber_descriptor; + } + + protected FieldAccessorTable + internalGetFieldAccessorTable() { + return GooglePB.internal_static_org_apache_dubbo_common_serialize_protobuf_model_PhoneNumber_fieldAccessorTable + .ensureFieldAccessorsInitialized( + GooglePB.PhoneNumber.class, GooglePB.PhoneNumber.Builder.class); + } + + private int bitField0_; + public static final int NUMBER_FIELD_NUMBER = 1; + private volatile Object number_; + /** + * required string number = 1; + */ + public boolean hasNumber() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + /** + * required string number = 1; + */ + public String getNumber() { + Object ref = number_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (bs.isValidUtf8()) { + number_ = s; + } + return s; + } + } + /** + * required string number = 1; + */ + public com.google.protobuf.ByteString + getNumberBytes() { + Object ref = number_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (String) ref); + number_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int TYPE_FIELD_NUMBER = 2; + private int type_; + /** + * optional .org.apache.dubbo.common.serialize.protobuf.model.PhoneType type = 2 [default = HOME]; + */ + public boolean hasType() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + /** + * optional .org.apache.dubbo.common.serialize.protobuf.model.PhoneType type = 2 [default = HOME]; + */ + public GooglePB.PhoneType getType() { + GooglePB.PhoneType result = GooglePB.PhoneType.valueOf(type_); + return result == null ? GooglePB.PhoneType.HOME : result; + } + + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + if (!hasNumber()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + if (((bitField0_ & 0x00000001) == 0x00000001)) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 1, number_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeEnum(2, type_); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, number_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeEnumSize(2, type_); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @Override + public boolean equals(final Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof GooglePB.PhoneNumber)) { + return super.equals(obj); + } + GooglePB.PhoneNumber other = (GooglePB.PhoneNumber) obj; + + boolean result = true; + result = result && (hasNumber() == other.hasNumber()); + if (hasNumber()) { + result = result && getNumber() + .equals(other.getNumber()); + } + result = result && (hasType() == other.hasType()); + if (hasType()) { + result = result && type_ == other.type_; + } + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + if (hasNumber()) { + hash = (37 * hash) + NUMBER_FIELD_NUMBER; + hash = (53 * hash) + getNumber().hashCode(); + } + if (hasType()) { + hash = (37 * hash) + TYPE_FIELD_NUMBER; + hash = (53 * hash) + type_; + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static GooglePB.PhoneNumber parseFrom( + java.nio.ByteBuffer data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static GooglePB.PhoneNumber parseFrom( + java.nio.ByteBuffer data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static GooglePB.PhoneNumber parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static GooglePB.PhoneNumber parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static GooglePB.PhoneNumber parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static GooglePB.PhoneNumber parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static GooglePB.PhoneNumber parseFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static GooglePB.PhoneNumber parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + public static GooglePB.PhoneNumber parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input); + } + public static GooglePB.PhoneNumber parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + public static GooglePB.PhoneNumber parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static GooglePB.PhoneNumber parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + public static Builder newBuilder(GooglePB.PhoneNumber prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { + return this == DEFAULT_INSTANCE + ? new Builder() : new Builder().mergeFrom(this); + } + + @Override + protected Builder newBuilderForType( + BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessageV3.Builder implements + // @@protoc_insertion_point(builder_implements:org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber) + GooglePB.PhoneNumberOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return GooglePB.internal_static_org_apache_dubbo_common_serialize_protobuf_model_PhoneNumber_descriptor; + } + + protected FieldAccessorTable + internalGetFieldAccessorTable() { + return GooglePB.internal_static_org_apache_dubbo_common_serialize_protobuf_model_PhoneNumber_fieldAccessorTable + .ensureFieldAccessorsInitialized( + GooglePB.PhoneNumber.class, GooglePB.PhoneNumber.Builder.class); + } + + // Construct using org.apache.dubbo.common.serialize.protobuf.model.GooglePB.PhoneNumber.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3 + .alwaysUseFieldBuilders) { + } + } + public Builder clear() { + super.clear(); + number_ = ""; + bitField0_ = (bitField0_ & ~0x00000001); + type_ = 1; + bitField0_ = (bitField0_ & ~0x00000002); + return this; + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return GooglePB.internal_static_org_apache_dubbo_common_serialize_protobuf_model_PhoneNumber_descriptor; + } + + public GooglePB.PhoneNumber getDefaultInstanceForType() { + return GooglePB.PhoneNumber.getDefaultInstance(); + } + + public GooglePB.PhoneNumber build() { + GooglePB.PhoneNumber result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public GooglePB.PhoneNumber buildPartial() { + GooglePB.PhoneNumber result = new GooglePB.PhoneNumber(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.number_ = number_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.type_ = type_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder clone() { + return (Builder) super.clone(); + } + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, + Object value) { + return (Builder) super.setField(field, value); + } + public Builder clearField( + com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } + public Builder clearOneof( + com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + int index, Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + Object value) { + return (Builder) super.addRepeatedField(field, value); + } + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof GooglePB.PhoneNumber) { + return mergeFrom((GooglePB.PhoneNumber)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(GooglePB.PhoneNumber other) { + if (other == GooglePB.PhoneNumber.getDefaultInstance()) return this; + if (other.hasNumber()) { + bitField0_ |= 0x00000001; + number_ = other.number_; + onChanged(); + } + if (other.hasType()) { + setType(other.getType()); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + public final boolean isInitialized() { + if (!hasNumber()) { + return false; + } + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + GooglePB.PhoneNumber parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (GooglePB.PhoneNumber) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + private int bitField0_; + + private Object number_ = ""; + /** + * required string number = 1; + */ + public boolean hasNumber() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + /** + * required string number = 1; + */ + public String getNumber() { + Object ref = number_; + if (!(ref instanceof String)) { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (bs.isValidUtf8()) { + number_ = s; + } + return s; + } else { + return (String) ref; + } + } + /** + * required string number = 1; + */ + public com.google.protobuf.ByteString + getNumberBytes() { + Object ref = number_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (String) ref); + number_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + /** + * required string number = 1; + */ + public Builder setNumber( + String value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000001; + number_ = value; + onChanged(); + return this; + } + /** + * required string number = 1; + */ + public Builder clearNumber() { + bitField0_ = (bitField0_ & ~0x00000001); + number_ = getDefaultInstance().getNumber(); + onChanged(); + return this; + } + /** + * required string number = 1; + */ + public Builder setNumberBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000001; + number_ = value; + onChanged(); + return this; + } + + private int type_ = 1; + /** + * optional .org.apache.dubbo.common.serialize.protobuf.model.PhoneType type = 2 [default = HOME]; + */ + public boolean hasType() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + /** + * optional .org.apache.dubbo.common.serialize.protobuf.model.PhoneType type = 2 [default = HOME]; + */ + public GooglePB.PhoneType getType() { + GooglePB.PhoneType result = GooglePB.PhoneType.valueOf(type_); + return result == null ? GooglePB.PhoneType.HOME : result; + } + /** + * optional .org.apache.dubbo.common.serialize.protobuf.model.PhoneType type = 2 [default = HOME]; + */ + public Builder setType(GooglePB.PhoneType value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000002; + type_ = value.getNumber(); + onChanged(); + return this; + } + /** + * optional .org.apache.dubbo.common.serialize.protobuf.model.PhoneType type = 2 [default = HOME]; + */ + public Builder clearType() { + bitField0_ = (bitField0_ & ~0x00000002); + type_ = 1; + onChanged(); + return this; + } + public final Builder setUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFields(unknownFields); + } + + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + + // @@protoc_insertion_point(builder_scope:org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber) + } + + // @@protoc_insertion_point(class_scope:org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber) + private static final GooglePB.PhoneNumber DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new GooglePB.PhoneNumber(); + } + + public static GooglePB.PhoneNumber getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + @Deprecated public static final com.google.protobuf.Parser + PARSER = new com.google.protobuf.AbstractParser() { + public PhoneNumber parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new PhoneNumber(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public GooglePB.PhoneNumber getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + } + + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBRequestType_descriptor; + private static final + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBRequestType_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBRequestType_DoubleMapEntry_descriptor; + private static final + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBRequestType_DoubleMapEntry_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBResponseType_descriptor; + private static final + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBResponseType_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_org_apache_dubbo_common_serialize_protobuf_model_PhoneNumber_descriptor; + private static final + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_org_apache_dubbo_common_serialize_protobuf_model_PhoneNumber_fieldAccessorTable; + + public static com.google.protobuf.Descriptors.FileDescriptor + getDescriptor() { + return descriptor; + } + private static com.google.protobuf.Descriptors.FileDescriptor + descriptor; + static { + String[] descriptorData = { + "\n\016GooglePB.proto\0220org.apache.dubbo.commo" + + "n.serialize.protobuf.model\"\220\003\n\rPBRequest" + + "Type\022\r\n\005money\030\001 \001(\001\022\014\n\004cash\030\002 \001(\002\022\013\n\003age" + + "\030\003 \001(\005\022\013\n\003num\030\004 \001(\003\022\013\n\003sex\030\005 \001(\010\022\014\n\004name" + + "\030\006 \001(\t\022\013\n\003msg\030\007 \001(\014\022L\n\005phone\030\010 \003(\0132=.org" + + ".apache.dubbo.common.serialize.protobuf." + + "model.PhoneNumber\022a\n\tdoubleMap\030\t \003(\0132N.o" + + "rg.apache.dubbo.common.serialize.protobu" + + "f.model.PBRequestType.DoubleMapEntry\032o\n\016" + + "DoubleMapEntry\022\013\n\003key\030\001 \001(\t\022L\n\005value\030\002 \001", + "(\0132=.org.apache.dubbo.common.serialize.p" + + "rotobuf.model.PhoneNumber:\0028\001\"{\n\016PBRespo" + + "nseType\022\013\n\003msg\030\001 \001(\t\022\\\n\023CDubboPBRequestT" + + "ype\030\003 \001(\0132?.org.apache.dubbo.common.seri" + + "alize.protobuf.model.PBRequestType\"n\n\013Ph" + + "oneNumber\022\016\n\006number\030\001 \002(\t\022O\n\004type\030\002 \001(\0162" + + ";.org.apache.dubbo.common.serialize.prot" + + "obuf.model.PhoneType:\004HOME*+\n\tPhoneType\022" + + "\n\n\006MOBILE\020\000\022\010\n\004HOME\020\001\022\010\n\004WORK\020\0022\241\001\n\017CDub" + + "boPBService\022\215\001\n\010sayHello\022?.org.apache.du", + "bbo.common.serialize.protobuf.model.PBRe" + + "questType\032@.org.apache.dubbo.common.seri" + + "alize.protobuf.model.PBResponseType" + }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor + .internalBuildGeneratedFileFrom(descriptorData, + new com.google.protobuf.Descriptors.FileDescriptor[] { + }, assigner); + internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBRequestType_descriptor = + getDescriptor().getMessageTypes().get(0); + internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBRequestType_fieldAccessorTable = new + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBRequestType_descriptor, + new String[] { "Money", "Cash", "Age", "Num", "Sex", "Name", "Msg", "Phone", "DoubleMap", }); + internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBRequestType_DoubleMapEntry_descriptor = + internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBRequestType_descriptor.getNestedTypes().get(0); + internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBRequestType_DoubleMapEntry_fieldAccessorTable = new + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBRequestType_DoubleMapEntry_descriptor, + new String[] { "Key", "Value", }); + internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBResponseType_descriptor = + getDescriptor().getMessageTypes().get(1); + internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBResponseType_fieldAccessorTable = new + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_org_apache_dubbo_common_serialize_protobuf_model_PBResponseType_descriptor, + new String[] { "Msg", "CDubboPBRequestType", }); + internal_static_org_apache_dubbo_common_serialize_protobuf_model_PhoneNumber_descriptor = + getDescriptor().getMessageTypes().get(2); + internal_static_org_apache_dubbo_common_serialize_protobuf_model_PhoneNumber_fieldAccessorTable = new + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_org_apache_dubbo_common_serialize_protobuf_model_PhoneNumber_descriptor, + new String[] { "Number", "Type", }); + } + + // @@protoc_insertion_point(outer_class_scope) +} diff --git a/dubbo-serialization/dubbo-serialization-test/src/test/resources/protobuf/GooglePB.proto b/dubbo-serialization/dubbo-serialization-test/src/test/resources/protobuf/GooglePB.proto new file mode 100644 index 00000000000..bda3e37b5a0 --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-test/src/test/resources/protobuf/GooglePB.proto @@ -0,0 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +syntax = "proto2"; + +package org.apache.dubbo.common.serialize.protobuf.model; + +message PBRequestType { + optional double money = 1; + optional float cash = 2; + optional int32 age = 3; + optional int64 num = 4; + optional bool sex = 5; + optional string name = 6; + optional bytes msg = 7; + repeated org.apache.dubbo.common.serialize.protobuf.model.PhoneNumber phone = 8; + map doubleMap = 9; +} + +message PBResponseType { + optional string msg = 1; + optional org.apache.dubbo.common.serialize.protobuf.model.PBRequestType CDubboPBRequestType = 3; +} + +message PhoneNumber { + required string number = 1; + optional org.apache.dubbo.common.serialize.protobuf.model.PhoneType type = 2 [default = HOME]; +} + +enum PhoneType { + MOBILE = 0; + HOME = 1; + WORK = 2; +} + +service CDubboPBService { + rpc sayHello (org.apache.dubbo.common.serialize.protobuf.model.PBRequestType) returns (org.apache.dubbo.common.serialize.protobuf.model.PBResponseType); +} \ No newline at end of file diff --git a/dubbo-serialization/pom.xml b/dubbo-serialization/pom.xml index b6b4b5c5cef..448aa078628 100644 --- a/dubbo-serialization/pom.xml +++ b/dubbo-serialization/pom.xml @@ -39,6 +39,7 @@ dubbo-serialization-avro dubbo-serialization-test dubbo-serialization-gson + dubbo-serialization-protobuf-json dubbo-serialization-native-hession From 5fd41d7b27b8bfa4230df2dc48c7c0d57b0ef98c Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Wed, 8 May 2019 17:22:51 +0800 Subject: [PATCH 034/115] =?UTF-8?q?dubbox=E5=8D=87=E7=BA=A7dubbo=E7=89=88?= =?UTF-8?q?=E6=9C=AC=E7=9A=84=E5=85=BC=E5=AE=B9=E6=80=A7=E9=97=AE=E9=A2=98?= =?UTF-8?q?=20(#3996)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #3537 --- .../java/org/apache/dubbo/common/Version.java | 21 ++++++++++++------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Version.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Version.java index ffbc31241a1..a015b44e9e2 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/Version.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Version.java @@ -37,7 +37,7 @@ */ public final class Version { private static final Logger logger = LoggerFactory.getLogger(Version.class); - + private static final Pattern PREFIX_DIGITS_PATTERN = Pattern.compile("^([0-9]*).*"); // Dubbo RPC protocol version, for compatibility, it must not be between 2.0.10 ~ 2.6.2 @@ -104,6 +104,11 @@ public static boolean isSupportResponseAttachment(String version) { return false; } + // 2.8.x is reserved for dubbox + if (iVersion >= 2080000 && iVersion < 2090000) { + return false; + } + return iVersion >= LOWEST_VERSION_FOR_RESPONSE_ATTACHMENT; } @@ -157,19 +162,19 @@ public static String getVersion(Class cls, String defaultVersion) { return version; } } - + // guess version fro jar file name if nothing's found from MANIFEST.MF CodeSource codeSource = cls.getProtectionDomain().getCodeSource(); if (codeSource == null) { logger.info("No codeSource for class " + cls.getName() + " when getVersion, use default version " + defaultVersion); return defaultVersion; - } - + } + String file = codeSource.getLocation().getFile(); if (!StringUtils.isEmpty(file) && file.endsWith(".jar")) { version = getFromFile(file); } - + // return default version if no version info is found return StringUtils.isEmpty(version) ? defaultVersion : version; } catch (Throwable e) { @@ -185,19 +190,19 @@ public static String getVersion(Class cls, String defaultVersion) { private static String getFromFile(String file) { // remove suffix ".jar": "path/to/group-module-x.y.z" file = file.substring(0, file.length() - 4); - + // remove path: "group-module-x.y.z" int i = file.lastIndexOf('/'); if (i >= 0) { file = file.substring(i + 1); } - + // remove group: "module-x.y.z" i = file.indexOf("-"); if (i >= 0) { file = file.substring(i + 1); } - + // remove module: "x.y.z" while (file.length() > 0 && !Character.isDigit(file.charAt(0))) { i = file.indexOf("-"); From f95e29a0e049046b066eec7e84643315dce5c0fb Mon Sep 17 00:00:00 2001 From: myPrecious Date: Thu, 9 May 2019 22:23:03 +0800 Subject: [PATCH 035/115] [Dubbo-3846] Support Nacos as config center (#3988) --- dubbo-all/pom.xml | 8 + dubbo-bom/pom.xml | 10 + .../org/apache/dubbo/common/Constants.java | 2 + .../dubbo-configcenter-nacos/pom.xml | 45 +++ .../nacos/NacosDynamicConfiguration.java | 265 ++++++++++++++++++ .../NacosDynamicConfigurationFactory.java | 40 +++ ...o.configcenter.DynamicConfigurationFactory | 1 + .../nacos/NacosDynamicConfigurationTest.java | 136 +++++++++ dubbo-configcenter/pom.xml | 1 + .../AbstractConfiguratorListener.java | 3 +- 10 files changed, 510 insertions(+), 1 deletion(-) create mode 100644 dubbo-configcenter/dubbo-configcenter-nacos/pom.xml create mode 100644 dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java create mode 100644 dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationFactory.java create mode 100644 dubbo-configcenter/dubbo-configcenter-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.configcenter.DynamicConfigurationFactory create mode 100644 dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java diff --git a/dubbo-all/pom.xml b/dubbo-all/pom.xml index c353874f88d..6dc00fbcda7 100644 --- a/dubbo-all/pom.xml +++ b/dubbo-all/pom.xml @@ -415,6 +415,13 @@ compile true + + org.apache.dubbo + dubbo-configcenter-nacos + ${project.version} + compile + true + org.apache.dubbo dubbo-configcenter-consul @@ -599,6 +606,7 @@ org.apache.dubbo:dubbo-configcenter-zookeeper org.apache.dubbo:dubbo-configcenter-consul org.apache.dubbo:dubbo-configcenter-etcd + org.apache.dubbo:dubbo-configcenter-nacos org.apache.dubbo:dubbo-metadata-report-api org.apache.dubbo:dubbo-metadata-definition org.apache.dubbo:dubbo-metadata-report-redis diff --git a/dubbo-bom/pom.xml b/dubbo-bom/pom.xml index a7e44dcf6dc..2b1e5feb2f6 100644 --- a/dubbo-bom/pom.xml +++ b/dubbo-bom/pom.xml @@ -257,6 +257,11 @@ dubbo-registry-consul ${project.version} + + org.apache.dubbo + dubbo-registry-nacos + ${project.version} + org.apache.dubbo dubbo-registry-sofa @@ -402,6 +407,11 @@ dubbo-configcenter-etcd ${project.version} + + org.apache.dubbo + dubbo-configcenter-nacos + ${project.version} + org.apache.dubbo dubbo-metadata-definition diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java index cc52e77d6f7..31d5fc73e31 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java @@ -200,6 +200,8 @@ public class Constants { public static final String PROPERTIES_CHAR_SEPERATOR = "-"; + public static final String GROUP_CHAR_SEPERATOR = ":"; + public static final String HIDE_KEY_PREFIX = "."; public static final String DEFAULT_KEY_PREFIX = "default."; diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml b/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml new file mode 100644 index 00000000000..bd5397c92b6 --- /dev/null +++ b/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml @@ -0,0 +1,45 @@ + + + + + + dubbo-configcenter + org.apache.dubbo + ${revision} + + 4.0.0 + + dubbo-configcenter-nacos + jar + ${project.artifactId} + The nacos implementation of the config-center api + + + + org.apache.dubbo + dubbo-configcenter-api + ${project.parent.version} + + + com.alibaba.nacos + nacos-client + + + diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java new file mode 100644 index 00000000000..fdb536fa8a3 --- /dev/null +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java @@ -0,0 +1,265 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.configcenter.support.nacos; + +import com.alibaba.nacos.api.NacosFactory; +import com.alibaba.nacos.api.config.ConfigService; +import com.alibaba.nacos.api.config.listener.AbstractSharedListener; +import com.alibaba.nacos.api.exception.NacosException; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.common.utils.StringUtils; +import org.apache.dubbo.configcenter.ConfigChangeEvent; +import org.apache.dubbo.configcenter.ConfigChangeType; +import org.apache.dubbo.configcenter.ConfigurationListener; +import org.apache.dubbo.configcenter.DynamicConfiguration; + +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.concurrent.Executor; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArraySet; +import static com.alibaba.nacos.api.PropertyKeyConst.ACCESS_KEY; +import static com.alibaba.nacos.api.PropertyKeyConst.CLUSTER_NAME; +import static com.alibaba.nacos.api.PropertyKeyConst.ENDPOINT; +import static com.alibaba.nacos.api.PropertyKeyConst.SECRET_KEY; +import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; +import static com.alibaba.nacos.api.PropertyKeyConst.NAMESPACE; +import static com.alibaba.nacos.client.naming.utils.UtilAndComs.NACOS_NAMING_LOG_NAME; +import static org.apache.dubbo.common.Constants.BACKUP_KEY; +import static org.apache.dubbo.common.Constants.CONFIG_NAMESPACE_KEY; +import static org.apache.dubbo.common.Constants.GROUP_CHAR_SEPERATOR; +import static org.apache.dubbo.common.Constants.PROPERTIES_CHAR_SEPERATOR; + +/** + * The nacos implementation of {@link DynamicConfiguration} + */ +public class NacosDynamicConfiguration implements DynamicConfiguration { + + private final Logger logger = LoggerFactory.getLogger(getClass()); + + /** + * The final root path would be: /$NAME_SPACE/config + */ + private String rootPath; + + /** + * The nacos configService + */ + + private ConfigService configService; + + /** + * The map store the key to {@link NacosConfigListener} mapping + */ + private final ConcurrentMap watchListenerMap; + + NacosDynamicConfiguration(URL url) { + rootPath = url.getParameter(CONFIG_NAMESPACE_KEY, DEFAULT_GROUP) + "-config"; + buildConfigService(url); + watchListenerMap = new ConcurrentHashMap<>(); + } + + private ConfigService buildConfigService(URL url) { + Properties nacosProperties = buildNacosProperties(url); + try { + configService = NacosFactory.createConfigService(nacosProperties); + } catch (NacosException e) { + if (logger.isErrorEnabled()) { + logger.error(e.getErrMsg(), e); + } + throw new IllegalStateException(e); + } + return configService; + } + + public void publishNacosConfig(String key, String value) { + try { + String[] keyAndGroup = getKeyAndGroup(key); + configService.publishConfig(keyAndGroup[0], keyAndGroup[1], value); + } catch (NacosException e) { + logger.error(e.getErrMsg()); + } + } + + private String[] getKeyAndGroup(String key) { + int i = key.lastIndexOf(GROUP_CHAR_SEPERATOR); + if (i < 0) { + return new String[]{key, null}; + } else { + return new String[]{key.substring(0, i), key.substring(i+1)}; + } + } + + private Properties buildNacosProperties(URL url) { + Properties properties = new Properties(); + setServerAddr(url, properties); + setProperties(url, properties); + return properties; + } + + private void setServerAddr(URL url, Properties properties) { + StringBuilder serverAddrBuilder = + new StringBuilder(url.getHost()) // Host + .append(":") + .append(url.getPort()); // Port + + // Append backup parameter as other servers + String backup = url.getParameter(BACKUP_KEY); + if (backup != null) { + serverAddrBuilder.append(",").append(backup); + } + String serverAddr = serverAddrBuilder.toString(); + properties.put(SERVER_ADDR, serverAddr); + } + + private void setProperties(URL url, Properties properties) { + putPropertyIfAbsent(url, properties, NAMESPACE); + putPropertyIfAbsent(url, properties, NACOS_NAMING_LOG_NAME); + putPropertyIfAbsent(url, properties, ENDPOINT); + putPropertyIfAbsent(url, properties, ACCESS_KEY); + putPropertyIfAbsent(url, properties, SECRET_KEY); + putPropertyIfAbsent(url, properties, CLUSTER_NAME); + } + + private void putPropertyIfAbsent(URL url, Properties properties, String propertyName) { + String propertyValue = url.getParameter(propertyName); + if (StringUtils.isNotEmpty(propertyValue)) { + properties.setProperty(propertyName, propertyValue); + } + } + + /** + * Ignores the group parameter. + * + * @param key property key the native listener will listen on + * @param group to distinguish different set of properties + * @return + */ + private NacosConfigListener createTargetListener(String key, String group) { + NacosConfigListener configListener = new NacosConfigListener(); + configListener.fillContext(key, group); + return configListener; + } + + @Override + public void addListener(String key, String group, ConfigurationListener listener) { + String[] keyAndGroup = getKeyAndGroup(key); + if (keyAndGroup[1] != null) { + group = keyAndGroup[1]; + } + String finalGroup = group; + NacosConfigListener nacosConfigListener = watchListenerMap.computeIfAbsent(generateKey(key, group), k -> createTargetListener(key, finalGroup)); + String keyInNacos = rootPath + PROPERTIES_CHAR_SEPERATOR + key; + nacosConfigListener.addListener(listener); + try { + configService.addListener(keyInNacos, group, nacosConfigListener); + System.out.println("1"); + } catch (NacosException e) { + logger.error(e.getMessage()); + } + } + + private String generateKey(String key, String group) { + if (StringUtils.isNotEmpty(group)) { + key = key + GROUP_CHAR_SEPERATOR + group; + } + return key; + } + + @Override + public void removeListener(String key, String group, ConfigurationListener listener) { + NacosConfigListener eventListener = watchListenerMap.get(generateKey(key, group)); + if (eventListener != null) { + eventListener.removeListener(listener); + } + } + + @Override + public String getConfig(String key, String group, long timeout) throws IllegalStateException { + key = generateKey(key, group); + return (String) getInternalProperty(rootPath + PROPERTIES_CHAR_SEPERATOR + key); + } + + @Override + public Object getInternalProperty(String key) { + try { + String[] keyAndGroup = getKeyAndGroup(key); + return configService.getConfig(keyAndGroup[0], keyAndGroup[1], 5000L); + } catch (NacosException e) { + logger.error(e.getMessage()); + } + return null; + } + + public class NacosConfigListener extends AbstractSharedListener { + + private Set listeners = new CopyOnWriteArraySet<>(); + /** + * cache data to store old value + */ + private Map cacheData = new ConcurrentHashMap<>(); + + @Override + public Executor getExecutor() { + return null; + } + + /** + * receive + * + * @param dataId data ID + * @param group group + * @param configInfo content + */ + @Override + public void innerReceive(String dataId, String group, String configInfo) { + String oldValue = cacheData.get(dataId); + ConfigChangeEvent event = new ConfigChangeEvent(dataId, configInfo, getChangeType(configInfo, oldValue)); + if (configInfo == null) { + cacheData.remove(dataId); + } else { + cacheData.put(dataId, configInfo); + } + listeners.forEach(listener -> listener.process(event)); + } + + void addListener(ConfigurationListener configurationListener) { + + this.listeners.add(configurationListener); + } + + void removeListener(ConfigurationListener configurationListener) { + this.listeners.remove(configurationListener); + } + + private ConfigChangeType getChangeType(String configInfo, String oldValue) { + if (StringUtils.isBlank(configInfo)) { + return ConfigChangeType.DELETED; + } + if (StringUtils.isBlank(oldValue)) { + return ConfigChangeType.ADDED; + } + return ConfigChangeType.MODIFIED; + } + } + +} diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationFactory.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationFactory.java new file mode 100644 index 00000000000..2246741c1cb --- /dev/null +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationFactory.java @@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.configcenter.support.nacos; + +import com.alibaba.nacos.api.PropertyKeyConst; +import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.configcenter.AbstractDynamicConfigurationFactory; +import org.apache.dubbo.configcenter.DynamicConfiguration; + +/** + * The nacos implementation of {@link AbstractDynamicConfigurationFactory} + */ +public class NacosDynamicConfigurationFactory extends AbstractDynamicConfigurationFactory { + + @Override + protected DynamicConfiguration createDynamicConfiguration(URL url) { + URL nacosURL = url; + if (Constants.DUBBO.equals(url.getParameter(PropertyKeyConst.NAMESPACE))) { + // Nacos use empty string as default name space, replace default namespace "dubbo" to "" + nacosURL = url.removeParameter(PropertyKeyConst.NAMESPACE); + } + return new NacosDynamicConfiguration(nacosURL); + } +} diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.configcenter.DynamicConfigurationFactory b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.configcenter.DynamicConfigurationFactory new file mode 100644 index 00000000000..b9c75a4c980 --- /dev/null +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.configcenter.DynamicConfigurationFactory @@ -0,0 +1 @@ +nacos=org.apache.dubbo.configcenter.support.nacos.NacosDynamicConfigurationFactory \ No newline at end of file diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java new file mode 100644 index 00000000000..f5ac1d38ccb --- /dev/null +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java @@ -0,0 +1,136 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.configcenter.support.nacos; + +import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.configcenter.ConfigChangeEvent; +import org.apache.dubbo.configcenter.ConfigurationListener; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Disabled; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.CountDownLatch; + +/** + * Unit test for nacos config center support + */ +@Disabled +public class NacosDynamicConfigurationTest { + + private static NacosDynamicConfiguration config; + + @Test + public void testGetConfig() throws Exception { + + put("dubbo-config-org.apache.dubbo.nacos.testService.configurators", "hello"); + Thread.sleep(200); + put("dubbo-config-dubbo.properties:test", "aaa=bbb"); + Thread.sleep(200); + Assertions.assertEquals("hello", config.getConfig("org.apache.dubbo.nacos.testService.configurators")); + Assertions.assertEquals("aaa=bbb", config.getConfig("dubbo.properties", "test")); + } + + @Test + public void testAddListener() throws Exception { + CountDownLatch latch = new CountDownLatch(4); + TestListener listener1 = new TestListener(latch); + TestListener listener2 = new TestListener(latch); + TestListener listener3 = new TestListener(latch); + TestListener listener4 = new TestListener(latch); + + + config.addListener("AService.configurators", listener1); + config.addListener("AService.configurators", listener2); + config.addListener("testapp.tagrouters", listener3); + config.addListener("testapp.tagrouters", listener4); + + put("dubbo-config-AService.configurators", "new value1"); + Thread.sleep(200); + put("dubbo-config-testapp.tagrouters", "new value2"); + Thread.sleep(200); + put("dubbo-config-testapp", "new value3"); + Thread.sleep(5000); + + latch.await(); + + Assertions.assertEquals(1, listener1.getCount("dubbo-config-AService.configurators")); + Assertions.assertEquals(1, listener2.getCount("dubbo-config-AService.configurators")); + Assertions.assertEquals(1, listener3.getCount("dubbo-config-testapp.tagrouters")); + Assertions.assertEquals(1, listener4.getCount("dubbo-config-testapp.tagrouters")); + + Assertions.assertEquals("new value1", listener1.getValue()); + Assertions.assertEquals("new value1", listener2.getValue()); + Assertions.assertEquals("new value2", listener3.getValue()); + Assertions.assertEquals("new value2", listener4.getValue()); + + } + + private void put(String key, String value) { + try { + config.publishNacosConfig(key, value); + } catch (Exception e) { + System.out.println("Error put value to nacos."); + } + } + + @BeforeAll + public static void setUp() { + String urlForDubbo = "nacos://" + "127.0.0.1:8848" + "/org.apache.dubbo.nacos.testService"; + // timeout in 15 seconds. + URL url = URL.valueOf(urlForDubbo) + .addParameter(Constants.SESSION_TIMEOUT_KEY, 15000); + config = new NacosDynamicConfiguration(url); + } + + @AfterAll + public static void tearDown() { + } + + private class TestListener implements ConfigurationListener { + private CountDownLatch latch; + private String value; + private Map countMap = new HashMap<>(); + + public TestListener(CountDownLatch latch) { + this.latch = latch; + } + + @Override + public void process(ConfigChangeEvent event) { + System.out.println(this + ": " + event); + Integer count = countMap.computeIfAbsent(event.getKey(), k -> new Integer(0)); + countMap.put(event.getKey(), ++count); + value = event.getValue(); + latch.countDown(); + } + + public int getCount(String key) { + return countMap.get(key); + } + + public String getValue() { + return value; + } + } + +} diff --git a/dubbo-configcenter/pom.xml b/dubbo-configcenter/pom.xml index c6fb983bb72..0de20d319c7 100644 --- a/dubbo-configcenter/pom.xml +++ b/dubbo-configcenter/pom.xml @@ -35,5 +35,6 @@ dubbo-configcenter-apollo dubbo-configcenter-consul dubbo-configcenter-etcd + dubbo-configcenter-nacos diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java index 8b0b43fad9d..3aea7e6177e 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java @@ -16,6 +16,7 @@ */ package org.apache.dubbo.registry.integration; +import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; @@ -41,7 +42,7 @@ public abstract class AbstractConfiguratorListener implements ConfigurationListe protected final void initWith(String key) { DynamicConfiguration dynamicConfiguration = DynamicConfiguration.getDynamicConfiguration(); dynamicConfiguration.addListener(key, this); - String rawConfig = dynamicConfiguration.getConfig(key); + String rawConfig = dynamicConfiguration.getConfig(key, Constants.DUBBO); if (!StringUtils.isEmpty(rawConfig)) { process(new ConfigChangeEvent(key, rawConfig)); } From 09d8a6ea6ed58a331115bfb5b93bda1647229e6e Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Fri, 10 May 2019 12:59:57 +0800 Subject: [PATCH 036/115] Need to enhance DecodeableRpcResult error message (#3995) Fixes #3994 --- .../apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java index fac7c64a6ca..0edfdb8f3a3 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java @@ -97,7 +97,7 @@ public Object decode(Channel channel, InputStream input) throws IOException { handleAttachment(in); break; default: - throw new IOException("Unknown result flag, expect '0' '1' '2', get " + flag); + throw new IOException("Unknown result flag, expect '0' '1' '2' '3' '4' '5', but received: " + flag); } if (in instanceof Cleanable) { ((Cleanable) in).cleanup(); From d5c517607b5bb5360c56b8d619799b2795594040 Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Fri, 10 May 2019 13:01:06 +0800 Subject: [PATCH 037/115] port #3568 into main trunk (#3993) fixes #3991 --- .../java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java index 38650c2b2ef..bc8c7470184 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java @@ -73,12 +73,13 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro byte status = header[3]; res.setStatus(status); try { - ObjectInput in = CodecSupport.deserialize(channel.getUrl(), is, proto); if (status == Response.OK) { Object data; if (res.isHeartbeat()) { + ObjectInput in = CodecSupport.deserialize(channel.getUrl(), is, proto); data = decodeHeartbeatData(channel, in); } else if (res.isEvent()) { + ObjectInput in = CodecSupport.deserialize(channel.getUrl(), is, proto); data = decodeEventData(channel, in); } else { DecodeableRpcResult result; @@ -97,6 +98,7 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro } res.setResult(data); } else { + ObjectInput in = CodecSupport.deserialize(channel.getUrl(), is, proto); res.setErrorMessage(in.readUTF()); } } catch (Throwable t) { From 30c3c2f43190e736bf2564160509b36b3a21a8de Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Fri, 10 May 2019 14:19:52 +0800 Subject: [PATCH 038/115] Seperate Constants.java into some SubConstants Class - step 1 (#4017) see #3137 --- .../ConsistentHashLoadBalance.java | 13 +- .../org/apache/dubbo/common/Constants.java | 966 +++++++++--------- .../integration/RegistryProtocol.java | 3 +- .../remoting/transport/CodecSupport.java | 6 +- .../apache/dubbo/remoting/etcd/Constants.java | 31 + .../remoting/etcd/jetcd/JEtcdClient.java | 8 +- .../dubbo/common/serialize/Constants.java | 33 + .../serialize/avro/AvroSerialization.java | 5 +- .../fastjson/FastJsonSerialization.java | 5 +- .../serialize/fst/FstSerialization.java | 5 +- .../serialize/gson/GsonSerialization.java | 5 +- .../hessian2/Hessian2Serialization.java | 5 +- .../java/CompactedJavaSerialization.java | 5 +- .../serialize/java/JavaSerialization.java | 5 +- .../nativejava/NativeJavaSerialization.java | 5 +- .../serialize/kryo/KryoSerialization.java | 5 +- .../hessian/Hessian2Serialization.java | 4 +- .../support/GenericProtobufSerialization.java | 6 +- .../protostuff/ProtostuffSerialization.java | 5 +- .../serialize/avro/AvroSerializationTest.java | 4 +- 20 files changed, 608 insertions(+), 516 deletions(-) create mode 100644 dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/Constants.java create mode 100644 dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/Constants.java diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalance.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalance.java index 03c0dc9173d..75ebc8a7682 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalance.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalance.java @@ -31,15 +31,22 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -import static org.apache.dubbo.common.Constants.HASH_ARGUMENTS; -import static org.apache.dubbo.common.Constants.HASH_NODES; - /** * ConsistentHashLoadBalance */ public class ConsistentHashLoadBalance extends AbstractLoadBalance { public static final String NAME = "consistenthash"; + /** + * Hash nodes name + */ + public static final String HASH_NODES = "hash.nodes"; + + /** + * Hash arguments name + */ + public static final String HASH_ARGUMENTS = "hash.arguments"; + private final ConcurrentMap> selectors = new ConcurrentHashMap>(); @SuppressWarnings("unchecked") diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java index 31d5fc73e31..42c9f39748f 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java @@ -25,305 +25,256 @@ */ public class Constants { + // BEGIN common public static final String DUBBO = "dubbo"; public static final String PROVIDER = "provider"; public static final String CONSUMER = "consumer"; - public static final String REGISTER = "register"; - - public static final String UNREGISTER = "unregister"; - - public static final String SUBSCRIBE = "subscribe"; - - public static final String UNSUBSCRIBE = "unsubscribe"; + public static final String APPLICATION_KEY = "application"; - public static final String CATEGORY_KEY = "category"; + public static final String REMOTE_APPLICATION_KEY = "remote.application"; - public static final String PROVIDERS_CATEGORY = "providers"; + public static final String ENABLED_KEY = "enabled"; - public static final String CONSUMERS_CATEGORY = "consumers"; + public static final String DISABLED_KEY = "disabled"; - public static final String ROUTERS_CATEGORY = "routers"; + public static final String DUBBO_PROPERTIES_KEY = "dubbo.properties.file"; - public static final String DYNAMIC_ROUTERS_CATEGORY = "dynamicrouters"; + public static final String DEFAULT_DUBBO_PROPERTIES = "dubbo.properties"; - public static final String CONFIGURATORS_CATEGORY = "configurators"; + public static final String ANY_VALUE = "*"; - public static final String DYNAMIC_CONFIGURATORS_CATEGORY = "dynamicconfigurators"; - public static final String APP_DYNAMIC_CONFIGURATORS_CATEGORY = "appdynamicconfigurators"; + public static final String COMMA_SEPARATOR = ","; - public static final String CONFIGURATORS_SUFFIX = ".configurators"; + public static final Pattern COMMA_SPLIT_PATTERN = Pattern.compile("\\s*[,]+\\s*"); - public static final String ROUTERS_SUFFIX = ".routers"; + public final static String PATH_SEPARATOR = "/"; - public static final String CONFIG_CLUSTER_KEY = "config.cluster"; - public static final String CONFIG_NAMESPACE_KEY = "config.namespace"; - public static final String CONFIG_GROUP_KEY = "config.group"; - public static final String CONFIG_CHECK_KEY = "config.check"; - public static final String CONFIG_CONFIGFILE_KEY = "config.config-file"; - public static final String CONFIG_ENABLE_KEY = "config.highest-priority"; - public static final String CONFIG_TIMEOUT_KEY = "config.timeout"; - public static final String CONFIG_APPNAME_KEY = "config.app-name"; + public final static String PROTOCOL_SEPARATOR = "://"; - public static final String DEFAULT_CATEGORY = PROVIDERS_CATEGORY; + public static final String REGISTRY_SEPARATOR = "|"; - public static final String ENABLED_KEY = "enabled"; + public static final Pattern REGISTRY_SPLIT_PATTERN = Pattern.compile("\\s*[|;]+\\s*"); - public static final String DISABLED_KEY = "disabled"; + public static final String SEMICOLON_SEPARATOR = ";"; - public static final String VALIDATION_KEY = "validation"; + public static final Pattern SEMICOLON_SPLIT_PATTERN = Pattern.compile("\\s*[;]+\\s*"); - public static final String CACHE_KEY = "cache"; + public static final String DEFAULT_PROXY = "javassist"; - public static final String DYNAMIC_KEY = "dynamic"; + public static final String DEFAULT_DIRECTORY = "dubbo"; - public static final String STATUS_KEY = "status"; + public static final String PROTOCOL_KEY = "protocol"; - public static final String CONTEXTPATH_KEY = "contextpath"; + public static final String DEFAULT_PROTOCOL = "dubbo"; - public static final String LISTENER_KEY = "listener"; + public static final String DEFAULT_THREAD_NAME = "Dubbo"; - public static final String LAYER_KEY = "layer"; + public static final int DEFAULT_CORE_THREADS = 0; - public static final String DUBBO_PROPERTIES_KEY = "dubbo.properties.file"; + public static final int DEFAULT_THREADS = 200; - public static final String DEFAULT_DUBBO_PROPERTIES = "dubbo.properties"; + public static final String THREADPOOL_KEY = "threadpool"; - public static final String SENT_KEY = "sent"; + public static final String THREAD_NAME_KEY = "threadname"; - public static final boolean DEFAULT_SENT = false; + public static final String CORE_THREADS_KEY = "corethreads"; - public static final String REGISTRY_PROTOCOL = "registry"; + public static final String THREADS_KEY = "threads"; - public static final String $INVOKE = "$invoke"; + public static final String QUEUES_KEY = "queues"; - public static final String $ECHO = "$echo"; + public static final String ALIVE_KEY = "alive"; - public static final int DEFAULT_IO_THREADS = Math.min(Runtime.getRuntime().availableProcessors() + 1, 32); + public static final String DEFAULT_THREADPOOL = "limited"; - public static final String DEFAULT_PROXY = "javassist"; + public static final String DEFAULT_CLIENT_THREADPOOL = "cached"; - /** - * 8M - */ - public static final int DEFAULT_PAYLOAD = 8 * 1024 * 1024; + public static final String IO_THREADS_KEY = "iothreads"; - public static final String DEFAULT_CLUSTER = "failover"; + public static final int DEFAULT_QUEUES = 0; - public static final String DEFAULT_DIRECTORY = "dubbo"; + public static final int DEFAULT_ALIVE = 60 * 1000; - public static final String DEFAULT_LOADBALANCE = "random"; + public static final String TIMEOUT_KEY = "timeout"; - public static final String DEFAULT_PROTOCOL = "dubbo"; + public static final int DEFAULT_TIMEOUT = 1000; - public static final String DEFAULT_EXCHANGER = "header"; + public static final String REMOVE_VALUE_PREFIX = "-"; - public static final String DEFAULT_TRANSPORTER = "netty"; + public static final String PROPERTIES_CHAR_SEPERATOR = "-"; + + public static final String GROUP_CHAR_SEPERATOR = ":"; - public static final String DEFAULT_REMOTING_SERVER = "netty"; + public static final String HIDE_KEY_PREFIX = "."; + + public static final String DEFAULT_KEY_PREFIX = "default."; - public static final String DEFAULT_REMOTING_CLIENT = "netty"; + public static final String DEFAULT_KEY = "default"; - public static final String DEFAULT_REMOTING_CODEC = "dubbo"; - public static final String DEFAULT_REMOTING_SERIALIZATION = "hessian2"; + /** + * Default timeout value in milliseconds for server shutdown + */ + public static final int DEFAULT_SERVER_SHUTDOWN_TIMEOUT = 10000; - public static final String DEFAULT_HTTP_SERVER = "servlet"; + public static final String SIDE_KEY = "side"; - public static final String DEFAULT_HTTP_CLIENT = "jdk"; + public static final String PROVIDER_SIDE = "provider"; - public static final String DEFAULT_HTTP_SERIALIZATION = "json"; + public static final String CONSUMER_SIDE = "consumer"; - public static final String DEFAULT_CHARSET = "UTF-8"; + public static final String ANYHOST_KEY = "anyhost"; - public static final int DEFAULT_WEIGHT = 100; + public static final String ANYHOST_VALUE = "0.0.0.0"; - public static final int DEFAULT_FORKS = 2; + public static final String LOCALHOST_KEY = "localhost"; - public static final String DEFAULT_THREAD_NAME = "Dubbo"; + public static final String LOCALHOST_VALUE = "127.0.0.1"; - public static final int DEFAULT_CORE_THREADS = 0; + public static final String METHODS_KEY = "methods"; - public static final int DEFAULT_THREADS = 200; + public static final String METHOD_KEY = "method"; - public static final boolean DEFAULT_KEEP_ALIVE = true; + public static final String PID_KEY = "pid"; - public static final int DEFAULT_QUEUES = 0; + public static final String TIMESTAMP_KEY = "timestamp"; - public static final int DEFAULT_ALIVE = 60 * 1000; + public static final String GROUP_KEY = "group"; - /** - * By default, a consumer JVM instance and a provider JVM instance share a long TCP connection (except when connections are set), - * which can set the number of long TCP connections shared to avoid the bottleneck of sharing a single long TCP connection. - */ - public static final String DEFAULT_SHARE_CONNECTIONS = "1"; + public static final String PATH_KEY = "path"; - public static final String SHARE_CONNECTIONS_KEY = "shareconnections"; + public static final String INTERFACE_KEY = "interface"; - public static final int DEFAULT_ACCEPTS = 0; + public static final String FILE_KEY = "file"; - public static final int DEFAULT_IDLE_TIMEOUT = 600 * 1000; + public static final String DUMP_DIRECTORY = "dump.directory"; - public static final int DEFAULT_HEARTBEAT = 60 * 1000; + public static final String CLASSIFIER_KEY = "classifier"; - public static final int DEFAULT_TIMEOUT = 1000; + public static final String VERSION_KEY = "version"; - public static final int DEFAULT_CONNECT_TIMEOUT = 3000; + public static final String REVISION_KEY = "revision"; /** - * public static final int DEFAULT_REGISTRY_CONNECT_TIMEOUT = 5000; + * package version in the manifest */ - public static final int DEFAULT_RETRIES = 2; + public static final String RELEASE_KEY = "release"; - public static final int DEFAULT_FAILBACK_TASKS = 100; + public static final int MAX_PROXY_COUNT = 65535; + // END common - public static final int DEFAULT_FAILBACK_TIMES = 3; + // BEGIN dubbo-remoting-api + public static final String PAYLOAD_KEY = "payload"; + /** + * 8M + */ + public static final int DEFAULT_PAYLOAD = 8 * 1024 * 1024; - public static final int MAX_PROXY_COUNT = 65535; + public static final String BUFFER_KEY = "buffer"; /** * default buffer size is 8k. */ public static final int DEFAULT_BUFFER_SIZE = 8 * 1024; - public static final Integer DEFAULT_METADATA_REPORT_RETRY_TIMES = 100; - public static final Integer DEFAULT_METADATA_REPORT_RETRY_PERIOD = 3000; - public static final Boolean DEFAULT_METADATA_REPORT_CYCLE_REPORT = true; - public static final int MAX_BUFFER_SIZE = 16 * 1024; public static final int MIN_BUFFER_SIZE = 1 * 1024; - public static final String REMOVE_VALUE_PREFIX = "-"; + public static final String CONNECT_TIMEOUT_KEY = "connect.timeout"; - public static final String PROPERTIES_CHAR_SEPERATOR = "-"; + public static final int DEFAULT_CONNECT_TIMEOUT = 3000; - public static final String GROUP_CHAR_SEPERATOR = ":"; + public static final String HEARTBEAT_KEY = "heartbeat"; - public static final String HIDE_KEY_PREFIX = "."; + public static final int DEFAULT_HEARTBEAT = 60 * 1000; - public static final String DEFAULT_KEY_PREFIX = "default."; + public static final String IDLE_TIMEOUT_KEY = "idle.timeout"; - public static final String DEFAULT_KEY = "default"; + public static final int DEFAULT_IDLE_TIMEOUT = 600 * 1000; - public static final String LOADBALANCE_KEY = "loadbalance"; + public static final String ACCEPTS_KEY = "accepts"; - /** - * key for router type, for e.g., "script"/"file", corresponding to ScriptRouterFactory.NAME, FileRouterFactory.NAME - */ - public static final String ROUTER_KEY = "router"; + public static final int DEFAULT_ACCEPTS = 0; - public static final String CLUSTER_KEY = "cluster"; + public static final String SERIALIZATION_KEY = "serialization"; - public static final String REGISTRY_KEY = "registry"; + public static final String DEFAULT_REMOTING_SERIALIZATION = "hessian2"; - public static final String METADATA_REPORT_KEY = "metadata"; + public static final String CODEC_KEY = "codec"; - public static final String MONITOR_KEY = "monitor"; + public static final String DEFAULT_REMOTING_CODEC = "dubbo"; - public static final String SIDE_KEY = "side"; + public static final String SERVER_KEY = "server"; - public static final String PROVIDER_SIDE = "provider"; + public static final String DEFAULT_REMOTING_SERVER = "netty"; - public static final String CONSUMER_SIDE = "consumer"; + public static final String CLIENT_KEY = "client"; - public static final String DEFAULT_REGISTRY = "dubbo"; + public static final String DEFAULT_REMOTING_CLIENT = "netty"; - public static final String BACKUP_KEY = "backup"; + public static final String TRANSPORTER_KEY = "transporter"; - public static final String DIRECTORY_KEY = "directory"; + public static final String DEFAULT_TRANSPORTER = "netty"; - public static final String DEPRECATED_KEY = "deprecated"; + public static final String EXCHANGER_KEY = "exchanger"; - public static final String ANYHOST_KEY = "anyhost"; + public static final String DEFAULT_EXCHANGER = "header"; - public static final String ANYHOST_VALUE = "0.0.0.0"; + public static final String DISPACTHER_KEY = "dispacther"; - public static final String LOCALHOST_KEY = "localhost"; + public static final int DEFAULT_IO_THREADS = Math.min(Runtime.getRuntime().availableProcessors() + 1, 32); - public static final String LOCALHOST_VALUE = "127.0.0.1"; + public static final String BIND_IP_KEY = "bind.ip"; - public static final String APPLICATION_KEY = "application"; + public static final String BIND_PORT_KEY = "bind.port"; - public static final String REMOTE_APPLICATION_KEY = "remote.application"; + public static final String SENT_KEY = "sent"; - public static final String LOCAL_KEY = "local"; + public static final boolean DEFAULT_SENT = false; - public static final String STUB_KEY = "stub"; + public static final String DISPATCHER_KEY = "dispatcher"; - public static final String MOCK_KEY = "mock"; + public static final String CHANNEL_HANDLER_KEY = "channel.handler"; - public static final String PROTOCOL_KEY = "protocol"; + public static final String DEFAULT_CHANNEL_HANDLER = "default"; - public static final String LOGSTAT_PROTOCOL = "logstat"; + public static final String SERVICE_DESCIPTOR_KEY = "serviceDescriptor"; - public static final String DUBBO_PROTOCOL = DUBBO; + public static final String CONNECT_QUEUE_CAPACITY = "connect.queue.capacity"; - public static final String ZOOKEEPER_PROTOCOL = "zookeeper"; + public static final String CONNECT_QUEUE_WARNING_SIZE = "connect.queue.warning.size"; - public static final String PROXY_KEY = "proxy"; + public static final int DEFAULT_CONNECT_QUEUE_WARNING_SIZE = 1000; - public static final String WEIGHT_KEY = "weight"; + public static final String CHANNEL_ATTRIBUTE_READONLY_KEY = "channel.readonly"; - public static final String FORKS_KEY = "forks"; + public static final String CHANNEL_READONLYEVENT_SENT_KEY = "channel.readonly.sent"; - public static final String DEFAULT_THREADPOOL = "limited"; + public static final String CHANNEL_SEND_READONLYEVENT_KEY = "channel.readonly.send"; - public static final String DEFAULT_CLIENT_THREADPOOL = "cached"; + public static final String EXECUTOR_SERVICE_COMPONENT_KEY = ExecutorService.class.getName(); - public static final String THREADPOOL_KEY = "threadpool"; + public static final String CHARSET_KEY = "charset"; - public static final String THREAD_NAME_KEY = "threadname"; + public static final String DEFAULT_CHARSET = "UTF-8"; - public static final String IO_THREADS_KEY = "iothreads"; + public static final String BACKUP_KEY = "backup"; - public static final String CORE_THREADS_KEY = "corethreads"; + /** + * Every heartbeat duration / HEATBEAT_CHECK_TICK, check if a heartbeat should be sent. Every heartbeat timeout + * duration / HEATBEAT_CHECK_TICK, check if a connection should be closed on server side, and if reconnect on + * client side + */ + public static final int HEARTBEAT_CHECK_TICK = 3; - public static final String THREADS_KEY = "threads"; - - public static final String QUEUES_KEY = "queues"; - - public static final String ALIVE_KEY = "alive"; - - public static final String EXECUTES_KEY = "executes"; - - public static final String BUFFER_KEY = "buffer"; - - public static final String PAYLOAD_KEY = "payload"; - - public static final String REFERENCE_FILTER_KEY = "reference.filter"; - - public static final String INVOKER_LISTENER_KEY = "invoker.listener"; - - public static final String SERVICE_FILTER_KEY = "service.filter"; - - public static final String EXPORTER_LISTENER_KEY = "exporter.listener"; - - public static final String ACCESS_LOG_KEY = "accesslog"; - - public static final String ACTIVES_KEY = "actives"; - - public static final String CONNECTIONS_KEY = "connections"; - - public static final String ACCEPTS_KEY = "accepts"; - - public static final String IDLE_TIMEOUT_KEY = "idle.timeout"; - - public static final String HEARTBEAT_KEY = "heartbeat"; - - /** - * Every heartbeat duration / HEATBEAT_CHECK_TICK, check if a heartbeat should be sent. Every heartbeat timeout - * duration / HEATBEAT_CHECK_TICK, check if a connection should be closed on server side, and if reconnect on - * client side - */ - public static final int HEARTBEAT_CHECK_TICK = 3; - - /** - * the least heartbeat during is 1000 ms. - */ - public static final long LEAST_HEARTBEAT_DURATION = 1000; + /** + * the least heartbeat during is 1000 ms. + */ + public static final long LEAST_HEARTBEAT_DURATION = 1000; /** * ticks per wheel. @@ -332,272 +283,304 @@ public class Constants { public static final String HEARTBEAT_TIMEOUT_KEY = "heartbeat.timeout"; - public static final String CONNECT_TIMEOUT_KEY = "connect.timeout"; + public static final String RECONNECT_KEY = "reconnect"; - public static final String TIMEOUT_KEY = "timeout"; + public static final int DEFAULT_RECONNECT_PERIOD = 2000; - public static final String RETRIES_KEY = "retries"; + public static final String SEND_RECONNECT_KEY = "send.reconnect"; - public static final String FAIL_BACK_TASKS_KEY = "failbacktasks"; + public static final String CHECK_KEY = "check"; public static final String PROMPT_KEY = "prompt"; public static final String DEFAULT_PROMPT = "dubbo>"; + // END dubbo-remoting-api - public static final String CODEC_KEY = "codec"; - - public static final String SERIALIZATION_KEY = "serialization"; - - public static final String EXTENSION_KEY = "extension"; - - public static final String KEEP_ALIVE_KEY = "keepalive"; - - public static final String OPTIMIZER_KEY = "optimizer"; + // BEGIN dubbo-rpc-hessian + public static final String HESSIAN2_REQUEST_KEY = "hessian2.request"; - public static final String EXCHANGER_KEY = "exchanger"; + public static final boolean DEFAULT_HESSIAN2_REQUEST = false; - public static final String DISPACTHER_KEY = "dispacther"; + public static final String HESSIAN_OVERLOAD_METHOD_KEY = "hessian.overload.method"; - public static final String TRANSPORTER_KEY = "transporter"; + public static final boolean DEFAULT_HESSIAN_OVERLOAD_METHOD = false; - public static final String SERVER_KEY = "server"; + public static final String DEFAULT_HTTP_CLIENT = "jdk"; - public static final String CLIENT_KEY = "client"; + public static final String DEFAULT_HTTP_SERVER = "servlet"; - public static final String ID_KEY = "id"; + public static final String DEFAULT_HTTP_SERIALIZATION = "json"; + // END dubbo-rpc-hessian - public static final String ASYNC_KEY = "async"; + // BEGIN dubbo-rpc-dubbo + public static final String SHARE_CONNECTIONS_KEY = "shareconnections"; - public static final String FUTURE_GENERATED_KEY = "future_generated"; - public static final String FUTURE_RETURNTYPE_KEY = "future_returntype"; + /** + * By default, a consumer JVM instance and a provider JVM instance share a long TCP connection (except when connections are set), + * which can set the number of long TCP connections shared to avoid the bottleneck of sharing a single long TCP connection. + */ + public static final String DEFAULT_SHARE_CONNECTIONS = "1"; - public static final String ASYNC_SUFFIX = "Async"; + public static final String INPUT_KEY = "input"; - public static final String RETURN_KEY = "return"; + public static final String OUTPUT_KEY = "output"; - public static final String TOKEN_KEY = "token"; + public static final String DECODE_IN_IO_THREAD_KEY = "decode.in.io"; - public static final String METHOD_KEY = "method"; + public static final boolean DEFAULT_DECODE_IN_IO_THREAD = true; - public static final String METHODS_KEY = "methods"; + /** + * callback inst id + */ + public static final String CALLBACK_SERVICE_KEY = "callback.service.instid"; - public static final String CHARSET_KEY = "charset"; + /** + * The limit of callback service instances for one interface on every client + */ + public static final String CALLBACK_INSTANCES_LIMIT_KEY = "callbacks"; - public static final String RECONNECT_KEY = "reconnect"; + /** + * The default limit number for callback service instances + * + * @see #CALLBACK_INSTANCES_LIMIT_KEY + */ + public static final int DEFAULT_CALLBACK_INSTANCES = 1; - public static final String SEND_RECONNECT_KEY = "send.reconnect"; + public static final String CALLBACK_SERVICE_PROXY_KEY = "callback.service.proxy"; - public static final int DEFAULT_RECONNECT_PERIOD = 2000; + public static final String IS_CALLBACK_SERVICE = "is_callback_service"; - public static final String SHUTDOWN_TIMEOUT_KEY = "shutdown.timeout"; + /** + * Invokers in channel's callback + */ + public static final String CHANNEL_CALLBACK_KEY = "channel.callback.invokers.key"; - public static final int DEFAULT_SHUTDOWN_TIMEOUT = 1000 * 60 * 15; + /** + * The initial state for lazy connection + */ + public static final String LAZY_CONNECT_INITIAL_STATE_KEY = "connect.lazy.initial.state"; - public static final String PID_KEY = "pid"; + /** + * The default value of lazy connection's initial state: true + * + * @see #LAZY_CONNECT_INITIAL_STATE_KEY + */ + public static final boolean DEFAULT_LAZY_CONNECT_INITIAL_STATE = true; - public static final String TIMESTAMP_KEY = "timestamp"; + public static final String OPTIMIZER_KEY = "optimizer"; + // END dubbo-rpc-dubbo - public static final String REMOTE_TIMESTAMP_KEY = "remote.timestamp"; - public static final String WARMUP_KEY = "warmup"; + // BEGIN dubbo-rpc-api + public static final String DUBBO_VERSION_KEY = "dubbo"; - public static final int DEFAULT_WARMUP = 10 * 60 * 1000; + public static final String LOCAL_KEY = "local"; - public static final String CHECK_KEY = "check"; + public static final String STUB_KEY = "stub"; - public static final String REGISTER_KEY = "register"; + public static final String MOCK_KEY = "mock"; - public static final String SUBSCRIBE_KEY = "subscribe"; + public static final String DEPRECATED_KEY = "deprecated"; - public static final String GROUP_KEY = "group"; + public static final String $INVOKE = "$invoke"; - public static final String PATH_KEY = "path"; + public static final String $ECHO = "$echo"; - public static final String INTERFACE_KEY = "interface"; + public static final String RETURN_PREFIX = "return "; - public static final String INTERFACES = "interfaces"; + public static final String THROW_PREFIX = "throw"; - public static final String GENERIC_KEY = "generic"; + public static final String FAIL_PREFIX = "fail:"; - public static final String FILE_KEY = "file"; + public static final String FORCE_PREFIX = "force:"; - public static final String DUMP_DIRECTORY = "dump.directory"; + public static final String MERGER_KEY = "merger"; - public static final String WAIT_KEY = "wait"; + public static final String IS_SERVER_KEY = "isserver"; - public static final String CLASSIFIER_KEY = "classifier"; + public static final String FORCE_USE_TAG = "dubbo.force.tag"; - public static final String VERSION_KEY = "version"; + public static final String GENERIC_SERIALIZATION_NATIVE_JAVA = "nativejava"; - public static final String REVISION_KEY = "revision"; + public static final String GENERIC_SERIALIZATION_DEFAULT = "true"; - public static final String DUBBO_VERSION_KEY = "dubbo"; + public static final String GENERIC_SERIALIZATION_BEAN = "bean"; - public static final String HESSIAN_VERSION_KEY = "hessian.version"; + public static final String GENERIC_SERIALIZATION_PROTOBUF = "protobuf-json"; - public static final String DISPATCHER_KEY = "dispatcher"; + public static final String TPS_LIMIT_RATE_KEY = "tps"; - public static final String CHANNEL_HANDLER_KEY = "channel.handler"; + public static final String TPS_LIMIT_INTERVAL_KEY = "tps.interval"; - public static final String DEFAULT_CHANNEL_HANDLER = "default"; + public static final long DEFAULT_TPS_LIMIT_INTERVAL = 60 * 1000; - public static final String SERVICE_DESCIPTOR_KEY = "serviceDescriptor"; + public static final String AUTO_ATTACH_INVOCATIONID_KEY = "invocationid.autoattach"; - public static final String ANY_VALUE = "*"; + public static final String STUB_EVENT_KEY = "dubbo.stub.event"; - public static final String COMMA_SEPARATOR = ","; + public static final boolean DEFAULT_STUB_EVENT = false; - public static final Pattern COMMA_SPLIT_PATTERN = Pattern - .compile("\\s*[,]+\\s*"); + public static final String STUB_EVENT_METHODS_KEY = "dubbo.stub.event.methods"; - public final static String PATH_SEPARATOR = "/"; + public static final String PROXY_KEY = "proxy"; - public final static String PROTOCOL_SEPARATOR = "://"; + public static final String EXECUTES_KEY = "executes"; - public static final String REGISTRY_SEPARATOR = "|"; + public static final String REFERENCE_FILTER_KEY = "reference.filter"; - public static final Pattern REGISTRY_SPLIT_PATTERN = Pattern - .compile("\\s*[|;]+\\s*"); + public static final String INVOKER_LISTENER_KEY = "invoker.listener"; - public static final String SEMICOLON_SEPARATOR = ";"; + public static final String SERVICE_FILTER_KEY = "service.filter"; - public static final Pattern SEMICOLON_SPLIT_PATTERN = Pattern - .compile("\\s*[;]+\\s*"); + public static final String EXPORTER_LISTENER_KEY = "exporter.listener"; - public static final String CONNECT_QUEUE_CAPACITY = "connect.queue.capacity"; + public static final String ACCESS_LOG_KEY = "accesslog"; - public static final String CONNECT_QUEUE_WARNING_SIZE = "connect.queue.warning.size"; + public static final String ACTIVES_KEY = "actives"; - public static final int DEFAULT_CONNECT_QUEUE_WARNING_SIZE = 1000; + public static final String CONNECTIONS_KEY = "connections"; - public static final String CHANNEL_ATTRIBUTE_READONLY_KEY = "channel.readonly"; + public static final String ID_KEY = "id"; - public static final String CHANNEL_READONLYEVENT_SENT_KEY = "channel.readonly.sent"; + public static final String ASYNC_KEY = "async"; - public static final String CHANNEL_SEND_READONLYEVENT_KEY = "channel.readonly.send"; + public static final String FUTURE_GENERATED_KEY = "future_generated"; - public static final String COUNT_PROTOCOL = "count"; + public static final String FUTURE_RETURNTYPE_KEY = "future_returntype"; - public static final String TRACE_PROTOCOL = "trace"; + public static final String RETURN_KEY = "return"; - public static final String EMPTY_PROTOCOL = "empty"; + public static final String TOKEN_KEY = "token"; - public static final String ADMIN_PROTOCOL = "admin"; + public static final String INTERFACES = "interfaces"; - public static final String PROVIDER_PROTOCOL = "provider"; + public static final String GENERIC_KEY = "generic"; - public static final String CONSUMER_PROTOCOL = "consumer"; + public static final String LOCAL_PROTOCOL = "injvm"; + // END dubbo-rpc-api - public static final String ROUTE_PROTOCOL = "route"; - public static final String SCRIPT_PROTOCOL = "script"; + // BEGIN dubbo-rpc-rest + public static final String KEEP_ALIVE_KEY = "keepalive"; - public static final String CONDITION_PROTOCOL = "condition"; + public static final boolean DEFAULT_KEEP_ALIVE = true; - public static final String MOCK_PROTOCOL = "mock"; + public static final String EXTENSION_KEY = "extension"; + // END dubbo-rpc-rest - public static final String RETURN_PREFIX = "return "; - public static final String THROW_PREFIX = "throw"; + // BEGIN dubbo-config-api + public static final String CLUSTER_KEY = "cluster"; - public static final String FAIL_PREFIX = "fail:"; + public static final String STATUS_KEY = "status"; - public static final String FORCE_PREFIX = "force:"; + public static final String CONTEXTPATH_KEY = "contextpath"; - public static final String FORCE_KEY = "force"; + public static final String LISTENER_KEY = "listener"; - public static final String MERGER_KEY = "merger"; + public static final String LAYER_KEY = "layer"; /** - * simple the registry for provider. - * - * @since 2.7.0 + * General */ - public static final String SIMPLIFIED_KEY = "simplified"; - /** - * After simplify the registry, should add some paramter individually for provider. - * - * @since 2.7.0 + * Application name; */ - public static final String EXTRA_KEYS_KEY = "extra-keys"; + public static final String NAME = "name"; /** - * To decide whether to exclude unavailable invoker from the cluster + * Application owner name; */ - public static final String CLUSTER_AVAILABLE_CHECK_KEY = "cluster.availablecheck"; + public static final String OWNER = "owner"; /** - * The default value of cluster.availablecheck - * - * @see #CLUSTER_AVAILABLE_CHECK_KEY + * Running application organization name. */ - public static final boolean DEFAULT_CLUSTER_AVAILABLE_CHECK = true; + public static final String ORGANIZATION = "organization"; /** - * To decide whether to enable sticky strategy for cluster + * Application architecture name. */ - public static final String CLUSTER_STICKY_KEY = "sticky"; + public static final String ARCHITECTURE = "architecture"; /** - * The default value of sticky - * - * @see #CLUSTER_STICKY_KEY + * Environment name */ - public static final boolean DEFAULT_CLUSTER_STICKY = false; + public static final String ENVIRONMENT = "environment"; /** - * To decide whether to make connection when the client is created + * Test environment key. */ - public static final String LAZY_CONNECT_KEY = "lazy"; + public static final String TEST_ENVIRONMENT = "test"; /** - * The initial state for lazy connection + * Development environment key. */ - public static final String LAZY_CONNECT_INITIAL_STATE_KEY = "connect.lazy.initial.state"; + public static final String DEVELOPMENT_ENVIRONMENT = "develop"; /** - * The default value of lazy connection's initial state: true - * - * @see #LAZY_CONNECT_INITIAL_STATE_KEY + * Production environment key. */ - public static final boolean DEFAULT_LAZY_CONNECT_INITIAL_STATE = true; + public static final String PRODUCTION_ENVIRONMENT = "product"; - /** - * To decide whether register center saves file synchronously, the default value is asynchronously - */ - public static final String REGISTRY_FILESAVE_SYNC_KEY = "save.file"; + public static final String CONFIG_CLUSTER_KEY = "config.cluster"; + public static final String CONFIG_NAMESPACE_KEY = "config.namespace"; + public static final String CONFIG_GROUP_KEY = "config.group"; + public static final String CONFIG_CHECK_KEY = "config.check"; - /** - * Period of registry center's retry interval - */ - public static final String REGISTRY_RETRY_PERIOD_KEY = "retry.period"; + public static final String CONFIG_CONFIGFILE_KEY = "config.config-file"; + public static final String CONFIG_ENABLE_KEY = "config.highest-priority"; + public static final String CONFIG_TIMEOUT_KEY = "config.timeout"; + public static final String CONFIG_APPNAME_KEY = "config.app-name"; - /** - * Most retry times - */ - public static final String REGISTRY_RETRY_TIMES_KEY = "retry.times"; + public static final String USERNAME_KEY = "username"; - /** - * Default value for the period of retry interval in milliseconds: 5000 - */ - public static final int DEFAULT_REGISTRY_RETRY_PERIOD = 5 * 1000; + public static final String PASSWORD_KEY = "password"; - /** - * Default value for the times of retry: 3 - */ - public static final int DEFAULT_REGISTRY_RETRY_TIMES = 3; + public static final String HOST_KEY = "host"; - /** - * Reconnection period in milliseconds for register center - */ - public static final String REGISTRY_RECONNECT_PERIOD_KEY = "reconnect.period"; + public static final String PORT_KEY = "port"; - public static final int DEFAULT_REGISTRY_RECONNECT_PERIOD = 3 * 1000; + public static final String MULTICAST = "multicast"; - public static final String SESSION_TIMEOUT_KEY = "session"; + public static final String REGISTER_IP_KEY = "register.ip"; - public static final int DEFAULT_SESSION_TIMEOUT = 60 * 1000; + public static final String DUBBO_IP_TO_REGISTRY = "DUBBO_IP_TO_REGISTRY"; + + public static final String DUBBO_PORT_TO_REGISTRY = "DUBBO_PORT_TO_REGISTRY"; + + public static final String DUBBO_IP_TO_BIND = "DUBBO_IP_TO_BIND"; + + public static final String DUBBO_PORT_TO_BIND = "DUBBO_PORT_TO_BIND"; + + public static final String SCOPE_KEY = "scope"; + + public static final String SCOPE_LOCAL = "local"; + + public static final String SCOPE_REMOTE = "remote"; + + public static final String SCOPE_NONE = "none"; + + public static final String ON_CONNECT_KEY = "onconnect"; + + public static final String ON_DISCONNECT_KEY = "ondisconnect"; + + public static final String ON_INVOKE_METHOD_KEY = "oninvoke.method"; + + public static final String ON_RETURN_METHOD_KEY = "onreturn.method"; + + public static final String ON_THROW_METHOD_KEY = "onthrow.method"; + + public static final String ON_INVOKE_INSTANCE_KEY = "oninvoke.instance"; + + public static final String ON_RETURN_INSTANCE_KEY = "onreturn.instance"; + + public static final String ON_THROW_INSTANCE_KEY = "onthrow.instance"; + + @Deprecated + public static final String SHUTDOWN_WAIT_SECONDS_KEY = "dubbo.service.shutdown.wait.seconds"; + + public static final String SHUTDOWN_WAIT_KEY = "dubbo.service.shutdown.wait"; /** * The key name for export URL in register center @@ -610,263 +593,248 @@ public class Constants { public static final String REFER_KEY = "refer"; /** - * callback inst id + * To decide whether to make connection when the client is created */ - public static final String CALLBACK_SERVICE_KEY = "callback.service.instid"; + public static final String LAZY_CONNECT_KEY = "lazy"; - /** - * The limit of callback service instances for one interface on every client - */ - public static final String CALLBACK_INSTANCES_LIMIT_KEY = "callbacks"; + public static final String DUBBO_PROTOCOL = DUBBO; - /** - * The default limit number for callback service instances - * - * @see #CALLBACK_INSTANCES_LIMIT_KEY - */ - public static final int DEFAULT_CALLBACK_INSTANCES = 1; + public static final String ZOOKEEPER_PROTOCOL = "zookeeper"; - public static final String CALLBACK_SERVICE_PROXY_KEY = "callback.service.proxy"; + // FIXME: is this still useful? + public static final String SHUTDOWN_TIMEOUT_KEY = "shutdown.timeout"; - public static final String IS_CALLBACK_SERVICE = "is_callback_service"; + public static final int DEFAULT_SHUTDOWN_TIMEOUT = 1000 * 60 * 15; - /** - * Invokers in channel's callback - */ - public static final String CHANNEL_CALLBACK_KEY = "channel.callback.invokers.key"; + public static final String PROTOCOLS_SUFFIX = "dubbo.protocols."; - @Deprecated - public static final String SHUTDOWN_WAIT_SECONDS_KEY = "dubbo.service.shutdown.wait.seconds"; + public static final String PROTOCOL_SUFFIX = "dubbo.protocol."; - public static final String SHUTDOWN_WAIT_KEY = "dubbo.service.shutdown.wait"; + public static final String REGISTRIES_SUFFIX = "dubbo.registries."; - public static final String IS_SERVER_KEY = "isserver"; + public static final String TELNET = "telnet"; - /** - * Default timeout value in milliseconds for server shutdown - */ - public static final int DEFAULT_SERVER_SHUTDOWN_TIMEOUT = 10000; + public static final String QOS_ENABLE = "qos.enable"; - public static final String ON_CONNECT_KEY = "onconnect"; + public static final String QOS_PORT = "qos.port"; + + public static final String ACCEPT_FOREIGN_IP = "qos.accept.foreign.ip"; + // END dubbo-congfig-api + + // BEGIN dubbo-cluster + /** + * key for router type, for e.g., "script"/"file", corresponding to ScriptRouterFactory.NAME, FileRouterFactory.NAME + */ + public static final String ROUTER_KEY = "router"; - public static final String ON_DISCONNECT_KEY = "ondisconnect"; + public static final String LOADBALANCE_KEY = "loadbalance"; - public static final String ON_INVOKE_METHOD_KEY = "oninvoke.method"; + public static final String DEFAULT_LOADBALANCE = "random"; - public static final String ON_RETURN_METHOD_KEY = "onreturn.method"; + public static final String FAIL_BACK_TASKS_KEY = "failbacktasks"; - public static final String ON_THROW_METHOD_KEY = "onthrow.method"; + public static final int DEFAULT_FAILBACK_TASKS = 100; - public static final String ON_INVOKE_INSTANCE_KEY = "oninvoke.instance"; + public static final String RETRIES_KEY = "retries"; - public static final String ON_RETURN_INSTANCE_KEY = "onreturn.instance"; + public static final int DEFAULT_RETRIES = 2; - public static final String ON_THROW_INSTANCE_KEY = "onthrow.instance"; + public static final int DEFAULT_FAILBACK_TIMES = 3; - public static final String OVERRIDE_PROTOCOL = "override"; + public static final String FORKS_KEY = "forks"; - public static final String CONFIG_PROTOCOL = "config"; + public static final int DEFAULT_FORKS = 2; - public static final String PRIORITY_KEY = "priority"; + public static final String WEIGHT_KEY = "weight"; - public static final String RULE_KEY = "rule"; + public static final int DEFAULT_WEIGHT = 100; - public static final String TYPE_KEY = "type"; + public static final String MOCK_PROTOCOL = "mock"; - public static final String RUNTIME_KEY = "runtime"; + public static final String FORCE_KEY = "force"; /** - * when ROUTER_KEY's value is set to ROUTER_TYPE_CLEAR, RegistryDirectory will clean all current routers + * To decide whether to exclude unavailable invoker from the cluster */ - public static final String ROUTER_TYPE_CLEAR = "clean"; + public static final String CLUSTER_AVAILABLE_CHECK_KEY = "cluster.availablecheck"; - public static final String DEFAULT_SCRIPT_TYPE_KEY = "javascript"; + /** + * The default value of cluster.availablecheck + * + * @see #CLUSTER_AVAILABLE_CHECK_KEY + */ + public static final boolean DEFAULT_CLUSTER_AVAILABLE_CHECK = true; - public static final String STUB_EVENT_KEY = "dubbo.stub.event"; + /** + * To decide whether to enable sticky strategy for cluster + */ + public static final String CLUSTER_STICKY_KEY = "sticky"; - public static final boolean DEFAULT_STUB_EVENT = false; + /** + * The default value of sticky + * + * @see #CLUSTER_STICKY_KEY + */ + public static final boolean DEFAULT_CLUSTER_STICKY = false; - public static final String STUB_EVENT_METHODS_KEY = "dubbo.stub.event.methods"; + public static final String ADDRESS_KEY = "address"; /** * When this attribute appears in invocation's attachment, mock invoker will be used */ public static final String INVOCATION_NEED_MOCK = "invocation.need.mock"; - public static final String LOCAL_PROTOCOL = "injvm"; - - public static final String AUTO_ATTACH_INVOCATIONID_KEY = "invocationid.autoattach"; - - public static final String SCOPE_KEY = "scope"; - - public static final String SCOPE_LOCAL = "local"; - - public static final String SCOPE_REMOTE = "remote"; - - public static final String SCOPE_NONE = "none"; + /** + * when ROUTER_KEY's value is set to ROUTER_TYPE_CLEAR, RegistryDirectory will clean all current routers + */ + public static final String ROUTER_TYPE_CLEAR = "clean"; - public static final String RELIABLE_PROTOCOL = "napoli"; + public static final String DEFAULT_SCRIPT_TYPE_KEY = "javascript"; - public static final String TPS_LIMIT_RATE_KEY = "tps"; + public static final String PRIORITY_KEY = "priority"; - public static final String TPS_LIMIT_INTERVAL_KEY = "tps.interval"; + public static final String RULE_KEY = "rule"; - public static final long DEFAULT_TPS_LIMIT_INTERVAL = 60 * 1000; + public static final String TYPE_KEY = "type"; - public static final String DECODE_IN_IO_THREAD_KEY = "decode.in.io"; + public static final String RUNTIME_KEY = "runtime"; - public static final boolean DEFAULT_DECODE_IN_IO_THREAD = true; + public static final String TAG_KEY = "dubbo.tag"; - public static final String INPUT_KEY = "input"; + public static final String REMOTE_TIMESTAMP_KEY = "remote.timestamp"; - public static final String OUTPUT_KEY = "output"; + public static final String WARMUP_KEY = "warmup"; - public static final String EXECUTOR_SERVICE_COMPONENT_KEY = ExecutorService.class.getName(); + public static final int DEFAULT_WARMUP = 10 * 60 * 1000; - public static final String GENERIC_SERIALIZATION_NATIVE_JAVA = "nativejava"; + public static final String CONFIG_VERSION_KEY = "configVersion"; - public static final String GENERIC_SERIALIZATION_DEFAULT = "true"; + public static final String OVERRIDE_PROVIDERS_KEY = "providerAddresses"; + // END dubbo-cluster - public static final String GENERIC_SERIALIZATION_BEAN = "bean"; + // BEGIN dubbo-registry-api + public static final String REGISTER_KEY = "register"; - public static final String GENERIC_SERIALIZATION_PROTOBUF = "protobuf-json"; + public static final String SUBSCRIBE_KEY = "subscribe"; - public static final String DUBBO_IP_TO_REGISTRY = "DUBBO_IP_TO_REGISTRY"; + public static final String REGISTRY_KEY = "registry"; - public static final String DUBBO_PORT_TO_REGISTRY = "DUBBO_PORT_TO_REGISTRY"; + public static final String DEFAULT_REGISTRY = "dubbo"; - public static final String DUBBO_IP_TO_BIND = "DUBBO_IP_TO_BIND"; + public static final String REGISTRY_PROTOCOL = "registry"; - public static final String DUBBO_PORT_TO_BIND = "DUBBO_PORT_TO_BIND"; + public static final String DYNAMIC_KEY = "dynamic"; - public static final String BIND_IP_KEY = "bind.ip"; + public static final String REGISTER = "register"; - public static final String BIND_PORT_KEY = "bind.port"; + public static final String UNREGISTER = "unregister"; - public static final String REGISTER_IP_KEY = "register.ip"; + public static final String SUBSCRIBE = "subscribe"; - public static final String QOS_ENABLE = "qos.enable"; + public static final String UNSUBSCRIBE = "unsubscribe"; - public static final String QOS_PORT = "qos.port"; + public static final String CATEGORY_KEY = "category"; - public static final String ACCEPT_FOREIGN_IP = "qos.accept.foreign.ip"; + public static final String PROVIDERS_CATEGORY = "providers"; - public static final String HESSIAN2_REQUEST_KEY = "hessian2.request"; + public static final String CONSUMERS_CATEGORY = "consumers"; - public static final boolean DEFAULT_HESSIAN2_REQUEST = false; + public static final String ROUTERS_CATEGORY = "routers"; - public static final String HESSIAN_OVERLOAD_METHOD_KEY = "hessian.overload.method"; + public static final String DYNAMIC_ROUTERS_CATEGORY = "dynamicrouters"; - public static final boolean DEFAULT_HESSIAN_OVERLOAD_METHOD = false; + public static final String DEFAULT_CATEGORY = PROVIDERS_CATEGORY; - public static final String MULTICAST = "multicast"; + public static final String CONFIGURATORS_CATEGORY = "configurators"; - public static final String TAG_KEY = "dubbo.tag"; + public static final String DYNAMIC_CONFIGURATORS_CATEGORY = "dynamicconfigurators"; - public static final String FORCE_USE_TAG = "dubbo.force.tag"; + public static final String APP_DYNAMIC_CONFIGURATORS_CATEGORY = "appdynamicconfigurators"; - public static final String HOST_KEY = "host"; + public static final String CONFIGURATORS_SUFFIX = ".configurators"; - public static final String PORT_KEY = "port"; + public static final String ROUTERS_SUFFIX = ".routers"; - public static final String USERNAME_KEY = "username"; + public static final String TRACE_PROTOCOL = "trace"; - public static final String PASSWORD_KEY = "password"; + public static final String EMPTY_PROTOCOL = "empty"; - public static final String ADDRESS_KEY = "address"; + public static final String ADMIN_PROTOCOL = "admin"; - public static final String RETRY_TIMES_KEY = "retry.times"; + public static final String PROVIDER_PROTOCOL = "provider"; - public static final String RETRY_PERIOD_KEY = "retry.period"; + public static final String CONSUMER_PROTOCOL = "consumer"; - public static final String SYNC_REPORT_KEY = "sync.report"; + public static final String ROUTE_PROTOCOL = "route"; - public static final String CYCLE_REPORT_KEY = "cycle.report"; + public static final String SCRIPT_PROTOCOL = "script"; - public static final String CONFIG_VERSION_KEY = "configVersion"; + public static final String CONDITION_PROTOCOL = "condition"; - public static final String COMPATIBLE_CONFIG_KEY = "compatible_config"; /** - * package version in the manifest + * simple the registry for provider. + * + * @since 2.7.0 */ - public static final String RELEASE_KEY = "release"; - - public static final String OVERRIDE_PROVIDERS_KEY = "providerAddresses"; + public static final String SIMPLIFIED_KEY = "simplified"; - public static final String PROTOCOLS_SUFFIX = "dubbo.protocols."; + /** + * After simplify the registry, should add some paramter individually for provider. + * + * @since 2.7.0 + */ + public static final String EXTRA_KEYS_KEY = "extra-keys"; - public static final String PROTOCOL_SUFFIX = "dubbo.protocol."; + public static final String OVERRIDE_PROTOCOL = "override"; - public static final String REGISTRIES_SUFFIX = "dubbo.registries."; + public static final String COMPATIBLE_CONFIG_KEY = "compatible_config"; public static final String[] DEFAULT_REGISTER_PROVIDER_KEYS = {APPLICATION_KEY, CODEC_KEY, EXCHANGER_KEY, SERIALIZATION_KEY, CLUSTER_KEY, CONNECTIONS_KEY, DEPRECATED_KEY, GROUP_KEY, LOADBALANCE_KEY, MOCK_KEY, PATH_KEY, TIMEOUT_KEY, TOKEN_KEY, VERSION_KEY, WARMUP_KEY, WEIGHT_KEY, TIMESTAMP_KEY, DUBBO_VERSION_KEY, RELEASE_KEY}; public static final String[] DEFAULT_REGISTER_CONSUMER_KEYS = {APPLICATION_KEY, VERSION_KEY, GROUP_KEY, DUBBO_VERSION_KEY, RELEASE_KEY}; - public static final String TELNET = "telnet"; - - /** - * Hash nodes name - */ - public static final String HASH_NODES = "hash.nodes"; - - /** - * Hash arguments name - */ - public static final String HASH_ARGUMENTS = "hash.arguments"; - - /** - * Application name; - */ - public static final String NAME = "name"; - - /** - * Application owner name; - */ - public static final String OWNER = "owner"; - /** - * Running application organization name. + * To decide whether register center saves file synchronously, the default value is asynchronously */ - public static final String ORGANIZATION = "organization"; + public static final String REGISTRY_FILESAVE_SYNC_KEY = "save.file"; /** - * Application architecture name. + * Period of registry center's retry interval */ - public static final String ARCHITECTURE = "architecture"; + public static final String REGISTRY_RETRY_PERIOD_KEY = "retry.period"; /** - * Environment name + * Most retry times */ - public static final String ENVIRONMENT = "environment"; + public static final String REGISTRY_RETRY_TIMES_KEY = "retry.times"; /** - * Test environment key. + * Default value for the period of retry interval in milliseconds: 5000 */ - public static final String TEST_ENVIRONMENT = "test"; + public static final int DEFAULT_REGISTRY_RETRY_PERIOD = 5 * 1000; /** - * Development environment key. + * Default value for the times of retry: 3 */ - public static final String DEVELOPMENT_ENVIRONMENT = "develop"; + public static final int DEFAULT_REGISTRY_RETRY_TIMES = 3; /** - * Production environment key. + * Reconnection period in milliseconds for register center */ - public static final String PRODUCTION_ENVIRONMENT = "product"; - - public static final String ETCD3_NOTIFY_MAXTHREADS_KEYS = "etcd3.notify.maxthreads"; + public static final String REGISTRY_RECONNECT_PERIOD_KEY = "reconnect.period"; - public static final int DEFAULT_ETCD3_NOTIFY_THREADS = DEFAULT_IO_THREADS; + public static final int DEFAULT_REGISTRY_RECONNECT_PERIOD = 3 * 1000; - public static final String DEFAULT_ETCD3_NOTIFY_QUEUES_KEY = "etcd3.notify.queues"; + public static final String SESSION_TIMEOUT_KEY = "session"; - public static final int DEFAULT_GRPC_QUEUES = 300_0000; + public static final int DEFAULT_SESSION_TIMEOUT = 60 * 1000; + // END dubbo-registry-api - /** - * metrics - */ + // BEGIN dubbo-monitor-api + public static final String MONITOR_KEY = "monitor"; + public static final String LOGSTAT_PROTOCOL = "logstat"; + public static final String COUNT_PROTOCOL = "count"; public static final String DUBBO_PROVIDER = "dubbo.provider"; public static final String DUBBO_CONSUMER = "dubbo.consumer"; public static final String DUBBO_PROVIDER_METHOD = "dubbo.provider.method"; @@ -877,20 +845,52 @@ public class Constants { public static final String METRICS_KEY = "metrics"; public static final String METRICS_PORT = "metrics.port"; public static final String METRICS_PROTOCOL = "metrics.protocol"; + // END dubbo-monitor-api + + // BEGIN dubbo-metadata-report-api + public static final String METADATA_REPORT_KEY = "metadata"; + + public static final String RETRY_TIMES_KEY = "retry.times"; + public static final Integer DEFAULT_METADATA_REPORT_RETRY_TIMES = 100; + + public static final String RETRY_PERIOD_KEY = "retry.period"; + + public static final Integer DEFAULT_METADATA_REPORT_RETRY_PERIOD = 3000; + + public static final String SYNC_REPORT_KEY = "sync.report"; + + public static final String CYCLE_REPORT_KEY = "cycle.report"; + + public static final Boolean DEFAULT_METADATA_REPORT_CYCLE_REPORT = true; + // END dubbo-metadata-report-api + + // BEGIN dubbo-filter-cache + public static final String CACHE_KEY = "cache"; + // END dubbo-filter-cache + + + // BEGIN dubbo-filter-validation + public static final String VALIDATION_KEY = "validation"; + // END dubbo-filter-validation + + public static final String DEFAULT_CLUSTER = "failover"; /** - * Serizlization ContentTypeId + * public static final int DEFAULT_REGISTRY_CONNECT_TIMEOUT = 5000; */ - public static final byte HESSIAN2_SERIALIZATION_ID = 2; - public static final byte JAVA_SERIALIZATION_ID = 3; - public static final byte COMPACTED_JAVA_SERIALIZATION_ID = 4; - public static final byte FASTJSON_SERIALIZATION_ID = 6; - public static final byte NATIVE_JAVA_SERIALIZATION_ID = 7; - public static final byte KRYO_SERIALIZATION_ID = 8; - public static final byte FST_SERIALIZATION_ID = 9; - public static final byte PROTOSTUFF_SERIALIZATION_ID = 10; - public static final byte AVRO_SERIALIZATION_ID = 11; - public static final byte GSON_SERIALIZATION_ID = 16; + public static final String DIRECTORY_KEY = "directory"; + + public static final String ASYNC_SUFFIX = "Async"; + + public static final String WAIT_KEY = "wait"; + + public static final String HESSIAN_VERSION_KEY = "hessian.version"; + + + public static final String CONFIG_PROTOCOL = "config"; + + + public static final String RELIABLE_PROTOCOL = "napoli"; } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java index a514728b62f..6c5870bd47e 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java @@ -64,7 +64,6 @@ import static org.apache.dubbo.common.Constants.CONFIGURATORS_SUFFIX; import static org.apache.dubbo.common.Constants.CONSUMERS_CATEGORY; import static org.apache.dubbo.common.Constants.CONSUMER_PROTOCOL; -import static org.apache.dubbo.common.Constants.DEFAULT_DIRECTORY; import static org.apache.dubbo.common.Constants.DEFAULT_REGISTER_CONSUMER_KEYS; import static org.apache.dubbo.common.Constants.DEFAULT_REGISTER_PROVIDER_KEYS; import static org.apache.dubbo.common.Constants.DEFAULT_REGISTRY; @@ -276,7 +275,7 @@ private Registry getRegistry(final Invoker originInvoker) { private URL getRegistryUrl(Invoker originInvoker) { URL registryUrl = originInvoker.getUrl(); if (REGISTRY_PROTOCOL.equals(registryUrl.getProtocol())) { - String protocol = registryUrl.getParameter(REGISTRY_KEY, DEFAULT_DIRECTORY); + String protocol = registryUrl.getParameter(REGISTRY_KEY, DEFAULT_REGISTRY); registryUrl = registryUrl.setProtocol(protocol).removeParameter(REGISTRY_KEY); } return registryUrl; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java index 9125f8479ac..ca48dcaf1e0 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java @@ -31,6 +31,10 @@ import java.util.Map; import java.util.Set; +import static org.apache.dubbo.common.serialize.Constants.COMPACTED_JAVA_SERIALIZATION_ID; +import static org.apache.dubbo.common.serialize.Constants.JAVA_SERIALIZATION_ID; +import static org.apache.dubbo.common.serialize.Constants.NATIVE_JAVA_SERIALIZATION_ID; + public class CodecSupport { private static final Logger logger = LoggerFactory.getLogger(CodecSupport.class); @@ -71,7 +75,7 @@ public static Serialization getSerialization(URL url, Byte id) throws IOExceptio String serializationName = url.getParameter(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION); // Check if "serialization id" passed from network matches the id on this side(only take effect for JDK serialization), for security purpose. if (serialization == null - || ((id == Constants.JAVA_SERIALIZATION_ID || id == Constants.NATIVE_JAVA_SERIALIZATION_ID || id == Constants.COMPACTED_JAVA_SERIALIZATION_ID) + || ((id == JAVA_SERIALIZATION_ID || id == NATIVE_JAVA_SERIALIZATION_ID || id == COMPACTED_JAVA_SERIALIZATION_ID) && !(serializationName.equals(ID_SERIALIZATIONNAME_MAP.get(id))))) { throw new IOException("Unexpected serialization id:" + id + " received from network, please check if the peer send the right id."); } diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/Constants.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/Constants.java new file mode 100644 index 00000000000..7bc1a98bd25 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/Constants.java @@ -0,0 +1,31 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.remoting.etcd; + +import static org.apache.dubbo.common.Constants.DEFAULT_IO_THREADS; + +public interface Constants { + String ETCD3_NOTIFY_MAXTHREADS_KEYS = "etcd3.notify.maxthreads"; + + int DEFAULT_ETCD3_NOTIFY_THREADS = DEFAULT_IO_THREADS; + + String DEFAULT_ETCD3_NOTIFY_QUEUES_KEY = "etcd3.notify.queues"; + + int DEFAULT_GRPC_QUEUES = 300_0000; +} + diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java index 634a6eda0b3..c1f8e2cb936 100644 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java +++ b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java @@ -60,6 +60,10 @@ import java.util.concurrent.locks.ReentrantLock; import static java.util.stream.Collectors.toList; +import static org.apache.dubbo.remoting.etcd.Constants.DEFAULT_ETCD3_NOTIFY_QUEUES_KEY; +import static org.apache.dubbo.remoting.etcd.Constants.DEFAULT_ETCD3_NOTIFY_THREADS; +import static org.apache.dubbo.remoting.etcd.Constants.DEFAULT_GRPC_QUEUES; +import static org.apache.dubbo.remoting.etcd.Constants.ETCD3_NOTIFY_MAXTHREADS_KEYS; import static org.apache.dubbo.remoting.etcd.jetcd.JEtcdClientWrapper.UTF_8; /** @@ -92,10 +96,10 @@ public JEtcdClient(URL url) { notifyExecutor = new ThreadPoolExecutor( 1 - , url.getParameter(Constants.ETCD3_NOTIFY_MAXTHREADS_KEYS, Constants.DEFAULT_ETCD3_NOTIFY_THREADS) + , url.getParameter(ETCD3_NOTIFY_MAXTHREADS_KEYS, DEFAULT_ETCD3_NOTIFY_THREADS) , Constants.DEFAULT_SESSION_TIMEOUT , TimeUnit.MILLISECONDS - , new LinkedBlockingQueue(url.getParameter(Constants.DEFAULT_ETCD3_NOTIFY_QUEUES_KEY, Constants.DEFAULT_GRPC_QUEUES * 3)) + , new LinkedBlockingQueue(url.getParameter(DEFAULT_ETCD3_NOTIFY_QUEUES_KEY, DEFAULT_GRPC_QUEUES * 3)) , new NamedThreadFactory("etcd3-notify", true)); clientWrapper.start(); diff --git a/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/Constants.java b/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/Constants.java new file mode 100644 index 00000000000..56cae66891a --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/Constants.java @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.common.serialize; + +public interface Constants { + byte HESSIAN2_SERIALIZATION_ID = 2; + byte JAVA_SERIALIZATION_ID = 3; + byte COMPACTED_JAVA_SERIALIZATION_ID = 4; + byte FASTJSON_SERIALIZATION_ID = 6; + byte NATIVE_JAVA_SERIALIZATION_ID = 7; + byte KRYO_SERIALIZATION_ID = 8; + byte FST_SERIALIZATION_ID = 9; + byte NATIVE_HESSIAN_SERIALIZATION_ID = 10; + byte PROTOSTUFF_SERIALIZATION_ID = 12; + byte AVRO_SERIALIZATION_ID = 11; + byte GSON_SERIALIZATION_ID = 16; + byte PROTOBUF_JSON_SERIALIZATION_ID = 21; +} diff --git a/dubbo-serialization/dubbo-serialization-avro/src/main/java/org/apache/dubbo/common/serialize/avro/AvroSerialization.java b/dubbo-serialization/dubbo-serialization-avro/src/main/java/org/apache/dubbo/common/serialize/avro/AvroSerialization.java index 37eb320f19b..7eb291ec343 100644 --- a/dubbo-serialization/dubbo-serialization-avro/src/main/java/org/apache/dubbo/common/serialize/avro/AvroSerialization.java +++ b/dubbo-serialization/dubbo-serialization-avro/src/main/java/org/apache/dubbo/common/serialize/avro/AvroSerialization.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.serialize.avro; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -26,11 +25,13 @@ import java.io.InputStream; import java.io.OutputStream; +import static org.apache.dubbo.common.serialize.Constants.AVRO_SERIALIZATION_ID; + public class AvroSerialization implements Serialization { @Override public byte getContentTypeId() { - return Constants.AVRO_SERIALIZATION_ID; + return AVRO_SERIALIZATION_ID; } @Override diff --git a/dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonSerialization.java b/dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonSerialization.java index d1d804e14d0..84c5721ce5b 100644 --- a/dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonSerialization.java +++ b/dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonSerialization.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.serialize.fastjson; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -26,6 +25,8 @@ import java.io.InputStream; import java.io.OutputStream; +import static org.apache.dubbo.common.serialize.Constants.FASTJSON_SERIALIZATION_ID; + /** * FastJson serialization implementation * @@ -37,7 +38,7 @@ public class FastJsonSerialization implements Serialization { @Override public byte getContentTypeId() { - return Constants.FASTJSON_SERIALIZATION_ID; + return FASTJSON_SERIALIZATION_ID; } @Override diff --git a/dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstSerialization.java b/dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstSerialization.java index c9201d22a3d..b8862f377ce 100644 --- a/dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstSerialization.java +++ b/dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstSerialization.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.serialize.fst; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -26,6 +25,8 @@ import java.io.InputStream; import java.io.OutputStream; +import static org.apache.dubbo.common.serialize.Constants.FST_SERIALIZATION_ID; + /** * Fst serialization implementation * @@ -37,7 +38,7 @@ public class FstSerialization implements Serialization { @Override public byte getContentTypeId() { - return Constants.FST_SERIALIZATION_ID; + return FST_SERIALIZATION_ID; } @Override diff --git a/dubbo-serialization/dubbo-serialization-gson/src/main/java/org/apache/dubbo/common/serialize/gson/GsonSerialization.java b/dubbo-serialization/dubbo-serialization-gson/src/main/java/org/apache/dubbo/common/serialize/gson/GsonSerialization.java index cb4c2f9b088..a22769a2802 100644 --- a/dubbo-serialization/dubbo-serialization-gson/src/main/java/org/apache/dubbo/common/serialize/gson/GsonSerialization.java +++ b/dubbo-serialization/dubbo-serialization-gson/src/main/java/org/apache/dubbo/common/serialize/gson/GsonSerialization.java @@ -17,7 +17,6 @@ package org.apache.dubbo.common.serialize.gson; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -27,12 +26,14 @@ import java.io.InputStream; import java.io.OutputStream; +import static org.apache.dubbo.common.serialize.Constants.GSON_SERIALIZATION_ID; + public class GsonSerialization implements Serialization { @Override public byte getContentTypeId() { - return Constants.GSON_SERIALIZATION_ID; + return GSON_SERIALIZATION_ID; } @Override diff --git a/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2Serialization.java b/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2Serialization.java index 2c46c5b1933..010a5b6f31a 100644 --- a/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2Serialization.java +++ b/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2Serialization.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.serialize.hessian2; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -26,6 +25,8 @@ import java.io.InputStream; import java.io.OutputStream; +import static org.apache.dubbo.common.serialize.Constants.HESSIAN2_SERIALIZATION_ID; + /** * Hessian2 serialization implementation, hessian2 is the default serialization protocol for dubbo * @@ -37,7 +38,7 @@ public class Hessian2Serialization implements Serialization { @Override public byte getContentTypeId() { - return Constants.HESSIAN2_SERIALIZATION_ID; + return HESSIAN2_SERIALIZATION_ID; } @Override diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/CompactedJavaSerialization.java b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/CompactedJavaSerialization.java index e1b75abf0a1..2df9db1aa2a 100644 --- a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/CompactedJavaSerialization.java +++ b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/CompactedJavaSerialization.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.serialize.java; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -26,6 +25,8 @@ import java.io.InputStream; import java.io.OutputStream; +import static org.apache.dubbo.common.serialize.Constants.COMPACTED_JAVA_SERIALIZATION_ID; + /** * Compacted java serialization implementation * @@ -37,7 +38,7 @@ public class CompactedJavaSerialization implements Serialization { @Override public byte getContentTypeId() { - return Constants.COMPACTED_JAVA_SERIALIZATION_ID; + return COMPACTED_JAVA_SERIALIZATION_ID; } @Override diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaSerialization.java b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaSerialization.java index 01d29ee7c04..2045e4efa45 100644 --- a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaSerialization.java +++ b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaSerialization.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.serialize.java; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -26,6 +25,8 @@ import java.io.InputStream; import java.io.OutputStream; +import static org.apache.dubbo.common.serialize.Constants.JAVA_SERIALIZATION_ID; + /** * Java serialization implementation * @@ -37,7 +38,7 @@ public class JavaSerialization implements Serialization { @Override public byte getContentTypeId() { - return Constants.JAVA_SERIALIZATION_ID; + return JAVA_SERIALIZATION_ID; } @Override diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/nativejava/NativeJavaSerialization.java b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/nativejava/NativeJavaSerialization.java index 2d89161ead9..6617d29f6ad 100644 --- a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/nativejava/NativeJavaSerialization.java +++ b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/nativejava/NativeJavaSerialization.java @@ -17,7 +17,6 @@ package org.apache.dubbo.common.serialize.nativejava; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -27,6 +26,8 @@ import java.io.InputStream; import java.io.OutputStream; +import static org.apache.dubbo.common.serialize.Constants.NATIVE_JAVA_SERIALIZATION_ID; + /** * Native java serialization implementation * @@ -39,7 +40,7 @@ public class NativeJavaSerialization implements Serialization { @Override public byte getContentTypeId() { - return Constants.NATIVE_JAVA_SERIALIZATION_ID; + return NATIVE_JAVA_SERIALIZATION_ID; } @Override diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/KryoSerialization.java b/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/KryoSerialization.java index 4f903ff707b..369192a9cd0 100644 --- a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/KryoSerialization.java +++ b/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/KryoSerialization.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.serialize.kryo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -26,6 +25,8 @@ import java.io.InputStream; import java.io.OutputStream; +import static org.apache.dubbo.common.serialize.Constants.KRYO_SERIALIZATION_ID; + /** * TODO for now kryo serialization doesn't deny classes that don't implement the serializable interface * @@ -37,7 +38,7 @@ public class KryoSerialization implements Serialization { @Override public byte getContentTypeId() { - return Constants.KRYO_SERIALIZATION_ID; + return KRYO_SERIALIZATION_ID; } @Override diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2Serialization.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2Serialization.java index aeda121d015..ee5887682d1 100644 --- a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2Serialization.java +++ b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2Serialization.java @@ -26,11 +26,13 @@ import java.io.InputStream; import java.io.OutputStream; +import static org.apache.dubbo.common.serialize.Constants.NATIVE_HESSIAN_SERIALIZATION_ID; + public class Hessian2Serialization implements Serialization { @Override public byte getContentTypeId() { - return 10; + return NATIVE_HESSIAN_SERIALIZATION_ID; } @Override diff --git a/dubbo-serialization/dubbo-serialization-protobuf-json/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufSerialization.java b/dubbo-serialization/dubbo-serialization-protobuf-json/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufSerialization.java index 8b9395c95b7..d3d23300173 100644 --- a/dubbo-serialization/dubbo-serialization-protobuf-json/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufSerialization.java +++ b/dubbo-serialization/dubbo-serialization-protobuf-json/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufSerialization.java @@ -24,6 +24,8 @@ import java.io.InputStream; import java.io.OutputStream; +import static org.apache.dubbo.common.serialize.Constants.PROTOBUF_JSON_SERIALIZATION_ID; + /** * This serizalization is use for google protobuf generic reference. * The entity be transported between client and server by json string. @@ -33,7 +35,7 @@ public class GenericProtobufSerialization implements Serialization { @Override public byte getContentTypeId() { - return 21; + return PROTOBUF_JSON_SERIALIZATION_ID; } @Override @@ -50,4 +52,4 @@ public ObjectOutput serialize(URL url, OutputStream output) { public ObjectInput deserialize(URL url, InputStream input) { return new GenericProtobufObjectInput(input); } -} \ No newline at end of file +} diff --git a/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffSerialization.java b/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffSerialization.java index 66b6833ba41..5218cef9835 100644 --- a/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffSerialization.java +++ b/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffSerialization.java @@ -17,7 +17,6 @@ package org.apache.dubbo.common.serialize.protostuff; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -27,6 +26,8 @@ import java.io.InputStream; import java.io.OutputStream; +import static org.apache.dubbo.common.serialize.Constants.PROTOSTUFF_SERIALIZATION_ID; + /** * Protostuff serialization implementation * @@ -37,7 +38,7 @@ public class ProtostuffSerialization implements Serialization { @Override public byte getContentTypeId() { - return Constants.PROTOSTUFF_SERIALIZATION_ID; + return PROTOSTUFF_SERIALIZATION_ID; } @Override diff --git a/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/avro/AvroSerializationTest.java b/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/avro/AvroSerializationTest.java index ee591cba4af..d679f384b2c 100644 --- a/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/avro/AvroSerializationTest.java +++ b/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/avro/AvroSerializationTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.serialize.avro; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; import org.hamcrest.Matchers; @@ -28,6 +27,7 @@ import java.io.InputStream; import java.io.OutputStream; +import static org.apache.dubbo.common.serialize.Constants.AVRO_SERIALIZATION_ID; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.mock; @@ -47,7 +47,7 @@ public void testContentType() { @Test public void testContentTypeId() { - assertThat(avroSerialization.getContentTypeId(), is(Constants.AVRO_SERIALIZATION_ID)); + assertThat(avroSerialization.getContentTypeId(), is(AVRO_SERIALIZATION_ID)); } @Test From 951ad3687adf286e6d483ee833ecfb1e8151d669 Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Fri, 10 May 2019 15:50:08 +0800 Subject: [PATCH 039/115] Solve #3137, step 2, seperate constants for cluster, common, filter, monitor, and registry (#4020) --- .../common/constants/ClusterConstants.java | 109 ++++++++++++ .../common/constants/CommonConstants.java | 160 ++++++++++++++++++ .../common/constants/FilterConstants.java | 24 +++ .../constants/MetadataReportConstants.java | 36 ++++ .../common/constants/MonitorConstants.java | 46 +++++ .../common/constants/RegistryConstants.java | 157 +++++++++++++++++ 6 files changed, 532 insertions(+) create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/constants/ClusterConstants.java create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/constants/FilterConstants.java create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/constants/MetadataReportConstants.java create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/constants/MonitorConstants.java create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ClusterConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ClusterConstants.java new file mode 100644 index 00000000000..269fd75a340 --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ClusterConstants.java @@ -0,0 +1,109 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.common.constants; + +public interface ClusterConstants { + /** + * key for router type, for e.g., "script"/"file", corresponding to ScriptRouterFactory.NAME, FileRouterFactory.NAME + */ + String ROUTER_KEY = "router"; + + String LOADBALANCE_KEY = "loadbalance"; + + String DEFAULT_LOADBALANCE = "random"; + + String FAIL_BACK_TASKS_KEY = "failbacktasks"; + + int DEFAULT_FAILBACK_TASKS = 100; + + String RETRIES_KEY = "retries"; + + int DEFAULT_RETRIES = 2; + + int DEFAULT_FAILBACK_TIMES = 3; + + String FORKS_KEY = "forks"; + + int DEFAULT_FORKS = 2; + + String WEIGHT_KEY = "weight"; + + int DEFAULT_WEIGHT = 100; + + String MOCK_PROTOCOL = "mock"; + + String FORCE_KEY = "force"; + + /** + * To decide whether to exclude unavailable invoker from the cluster + */ + String CLUSTER_AVAILABLE_CHECK_KEY = "cluster.availablecheck"; + + /** + * The default value of cluster.availablecheck + * + * @see #CLUSTER_AVAILABLE_CHECK_KEY + */ + boolean DEFAULT_CLUSTER_AVAILABLE_CHECK = true; + + /** + * To decide whether to enable sticky strategy for cluster + */ + String CLUSTER_STICKY_KEY = "sticky"; + + /** + * The default value of sticky + * + * @see #CLUSTER_STICKY_KEY + */ + boolean DEFAULT_CLUSTER_STICKY = false; + + String ADDRESS_KEY = "address"; + + /** + * When this attribute appears in invocation's attachment, mock invoker will be used + */ + String INVOCATION_NEED_MOCK = "invocation.need.mock"; + + /** + * when ROUTER_KEY's value is set to ROUTER_TYPE_CLEAR, RegistryDirectory will clean all current routers + */ + String ROUTER_TYPE_CLEAR = "clean"; + + String DEFAULT_SCRIPT_TYPE_KEY = "javascript"; + + String PRIORITY_KEY = "priority"; + + String RULE_KEY = "rule"; + + String TYPE_KEY = "type"; + + String RUNTIME_KEY = "runtime"; + + String TAG_KEY = "dubbo.tag"; + + String REMOTE_TIMESTAMP_KEY = "remote.timestamp"; + + String WARMUP_KEY = "warmup"; + + int DEFAULT_WARMUP = 10 * 60 * 1000; + + String CONFIG_VERSION_KEY = "configVersion"; + + String OVERRIDE_PROVIDERS_KEY = "providerAddresses"; +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java new file mode 100644 index 00000000000..3ce4f83ac0e --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java @@ -0,0 +1,160 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.common.constants; + +import java.util.regex.Pattern; + +public interface CommonConstants { + String DUBBO = "dubbo"; + + String PROVIDER = "provider"; + + String CONSUMER = "consumer"; + + String APPLICATION_KEY = "application"; + + String REMOTE_APPLICATION_KEY = "remote.application"; + + String ENABLED_KEY = "enabled"; + + String DISABLED_KEY = "disabled"; + + String DUBBO_PROPERTIES_KEY = "dubbo.properties.file"; + + String DEFAULT_DUBBO_PROPERTIES = "dubbo.properties"; + + String ANY_VALUE = "*"; + + String COMMA_SEPARATOR = ","; + + Pattern COMMA_SPLIT_PATTERN = Pattern.compile("\\s*[,]+\\s*"); + + public final static String PATH_SEPARATOR = "/"; + + public final static String PROTOCOL_SEPARATOR = "://"; + + String REGISTRY_SEPARATOR = "|"; + + Pattern REGISTRY_SPLIT_PATTERN = Pattern.compile("\\s*[|;]+\\s*"); + + String SEMICOLON_SEPARATOR = ";"; + + Pattern SEMICOLON_SPLIT_PATTERN = Pattern.compile("\\s*[;]+\\s*"); + + String DEFAULT_PROXY = "javassist"; + + String DEFAULT_DIRECTORY = "dubbo"; + + String PROTOCOL_KEY = "protocol"; + + String DEFAULT_PROTOCOL = "dubbo"; + + String DEFAULT_THREAD_NAME = "Dubbo"; + + int DEFAULT_CORE_THREADS = 0; + + int DEFAULT_THREADS = 200; + + String THREADPOOL_KEY = "threadpool"; + + String THREAD_NAME_KEY = "threadname"; + + String CORE_THREADS_KEY = "corethreads"; + + String THREADS_KEY = "threads"; + + String QUEUES_KEY = "queues"; + + String ALIVE_KEY = "alive"; + + String DEFAULT_THREADPOOL = "limited"; + + String DEFAULT_CLIENT_THREADPOOL = "cached"; + + String IO_THREADS_KEY = "iothreads"; + + int DEFAULT_QUEUES = 0; + + int DEFAULT_ALIVE = 60 * 1000; + + String TIMEOUT_KEY = "timeout"; + + int DEFAULT_TIMEOUT = 1000; + + String REMOVE_VALUE_PREFIX = "-"; + + String PROPERTIES_CHAR_SEPERATOR = "-"; + + String GROUP_CHAR_SEPERATOR = ":"; + + String HIDE_KEY_PREFIX = "."; + + String DEFAULT_KEY_PREFIX = "default."; + + String DEFAULT_KEY = "default"; + + /** + * Default timeout value in milliseconds for server shutdown + */ + int DEFAULT_SERVER_SHUTDOWN_TIMEOUT = 10000; + + String SIDE_KEY = "side"; + + String PROVIDER_SIDE = "provider"; + + String CONSUMER_SIDE = "consumer"; + + String ANYHOST_KEY = "anyhost"; + + String ANYHOST_VALUE = "0.0.0.0"; + + String LOCALHOST_KEY = "localhost"; + + String LOCALHOST_VALUE = "127.0.0.1"; + + String METHODS_KEY = "methods"; + + String METHOD_KEY = "method"; + + String PID_KEY = "pid"; + + String TIMESTAMP_KEY = "timestamp"; + + String GROUP_KEY = "group"; + + String PATH_KEY = "path"; + + String INTERFACE_KEY = "interface"; + + String FILE_KEY = "file"; + + String DUMP_DIRECTORY = "dump.directory"; + + String CLASSIFIER_KEY = "classifier"; + + String VERSION_KEY = "version"; + + String REVISION_KEY = "revision"; + + /** + * package version in the manifest + */ + String RELEASE_KEY = "release"; + + int MAX_PROXY_COUNT = 65535; +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/FilterConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/FilterConstants.java new file mode 100644 index 00000000000..f4199ffe418 --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/FilterConstants.java @@ -0,0 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.common.constants; + +public interface FilterConstants { + String CACHE_KEY = "cache"; + + String VALIDATION_KEY = "validation"; +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/MetadataReportConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/MetadataReportConstants.java new file mode 100644 index 00000000000..ee1119d4e6e --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/MetadataReportConstants.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.common.constants; + +public interface MetadataReportConstants { + String METADATA_REPORT_KEY = "metadata"; + + String RETRY_TIMES_KEY = "retry.times"; + + Integer DEFAULT_METADATA_REPORT_RETRY_TIMES = 100; + + String RETRY_PERIOD_KEY = "retry.period"; + + Integer DEFAULT_METADATA_REPORT_RETRY_PERIOD = 3000; + + String SYNC_REPORT_KEY = "sync.report"; + + String CYCLE_REPORT_KEY = "cycle.report"; + + Boolean DEFAULT_METADATA_REPORT_CYCLE_REPORT = true; +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/MonitorConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/MonitorConstants.java new file mode 100644 index 00000000000..94079bf5f95 --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/MonitorConstants.java @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.common.constants; + +public interface MonitorConstants { + String MONITOR_KEY = "monitor"; + + String LOGSTAT_PROTOCOL = "logstat"; + + String COUNT_PROTOCOL = "count"; + + String DUBBO_PROVIDER = "dubbo.provider"; + + String DUBBO_CONSUMER = "dubbo.consumer"; + + String DUBBO_PROVIDER_METHOD = "dubbo.provider.method"; + + String DUBBO_CONSUMER_METHOD = "dubbo.consumer.method"; + + String SERVICE = "service"; + + String METHOD = "method"; + + String DUBBO_GROUP = "dubbo"; + + String METRICS_KEY = "metrics"; + + String METRICS_PORT = "metrics.port"; + + String METRICS_PROTOCOL = "metrics.protocol"; +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java new file mode 100644 index 00000000000..bcfc9dcc436 --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java @@ -0,0 +1,157 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.common.constants; + +import static org.apache.dubbo.common.Constants.APPLICATION_KEY; +import static org.apache.dubbo.common.Constants.CLUSTER_KEY; +import static org.apache.dubbo.common.Constants.CODEC_KEY; +import static org.apache.dubbo.common.Constants.CONNECTIONS_KEY; +import static org.apache.dubbo.common.Constants.DEPRECATED_KEY; +import static org.apache.dubbo.common.Constants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.common.Constants.EXCHANGER_KEY; +import static org.apache.dubbo.common.Constants.GROUP_KEY; +import static org.apache.dubbo.common.Constants.LOADBALANCE_KEY; +import static org.apache.dubbo.common.Constants.MOCK_KEY; +import static org.apache.dubbo.common.Constants.PATH_KEY; +import static org.apache.dubbo.common.Constants.RELEASE_KEY; +import static org.apache.dubbo.common.Constants.SERIALIZATION_KEY; +import static org.apache.dubbo.common.Constants.TIMEOUT_KEY; +import static org.apache.dubbo.common.Constants.TIMESTAMP_KEY; +import static org.apache.dubbo.common.Constants.TOKEN_KEY; +import static org.apache.dubbo.common.Constants.VERSION_KEY; +import static org.apache.dubbo.common.Constants.WARMUP_KEY; +import static org.apache.dubbo.common.Constants.WEIGHT_KEY; + +public interface RegistryConstants { + String REGISTER_KEY = "register"; + + String SUBSCRIBE_KEY = "subscribe"; + + String REGISTRY_KEY = "registry"; + + String DEFAULT_REGISTRY = "dubbo"; + + String REGISTRY_PROTOCOL = "registry"; + + String DYNAMIC_KEY = "dynamic"; + + String REGISTER = "register"; + + String UNREGISTER = "unregister"; + + String SUBSCRIBE = "subscribe"; + + String UNSUBSCRIBE = "unsubscribe"; + + String CATEGORY_KEY = "category"; + + String PROVIDERS_CATEGORY = "providers"; + + String CONSUMERS_CATEGORY = "consumers"; + + String ROUTERS_CATEGORY = "routers"; + + String DYNAMIC_ROUTERS_CATEGORY = "dynamicrouters"; + + String DEFAULT_CATEGORY = PROVIDERS_CATEGORY; + + String CONFIGURATORS_CATEGORY = "configurators"; + + String DYNAMIC_CONFIGURATORS_CATEGORY = "dynamicconfigurators"; + + String APP_DYNAMIC_CONFIGURATORS_CATEGORY = "appdynamicconfigurators"; + + String CONFIGURATORS_SUFFIX = ".configurators"; + + String ROUTERS_SUFFIX = ".routers"; + + String TRACE_PROTOCOL = "trace"; + + String EMPTY_PROTOCOL = "empty"; + + String ADMIN_PROTOCOL = "admin"; + + String PROVIDER_PROTOCOL = "provider"; + + String CONSUMER_PROTOCOL = "consumer"; + + String ROUTE_PROTOCOL = "route"; + + String SCRIPT_PROTOCOL = "script"; + + String CONDITION_PROTOCOL = "condition"; + + /** + * simple the registry for provider. + * + * @since 2.7.0 + */ + String SIMPLIFIED_KEY = "simplified"; + + /** + * After simplify the registry, should add some paramter individually for provider. + * + * @since 2.7.0 + */ + String EXTRA_KEYS_KEY = "extra-keys"; + + String OVERRIDE_PROTOCOL = "override"; + + String COMPATIBLE_CONFIG_KEY = "compatible_config"; + + String[] DEFAULT_REGISTER_PROVIDER_KEYS = {APPLICATION_KEY, CODEC_KEY, EXCHANGER_KEY, SERIALIZATION_KEY, CLUSTER_KEY, CONNECTIONS_KEY, DEPRECATED_KEY, + GROUP_KEY, LOADBALANCE_KEY, MOCK_KEY, PATH_KEY, TIMEOUT_KEY, TOKEN_KEY, VERSION_KEY, WARMUP_KEY, WEIGHT_KEY, TIMESTAMP_KEY, DUBBO_VERSION_KEY, RELEASE_KEY}; + + String[] DEFAULT_REGISTER_CONSUMER_KEYS = {APPLICATION_KEY, VERSION_KEY, GROUP_KEY, DUBBO_VERSION_KEY, RELEASE_KEY}; + + /** + * To decide whether register center saves file synchronously, the default value is asynchronously + */ + String REGISTRY_FILESAVE_SYNC_KEY = "save.file"; + + /** + * Period of registry center's retry interval + */ + String REGISTRY_RETRY_PERIOD_KEY = "retry.period"; + + /** + * Most retry times + */ + String REGISTRY_RETRY_TIMES_KEY = "retry.times"; + + /** + * Default value for the period of retry interval in milliseconds: 5000 + */ + int DEFAULT_REGISTRY_RETRY_PERIOD = 5 * 1000; + + /** + * Default value for the times of retry: 3 + */ + int DEFAULT_REGISTRY_RETRY_TIMES = 3; + + /** + * Reconnection period in milliseconds for register center + */ + String REGISTRY_RECONNECT_PERIOD_KEY = "reconnect.period"; + + int DEFAULT_REGISTRY_RECONNECT_PERIOD = 3 * 1000; + + String SESSION_TIMEOUT_KEY = "session"; + + int DEFAULT_SESSION_TIMEOUT = 60 * 1000; +} From 6a1dd65088d92af401106dcacf2a3b44b0cbaff1 Mon Sep 17 00:00:00 2001 From: huazhongming Date: Fri, 10 May 2019 16:06:19 +0800 Subject: [PATCH 040/115] [DUBBO-3137]: step2 - seperate constants for config, remoting, rpc (#4021) * constants step2 * change interface --- .../common/constants/ConfigConstants.java | 175 ++++++++++++++++ .../common/constants/RemotingConstants.java | 154 ++++++++++++++ .../dubbo/common/constants/RpcConstants.java | 195 ++++++++++++++++++ 3 files changed, 524 insertions(+) create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/constants/ConfigConstants.java create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/constants/RemotingConstants.java create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/constants/RpcConstants.java diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ConfigConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ConfigConstants.java new file mode 100644 index 00000000000..5899641a625 --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ConfigConstants.java @@ -0,0 +1,175 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.common.constants; + +/** + * ConfigConstants + */ +public interface ConfigConstants { + // BEGIN dubbo-config-api + String CLUSTER_KEY = "cluster"; + + String STATUS_KEY = "status"; + + String CONTEXTPATH_KEY = "contextpath"; + + String LISTENER_KEY = "listener"; + + String LAYER_KEY = "layer"; + + /** + * General + */ + /** + * Application name; + */ + String NAME = "name"; + + /** + * Application owner name; + */ + String OWNER = "owner"; + + /** + * Running application organization name. + */ + String ORGANIZATION = "organization"; + + /** + * Application architecture name. + */ + String ARCHITECTURE = "architecture"; + + /** + * Environment name + */ + String ENVIRONMENT = "environment"; + + /** + * Test environment key. + */ + String TEST_ENVIRONMENT = "test"; + + /** + * Development environment key. + */ + String DEVELOPMENT_ENVIRONMENT = "develop"; + + /** + * Production environment key. + */ + String PRODUCTION_ENVIRONMENT = "product"; + + String CONFIG_CLUSTER_KEY = "config.cluster"; + String CONFIG_NAMESPACE_KEY = "config.namespace"; + String CONFIG_GROUP_KEY = "config.group"; + String CONFIG_CHECK_KEY = "config.check"; + + String CONFIG_CONFIGFILE_KEY = "config.config-file"; + String CONFIG_ENABLE_KEY = "config.highest-priority"; + String CONFIG_TIMEOUT_KEY = "config.timeout"; + String CONFIG_APPNAME_KEY = "config.app-name"; + + String USERNAME_KEY = "username"; + + String PASSWORD_KEY = "password"; + + String HOST_KEY = "host"; + + String PORT_KEY = "port"; + + String MULTICAST = "multicast"; + + String REGISTER_IP_KEY = "register.ip"; + + String DUBBO_IP_TO_REGISTRY = "DUBBO_IP_TO_REGISTRY"; + + String DUBBO_PORT_TO_REGISTRY = "DUBBO_PORT_TO_REGISTRY"; + + String DUBBO_IP_TO_BIND = "DUBBO_IP_TO_BIND"; + + String DUBBO_PORT_TO_BIND = "DUBBO_PORT_TO_BIND"; + + String SCOPE_KEY = "scope"; + + String SCOPE_LOCAL = "local"; + + String SCOPE_REMOTE = "remote"; + + String SCOPE_NONE = "none"; + + String ON_CONNECT_KEY = "onconnect"; + + String ON_DISCONNECT_KEY = "ondisconnect"; + + String ON_INVOKE_METHOD_KEY = "oninvoke.method"; + + String ON_RETURN_METHOD_KEY = "onreturn.method"; + + String ON_THROW_METHOD_KEY = "onthrow.method"; + + String ON_INVOKE_INSTANCE_KEY = "oninvoke.instance"; + + String ON_RETURN_INSTANCE_KEY = "onreturn.instance"; + + String ON_THROW_INSTANCE_KEY = "onthrow.instance"; + + @Deprecated + String SHUTDOWN_WAIT_SECONDS_KEY = "dubbo.service.shutdown.wait.seconds"; + + String SHUTDOWN_WAIT_KEY = "dubbo.service.shutdown.wait"; + + /** + * The key name for export URL in register center + */ + String EXPORT_KEY = "export"; + + /** + * The key name for reference URL in register center + */ + String REFER_KEY = "refer"; + + /** + * To decide whether to make connection when the client is created + */ + String LAZY_CONNECT_KEY = "lazy"; + + String DUBBO_PROTOCOL = "dubbo"; + + String ZOOKEEPER_PROTOCOL = "zookeeper"; + + // FIXME: is this still useful? + String SHUTDOWN_TIMEOUT_KEY = "shutdown.timeout"; + + int DEFAULT_SHUTDOWN_TIMEOUT = 1000 * 60 * 15; + + String PROTOCOLS_SUFFIX = "dubbo.protocols."; + + String PROTOCOL_SUFFIX = "dubbo.protocol."; + + String REGISTRIES_SUFFIX = "dubbo.registries."; + + String TELNET = "telnet"; + + String QOS_ENABLE = "qos.enable"; + + String QOS_PORT = "qos.port"; + + String ACCEPT_FOREIGN_IP = "qos.accept.foreign.ip"; + // END dubbo-congfig-api +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RemotingConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RemotingConstants.java new file mode 100644 index 00000000000..4e50feea1c9 --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RemotingConstants.java @@ -0,0 +1,154 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.common.constants; + +import java.util.concurrent.ExecutorService; + +/** + * RemotingConstants + */ +public interface RemotingConstants { + + String PAYLOAD_KEY = "payload"; + /** + * 8M + */ + int DEFAULT_PAYLOAD = 8 * 1024 * 1024; + + String BUFFER_KEY = "buffer"; + + /** + * default buffer size is 8k. + */ + int DEFAULT_BUFFER_SIZE = 8 * 1024; + + int MAX_BUFFER_SIZE = 16 * 1024; + + int MIN_BUFFER_SIZE = 1 * 1024; + + String CONNECT_TIMEOUT_KEY = "connect.timeout"; + + int DEFAULT_CONNECT_TIMEOUT = 3000; + + String HEARTBEAT_KEY = "heartbeat"; + + int DEFAULT_HEARTBEAT = 60 * 1000; + + String IDLE_TIMEOUT_KEY = "idle.timeout"; + + int DEFAULT_IDLE_TIMEOUT = 600 * 1000; + + String ACCEPTS_KEY = "accepts"; + + int DEFAULT_ACCEPTS = 0; + + String SERIALIZATION_KEY = "serialization"; + + String DEFAULT_REMOTING_SERIALIZATION = "hessian2"; + + String CODEC_KEY = "codec"; + + String DEFAULT_REMOTING_CODEC = "dubbo"; + + String SERVER_KEY = "server"; + + String DEFAULT_REMOTING_SERVER = "netty"; + + String CLIENT_KEY = "client"; + + String DEFAULT_REMOTING_CLIENT = "netty"; + + String TRANSPORTER_KEY = "transporter"; + + String DEFAULT_TRANSPORTER = "netty"; + + String EXCHANGER_KEY = "exchanger"; + + String DEFAULT_EXCHANGER = "header"; + + String DISPACTHER_KEY = "dispacther"; + + int DEFAULT_IO_THREADS = Math.min(Runtime.getRuntime().availableProcessors() + 1, 32); + + String BIND_IP_KEY = "bind.ip"; + + String BIND_PORT_KEY = "bind.port"; + + String SENT_KEY = "sent"; + + boolean DEFAULT_SENT = false; + + String DISPATCHER_KEY = "dispatcher"; + + String CHANNEL_HANDLER_KEY = "channel.handler"; + + String DEFAULT_CHANNEL_HANDLER = "default"; + + String SERVICE_DESCIPTOR_KEY = "serviceDescriptor"; + + String CONNECT_QUEUE_CAPACITY = "connect.queue.capacity"; + + String CONNECT_QUEUE_WARNING_SIZE = "connect.queue.warning.size"; + + int DEFAULT_CONNECT_QUEUE_WARNING_SIZE = 1000; + + String CHANNEL_ATTRIBUTE_READONLY_KEY = "channel.readonly"; + + String CHANNEL_READONLYEVENT_SENT_KEY = "channel.readonly.sent"; + + String CHANNEL_SEND_READONLYEVENT_KEY = "channel.readonly.send"; + + String EXECUTOR_SERVICE_COMPONENT_KEY = ExecutorService.class.getName(); + + String CHARSET_KEY = "charset"; + + String DEFAULT_CHARSET = "UTF-8"; + + String BACKUP_KEY = "backup"; + + /** + * Every heartbeat duration / HEATBEAT_CHECK_TICK, check if a heartbeat should be sent. Every heartbeat timeout + * duration / HEATBEAT_CHECK_TICK, check if a connection should be closed on server side, and if reconnect on + * client side + */ + int HEARTBEAT_CHECK_TICK = 3; + + /** + * the least heartbeat during is 1000 ms. + */ + long LEAST_HEARTBEAT_DURATION = 1000; + + /** + * ticks per wheel. + */ + int TICKS_PER_WHEEL = 128; + + String HEARTBEAT_TIMEOUT_KEY = "heartbeat.timeout"; + + String RECONNECT_KEY = "reconnect"; + + int DEFAULT_RECONNECT_PERIOD = 2000; + + String SEND_RECONNECT_KEY = "send.reconnect"; + + String CHECK_KEY = "check"; + + String PROMPT_KEY = "prompt"; + + String DEFAULT_PROMPT = "dubbo>"; +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RpcConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RpcConstants.java new file mode 100644 index 00000000000..9e7302ff0ad --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RpcConstants.java @@ -0,0 +1,195 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.common.constants; + +/** + * RpcConstants + */ +public interface RpcConstants { + // BEGIN dubbo-rpc-hessian + String HESSIAN2_REQUEST_KEY = "hessian2.request"; + + boolean DEFAULT_HESSIAN2_REQUEST = false; + + String HESSIAN_OVERLOAD_METHOD_KEY = "hessian.overload.method"; + + boolean DEFAULT_HESSIAN_OVERLOAD_METHOD = false; + + String DEFAULT_HTTP_CLIENT = "jdk"; + + String DEFAULT_HTTP_SERVER = "servlet"; + + String DEFAULT_HTTP_SERIALIZATION = "json"; + // END dubbo-rpc-hessian + + // BEGIN dubbo-rpc-dubbo + String SHARE_CONNECTIONS_KEY = "shareconnections"; + + /** + * By default, a consumer JVM instance and a provider JVM instance share a long TCP connection (except when connections are set), + * which can set the number of long TCP connections shared to avoid the bottleneck of sharing a single long TCP connection. + */ + String DEFAULT_SHARE_CONNECTIONS = "1"; + + String INPUT_KEY = "input"; + + String OUTPUT_KEY = "output"; + + String DECODE_IN_IO_THREAD_KEY = "decode.in.io"; + + boolean DEFAULT_DECODE_IN_IO_THREAD = true; + + /** + * callback inst id + */ + String CALLBACK_SERVICE_KEY = "callback.service.instid"; + + /** + * The limit of callback service instances for one interface on every client + */ + String CALLBACK_INSTANCES_LIMIT_KEY = "callbacks"; + + /** + * The default limit number for callback service instances + * + * @see #CALLBACK_INSTANCES_LIMIT_KEY + */ + int DEFAULT_CALLBACK_INSTANCES = 1; + + String CALLBACK_SERVICE_PROXY_KEY = "callback.service.proxy"; + + String IS_CALLBACK_SERVICE = "is_callback_service"; + + /** + * Invokers in channel's callback + */ + String CHANNEL_CALLBACK_KEY = "channel.callback.invokers.key"; + + /** + * The initial state for lazy connection + */ + String LAZY_CONNECT_INITIAL_STATE_KEY = "connect.lazy.initial.state"; + + /** + * The default value of lazy connection's initial state: true + * + * @see #LAZY_CONNECT_INITIAL_STATE_KEY + */ + boolean DEFAULT_LAZY_CONNECT_INITIAL_STATE = true; + + String OPTIMIZER_KEY = "optimizer"; + // END dubbo-rpc-dubbo + + + // BEGIN dubbo-rpc-api + String DUBBO_VERSION_KEY = "dubbo"; + + String LOCAL_KEY = "local"; + + String STUB_KEY = "stub"; + + String MOCK_KEY = "mock"; + + String DEPRECATED_KEY = "deprecated"; + + String $INVOKE = "$invoke"; + + String $ECHO = "$echo"; + + String RETURN_PREFIX = "return "; + + String THROW_PREFIX = "throw"; + + String FAIL_PREFIX = "fail:"; + + String FORCE_PREFIX = "force:"; + + String MERGER_KEY = "merger"; + + String IS_SERVER_KEY = "isserver"; + + String FORCE_USE_TAG = "dubbo.force.tag"; + + String GENERIC_SERIALIZATION_NATIVE_JAVA = "nativejava"; + + String GENERIC_SERIALIZATION_DEFAULT = "true"; + + String GENERIC_SERIALIZATION_BEAN = "bean"; + + String GENERIC_SERIALIZATION_PROTOBUF = "protobuf-json"; + + String TPS_LIMIT_RATE_KEY = "tps"; + + String TPS_LIMIT_INTERVAL_KEY = "tps.interval"; + + long DEFAULT_TPS_LIMIT_INTERVAL = 60 * 1000; + + String AUTO_ATTACH_INVOCATIONID_KEY = "invocationid.autoattach"; + + String STUB_EVENT_KEY = "dubbo.stub.event"; + + boolean DEFAULT_STUB_EVENT = false; + + String STUB_EVENT_METHODS_KEY = "dubbo.stub.event.methods"; + + String PROXY_KEY = "proxy"; + + String EXECUTES_KEY = "executes"; + + String REFERENCE_FILTER_KEY = "reference.filter"; + + String INVOKER_LISTENER_KEY = "invoker.listener"; + + String SERVICE_FILTER_KEY = "service.filter"; + + String EXPORTER_LISTENER_KEY = "exporter.listener"; + + String ACCESS_LOG_KEY = "accesslog"; + + String ACTIVES_KEY = "actives"; + + String CONNECTIONS_KEY = "connections"; + + String ID_KEY = "id"; + + String ASYNC_KEY = "async"; + + String FUTURE_GENERATED_KEY = "future_generated"; + + String FUTURE_RETURNTYPE_KEY = "future_returntype"; + + String RETURN_KEY = "return"; + + String TOKEN_KEY = "token"; + + String INTERFACES = "interfaces"; + + String GENERIC_KEY = "generic"; + + String LOCAL_PROTOCOL = "injvm"; + // END dubbo-rpc-api + + + // BEGIN dubbo-rpc-rest + String KEEP_ALIVE_KEY = "keepalive"; + + boolean DEFAULT_KEEP_ALIVE = true; + + String EXTENSION_KEY = "extension"; + // END dubbo-rpc-rest +} From 8e3675ef06d085aa1538de82cb8337a146dc76e4 Mon Sep 17 00:00:00 2001 From: huazhongming Date: Sat, 11 May 2019 17:38:37 +0800 Subject: [PATCH 041/115] [DUBBO-3137]: step3 - seperate constants for remoting (#4023) * constants step3-remoting * remove import * modify --- .../configurator/AbstractConfigurator.java | 3 ++- .../rpc/cluster/support/ClusterUtils.java | 5 +++-- .../org/apache/dubbo/common/Constants.java | 4 +++- .../java/org/apache/dubbo/common/URL.java | 5 +++-- .../common/constants/RegistryConstants.java | 6 +++--- .../apache/dubbo/common/utils/UrlUtils.java | 7 ++++--- .../dubbo/config/AbstractReferenceConfig.java | 3 ++- .../apache/dubbo/config/ProtocolConfig.java | 15 ++++++++------- .../apache/dubbo/config/ProviderConfig.java | 7 ++++--- .../apache/dubbo/config/ReferenceConfig.java | 3 ++- .../apache/dubbo/config/RegistryConfig.java | 7 ++++--- .../apache/dubbo/config/ServiceConfig.java | 5 +++-- .../dubbo/config/annotation/Reference.java | 3 ++- .../config/AbstractReferenceConfigTest.java | 3 ++- .../dubbo/config/ServiceConfigTest.java | 5 +++-- .../nacos/NacosDynamicConfiguration.java | 2 +- .../integration/MetadataReportService.java | 5 +++-- .../monitor/dubbo/DubboMonitorFactory.java | 2 +- .../dubbo/monitor/dubbo/MetricsFilter.java | 3 ++- .../integration/RegistryDirectory.java | 3 ++- .../integration/RegistryProtocol.java | 6 +++--- .../registry/support/FailbackRegistry.java | 17 +++++++++-------- .../dubbo/registry/dubbo/DubboRegistry.java | 3 ++- .../registry/dubbo/DubboRegistryFactory.java | 9 +++++---- .../registry/dubbo/DubboRegistryTest.java | 5 +++-- .../registry/dubbo/RegistryDirectoryTest.java | 3 ++- .../dubbo/registry/etcd/EtcdRegistry.java | 5 +++-- .../dubbo/registry/etcd/EtcdRegistryTest.java | 3 ++- .../registry/nacos/NacosRegistryFactory.java | 2 +- .../dubbo/registry/redis/RedisRegistry.java | 3 ++- .../registry/redis/RedisRegistryTest.java | 2 +- .../registry/zookeeper/ZookeeperRegistry.java | 5 +++-- .../java/org/apache/dubbo/remoting/Codec.java | 6 +++--- .../org/apache/dubbo/remoting/Codec2.java | 6 +++--- .../org/apache/dubbo/remoting/Dispatcher.java | 4 ++-- .../apache/dubbo/remoting/Transporter.java | 6 +++--- .../dubbo/remoting/exchange/Exchanger.java | 6 +++--- .../dubbo/remoting/exchange/Exchangers.java | 8 ++++---- .../support/header/HeaderExchangeClient.java | 12 ++++++------ .../support/header/HeaderExchangeHandler.java | 4 ++-- .../support/header/HeaderExchangeServer.java | 14 +++++++------- .../support/header/HeartbeatHandler.java | 4 ++-- .../remoting/telnet/codec/TelnetCodec.java | 8 ++++---- .../telnet/support/TelnetHandlerAdapter.java | 3 ++- .../remoting/transport/AbstractClient.java | 5 +++-- .../remoting/transport/AbstractCodec.java | 5 +++-- .../remoting/transport/AbstractEndpoint.java | 11 ++++++----- .../remoting/transport/AbstractPeer.java | 4 ++-- .../remoting/transport/AbstractServer.java | 19 ++++++++++--------- .../remoting/transport/CodecSupport.java | 6 +++--- .../dispatcher/WrappedChannelHandler.java | 3 ++- .../ConnectionOrderedChannelHandler.java | 5 +++-- .../dubbo/remoting/ChanelHandlerTest.java | 5 +++-- .../remoting/PerformanceClientCloseTest.java | 5 +++-- .../remoting/PerformanceClientFixedTest.java | 5 +++-- .../dubbo/remoting/PerformanceClientTest.java | 6 +++--- .../dubbo/remoting/PerformanceServerTest.java | 11 ++++++----- .../remoting/codec/ExchangeCodecTest.java | 9 ++++----- .../support/header/HeartBeatTaskTest.java | 5 +++-- .../handler/HeaderExchangeHandlerTest.java | 4 ++-- .../codec/DeprecatedTelnetCodec.java | 9 +++++---- .../apache/dubbo/remoting/etcd/Constants.java | 2 +- .../dubbo/remoting/etcd/EtcdTransporter.java | 4 ++-- .../grizzly/GrizzlyCodecAdapter.java | 6 +++--- .../dubbo/remoting/http/HttpBinder.java | 4 ++-- .../remoting/http/jetty/JettyHttpServer.java | 13 +++++++------ .../http/servlet/ServletHttpServer.java | 4 ++-- .../http/tomcat/TomcatHttpServer.java | 3 ++- .../http/jetty/JettyHttpBinderTest.java | 4 ++-- .../http/tomcat/TomcatHttpBinderTest.java | 4 ++-- .../remoting/transport/mina/MinaClient.java | 4 ++-- .../transport/mina/MinaCodecAdapter.java | 6 +++--- .../remoting/transport/mina/MinaServer.java | 3 ++- .../remoting/transport/netty/NettyClient.java | 4 ++-- .../transport/netty/NettyCodecAdapter.java | 6 +++--- .../remoting/transport/netty/NettyServer.java | 3 ++- .../support/header/HeartbeatHandlerTest.java | 14 +++++++------- .../transport/netty/ClientReconnectTest.java | 4 ++-- .../netty/NettyClientToServerTest.java | 6 +++--- .../transport/netty4/NettyClient.java | 4 ++-- .../transport/netty4/NettyServer.java | 3 ++- .../transport/netty4/ClientReconnectTest.java | 4 ++-- .../netty4/NettyClientToServerTest.java | 6 +++--- .../netty4/NettyTransporterTest.java | 6 +++--- .../exchange/support/ExchangeServerPeer.java | 4 ++-- .../remoting/p2p/support/ServerPeer.java | 4 ++-- .../zookeeper/ZookeeperTransporter.java | 4 ++-- .../support/AbstractZookeeperTransporter.java | 7 ++++--- .../dubbo/rpc/filter/CompatibleFilter.java | 4 ++-- .../dubbo/rpc/protocol/AbstractProtocol.java | 3 ++- .../rpc/protocol/AbstractProxyProtocol.java | 5 +++-- .../protocol/dubbo/ChannelWrappedInvoker.java | 3 ++- .../rpc/protocol/dubbo/DubboInvoker.java | 5 +++-- .../rpc/protocol/dubbo/DubboProtocol.java | 17 +++++++++-------- .../dubbo/LazyConnectExchangeClient.java | 3 ++- .../dubbo/ReferenceCountExchangeClient.java | 5 +++-- .../protocol/dubbo/filter/TraceFilter.java | 3 ++- .../dubbo/status/ThreadPoolStatusChecker.java | 4 ++-- .../dubbo/DubboInvokerAvilableTest.java | 9 +++++---- .../rpc/protocol/dubbo/DubboProtocolTest.java | 6 +++--- .../DubboHessianURLConnectionFactory.java | 4 ++-- .../rpc/protocol/hessian/HessianProtocol.java | 7 ++++--- .../hessian/HttpClientConnectionFactory.java | 4 ++-- .../dubbo/rpc/protocol/http/HttpProtocol.java | 7 ++++--- .../protocol/memcached/MemcachedProtocol.java | 4 ++-- .../rpc/protocol/redis/RedisProtocol.java | 3 ++- .../rpc/protocol/redis/RedisProtocolTest.java | 4 ++-- .../dubbo/rpc/protocol/rest/NettyServer.java | 9 +++++---- .../dubbo/rpc/protocol/rest/RestProtocol.java | 7 ++++--- .../rpc/protocol/rest/RestProtocolTest.java | 11 ++++++----- .../rpc/protocol/thrift/ThriftInvoker.java | 3 ++- .../rpc/protocol/thrift/ThriftProtocol.java | 11 ++++++----- .../webservice/WebServiceProtocol.java | 3 ++- 113 files changed, 350 insertions(+), 287 deletions(-) diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java index 5e53b1bbd54..15665a5b74e 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.cluster.Configurator; @@ -104,7 +105,7 @@ private URL configureIfMatch(String host, URL url) { || configApplication.equals(currentApplication)) { Set conditionKeys = new HashSet(); conditionKeys.add(Constants.CATEGORY_KEY); - conditionKeys.add(Constants.CHECK_KEY); + conditionKeys.add(RemotingConstants.CHECK_KEY); conditionKeys.add(Constants.DYNAMIC_KEY); conditionKeys.add(Constants.ENABLED_KEY); conditionKeys.add(Constants.GROUP_KEY); diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java index e6ed749f0cb..6c58740eb88 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.StringUtils; import java.util.HashMap; @@ -59,8 +60,8 @@ public static URL mergeUrl(URL remoteUrl, Map localMap) { map.remove(Constants.ALIVE_KEY); map.remove(Constants.DEFAULT_KEY_PREFIX + Constants.ALIVE_KEY); - map.remove(Constants.TRANSPORTER_KEY); - map.remove(Constants.DEFAULT_KEY_PREFIX + Constants.TRANSPORTER_KEY); + map.remove(RemotingConstants.TRANSPORTER_KEY); + map.remove(Constants.DEFAULT_KEY_PREFIX + RemotingConstants.TRANSPORTER_KEY); map.remove(Constants.ASYNC_KEY); map.remove(Constants.DEFAULT_KEY_PREFIX + Constants.ASYNC_KEY); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java index 42c9f39748f..73c1f21662d 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java @@ -17,6 +17,8 @@ package org.apache.dubbo.common; +import org.apache.dubbo.common.constants.RemotingConstants; + import java.util.concurrent.ExecutorService; import java.util.regex.Pattern; @@ -789,7 +791,7 @@ public class Constants { public static final String COMPATIBLE_CONFIG_KEY = "compatible_config"; - public static final String[] DEFAULT_REGISTER_PROVIDER_KEYS = {APPLICATION_KEY, CODEC_KEY, EXCHANGER_KEY, SERIALIZATION_KEY, CLUSTER_KEY, CONNECTIONS_KEY, DEPRECATED_KEY, + public static final String[] DEFAULT_REGISTER_PROVIDER_KEYS = {APPLICATION_KEY, RemotingConstants.CODEC_KEY, RemotingConstants.EXCHANGER_KEY, RemotingConstants.SERIALIZATION_KEY, CLUSTER_KEY, CONNECTIONS_KEY, DEPRECATED_KEY, GROUP_KEY, LOADBALANCE_KEY, MOCK_KEY, PATH_KEY, TIMEOUT_KEY, TOKEN_KEY, VERSION_KEY, WARMUP_KEY, WEIGHT_KEY, TIMESTAMP_KEY, DUBBO_VERSION_KEY, RELEASE_KEY}; public static final String[] DEFAULT_REGISTER_CONSUMER_KEYS = {APPLICATION_KEY, VERSION_KEY, GROUP_KEY, DUBBO_VERSION_KEY, RELEASE_KEY}; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java b/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java index 35a3b7bd1f9..e77e6ff208e 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.config.Configuration; import org.apache.dubbo.common.config.InmemoryConfiguration; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.NetUtils; @@ -414,7 +415,7 @@ public String getBackupAddress() { public String getBackupAddress(int defaultPort) { StringBuilder address = new StringBuilder(appendDefaultPort(getAddress(), defaultPort)); - String[] backups = getParameter(Constants.BACKUP_KEY, new String[0]); + String[] backups = getParameter(RemotingConstants.BACKUP_KEY, new String[0]); if (ArrayUtils.isNotEmpty(backups)) { for (String backup : backups) { address.append(","); @@ -427,7 +428,7 @@ public String getBackupAddress(int defaultPort) { public List getBackupUrls() { List urls = new ArrayList<>(); urls.add(this); - String[] backups = getParameter(Constants.BACKUP_KEY, new String[0]); + String[] backups = getParameter(RemotingConstants.BACKUP_KEY, new String[0]); if (backups != null && backups.length > 0) { for (String backup : backups) { urls.add(this.setAddress(backup)); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java index bcfc9dcc436..331a67c587c 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java @@ -19,17 +19,17 @@ import static org.apache.dubbo.common.Constants.APPLICATION_KEY; import static org.apache.dubbo.common.Constants.CLUSTER_KEY; -import static org.apache.dubbo.common.Constants.CODEC_KEY; +import static org.apache.dubbo.common.constants.RemotingConstants.CODEC_KEY; import static org.apache.dubbo.common.Constants.CONNECTIONS_KEY; import static org.apache.dubbo.common.Constants.DEPRECATED_KEY; import static org.apache.dubbo.common.Constants.DUBBO_VERSION_KEY; -import static org.apache.dubbo.common.Constants.EXCHANGER_KEY; +import static org.apache.dubbo.common.constants.RemotingConstants.EXCHANGER_KEY; import static org.apache.dubbo.common.Constants.GROUP_KEY; import static org.apache.dubbo.common.Constants.LOADBALANCE_KEY; import static org.apache.dubbo.common.Constants.MOCK_KEY; import static org.apache.dubbo.common.Constants.PATH_KEY; import static org.apache.dubbo.common.Constants.RELEASE_KEY; -import static org.apache.dubbo.common.Constants.SERIALIZATION_KEY; +import static org.apache.dubbo.common.constants.RemotingConstants.SERIALIZATION_KEY; import static org.apache.dubbo.common.Constants.TIMEOUT_KEY; import static org.apache.dubbo.common.Constants.TIMESTAMP_KEY; import static org.apache.dubbo.common.Constants.TOKEN_KEY; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java index f7ca5c007b9..32ab016af43 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import java.util.ArrayList; import java.util.HashMap; @@ -60,7 +61,7 @@ public static URL parseURL(String address, Map defaults) { } backup.append(addresses[i]); } - url += URL_PARAM_STARTING_SYMBOL + Constants.BACKUP_KEY + "=" + backup.toString(); + url += URL_PARAM_STARTING_SYMBOL + RemotingConstants.BACKUP_KEY + "=" + backup.toString(); } } String defaultProtocol = defaults == null ? null : defaults.get(Constants.PROTOCOL_KEY); @@ -468,12 +469,12 @@ public static boolean isProvider(URL url) { } public static int getHeartbeat(URL url) { - return url.getParameter(Constants.HEARTBEAT_KEY, Constants.DEFAULT_HEARTBEAT); + return url.getParameter(RemotingConstants.HEARTBEAT_KEY, RemotingConstants.DEFAULT_HEARTBEAT); } public static int getIdleTimeout(URL url) { int heartBeat = getHeartbeat(url); - int idleTimeout = url.getParameter(Constants.HEARTBEAT_TIMEOUT_KEY, heartBeat * 3); + int idleTimeout = url.getParameter(RemotingConstants.HEARTBEAT_TIMEOUT_KEY, heartBeat * 3); if (idleTimeout < heartBeat * 2) { throw new IllegalStateException("idleTimeout < heartbeatInterval * 2"); } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java index cf490ed4079..75281e965e1 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java @@ -17,6 +17,7 @@ package org.apache.dubbo.config; import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.config.support.Parameter; import org.apache.dubbo.rpc.InvokerListener; import org.apache.dubbo.rpc.support.ProtocolUtils; @@ -179,7 +180,7 @@ public Boolean getStubevent() { return stubevent; } - @Parameter(key = Constants.RECONNECT_KEY) + @Parameter(key = RemotingConstants.RECONNECT_KEY) public String getReconnect() { return reconnect; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java index 008f7bf03fb..4cb2f7dcdd7 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java @@ -17,6 +17,7 @@ package org.apache.dubbo.config; import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.common.status.StatusChecker; @@ -318,7 +319,7 @@ public String getCodec() { public void setCodec(String codec) { if (Constants.DUBBO_PROTOCOL.equals(name)) { - checkMultiExtension(Codec.class, Constants.CODEC_KEY, codec); + checkMultiExtension(Codec.class, RemotingConstants.CODEC_KEY, codec); } this.codec = codec; } @@ -329,7 +330,7 @@ public String getSerialization() { public void setSerialization(String serialization) { if (Constants.DUBBO_PROTOCOL.equals(name)) { - checkMultiExtension(Serialization.class, Constants.SERIALIZATION_KEY, serialization); + checkMultiExtension(Serialization.class, RemotingConstants.SERIALIZATION_KEY, serialization); } this.serialization = serialization; } @@ -372,7 +373,7 @@ public String getServer() { public void setServer(String server) { if (Constants.DUBBO_PROTOCOL.equals(name)) { - checkMultiExtension(Transporter.class, Constants.SERVER_KEY, server); + checkMultiExtension(Transporter.class, RemotingConstants.SERVER_KEY, server); } this.server = server; } @@ -383,7 +384,7 @@ public String getClient() { public void setClient(String client) { if (Constants.DUBBO_PROTOCOL.equals(name)) { - checkMultiExtension(Transporter.class, Constants.CLIENT_KEY, client); + checkMultiExtension(Transporter.class, RemotingConstants.CLIENT_KEY, client); } this.client = client; } @@ -436,7 +437,7 @@ public String getTransporter() { } public void setTransporter(String transporter) { - checkExtension(Transporter.class, Constants.TRANSPORTER_KEY, transporter); + checkExtension(Transporter.class, RemotingConstants.TRANSPORTER_KEY, transporter); this.transporter = transporter; } @@ -445,7 +446,7 @@ public String getExchanger() { } public void setExchanger(String exchanger) { - checkExtension(Exchanger.class, Constants.EXCHANGER_KEY, exchanger); + checkExtension(Exchanger.class, RemotingConstants.EXCHANGER_KEY, exchanger); this.exchanger = exchanger; } @@ -475,7 +476,7 @@ public String getDispatcher() { } public void setDispatcher(String dispatcher) { - checkExtension(Dispatcher.class, Constants.DISPACTHER_KEY, dispatcher); + checkExtension(Dispatcher.class, RemotingConstants.DISPACTHER_KEY, dispatcher); this.dispatcher = dispatcher; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProviderConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProviderConfig.java index 58e9748d312..b76ab7958fb 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProviderConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProviderConfig.java @@ -17,6 +17,7 @@ package org.apache.dubbo.config; import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.status.StatusChecker; import org.apache.dubbo.common.threadpool.ThreadPool; import org.apache.dubbo.config.support.Parameter; @@ -367,7 +368,7 @@ public String getTransporter() { } public void setTransporter(String transporter) { - checkExtension(Transporter.class, Constants.TRANSPORTER_KEY, transporter); + checkExtension(Transporter.class, RemotingConstants.TRANSPORTER_KEY, transporter); this.transporter = transporter; } @@ -376,7 +377,7 @@ public String getExchanger() { } public void setExchanger(String exchanger) { - checkExtension(Exchanger.class, Constants.EXCHANGER_KEY, exchanger); + checkExtension(Exchanger.class, RemotingConstants.EXCHANGER_KEY, exchanger); this.exchanger = exchanger; } @@ -406,7 +407,7 @@ public String getDispatcher() { } public void setDispatcher(String dispatcher) { - checkExtension(Dispatcher.class, Constants.DISPATCHER_KEY, dispatcher); + checkExtension(Dispatcher.class, RemotingConstants.DISPATCHER_KEY, dispatcher); checkExtension(Dispatcher.class, "dispather", dispatcher); this.dispatcher = dispatcher; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java index 5ecae9c0519..32f5dd14dcd 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java @@ -20,6 +20,7 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.bytecode.Wrapper; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.CollectionUtils; @@ -561,7 +562,7 @@ public String getClient() { } public void setClient(String client) { - checkName(Constants.CLIENT_KEY, client); + checkName(RemotingConstants.CLIENT_KEY, client); this.client = client; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java index 994518795f1..bb72e218e85 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java @@ -17,6 +17,7 @@ package org.apache.dubbo.config; import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.support.Parameter; @@ -269,7 +270,7 @@ public String getTransporter() { } public void setTransporter(String transporter) { - checkName(Constants.TRANSPORTER_KEY, transporter); + checkName(RemotingConstants.TRANSPORTER_KEY, transporter); /*if(transporter != null && transporter.length() > 0 && ! ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(transporter)){ throw new IllegalStateException("No such transporter type : " + transporter); }*/ @@ -281,7 +282,7 @@ public String getServer() { } public void setServer(String server) { - checkName(Constants.SERVER_KEY, server); + checkName(RemotingConstants.SERVER_KEY, server); /*if(server != null && server.length() > 0 && ! ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(server)){ throw new IllegalStateException("No such server type : " + server); }*/ @@ -293,7 +294,7 @@ public String getClient() { } public void setClient(String client) { - checkName(Constants.CLIENT_KEY, client); + checkName(RemotingConstants.CLIENT_KEY, client); /*if(client != null && client.length() > 0 && ! ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(client)){ throw new IllegalStateException("No such client type : " + client); }*/ diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index 86c5ed45f9a..0c755b475bf 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -22,6 +22,7 @@ import org.apache.dubbo.common.Version; import org.apache.dubbo.common.bytecode.Wrapper; import org.apache.dubbo.common.config.Environment; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.CollectionUtils; @@ -684,7 +685,7 @@ private String findConfigedHosts(ProtocolConfig protocolConfig, List regist } } - map.put(Constants.BIND_IP_KEY, hostToBind); + map.put(RemotingConstants.BIND_IP_KEY, hostToBind); // registry ip is not used for bind ip by default String hostToRegistry = getValueFromConfig(protocolConfig, Constants.DUBBO_IP_TO_REGISTRY); @@ -736,7 +737,7 @@ private Integer findConfigedPorts(ProtocolConfig protocolConfig, String name, Ma } // save bind port, used as url's key later - map.put(Constants.BIND_PORT_KEY, String.valueOf(portToBind)); + map.put(RemotingConstants.BIND_PORT_KEY, String.valueOf(portToBind)); // registry port, not used as bind port by default String portToRegistryStr = getValueFromConfig(protocolConfig, Constants.DUBBO_PORT_TO_REGISTRY); diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java index c4851bd1031..5b22abdbc9b 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java @@ -17,6 +17,7 @@ package org.apache.dubbo.config.annotation; import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.rpc.ExporterListener; import org.apache.dubbo.rpc.Filter; @@ -101,7 +102,7 @@ * Whether to reconnect if connection is lost, if not specify, reconnect is enabled by default, and the interval * for retry connecting is 2000 ms * - * @see Constants#DEFAULT_RECONNECT_PERIOD + * @see RemotingConstants#DEFAULT_RECONNECT_PERIOD */ String reconnect() default ""; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java index c77d3fde823..92985b20f7b 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java @@ -19,6 +19,7 @@ import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.RemotingConstants; import org.junit.jupiter.api.Test; import java.util.HashMap; @@ -125,7 +126,7 @@ public void testReconnect() throws Exception { Map parameters = new HashMap(); AbstractInterfaceConfig.appendParameters(parameters, referenceConfig); assertThat(referenceConfig.getReconnect(), equalTo("reconnect")); - assertThat(parameters, hasKey(Constants.RECONNECT_KEY)); + assertThat(parameters, hasKey(RemotingConstants.RECONNECT_KEY)); } @Test diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java index 2dff18b5af5..3a54f30c5ff 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java @@ -19,6 +19,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.config.api.DemoService; import org.apache.dubbo.config.api.Greeting; import org.apache.dubbo.config.context.ConfigManager; @@ -132,8 +133,8 @@ public void testExport() throws Exception { assertThat(url.getPath(), equalTo(DemoService.class.getName())); assertThat(url.getParameters(), hasEntry(Constants.ANYHOST_KEY, "true")); assertThat(url.getParameters(), hasEntry(Constants.APPLICATION_KEY, "app")); - assertThat(url.getParameters(), hasKey(Constants.BIND_IP_KEY)); - assertThat(url.getParameters(), hasKey(Constants.BIND_PORT_KEY)); + assertThat(url.getParameters(), hasKey(RemotingConstants.BIND_IP_KEY)); + assertThat(url.getParameters(), hasKey(RemotingConstants.BIND_PORT_KEY)); assertThat(url.getParameters(), hasEntry(Constants.EXPORT_KEY, "true")); assertThat(url.getParameters(), hasEntry("echo.0.callback", "false")); assertThat(url.getParameters(), hasEntry(Constants.GENERIC_KEY, "false")); diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java index fdb536fa8a3..2d63c99ec29 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java @@ -44,7 +44,7 @@ import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; import static com.alibaba.nacos.api.PropertyKeyConst.NAMESPACE; import static com.alibaba.nacos.client.naming.utils.UtilAndComs.NACOS_NAMING_LOG_NAME; -import static org.apache.dubbo.common.Constants.BACKUP_KEY; +import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; import static org.apache.dubbo.common.Constants.CONFIG_NAMESPACE_KEY; import static org.apache.dubbo.common.Constants.GROUP_CHAR_SEPERATOR; import static org.apache.dubbo.common.Constants.PROPERTIES_CHAR_SEPERATOR; diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/MetadataReportService.java b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/MetadataReportService.java index f2428f9fe9e..832dac62fe8 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/MetadataReportService.java +++ b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/MetadataReportService.java @@ -19,6 +19,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -78,7 +79,7 @@ public static MetadataReportService instance(Supplier metadataReportUrl) { public void publishProvider(URL providerUrl) throws RpcException { //first add into the list // remove the individul param - providerUrl = providerUrl.removeParameters(Constants.PID_KEY, Constants.TIMESTAMP_KEY, Constants.BIND_IP_KEY, Constants.BIND_PORT_KEY, Constants.TIMESTAMP_KEY); + providerUrl = providerUrl.removeParameters(Constants.PID_KEY, Constants.TIMESTAMP_KEY, RemotingConstants.BIND_IP_KEY, RemotingConstants.BIND_PORT_KEY, Constants.TIMESTAMP_KEY); try { String interfaceName = providerUrl.getParameter(Constants.INTERFACE_KEY); @@ -98,7 +99,7 @@ public void publishProvider(URL providerUrl) throws RpcException { } public void publishConsumer(URL consumerURL) throws RpcException { - consumerURL = consumerURL.removeParameters(Constants.PID_KEY, Constants.TIMESTAMP_KEY, Constants.BIND_IP_KEY, Constants.BIND_PORT_KEY, Constants.TIMESTAMP_KEY); + consumerURL = consumerURL.removeParameters(Constants.PID_KEY, Constants.TIMESTAMP_KEY, RemotingConstants.BIND_IP_KEY, RemotingConstants.BIND_PORT_KEY, Constants.TIMESTAMP_KEY); metadataReport.storeConsumerMetadata(new MetadataIdentifier(consumerURL.getServiceInterface(), consumerURL.getParameter(Constants.VERSION_KEY), consumerURL.getParameter(Constants.GROUP_KEY),Constants.CONSUMER_SIDE, consumerURL.getParameter(Constants.APPLICATION_KEY)), consumerURL.getParameters()); diff --git a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java index 2c80bc4e5b5..5d73112bfd4 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java +++ b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java @@ -26,7 +26,7 @@ import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; -import static org.apache.dubbo.common.Constants.CHECK_KEY; +import static org.apache.dubbo.common.constants.RemotingConstants.CHECK_KEY; import static org.apache.dubbo.common.Constants.DUBBO_PROTOCOL; import static org.apache.dubbo.common.Constants.PROTOCOL_KEY; import static org.apache.dubbo.common.Constants.REFERENCE_FILTER_KEY; diff --git a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java index 90544aaf8a1..a05c510de71 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java +++ b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java @@ -28,6 +28,7 @@ import com.alibaba.metrics.common.MetricsCollectorFactory; import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -165,7 +166,7 @@ private void setCompassQuantity(String groupName, String result, long duration, private List getThreadPoolMessage() { DataStore dataStore = ExtensionLoader.getExtensionLoader(DataStore.class).getDefaultExtension(); - Map executors = dataStore.get(Constants.EXECUTOR_SERVICE_COMPONENT_KEY); + Map executors = dataStore.get(RemotingConstants.EXECUTOR_SERVICE_COMPONENT_KEY); List threadPoolMtricList = new ArrayList<>(); for (Map.Entry entry : executors.entrySet()) { diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java index 54bb0068a3e..9538742ede1 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java @@ -20,6 +20,7 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.Version; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -432,7 +433,7 @@ private URL mergeUrl(URL providerUrl) { providerUrl = overrideWithConfigurator(providerUrl); - providerUrl = providerUrl.addParameter(Constants.CHECK_KEY, String.valueOf(false)); // Do not check whether the connection is successful or not, always create Invoker! + providerUrl = providerUrl.addParameter(RemotingConstants.CHECK_KEY, String.valueOf(false)); // Do not check whether the connection is successful or not, always create Invoker! // The combination of directoryUrl and override is at the end of notify, which can't be handled here this.overrideDirectoryUrl = this.overrideDirectoryUrl.addParametersIfAbsent(providerUrl.getParameters()); // Merge the provider side parameters diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java index 6c5870bd47e..b1b3393b1cf 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java @@ -55,10 +55,10 @@ import static java.util.concurrent.Executors.newSingleThreadExecutor; import static org.apache.dubbo.common.Constants.ACCEPT_FOREIGN_IP; import static org.apache.dubbo.common.Constants.ANY_VALUE; -import static org.apache.dubbo.common.Constants.BIND_IP_KEY; -import static org.apache.dubbo.common.Constants.BIND_PORT_KEY; +import static org.apache.dubbo.common.constants.RemotingConstants.BIND_IP_KEY; +import static org.apache.dubbo.common.constants.RemotingConstants.BIND_PORT_KEY; import static org.apache.dubbo.common.Constants.CATEGORY_KEY; -import static org.apache.dubbo.common.Constants.CHECK_KEY; +import static org.apache.dubbo.common.constants.RemotingConstants.CHECK_KEY; import static org.apache.dubbo.common.Constants.COMMA_SPLIT_PATTERN; import static org.apache.dubbo.common.Constants.CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.Constants.CONFIGURATORS_SUFFIX; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java index cbf1527231f..1132ad8b60f 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.timer.HashedWheelTimer; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.NamedThreadFactory; @@ -233,8 +234,8 @@ public void register(URL url) { Throwable t = e; // If the startup detection is opened, the Exception is thrown directly. - boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) - && url.getParameter(Constants.CHECK_KEY, true) + boolean check = getUrl().getParameter(RemotingConstants.CHECK_KEY, true) + && url.getParameter(RemotingConstants.CHECK_KEY, true) && !Constants.CONSUMER_PROTOCOL.equals(url.getProtocol()); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { @@ -263,8 +264,8 @@ public void unregister(URL url) { Throwable t = e; // If the startup detection is opened, the Exception is thrown directly. - boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) - && url.getParameter(Constants.CHECK_KEY, true) + boolean check = getUrl().getParameter(RemotingConstants.CHECK_KEY, true) + && url.getParameter(RemotingConstants.CHECK_KEY, true) && !Constants.CONSUMER_PROTOCOL.equals(url.getProtocol()); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { @@ -297,8 +298,8 @@ public void subscribe(URL url, NotifyListener listener) { logger.error("Failed to subscribe " + url + ", Using cached list: " + urls + " from cache file: " + getUrl().getParameter(Constants.FILE_KEY, System.getProperty("user.home") + "/dubbo-registry-" + url.getHost() + ".cache") + ", cause: " + t.getMessage(), t); } else { // If the startup detection is opened, the Exception is thrown directly. - boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) - && url.getParameter(Constants.CHECK_KEY, true); + boolean check = getUrl().getParameter(RemotingConstants.CHECK_KEY, true) + && url.getParameter(RemotingConstants.CHECK_KEY, true); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { @@ -326,8 +327,8 @@ public void unsubscribe(URL url, NotifyListener listener) { Throwable t = e; // If the startup detection is opened, the Exception is thrown directly. - boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) - && url.getParameter(Constants.CHECK_KEY, true); + boolean check = getUrl().getParameter(RemotingConstants.CHECK_KEY, true) + && url.getParameter(RemotingConstants.CHECK_KEY, true); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { diff --git a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistry.java b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistry.java index c936d2979be..05c785a7e23 100644 --- a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistry.java +++ b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistry.java @@ -19,6 +19,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ExecutorUtil; @@ -100,7 +101,7 @@ protected final void connect() { clientLock.unlock(); } } catch (Throwable t) { // Ignore all the exceptions and wait for the next retry - if (getUrl().getParameter(Constants.CHECK_KEY, true)) { + if (getUrl().getParameter(RemotingConstants.CHECK_KEY, true)) { if (t instanceof RuntimeException) { throw (RuntimeException) t; } diff --git a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java index ee331c83186..c199774b391 100644 --- a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java +++ b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java @@ -20,6 +20,7 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.bytecode.Wrapper; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.registry.Registry; @@ -54,10 +55,10 @@ private static URL getRegistryURL(URL url) { .addParameter(Constants.INTERFACE_KEY, RegistryService.class.getName()) .addParameter(Constants.CLUSTER_STICKY_KEY, "true") .addParameter(Constants.LAZY_CONNECT_KEY, "true") - .addParameter(Constants.RECONNECT_KEY, "false") + .addParameter(RemotingConstants.RECONNECT_KEY, "false") .addParameterIfAbsent(Constants.TIMEOUT_KEY, "10000") .addParameterIfAbsent(Constants.CALLBACK_INSTANCES_LIMIT_KEY, "10000") - .addParameterIfAbsent(Constants.CONNECT_TIMEOUT_KEY, "10000") + .addParameterIfAbsent(RemotingConstants.CONNECT_TIMEOUT_KEY, "10000") .addParameter(Constants.METHODS_KEY, StringUtils.join(new HashSet<>(Arrays.asList(Wrapper.getWrapper(RegistryService.class).getDeclaredMethodNames())), ",")) //.addParameter(Constants.STUB_KEY, RegistryServiceStub.class.getName()) //.addParameter(Constants.STUB_EVENT_KEY, Boolean.TRUE.toString()) //for event dispatch @@ -83,8 +84,8 @@ public void setCluster(Cluster cluster) { public Registry createRegistry(URL url) { url = getRegistryURL(url); List urls = new ArrayList<>(); - urls.add(url.removeParameter(Constants.BACKUP_KEY)); - String backup = url.getParameter(Constants.BACKUP_KEY); + urls.add(url.removeParameter(RemotingConstants.BACKUP_KEY)); + String backup = url.getParameter(RemotingConstants.BACKUP_KEY); if (backup != null && backup.length() > 0) { String[] addresses = Constants.COMMA_SPLIT_PATTERN.split(backup); for (String address : addresses) { diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DubboRegistryTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DubboRegistryTest.java index 3a317785a09..336383f5c99 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DubboRegistryTest.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DubboRegistryTest.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NetUtils; @@ -55,10 +56,10 @@ public class DubboRegistryTest { @BeforeEach public void setUp() { registryURL = new URL(Constants.REGISTRY_PROTOCOL, NetUtils.getLocalHost(), NetUtils.getAvailablePort()) - .addParameter(Constants.CHECK_KEY, false) + .addParameter(RemotingConstants.CHECK_KEY, false) .setServiceInterface(RegistryService.class.getName()); serviceURL = new URL(DubboProtocol.NAME, NetUtils.getLocalHost(), NetUtils.getAvailablePort()) - .addParameter(Constants.CHECK_KEY, false) + .addParameter(RemotingConstants.CHECK_KEY, false) .setServiceInterface(RegistryService.class.getName()); registryService = new MockDubboRegistry(registryURL); diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java index 7d672097596..e6911fd8347 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.LogUtil; import org.apache.dubbo.common.utils.NetUtils; @@ -371,7 +372,7 @@ public void testParametersMerge() { Invoker invoker = (Invoker) invokers.get(0); URL url = invoker.getUrl(); - Assertions.assertEquals(false, url.getParameter(Constants.CHECK_KEY, false)); + Assertions.assertEquals(false, url.getParameter(RemotingConstants.CHECK_KEY, false)); } { serviceUrls.clear(); diff --git a/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistry.java b/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistry.java index f0516c37989..1f70044c164 100644 --- a/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistry.java +++ b/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistry.java @@ -34,6 +34,7 @@ package org.apache.dubbo.registry.etcd; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConcurrentHashSet; @@ -179,7 +180,7 @@ public void doSubscribe(URL url, NotifyListener listener) { * eg: /dubbo/interface, /dubbo/interface and so on. */ subscribe(url.setPath(child).addParameters(Constants.INTERFACE_KEY, child, - Constants.CHECK_KEY, String.valueOf(false)), listener); + RemotingConstants.CHECK_KEY, String.valueOf(false)), listener); } } }); @@ -196,7 +197,7 @@ public void doSubscribe(URL url, NotifyListener listener) { service = URL.decode(service); anyServices.add(service); subscribe(url.setPath(service).addParameters(Constants.INTERFACE_KEY, service, - Constants.CHECK_KEY, String.valueOf(false)), listener); + RemotingConstants.CHECK_KEY, String.valueOf(false)), listener); } } else { List urls = new ArrayList<>(); diff --git a/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java b/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java index c23c1d23a0a..7de75411791 100644 --- a/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java +++ b/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java @@ -52,6 +52,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.registry.NotifyListener; @@ -95,7 +96,7 @@ public class EtcdRegistryTest { + Constants.ROUTERS_CATEGORY + "," + Constants.CONFIGURATORS_CATEGORY, Constants.ENABLED_KEY, Constants.ANY_VALUE, - Constants.CHECK_KEY, String.valueOf(false)); + RemotingConstants.CHECK_KEY, String.valueOf(false)); @Test public void test_register() { diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistryFactory.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistryFactory.java index 52dcd112be6..d0e508d4533 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistryFactory.java +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistryFactory.java @@ -37,7 +37,7 @@ import static com.alibaba.nacos.api.PropertyKeyConst.SECRET_KEY; import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; import static com.alibaba.nacos.client.naming.utils.UtilAndComs.NACOS_NAMING_LOG_NAME; -import static org.apache.dubbo.common.Constants.BACKUP_KEY; +import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; /** * Nacos {@link RegistryFactory} diff --git a/dubbo-registry/dubbo-registry-redis/src/main/java/org/apache/dubbo/registry/redis/RedisRegistry.java b/dubbo-registry/dubbo-registry-redis/src/main/java/org/apache/dubbo/registry/redis/RedisRegistry.java index b693842eb91..5303ddc495a 100644 --- a/dubbo-registry/dubbo-registry-redis/src/main/java/org/apache/dubbo/registry/redis/RedisRegistry.java +++ b/dubbo-registry/dubbo-registry-redis/src/main/java/org/apache/dubbo/registry/redis/RedisRegistry.java @@ -20,6 +20,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ArrayUtils; @@ -125,7 +126,7 @@ public RedisRegistry(URL url) { List addresses = new ArrayList<>(); addresses.add(url.getAddress()); - String[] backups = url.getParameter(Constants.BACKUP_KEY, new String[0]); + String[] backups = url.getParameter(RemotingConstants.BACKUP_KEY, new String[0]); if (ArrayUtils.isNotEmpty(backups)) { addresses.addAll(Arrays.asList(backups)); } diff --git a/dubbo-registry/dubbo-registry-redis/src/test/java/org/apache/dubbo/registry/redis/RedisRegistryTest.java b/dubbo-registry/dubbo-registry-redis/src/test/java/org/apache/dubbo/registry/redis/RedisRegistryTest.java index 44650cef722..0cc1c3126a3 100644 --- a/dubbo-registry/dubbo-registry-redis/src/test/java/org/apache/dubbo/registry/redis/RedisRegistryTest.java +++ b/dubbo-registry/dubbo-registry-redis/src/test/java/org/apache/dubbo/registry/redis/RedisRegistryTest.java @@ -31,7 +31,7 @@ import java.util.Map; import java.util.Set; -import static org.apache.dubbo.common.Constants.BACKUP_KEY; +import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.java index 1c3eb27e982..102d5881af2 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.java @@ -19,6 +19,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; @@ -131,7 +132,7 @@ public void doSubscribe(final URL url, final NotifyListener listener) { if (!anyServices.contains(child)) { anyServices.add(child); subscribe(url.setPath(child).addParameters(Constants.INTERFACE_KEY, child, - Constants.CHECK_KEY, String.valueOf(false)), listener); + RemotingConstants.CHECK_KEY, String.valueOf(false)), listener); } } }); @@ -144,7 +145,7 @@ public void doSubscribe(final URL url, final NotifyListener listener) { service = URL.decode(service); anyServices.add(service); subscribe(url.setPath(service).addParameters(Constants.INTERFACE_KEY, service, - Constants.CHECK_KEY, String.valueOf(false)), listener); + RemotingConstants.CHECK_KEY, String.valueOf(false)), listener); } } } else { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec.java index ed2261d6126..d40d4a27215 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.remoting; -import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.SPI; @@ -45,7 +45,7 @@ public interface Codec { * @param output output stream. * @param message message. */ - @Adaptive({Constants.CODEC_KEY}) + @Adaptive({RemotingConstants.CODEC_KEY}) void encode(Channel channel, OutputStream output, Object message) throws IOException; /** @@ -56,7 +56,7 @@ public interface Codec { * @return message or NEED_MORE_INPUT poison. * @see #NEED_MORE_INPUT */ - @Adaptive({Constants.CODEC_KEY}) + @Adaptive({RemotingConstants.CODEC_KEY}) Object decode(Channel channel, InputStream input) throws IOException; } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec2.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec2.java index 2adfe477efb..7d6770b5fb5 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec2.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec2.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.remoting; -import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.remoting.buffer.ChannelBuffer; @@ -26,10 +26,10 @@ @SPI public interface Codec2 { - @Adaptive({Constants.CODEC_KEY}) + @Adaptive({RemotingConstants.CODEC_KEY}) void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException; - @Adaptive({Constants.CODEC_KEY}) + @Adaptive({RemotingConstants.CODEC_KEY}) Object decode(Channel channel, ChannelBuffer buffer) throws IOException; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Dispatcher.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Dispatcher.java index 2fd3133a5dc..201b0979c35 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Dispatcher.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Dispatcher.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.remoting; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.remoting.transport.dispatcher.all.AllDispatcher; @@ -35,7 +35,7 @@ public interface Dispatcher { * @param url * @return channel handler */ - @Adaptive({Constants.DISPATCHER_KEY, "dispather", "channel.handler"}) + @Adaptive({RemotingConstants.DISPATCHER_KEY, "dispather", "channel.handler"}) // The last two parameters are reserved for compatibility with the old configuration ChannelHandler dispatch(ChannelHandler handler, URL url); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Transporter.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Transporter.java index 33ac2bedd3f..6493ac51056 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Transporter.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Transporter.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.remoting; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.SPI; @@ -41,7 +41,7 @@ public interface Transporter { * @throws RemotingException * @see org.apache.dubbo.remoting.Transporters#bind(URL, ChannelHandler...) */ - @Adaptive({Constants.SERVER_KEY, Constants.TRANSPORTER_KEY}) + @Adaptive({RemotingConstants.SERVER_KEY, RemotingConstants.TRANSPORTER_KEY}) Server bind(URL url, ChannelHandler handler) throws RemotingException; /** @@ -53,7 +53,7 @@ public interface Transporter { * @throws RemotingException * @see org.apache.dubbo.remoting.Transporters#connect(URL, ChannelHandler...) */ - @Adaptive({Constants.CLIENT_KEY, Constants.TRANSPORTER_KEY}) + @Adaptive({RemotingConstants.CLIENT_KEY, RemotingConstants.TRANSPORTER_KEY}) Client connect(URL url, ChannelHandler handler) throws RemotingException; } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchanger.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchanger.java index 6f1ef5e6288..8c46273fff0 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchanger.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchanger.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.remoting.exchange; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.remoting.RemotingException; @@ -39,7 +39,7 @@ public interface Exchanger { * @param handler * @return message server */ - @Adaptive({Constants.EXCHANGER_KEY}) + @Adaptive({RemotingConstants.EXCHANGER_KEY}) ExchangeServer bind(URL url, ExchangeHandler handler) throws RemotingException; /** @@ -49,7 +49,7 @@ public interface Exchanger { * @param handler * @return message channel */ - @Adaptive({Constants.EXCHANGER_KEY}) + @Adaptive({RemotingConstants.EXCHANGER_KEY}) ExchangeClient connect(URL url, ExchangeHandler handler) throws RemotingException; } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchangers.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchangers.java index 073e18c7c0c..c3fc864b514 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchangers.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchangers.java @@ -16,9 +16,9 @@ */ package org.apache.dubbo.remoting.exchange; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; @@ -66,7 +66,7 @@ public static ExchangeServer bind(URL url, ExchangeHandler handler) throws Remot if (handler == null) { throw new IllegalArgumentException("handler == null"); } - url = url.addParameterIfAbsent(Constants.CODEC_KEY, "exchange"); + url = url.addParameterIfAbsent(RemotingConstants.CODEC_KEY, "exchange"); return getExchanger(url).bind(url, handler); } @@ -105,12 +105,12 @@ public static ExchangeClient connect(URL url, ExchangeHandler handler) throws Re if (handler == null) { throw new IllegalArgumentException("handler == null"); } - url = url.addParameterIfAbsent(Constants.CODEC_KEY, "exchange"); + url = url.addParameterIfAbsent(RemotingConstants.CODEC_KEY, "exchange"); return getExchanger(url).connect(url, handler); } public static Exchanger getExchanger(URL url) { - String type = url.getParameter(Constants.EXCHANGER_KEY, Constants.DEFAULT_EXCHANGER); + String type = url.getParameter(RemotingConstants.EXCHANGER_KEY, RemotingConstants.DEFAULT_EXCHANGER); return getExchanger(type); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java index 3e57fba90c4..944daac3079 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.remoting.exchange.support.header; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.timer.HashedWheelTimer; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.NamedThreadFactory; @@ -45,7 +45,7 @@ public class HeaderExchangeClient implements ExchangeClient { private final ExchangeChannel channel; private static final HashedWheelTimer IDLE_CHECK_TIMER = new HashedWheelTimer( - new NamedThreadFactory("dubbo-client-idleCheck", true), 1, TimeUnit.SECONDS, Constants.TICKS_PER_WHEEL); + new NamedThreadFactory("dubbo-client-idleCheck", true), 1, TimeUnit.SECONDS, RemotingConstants.TICKS_PER_WHEEL); private HeartbeatTimerTask heartBeatTimerTask; private ReconnectTimerTask reconnectTimerTask; @@ -206,15 +206,15 @@ private void doClose() { * Each interval cannot be less than 1000ms. */ private long calculateLeastDuration(int time) { - if (time / Constants.HEARTBEAT_CHECK_TICK <= 0) { - return Constants.LEAST_HEARTBEAT_DURATION; + if (time / RemotingConstants.HEARTBEAT_CHECK_TICK <= 0) { + return RemotingConstants.LEAST_HEARTBEAT_DURATION; } else { - return time / Constants.HEARTBEAT_CHECK_TICK; + return time / RemotingConstants.HEARTBEAT_CHECK_TICK; } } private boolean shouldReconnect(URL url) { - return url.getParameter(Constants.RECONNECT_KEY, true); + return url.getParameter(RemotingConstants.RECONNECT_KEY, true); } @Override diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java index 6f342f997c0..0b19d6afe31 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.remoting.exchange.support.header; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NetUtils; @@ -73,7 +73,7 @@ private static boolean isClientSide(Channel channel) { void handlerEvent(Channel channel, Request req) throws RemotingException { if (req.getData() != null && req.getData().equals(Request.READONLY_EVENT)) { - channel.setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); + channel.setAttribute(RemotingConstants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java index 8a74e234134..be52d6d601e 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java @@ -16,9 +16,9 @@ */ package org.apache.dubbo.remoting.exchange.support.header; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.timer.HashedWheelTimer; @@ -53,7 +53,7 @@ public class HeaderExchangeServer implements ExchangeServer { private AtomicBoolean closed = new AtomicBoolean(false); private static final HashedWheelTimer IDLE_CHECK_TIMER = new HashedWheelTimer(new NamedThreadFactory("dubbo-server-idleCheck", true), 1, - TimeUnit.SECONDS, Constants.TICKS_PER_WHEEL); + TimeUnit.SECONDS, RemotingConstants.TICKS_PER_WHEEL); private CloseTimerTask closeTimerTask; @@ -100,7 +100,7 @@ public void close(final int timeout) { if (timeout > 0) { final long max = (long) timeout; final long start = System.currentTimeMillis(); - if (getUrl().getParameter(Constants.CHANNEL_SEND_READONLYEVENT_KEY, true)) { + if (getUrl().getParameter(RemotingConstants.CHANNEL_SEND_READONLYEVENT_KEY, true)) { sendChannelReadOnlyEvent(); } while (HeaderExchangeServer.this.isRunning() @@ -131,7 +131,7 @@ private void sendChannelReadOnlyEvent() { for (Channel channel : channels) { try { if (channel.isConnected()) { - channel.send(request, getUrl().getParameter(Constants.CHANNEL_READONLYEVENT_SENT_KEY, true)); + channel.send(request, getUrl().getParameter(RemotingConstants.CHANNEL_READONLYEVENT_SENT_KEY, true)); } } catch (RemotingException e) { logger.warn("send cannot write message error.", e); @@ -246,10 +246,10 @@ public void send(Object message, boolean sent) throws RemotingException { * Each interval cannot be less than 1000ms. */ private long calculateLeastDuration(int time) { - if (time / Constants.HEARTBEAT_CHECK_TICK <= 0) { - return Constants.LEAST_HEARTBEAT_DURATION; + if (time / RemotingConstants.HEARTBEAT_CHECK_TICK <= 0) { + return RemotingConstants.LEAST_HEARTBEAT_DURATION; } else { - return time / Constants.HEARTBEAT_CHECK_TICK; + return time / RemotingConstants.HEARTBEAT_CHECK_TICK; } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandler.java index 71068714368..87d912187ea 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandler.java @@ -17,7 +17,7 @@ package org.apache.dubbo.remoting.exchange.support.header; -import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.Channel; @@ -69,7 +69,7 @@ public void received(Channel channel, Object message) throws RemotingException { res.setEvent(Response.HEARTBEAT_EVENT); channel.send(res); if (logger.isInfoEnabled()) { - int heartbeat = channel.getUrl().getParameter(Constants.HEARTBEAT_KEY, 0); + int heartbeat = channel.getUrl().getParameter(RemotingConstants.HEARTBEAT_KEY, 0); if (logger.isDebugEnabled()) { logger.debug("Received heartbeat from remote channel " + channel.getRemoteAddress() + ", cause: The channel has no data-transmission exceeds a heartbeat period" diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/codec/TelnetCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/codec/TelnetCodec.java index ce481fc8519..b34ee153692 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/codec/TelnetCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/codec/TelnetCodec.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.remoting.telnet.codec; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; @@ -60,7 +60,7 @@ public class TelnetCodec extends TransportCodec { private static Charset getCharset(Channel channel) { if (channel != null) { - Object attribute = channel.getAttribute(Constants.CHARSET_KEY); + Object attribute = channel.getAttribute(RemotingConstants.CHARSET_KEY); if (attribute instanceof String) { try { return Charset.forName((String) attribute); @@ -72,7 +72,7 @@ private static Charset getCharset(Channel channel) { } URL url = channel.getUrl(); if (url != null) { - String parameter = url.getParameter(Constants.CHARSET_KEY); + String parameter = url.getParameter(RemotingConstants.CHARSET_KEY); if (StringUtils.isNotEmpty(parameter)) { try { return Charset.forName(parameter); @@ -83,7 +83,7 @@ private static Charset getCharset(Channel channel) { } } try { - return Charset.forName(Constants.DEFAULT_CHARSET); + return Charset.forName(RemotingConstants.DEFAULT_CHARSET); } catch (Throwable t) { logger.warn(t.getMessage(), t); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java index 66418f3b573..89a781c5bef 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; @@ -31,7 +32,7 @@ public class TelnetHandlerAdapter extends ChannelHandlerAdapter implements Telne @Override public String telnet(Channel channel, String message) throws RemotingException { - String prompt = channel.getUrl().getParameterAndDecoded(Constants.PROMPT_KEY, Constants.DEFAULT_PROMPT); + String prompt = channel.getUrl().getParameterAndDecoded(RemotingConstants.PROMPT_KEY, RemotingConstants.DEFAULT_PROMPT); boolean noprompt = message.contains("--no-prompt"); message = message.replace("--no-prompt", ""); StringBuilder buf = new StringBuilder(); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractClient.java index dd02651e018..aa10dd819f5 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractClient.java @@ -19,6 +19,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -50,7 +51,7 @@ public abstract class AbstractClient extends AbstractEndpoint implements Client public AbstractClient(URL url, ChannelHandler handler) throws RemotingException { super(url, handler); - needReconnect = url.getParameter(Constants.SEND_RECONNECT_KEY, false); + needReconnect = url.getParameter(RemotingConstants.SEND_RECONNECT_KEY, false); try { doOpen(); @@ -67,7 +68,7 @@ public AbstractClient(URL url, ChannelHandler handler) throws RemotingException logger.info("Start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() + " connect to the server " + getRemoteAddress()); } } catch (RemotingException t) { - if (url.getParameter(Constants.CHECK_KEY, true)) { + if (url.getParameter(RemotingConstants.CHECK_KEY, true)) { close(); throw t; } else { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractCodec.java index 5269d2c571c..346f54ca320 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractCodec.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.Serialization; @@ -36,9 +37,9 @@ public abstract class AbstractCodec implements Codec2 { private static final Logger logger = LoggerFactory.getLogger(AbstractCodec.class); protected static void checkPayload(Channel channel, long size) throws IOException { - int payload = Constants.DEFAULT_PAYLOAD; + int payload = RemotingConstants.DEFAULT_PAYLOAD; if (channel != null && channel.getUrl() != null) { - payload = channel.getUrl().getParameter(Constants.PAYLOAD_KEY, Constants.DEFAULT_PAYLOAD); + payload = channel.getUrl().getParameter(RemotingConstants.PAYLOAD_KEY, RemotingConstants.DEFAULT_PAYLOAD); } if (payload > 0 && size > payload) { ExceedPayloadLimitException e = new ExceedPayloadLimitException("Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractEndpoint.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractEndpoint.java index 94b6be287b0..0a438bf7491 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractEndpoint.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractEndpoint.java @@ -19,6 +19,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.Resetable; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -44,11 +45,11 @@ public AbstractEndpoint(URL url, ChannelHandler handler) { super(url, handler); this.codec = getChannelCodec(url); this.timeout = url.getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); - this.connectTimeout = url.getPositiveParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT); + this.connectTimeout = url.getPositiveParameter(RemotingConstants.CONNECT_TIMEOUT_KEY, RemotingConstants.DEFAULT_CONNECT_TIMEOUT); } protected static Codec2 getChannelCodec(URL url) { - String codecName = url.getParameter(Constants.CODEC_KEY, "telnet"); + String codecName = url.getParameter(RemotingConstants.CODEC_KEY, "telnet"); if (ExtensionLoader.getExtensionLoader(Codec2.class).hasExtension(codecName)) { return ExtensionLoader.getExtensionLoader(Codec2.class).getExtension(codecName); } else { @@ -74,8 +75,8 @@ public void reset(URL url) { logger.error(t.getMessage(), t); } try { - if (url.hasParameter(Constants.CONNECT_TIMEOUT_KEY)) { - int t = url.getParameter(Constants.CONNECT_TIMEOUT_KEY, 0); + if (url.hasParameter(RemotingConstants.CONNECT_TIMEOUT_KEY)) { + int t = url.getParameter(RemotingConstants.CONNECT_TIMEOUT_KEY, 0); if (t > 0) { this.connectTimeout = t; } @@ -84,7 +85,7 @@ public void reset(URL url) { logger.error(t.getMessage(), t); } try { - if (url.hasParameter(Constants.CODEC_KEY)) { + if (url.hasParameter(RemotingConstants.CODEC_KEY)) { this.codec = getChannelCodec(url); } } catch (Throwable t) { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractPeer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractPeer.java index 18f235b9b63..2ec6fc603d0 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractPeer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractPeer.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.remoting.transport; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Endpoint; @@ -50,7 +50,7 @@ public AbstractPeer(URL url, ChannelHandler handler) { @Override public void send(Object message) throws RemotingException { - send(message, url.getParameter(Constants.SENT_KEY, false)); + send(message, url.getParameter(RemotingConstants.SENT_KEY, false)); } @Override diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractServer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractServer.java index 2020fee79fb..0af47a63c3e 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractServer.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -51,14 +52,14 @@ public AbstractServer(URL url, ChannelHandler handler) throws RemotingException super(url, handler); localAddress = getUrl().toInetSocketAddress(); - String bindIp = getUrl().getParameter(Constants.BIND_IP_KEY, getUrl().getHost()); - int bindPort = getUrl().getParameter(Constants.BIND_PORT_KEY, getUrl().getPort()); + String bindIp = getUrl().getParameter(RemotingConstants.BIND_IP_KEY, getUrl().getHost()); + int bindPort = getUrl().getParameter(RemotingConstants.BIND_PORT_KEY, getUrl().getPort()); if (url.getParameter(Constants.ANYHOST_KEY, false) || NetUtils.isInvalidLocalHost(bindIp)) { bindIp = Constants.ANYHOST_VALUE; } bindAddress = new InetSocketAddress(bindIp, bindPort); - this.accepts = url.getParameter(Constants.ACCEPTS_KEY, Constants.DEFAULT_ACCEPTS); - this.idleTimeout = url.getParameter(Constants.IDLE_TIMEOUT_KEY, Constants.DEFAULT_IDLE_TIMEOUT); + this.accepts = url.getParameter(RemotingConstants.ACCEPTS_KEY, RemotingConstants.DEFAULT_ACCEPTS); + this.idleTimeout = url.getParameter(RemotingConstants.IDLE_TIMEOUT_KEY, RemotingConstants.DEFAULT_IDLE_TIMEOUT); try { doOpen(); if (logger.isInfoEnabled()) { @@ -70,7 +71,7 @@ public AbstractServer(URL url, ChannelHandler handler) throws RemotingException } //fixme replace this with better method DataStore dataStore = ExtensionLoader.getExtensionLoader(DataStore.class).getDefaultExtension(); - executor = (ExecutorService) dataStore.get(Constants.EXECUTOR_SERVICE_COMPONENT_KEY, Integer.toString(url.getPort())); + executor = (ExecutorService) dataStore.get(RemotingConstants.EXECUTOR_SERVICE_COMPONENT_KEY, Integer.toString(url.getPort())); } protected abstract void doOpen() throws Throwable; @@ -83,8 +84,8 @@ public void reset(URL url) { return; } try { - if (url.hasParameter(Constants.ACCEPTS_KEY)) { - int a = url.getParameter(Constants.ACCEPTS_KEY, 0); + if (url.hasParameter(RemotingConstants.ACCEPTS_KEY)) { + int a = url.getParameter(RemotingConstants.ACCEPTS_KEY, 0); if (a > 0) { this.accepts = a; } @@ -93,8 +94,8 @@ public void reset(URL url) { logger.error(t.getMessage(), t); } try { - if (url.hasParameter(Constants.IDLE_TIMEOUT_KEY)) { - int t = url.getParameter(Constants.IDLE_TIMEOUT_KEY, 0); + if (url.hasParameter(RemotingConstants.IDLE_TIMEOUT_KEY)) { + int t = url.getParameter(RemotingConstants.IDLE_TIMEOUT_KEY, 0); if (t > 0) { this.idleTimeout = t; } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java index ca48dcaf1e0..cfa6c604e0f 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java @@ -17,8 +17,8 @@ package org.apache.dubbo.remoting.transport; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -67,12 +67,12 @@ public static Serialization getSerializationById(Byte id) { public static Serialization getSerialization(URL url) { return ExtensionLoader.getExtensionLoader(Serialization.class).getExtension( - url.getParameter(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION)); + url.getParameter(RemotingConstants.SERIALIZATION_KEY, RemotingConstants.DEFAULT_REMOTING_SERIALIZATION)); } public static Serialization getSerialization(URL url, Byte id) throws IOException { Serialization serialization = getSerializationById(id); - String serializationName = url.getParameter(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION); + String serializationName = url.getParameter(RemotingConstants.SERIALIZATION_KEY, RemotingConstants.DEFAULT_REMOTING_SERIALIZATION); // Check if "serialization id" passed from network matches the id on this side(only take effect for JDK serialization), for security purpose. if (serialization == null || ((id == JAVA_SERIALIZATION_ID || id == NATIVE_JAVA_SERIALIZATION_ID || id == COMPACTED_JAVA_SERIALIZATION_ID) diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java index 072f998e068..f545a413d3f 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -49,7 +50,7 @@ public WrappedChannelHandler(ChannelHandler handler, URL url) { this.url = url; executor = (ExecutorService) ExtensionLoader.getExtensionLoader(ThreadPool.class).getAdaptiveExtension().getExecutor(url); - String componentKey = Constants.EXECUTOR_SERVICE_COMPONENT_KEY; + String componentKey = RemotingConstants.EXECUTOR_SERVICE_COMPONENT_KEY; if (Constants.CONSUMER_SIDE.equalsIgnoreCase(url.getParameter(Constants.SIDE_KEY))) { componentKey = Constants.CONSUMER_SIDE; } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java index d6aff15a4a1..79465e68679 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.remoting.Channel; @@ -46,11 +47,11 @@ public ConnectionOrderedChannelHandler(ChannelHandler handler, URL url) { String threadName = url.getParameter(Constants.THREAD_NAME_KEY, Constants.DEFAULT_THREAD_NAME); connectionExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, - new LinkedBlockingQueue(url.getPositiveParameter(Constants.CONNECT_QUEUE_CAPACITY, Integer.MAX_VALUE)), + new LinkedBlockingQueue(url.getPositiveParameter(RemotingConstants.CONNECT_QUEUE_CAPACITY, Integer.MAX_VALUE)), new NamedThreadFactory(threadName, true), new AbortPolicyWithReport(threadName, url) ); // FIXME There's no place to release connectionExecutor! - queuewarninglimit = url.getParameter(Constants.CONNECT_QUEUE_WARNING_SIZE, Constants.DEFAULT_CONNECT_QUEUE_WARNING_SIZE); + queuewarninglimit = url.getParameter(RemotingConstants.CONNECT_QUEUE_WARNING_SIZE, RemotingConstants.DEFAULT_CONNECT_QUEUE_WARNING_SIZE); } @Override diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/ChanelHandlerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/ChanelHandlerTest.java index 7f226554383..2d87e54ed1b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/ChanelHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/ChanelHandlerTest.java @@ -17,6 +17,7 @@ package org.apache.dubbo.remoting; import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.exchange.ExchangeClient; @@ -79,8 +80,8 @@ public void testClient() throws Throwable { return; } final String server = System.getProperty("server", "127.0.0.1:9911"); - final String transporter = PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER); - final String serialization = PerformanceUtils.getProperty(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION); + final String transporter = PerformanceUtils.getProperty(RemotingConstants.TRANSPORTER_KEY, RemotingConstants.DEFAULT_TRANSPORTER); + final String serialization = PerformanceUtils.getProperty(RemotingConstants.SERIALIZATION_KEY, RemotingConstants.DEFAULT_REMOTING_SERIALIZATION); final int timeout = PerformanceUtils.getIntProperty(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); int sleep = PerformanceUtils.getIntProperty("sleep", 60 * 1000 * 60); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientCloseTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientCloseTest.java index cb6b99f51f9..d92648ac7d8 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientCloseTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientCloseTest.java @@ -17,6 +17,7 @@ package org.apache.dubbo.remoting; import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.exchange.ExchangeClient; @@ -43,8 +44,8 @@ public void testClient() throws Throwable { return; } final String server = System.getProperty("server", "127.0.0.1:9911"); - final String transporter = PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER); - final String serialization = PerformanceUtils.getProperty(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION); + final String transporter = PerformanceUtils.getProperty(RemotingConstants.TRANSPORTER_KEY, RemotingConstants.DEFAULT_TRANSPORTER); + final String serialization = PerformanceUtils.getProperty(RemotingConstants.SERIALIZATION_KEY, RemotingConstants.DEFAULT_REMOTING_SERIALIZATION); final int timeout = PerformanceUtils.getIntProperty(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); final int concurrent = PerformanceUtils.getIntProperty("concurrent", 1); final int runs = PerformanceUtils.getIntProperty("runs", Integer.MAX_VALUE); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java index 24009e83768..ae2aecc77be 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java @@ -17,6 +17,7 @@ package org.apache.dubbo.remoting; import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.exchange.ExchangeClient; @@ -40,8 +41,8 @@ public void testClient() throws Exception { return; } final String server = System.getProperty("server", "127.0.0.1:9911"); - final String transporter = PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER); - final String serialization = PerformanceUtils.getProperty(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION); + final String transporter = PerformanceUtils.getProperty(RemotingConstants.TRANSPORTER_KEY, RemotingConstants.DEFAULT_TRANSPORTER); + final String serialization = PerformanceUtils.getProperty(RemotingConstants.SERIALIZATION_KEY, RemotingConstants.DEFAULT_REMOTING_SERIALIZATION); final int timeout = PerformanceUtils.getIntProperty(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); //final int length = PerformanceUtils.getIntProperty("length", 1024); final int connectionCount = PerformanceUtils.getIntProperty(Constants.CONNECTIONS_KEY, 1); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java index e3e2347a9ee..43570b6c5a7 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java @@ -17,13 +17,13 @@ package org.apache.dubbo.remoting; import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.remoting.exchange.Exchangers; import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerAdapter; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.text.DecimalFormat; @@ -52,8 +52,8 @@ public void testClient() throws Throwable { return; } final String server = System.getProperty("server", "127.0.0.1:9911"); - final String transporter = PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER); - final String serialization = PerformanceUtils.getProperty(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION); + final String transporter = PerformanceUtils.getProperty(RemotingConstants.TRANSPORTER_KEY, RemotingConstants.DEFAULT_TRANSPORTER); + final String serialization = PerformanceUtils.getProperty(RemotingConstants.SERIALIZATION_KEY, RemotingConstants.DEFAULT_REMOTING_SERIALIZATION); final int timeout = PerformanceUtils.getIntProperty(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); final int length = PerformanceUtils.getIntProperty("length", 1024); final int connections = PerformanceUtils.getIntProperty(Constants.CONNECTIONS_KEY, 1); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.java index 413aa05b657..580dbb3e980 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.java @@ -17,6 +17,7 @@ package org.apache.dubbo.remoting; import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.exchange.ExchangeChannel; @@ -61,13 +62,13 @@ private static void restartServer(int times, int alive, int sleep) throws Except private static ExchangeServer statServer() throws Exception { final int port = PerformanceUtils.getIntProperty("port", 9911); - final String transporter = PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER); - final String serialization = PerformanceUtils.getProperty(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION); + final String transporter = PerformanceUtils.getProperty(RemotingConstants.TRANSPORTER_KEY, RemotingConstants.DEFAULT_TRANSPORTER); + final String serialization = PerformanceUtils.getProperty(RemotingConstants.SERIALIZATION_KEY, RemotingConstants.DEFAULT_REMOTING_SERIALIZATION); final String threadpool = PerformanceUtils.getProperty(Constants.THREADPOOL_KEY, Constants.DEFAULT_THREADPOOL); final int threads = PerformanceUtils.getIntProperty(Constants.THREADS_KEY, Constants.DEFAULT_THREADS); - final int iothreads = PerformanceUtils.getIntProperty(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS); - final int buffer = PerformanceUtils.getIntProperty(Constants.BUFFER_KEY, Constants.DEFAULT_BUFFER_SIZE); - final String channelHandler = PerformanceUtils.getProperty(Constants.DISPATCHER_KEY, ExecutionDispatcher.NAME); + final int iothreads = PerformanceUtils.getIntProperty(Constants.IO_THREADS_KEY, RemotingConstants.DEFAULT_IO_THREADS); + final int buffer = PerformanceUtils.getIntProperty(RemotingConstants.BUFFER_KEY, RemotingConstants.DEFAULT_BUFFER_SIZE); + final String channelHandler = PerformanceUtils.getProperty(RemotingConstants.DISPATCHER_KEY, ExecutionDispatcher.NAME); // Start server diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/ExchangeCodecTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/ExchangeCodecTest.java index ac17a41ed86..7b9cbca7f16 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/ExchangeCodecTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/ExchangeCodecTest.java @@ -17,8 +17,8 @@ package org.apache.dubbo.remoting.codec; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.Version; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.io.Bytes; import org.apache.dubbo.common.io.UnsafeByteArrayOutputStream; @@ -32,7 +32,6 @@ import org.apache.dubbo.remoting.exchange.codec.ExchangeCodec; import org.apache.dubbo.remoting.telnet.codec.TelnetCodec; -import org.apache.dubbo.remoting.transport.CodecSupport; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -65,7 +64,7 @@ public class ExchangeCodecTest extends TelnetCodecTest { private static final short MAGIC = (short) 0xdabb; private static final byte MAGIC_HIGH = (byte) Bytes.short2bytes(MAGIC)[0]; private static final byte MAGIC_LOW = (byte) Bytes.short2bytes(MAGIC)[1]; - Serialization serialization = getSerialization(Constants.DEFAULT_REMOTING_SERIALIZATION); + Serialization serialization = getSerialization(RemotingConstants.DEFAULT_REMOTING_SERIALIZATION); private static Serialization getSerialization(String name) { Serialization serialization = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(name); @@ -443,7 +442,7 @@ public void testMessageLengthExceedPayloadLimitWhenEncode() throws Exception { Request request = new Request(1L); request.setData("hello"); ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(512); - AbstractMockChannel channel = getCliendSideChannel(url.addParameter(Constants.PAYLOAD_KEY, 4)); + AbstractMockChannel channel = getCliendSideChannel(url.addParameter(RemotingConstants.PAYLOAD_KEY, 4)); try { codec.encode(channel, encodeBuffer, request); Assertions.fail(); @@ -454,7 +453,7 @@ public void testMessageLengthExceedPayloadLimitWhenEncode() throws Exception { Response response = new Response(1L); response.setResult("hello"); encodeBuffer = ChannelBuffers.dynamicBuffer(512); - channel = getServerSideChannel(url.addParameter(Constants.PAYLOAD_KEY, 4)); + channel = getServerSideChannel(url.addParameter(RemotingConstants.PAYLOAD_KEY, 4)); codec.encode(channel, encodeBuffer, response); Assertions.assertTrue(channel.getReceivedMessage() instanceof Response); Response receiveMessage = (Response) channel.getReceivedMessage(); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.java index 782b8480cdc..24a4080c486 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.java @@ -19,6 +19,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.timer.HashedWheelTimer; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.exchange.Request; @@ -42,7 +43,7 @@ public class HeartBeatTaskTest { @BeforeEach public void setup() throws Exception { long tickDuration = 1000; - heartbeatTimer = new HashedWheelTimer(tickDuration / Constants.HEARTBEAT_CHECK_TICK, TimeUnit.MILLISECONDS); + heartbeatTimer = new HashedWheelTimer(tickDuration / RemotingConstants.HEARTBEAT_CHECK_TICK, TimeUnit.MILLISECONDS); channel = new MockChannel() { @@ -53,7 +54,7 @@ public URL getUrl() { }; AbstractTimerTask.ChannelProvider cp = () -> Collections.singletonList(channel); - heartbeatTimerTask = new HeartbeatTimerTask(cp, tickDuration / Constants.HEARTBEAT_CHECK_TICK, (int) tickDuration); + heartbeatTimerTask = new HeartbeatTimerTask(cp, tickDuration / RemotingConstants.HEARTBEAT_CHECK_TICK, (int) tickDuration); } @Test diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/HeaderExchangeHandlerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/HeaderExchangeHandlerTest.java index 3c11eca1c45..c9c044d9a12 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/HeaderExchangeHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/HeaderExchangeHandlerTest.java @@ -17,7 +17,7 @@ package org.apache.dubbo.remoting.handler; -import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; @@ -160,7 +160,7 @@ public void test_received_request_event_readonly() throws RemotingException { final Channel mchannel = new MockedChannel(); HeaderExchangeHandler hexhandler = new HeaderExchangeHandler(new MockedExchangeHandler()); hexhandler.received(mchannel, request); - Assertions.assertTrue(mchannel.hasAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY)); + Assertions.assertTrue(mchannel.hasAttribute(RemotingConstants.CHANNEL_ATTRIBUTE_READONLY_KEY)); } @Test diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java index 49d3a02ce4d..5b30d5cbabb 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -55,9 +56,9 @@ public class DeprecatedTelnetCodec implements Codec { private static final List EXIT = Arrays.asList(new Object[]{new byte[]{3} /* Windows Ctrl+C */, new byte[]{-1, -12, -1, -3, 6} /* Linux Ctrl+C */, new byte[]{-1, -19, -1, -3, 6} /* Linux Pause */}); static void checkPayload(Channel channel, long size) throws IOException { - int payload = Constants.DEFAULT_PAYLOAD; + int payload = RemotingConstants.DEFAULT_PAYLOAD; if (channel != null && channel.getUrl() != null) { - payload = channel.getUrl().getPositiveParameter(Constants.PAYLOAD_KEY, Constants.DEFAULT_PAYLOAD); + payload = channel.getUrl().getPositiveParameter(RemotingConstants.PAYLOAD_KEY, RemotingConstants.DEFAULT_PAYLOAD); } if (size > payload) { IOException e = new IOException("Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel); @@ -68,7 +69,7 @@ static void checkPayload(Channel channel, long size) throws IOException { private static Charset getCharset(Channel channel) { if (channel != null) { - Object attribute = channel.getAttribute(Constants.CHARSET_KEY); + Object attribute = channel.getAttribute(RemotingConstants.CHARSET_KEY); if (attribute instanceof String) { try { return Charset.forName((String) attribute); @@ -80,7 +81,7 @@ private static Charset getCharset(Channel channel) { } URL url = channel.getUrl(); if (url != null) { - String parameter = url.getParameter(Constants.CHARSET_KEY); + String parameter = url.getParameter(RemotingConstants.CHARSET_KEY); if (StringUtils.isNotEmpty(parameter)) { try { return Charset.forName(parameter); diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/Constants.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/Constants.java index 7bc1a98bd25..48115a91560 100644 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/Constants.java +++ b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/Constants.java @@ -17,7 +17,7 @@ package org.apache.dubbo.remoting.etcd; -import static org.apache.dubbo.common.Constants.DEFAULT_IO_THREADS; +import static org.apache.dubbo.common.constants.RemotingConstants.DEFAULT_IO_THREADS; public interface Constants { String ETCD3_NOTIFY_MAXTHREADS_KEYS = "etcd3.notify.maxthreads"; diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/EtcdTransporter.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/EtcdTransporter.java index 2c0befb0a4c..821fc0524e0 100644 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/EtcdTransporter.java +++ b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/EtcdTransporter.java @@ -33,15 +33,15 @@ */ package org.apache.dubbo.remoting.etcd; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.SPI; @SPI("jetcd") public interface EtcdTransporter { - @Adaptive({Constants.CLIENT_KEY, Constants.TRANSPORTER_KEY}) + @Adaptive({RemotingConstants.CLIENT_KEY, RemotingConstants.TRANSPORTER_KEY}) EtcdClient connect(URL url); } diff --git a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyCodecAdapter.java b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyCodecAdapter.java index 4e813f36f01..a7162456795 100644 --- a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyCodecAdapter.java +++ b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyCodecAdapter.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.remoting.transport.grizzly; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Codec2; @@ -52,8 +52,8 @@ public GrizzlyCodecAdapter(Codec2 codec, URL url, ChannelHandler handler) { this.codec = codec; this.url = url; this.handler = handler; - int b = url.getPositiveParameter(Constants.BUFFER_KEY, Constants.DEFAULT_BUFFER_SIZE); - this.bufferSize = b >= Constants.MIN_BUFFER_SIZE && b <= Constants.MAX_BUFFER_SIZE ? b : Constants.DEFAULT_BUFFER_SIZE; + int b = url.getPositiveParameter(RemotingConstants.BUFFER_KEY, RemotingConstants.DEFAULT_BUFFER_SIZE); + this.bufferSize = b >= RemotingConstants.MIN_BUFFER_SIZE && b <= RemotingConstants.MAX_BUFFER_SIZE ? b : RemotingConstants.DEFAULT_BUFFER_SIZE; } @Override diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpBinder.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpBinder.java index 92e3dd02ce2..4f1392bf847 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpBinder.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpBinder.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.remoting.http; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.SPI; @@ -33,7 +33,7 @@ public interface HttpBinder { * @param url server url. * @return server. */ - @Adaptive({Constants.SERVER_KEY}) + @Adaptive({RemotingConstants.SERVER_KEY}) HttpServer bind(URL url, HttpHandler handler); } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpServer.java index 6ff19df36de..0274271b85b 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpServer.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpServer.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NetUtils; @@ -51,7 +52,7 @@ public JettyHttpServer(URL url, final HttpHandler handler) { Log.setLog(new StdErrLog()); Log.getLog().setDebugEnabled(false); - DispatcherServlet.addHttpHandler(url.getParameter(Constants.BIND_PORT_KEY, url.getPort()), handler); + DispatcherServlet.addHttpHandler(url.getParameter(RemotingConstants.BIND_PORT_KEY, url.getPort()), handler); int threads = url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS); QueuedThreadPool threadPool = new QueuedThreadPool(); @@ -63,11 +64,11 @@ public JettyHttpServer(URL url, final HttpHandler handler) { ServerConnector connector = new ServerConnector(server); - String bindIp = url.getParameter(Constants.BIND_IP_KEY, url.getHost()); + String bindIp = url.getParameter(RemotingConstants.BIND_IP_KEY, url.getHost()); if (!url.isAnyHost() && NetUtils.isValidLocalHost(bindIp)) { connector.setHost(bindIp); } - connector.setPort(url.getParameter(Constants.BIND_PORT_KEY, url.getPort())); + connector.setPort(url.getParameter(RemotingConstants.BIND_PORT_KEY, url.getPort())); server.addConnector(connector); @@ -80,12 +81,12 @@ public JettyHttpServer(URL url, final HttpHandler handler) { // TODO Context.SESSIONS is the best option here? (In jetty 9.x, it becomes ServletContextHandler.SESSIONS) ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS); context.setServletHandler(servletHandler); - ServletManager.getInstance().addServletContext(url.getParameter(Constants.BIND_PORT_KEY, url.getPort()), context.getServletContext()); + ServletManager.getInstance().addServletContext(url.getParameter(RemotingConstants.BIND_PORT_KEY, url.getPort()), context.getServletContext()); try { server.start(); } catch (Exception e) { - throw new IllegalStateException("Failed to start jetty server on " + url.getParameter(Constants.BIND_IP_KEY) + ":" + url.getParameter(Constants.BIND_PORT_KEY) + ", cause: " + throw new IllegalStateException("Failed to start jetty server on " + url.getParameter(RemotingConstants.BIND_IP_KEY) + ":" + url.getParameter(RemotingConstants.BIND_PORT_KEY) + ", cause: " + e.getMessage(), e); } } @@ -95,7 +96,7 @@ public void close() { super.close(); // - ServletManager.getInstance().removeServletContext(url.getParameter(Constants.BIND_PORT_KEY, url.getPort())); + ServletManager.getInstance().removeServletContext(url.getParameter(RemotingConstants.BIND_PORT_KEY, url.getPort())); if (server != null) { try { diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpServer.java index 772e46e99b4..cd23699e72a 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpServer.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpServer.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.remoting.http.servlet; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.remoting.http.support.AbstractHttpServer; @@ -25,7 +25,7 @@ public class ServletHttpServer extends AbstractHttpServer { public ServletHttpServer(URL url, HttpHandler handler) { super(url, handler); - DispatcherServlet.addHttpHandler(url.getParameter(Constants.BIND_PORT_KEY, 8080), handler); + DispatcherServlet.addHttpHandler(url.getParameter(RemotingConstants.BIND_PORT_KEY, 8080), handler); } } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java index f8a898c9713..901d5880471 100755 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.http.HttpHandler; @@ -54,7 +55,7 @@ public TomcatHttpServer(URL url, final HttpHandler handler) { // "minSpareThreads", String.valueOf(url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS))); tomcat.getConnector().setProperty( - "maxConnections", String.valueOf(url.getParameter(Constants.ACCEPTS_KEY, -1))); + "maxConnections", String.valueOf(url.getParameter(RemotingConstants.ACCEPTS_KEY, -1))); tomcat.getConnector().setProperty("URIEncoding", "UTF-8"); tomcat.getConnector().setProperty("connectionTimeout", "60000"); diff --git a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinderTest.java b/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinderTest.java index 0aca829f2be..63dae7b7e58 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinderTest.java +++ b/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinderTest.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.remoting.http.jetty; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.remoting.http.HttpServer; @@ -36,7 +36,7 @@ public class JettyHttpBinderTest { public void shouldAbleHandleRequestForJettyBinder() throws Exception { int port = NetUtils.getAvailablePort(); URL url = new URL("http", "localhost", port, - new String[]{Constants.BIND_PORT_KEY, String.valueOf(port)}); + new String[]{RemotingConstants.BIND_PORT_KEY, String.valueOf(port)}); HttpServer httpServer = new JettyHttpServer(url, new HttpHandler() { @Override public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { diff --git a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinderTest.java b/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinderTest.java index 9b3e3b16d63..086f624334e 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinderTest.java +++ b/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinderTest.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.remoting.http.tomcat; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.remoting.http.HttpServer; @@ -37,7 +37,7 @@ public class TomcatHttpBinderTest { public void shouldAbleHandleRequestForTomcatBinder() throws Exception { int port = NetUtils.getAvailablePort(); URL url = new URL("http", "localhost", port, - new String[]{Constants.BIND_PORT_KEY, String.valueOf(port)}); + new String[]{RemotingConstants.BIND_PORT_KEY, String.valueOf(port)}); HttpServer httpServer = new TomcatHttpBinder().bind(url, new HttpHandler() { @Override diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaClient.java b/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaClient.java index b5e9c8426d1..ee926a26477 100644 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaClient.java +++ b/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaClient.java @@ -16,9 +16,9 @@ */ package org.apache.dubbo.remoting.transport.mina; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NamedThreadFactory; @@ -71,7 +71,7 @@ protected void doOpen() throws Throwable { connector = c; } else { // set thread pool. - connector = new SocketConnector(Constants.DEFAULT_IO_THREADS, + connector = new SocketConnector(RemotingConstants.DEFAULT_IO_THREADS, Executors.newCachedThreadPool(new NamedThreadFactory("MinaClientWorker", true))); // config SocketConnectorConfig cfg = (SocketConnectorConfig) connector.getDefaultConfig(); diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaCodecAdapter.java b/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaCodecAdapter.java index 5e60fb2d490..128f119c062 100644 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaCodecAdapter.java +++ b/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaCodecAdapter.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.remoting.transport.mina; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Codec2; @@ -54,8 +54,8 @@ public MinaCodecAdapter(Codec2 codec, URL url, ChannelHandler handler) { this.codec = codec; this.url = url; this.handler = handler; - int b = url.getPositiveParameter(Constants.BUFFER_KEY, Constants.DEFAULT_BUFFER_SIZE); - this.bufferSize = b >= Constants.MIN_BUFFER_SIZE && b <= Constants.MAX_BUFFER_SIZE ? b : Constants.DEFAULT_BUFFER_SIZE; + int b = url.getPositiveParameter(RemotingConstants.BUFFER_KEY, RemotingConstants.DEFAULT_BUFFER_SIZE); + this.bufferSize = b >= RemotingConstants.MIN_BUFFER_SIZE && b <= RemotingConstants.MAX_BUFFER_SIZE ? b : RemotingConstants.DEFAULT_BUFFER_SIZE; } @Override diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaServer.java b/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaServer.java index 540213b4443..4937944eccb 100644 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaServer.java +++ b/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaServer.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ExecutorUtil; @@ -56,7 +57,7 @@ public MinaServer(URL url, ChannelHandler handler) throws RemotingException { @Override protected void doOpen() throws Throwable { // set thread pool. - acceptor = new SocketAcceptor(getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS), + acceptor = new SocketAcceptor(getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, RemotingConstants.DEFAULT_IO_THREADS), Executors.newCachedThreadPool(new NamedThreadFactory("MinaServerWorker", true))); // config diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyClient.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyClient.java index e9912985ebc..80b8ae60474 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyClient.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyClient.java @@ -16,9 +16,9 @@ */ package org.apache.dubbo.remoting.transport.netty; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NamedThreadFactory; @@ -50,7 +50,7 @@ public class NettyClient extends AbstractClient { // https://issues.jboss.org/browse/NETTY-424 private static final ChannelFactory CHANNEL_FACTORY = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(new NamedThreadFactory("NettyClientBoss", true)), Executors.newCachedThreadPool(new NamedThreadFactory("NettyClientWorker", true)), - Constants.DEFAULT_IO_THREADS); + RemotingConstants.DEFAULT_IO_THREADS); private ClientBootstrap bootstrap; private volatile Channel channel; // volatile, please copy reference to use diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyCodecAdapter.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyCodecAdapter.java index f23ee2dee09..5088001278c 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyCodecAdapter.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyCodecAdapter.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.remoting.transport.netty; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.remoting.Codec2; import org.apache.dubbo.remoting.buffer.DynamicChannelBuffer; @@ -56,8 +56,8 @@ public NettyCodecAdapter(Codec2 codec, URL url, org.apache.dubbo.remoting.Channe this.codec = codec; this.url = url; this.handler = handler; - int b = url.getPositiveParameter(Constants.BUFFER_KEY, Constants.DEFAULT_BUFFER_SIZE); - this.bufferSize = b >= Constants.MIN_BUFFER_SIZE && b <= Constants.MAX_BUFFER_SIZE ? b : Constants.DEFAULT_BUFFER_SIZE; + int b = url.getPositiveParameter(RemotingConstants.BUFFER_KEY, RemotingConstants.DEFAULT_BUFFER_SIZE); + this.bufferSize = b >= RemotingConstants.MIN_BUFFER_SIZE && b <= RemotingConstants.MAX_BUFFER_SIZE ? b : RemotingConstants.DEFAULT_BUFFER_SIZE; } public ChannelHandler getEncoder() { diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyServer.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyServer.java index 61cd3f1ef0c..b25461e0f14 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyServer.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyServer.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; @@ -67,7 +68,7 @@ protected void doOpen() throws Throwable { NettyHelper.setNettyLoggerFactory(); ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerBoss", true)); ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true)); - ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS)); + ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, RemotingConstants.DEFAULT_IO_THREADS)); bootstrap = new ServerBootstrap(channelFactory); final NettyHandler nettyHandler = new NettyHandler(getUrl(), this); diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java index 52c3e9d03e7..7a1134e8fae 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java @@ -17,8 +17,8 @@ package org.apache.dubbo.remoting.exchange.support.header; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.Channel; @@ -61,17 +61,17 @@ public void after() throws Exception { @Test public void testServerHeartbeat() throws Exception { URL serverURL = URL.valueOf("header://localhost:55555?transporter=netty3"); - serverURL = serverURL.addParameter(Constants.HEARTBEAT_KEY, 1000); + serverURL = serverURL.addParameter(RemotingConstants.HEARTBEAT_KEY, 1000); TestHeartbeatHandler handler = new TestHeartbeatHandler(); server = Exchangers.bind(serverURL, handler); System.out.println("Server bind successfully"); FakeChannelHandlers.setTestingChannelHandlers(); - serverURL = serverURL.removeParameter(Constants.HEARTBEAT_KEY); + serverURL = serverURL.removeParameter(RemotingConstants.HEARTBEAT_KEY); // Let the client not reply to the heartbeat, and turn off automatic reconnect to simulate the client dropped. - serverURL = serverURL.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000); - serverURL = serverURL.addParameter(Constants.RECONNECT_KEY, false); + serverURL = serverURL.addParameter(RemotingConstants.HEARTBEAT_KEY, 600 * 1000); + serverURL = serverURL.addParameter(RemotingConstants.RECONNECT_KEY, false); client = Exchangers.connect(serverURL); Thread.sleep(10000); @@ -82,7 +82,7 @@ public void testServerHeartbeat() throws Exception { @Test public void testHeartbeat() throws Exception { URL serverURL = URL.valueOf("header://localhost:55555?transporter=netty3"); - serverURL = serverURL.addParameter(Constants.HEARTBEAT_KEY, 1000); + serverURL = serverURL.addParameter(RemotingConstants.HEARTBEAT_KEY, 1000); TestHeartbeatHandler handler = new TestHeartbeatHandler(); server = Exchangers.bind(serverURL, handler); System.out.println("Server bind successfully"); @@ -104,7 +104,7 @@ public void testClientHeartbeat() throws Exception { System.out.println("Server bind successfully"); FakeChannelHandlers.resetChannelHandlers(); - serverURL = serverURL.addParameter(Constants.HEARTBEAT_KEY, 1000); + serverURL = serverURL.addParameter(RemotingConstants.HEARTBEAT_KEY, 1000); client = Exchangers.connect(serverURL); Thread.sleep(10000); Assertions.assertTrue(handler.connectCount > 0); diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientReconnectTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientReconnectTest.java index 4cb7eb6784d..52452126bf5 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientReconnectTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientReconnectTest.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.remoting.transport.netty; -import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.DubboAppender; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; @@ -70,7 +70,7 @@ public void testReconnect() throws RemotingException, InterruptedException { public Client startClient(int port, int heartbeat) throws RemotingException { - final String url = "exchange://127.0.0.1:" + port + "/client.reconnect.test?check=false&client=netty3&" + Constants.HEARTBEAT_KEY + "=" + heartbeat; + final String url = "exchange://127.0.0.1:" + port + "/client.reconnect.test?check=false&client=netty3&" + RemotingConstants.HEARTBEAT_KEY + "=" + heartbeat; return Exchangers.connect(url); } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientToServerTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientToServerTest.java index 3d4e52d022f..060efbe9d1f 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientToServerTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientToServerTest.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.remoting.transport.netty; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeServer; @@ -32,14 +32,14 @@ public class NettyClientToServerTest extends ClientToServerTest { protected ExchangeServer newServer(int port, Replier receiver) throws RemotingException { // add heartbeat cycle to avoid unstable ut. URL url = URL.valueOf("exchange://localhost:" + port + "?server=netty3"); - url = url.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000); + url = url.addParameter(RemotingConstants.HEARTBEAT_KEY, 600 * 1000); return Exchangers.bind(url, receiver); } protected ExchangeChannel newClient(int port) throws RemotingException { // add heartbeat cycle to avoid unstable ut. URL url = URL.valueOf("exchange://localhost:" + port + "?client=netty3&timeout=3000"); - url = url.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000); + url = url.addParameter(RemotingConstants.HEARTBEAT_KEY, 600 * 1000); return Exchangers.connect(url); } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java index 322d658b856..e772905bcec 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java @@ -16,9 +16,9 @@ */ package org.apache.dubbo.remoting.transport.netty4; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConfigUtils; @@ -51,7 +51,7 @@ public class NettyClient extends AbstractClient { private static final Logger logger = LoggerFactory.getLogger(NettyClient.class); - private static final NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup(Constants.DEFAULT_IO_THREADS, new DefaultThreadFactory("NettyClientWorker", true)); + private static final NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup(RemotingConstants.DEFAULT_IO_THREADS, new DefaultThreadFactory("NettyClientWorker", true)); private static final String SOCKS_PROXY_HOST = "socksProxyHost"; diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java index 62b6c55f93c..ad952a75ce1 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ExecutorUtil; @@ -74,7 +75,7 @@ protected void doOpen() throws Throwable { bootstrap = new ServerBootstrap(); bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss", true)); - workerGroup = new NioEventLoopGroup(getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS), + workerGroup = new NioEventLoopGroup(getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, RemotingConstants.DEFAULT_IO_THREADS), new DefaultThreadFactory("NettyServerWorker", true)); final NettyServerHandler nettyServerHandler = new NettyServerHandler(getUrl(), this); diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientReconnectTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientReconnectTest.java index f21918d3d15..1768183c3ee 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientReconnectTest.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientReconnectTest.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.remoting.transport.netty4; -import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.DubboAppender; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; @@ -72,7 +72,7 @@ public void testReconnect() throws RemotingException, InterruptedException { public Client startClient(int port, int heartbeat) throws RemotingException { - final String url = "exchange://127.0.0.1:" + port + "/client.reconnect.test?client=netty4&check=false&" + Constants.HEARTBEAT_KEY + "=" + heartbeat; + final String url = "exchange://127.0.0.1:" + port + "/client.reconnect.test?client=netty4&check=false&" + RemotingConstants.HEARTBEAT_KEY + "=" + heartbeat; return Exchangers.connect(url); } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyClientToServerTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyClientToServerTest.java index 1d3d5132d8a..04eaef883cc 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyClientToServerTest.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyClientToServerTest.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.remoting.transport.netty4; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeServer; @@ -32,14 +32,14 @@ public class NettyClientToServerTest extends ClientToServerTest { protected ExchangeServer newServer(int port, Replier receiver) throws RemotingException { // add heartbeat cycle to avoid unstable ut. URL url = URL.valueOf("exchange://localhost:" + port + "?server=netty4"); - url = url.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000); + url = url.addParameter(RemotingConstants.HEARTBEAT_KEY, 600 * 1000); return Exchangers.bind(url, receiver); } protected ExchangeChannel newClient(int port) throws RemotingException { // add heartbeat cycle to avoid unstable ut. URL url = URL.valueOf("exchange://localhost:" + port + "?client=netty4&timeout=3000"); - url = url.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000); + url = url.addParameter(RemotingConstants.HEARTBEAT_KEY, 600 * 1000); return Exchangers.connect(url); } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporterTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporterTest.java index b0bf7209a0c..db942c554e5 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporterTest.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporterTest.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.remoting.transport.netty4; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.RemotingException; @@ -36,7 +36,7 @@ public class NettyTransporterTest { public void shouldAbleToBindNetty4() throws Exception { int port = NetUtils.getAvailablePort(); URL url = new URL("http", "localhost", port, - new String[]{Constants.BIND_PORT_KEY, String.valueOf(port)}); + new String[]{RemotingConstants.BIND_PORT_KEY, String.valueOf(port)}); Server server = new NettyTransporter().bind(url, new ChannelHandlerAdapter()); @@ -49,7 +49,7 @@ public void shouldConnectToNetty4Server() throws Exception { int port = NetUtils.getAvailablePort(); URL url = new URL("http", "localhost", port, - new String[]{Constants.BIND_PORT_KEY, String.valueOf(port)}); + new String[]{RemotingConstants.BIND_PORT_KEY, String.valueOf(port)}); new NettyTransporter().bind(url, new ChannelHandlerAdapter() { diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/ExchangeServerPeer.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/ExchangeServerPeer.java index 35d5ff70147..2f534c9e8bd 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/ExchangeServerPeer.java +++ b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/ExchangeServerPeer.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.remoting.p2p.exchange.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.Channel; @@ -105,7 +105,7 @@ public ExchangeChannel getExchangeChannel(InetSocketAddress remoteAddress) { @Override public void send(Object message) throws RemotingException { - send(message, getUrl().getParameter(Constants.SENT_KEY, false)); + send(message, getUrl().getParameter(RemotingConstants.SENT_KEY, false)); } @Override diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/ServerPeer.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/ServerPeer.java index 83e5e8815b7..a6d215fb611 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/ServerPeer.java +++ b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/ServerPeer.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.remoting.p2p.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.Channel; @@ -92,7 +92,7 @@ public Channel getChannel(InetSocketAddress remoteAddress) { @Override public void send(Object message) throws RemotingException { - send(message, getUrl().getParameter(Constants.SENT_KEY, false)); + send(message, getUrl().getParameter(RemotingConstants.SENT_KEY, false)); } @Override diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/ZookeeperTransporter.java b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/ZookeeperTransporter.java index a339d97a177..96a459c93bc 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/ZookeeperTransporter.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/ZookeeperTransporter.java @@ -16,15 +16,15 @@ */ package org.apache.dubbo.remoting.zookeeper; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.SPI; @SPI("curator") public interface ZookeeperTransporter { - @Adaptive({Constants.CLIENT_KEY, Constants.TRANSPORTER_KEY}) + @Adaptive({RemotingConstants.CLIENT_KEY, RemotingConstants.TRANSPORTER_KEY}) ZookeeperClient connect(URL url); } diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/support/AbstractZookeeperTransporter.java b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/support/AbstractZookeeperTransporter.java index 72c702a1df3..ab6ada6a38c 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/support/AbstractZookeeperTransporter.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/support/AbstractZookeeperTransporter.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.zookeeper.ZookeeperClient; @@ -110,7 +111,7 @@ List getURLBackupAddress(URL url) { List addressList = new ArrayList(); addressList.add(url.getAddress()); - addressList.addAll(url.getParameter(Constants.BACKUP_KEY, Collections.EMPTY_LIST)); + addressList.addAll(url.getParameter(RemotingConstants.BACKUP_KEY, Collections.EMPTY_LIST)); return addressList; } @@ -138,8 +139,8 @@ URL toClientURL(URL url) { if (url.getParameter(Constants.TIMEOUT_KEY) != null) { parameterMap.put(Constants.TIMEOUT_KEY, url.getParameter(Constants.TIMEOUT_KEY)); } - if (url.getParameter(Constants.BACKUP_KEY) != null) { - parameterMap.put(Constants.BACKUP_KEY, url.getParameter(Constants.BACKUP_KEY)); + if (url.getParameter(RemotingConstants.BACKUP_KEY) != null) { + parameterMap.put(RemotingConstants.BACKUP_KEY, url.getParameter(RemotingConstants.BACKUP_KEY)); } return new URL(url.getProtocol(), url.getUsername(), url.getPassword(), url.getHost(), url.getPort(), ZookeeperTransporter.class.getName(), parameterMap); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/CompatibleFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/CompatibleFilter.java index ace832ca33c..74ab6d6f4de 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/CompatibleFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/CompatibleFilter.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.rpc.filter; -import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CompatibleTypeUtils; @@ -59,7 +59,7 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept Method method = invoker.getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes()); Class type = method.getReturnType(); Object newValue; - String serialization = invoker.getUrl().getParameter(Constants.SERIALIZATION_KEY); + String serialization = invoker.getUrl().getParameter(RemotingConstants.SERIALIZATION_KEY); if ("json".equals(serialization) || "fastjson".equals(serialization)) { // If the serialization key is json or fastjson diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java index 814e9182280..afac729e266 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConcurrentHashSet; @@ -44,7 +45,7 @@ public abstract class AbstractProtocol implements Protocol { protected final Set> invokers = new ConcurrentHashSet>(); protected static String serviceKey(URL url) { - int port = url.getParameter(Constants.BIND_PORT_KEY, url.getPort()); + int port = url.getParameter(RemotingConstants.BIND_PORT_KEY, url.getPort()); return serviceKey(port, url.getPath(), url.getParameter(Constants.VERSION_KEY), url.getParameter(Constants.GROUP_KEY)); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java index a77a5bdc5f3..ef9ab321cb4 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java @@ -19,6 +19,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invocation; @@ -130,11 +131,11 @@ protected RpcException getRpcException(Class type, URL url, Invocation invoca } protected String getAddr(URL url) { - String bindIp = url.getParameter(Constants.BIND_IP_KEY, url.getHost()); + String bindIp = url.getParameter(RemotingConstants.BIND_IP_KEY, url.getHost()); if (url.getParameter(Constants.ANYHOST_KEY, false)) { bindIp = Constants.ANYHOST_VALUE; } - return NetUtils.getIpByHost(bindIp) + ":" + url.getParameter(Constants.BIND_PORT_KEY, url.getPort()); + return NetUtils.getIpByHost(bindIp) + ":" + url.getParameter(RemotingConstants.BIND_PORT_KEY, url.getPort()); } protected int getErrorCode(Throwable e) { diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java index 4c78c1cceb9..14c76446143 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; @@ -59,7 +60,7 @@ protected Result doInvoke(Invocation invocation) throws Throwable { try { if (getUrl().getMethodParameter(invocation.getMethodName(), Constants.ASYNC_KEY, false)) { // may have concurrency issue - currentClient.send(inv, getUrl().getMethodParameter(invocation.getMethodName(), Constants.SENT_KEY, false)); + currentClient.send(inv, getUrl().getMethodParameter(invocation.getMethodName(), RemotingConstants.SENT_KEY, false)); return new RpcResult(); } int timeout = getUrl().getMethodParameter(invocation.getMethodName(), Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java index 5f2c61b1cae..0bddaf16384 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java @@ -19,6 +19,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.AtomicPositiveInteger; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.TimeoutException; @@ -85,7 +86,7 @@ protected Result doInvoke(final Invocation invocation) throws Throwable { boolean isOneway = RpcUtils.isOneway(getUrl(), invocation); int timeout = getUrl().getMethodParameter(methodName, Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); if (isOneway) { - boolean isSent = getUrl().getMethodParameter(methodName, Constants.SENT_KEY, false); + boolean isSent = getUrl().getMethodParameter(methodName, RemotingConstants.SENT_KEY, false); currentClient.send(inv, isSent); RpcContext.getContext().setFuture(null); return new RpcResult(); @@ -120,7 +121,7 @@ public boolean isAvailable() { return false; } for (ExchangeClient client : clients) { - if (client.isConnected() && !client.hasAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY)) { + if (client.isConnected() && !client.hasAttribute(RemotingConstants.CHANNEL_ATTRIBUTE_READONLY_KEY)) { //cannot write == not Available ? return true; } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java index 77443016cfb..9d881d08f0e 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java @@ -20,6 +20,7 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.config.ConfigurationUtils; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.serialize.support.SerializableClassRegistry; import org.apache.dubbo.common.serialize.support.SerializationOptimizer; @@ -315,12 +316,12 @@ private void openServer(URL url) { private ExchangeServer createServer(URL url) { url = URLBuilder.from(url) // send readonly event when server closes, it's enabled by default - .addParameterIfAbsent(Constants.CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString()) + .addParameterIfAbsent(RemotingConstants.CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString()) // enable heartbeat by default - .addParameterIfAbsent(Constants.HEARTBEAT_KEY, String.valueOf(Constants.DEFAULT_HEARTBEAT)) - .addParameter(Constants.CODEC_KEY, DubboCodec.NAME) + .addParameterIfAbsent(RemotingConstants.HEARTBEAT_KEY, String.valueOf(RemotingConstants.DEFAULT_HEARTBEAT)) + .addParameter(RemotingConstants.CODEC_KEY, DubboCodec.NAME) .build(); - String str = url.getParameter(Constants.SERVER_KEY, Constants.DEFAULT_REMOTING_SERVER); + String str = url.getParameter(RemotingConstants.SERVER_KEY, RemotingConstants.DEFAULT_REMOTING_SERVER); if (str != null && str.length() > 0 && !ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str)) { throw new RpcException("Unsupported server type: " + str + ", url: " + url); @@ -333,7 +334,7 @@ private ExchangeServer createServer(URL url) { throw new RpcException("Fail to start server(url: " + url + ") " + e.getMessage(), e); } - str = url.getParameter(Constants.CLIENT_KEY); + str = url.getParameter(RemotingConstants.CLIENT_KEY); if (str != null && str.length() > 0) { Set supportedTypes = ExtensionLoader.getExtensionLoader(Transporter.class).getSupportedExtensions(); if (!supportedTypes.contains(str)) { @@ -555,11 +556,11 @@ private ReferenceCountExchangeClient buildReferenceCountExchangeClient(URL url) private ExchangeClient initClient(URL url) { // client type setting. - String str = url.getParameter(Constants.CLIENT_KEY, url.getParameter(Constants.SERVER_KEY, Constants.DEFAULT_REMOTING_CLIENT)); + String str = url.getParameter(RemotingConstants.CLIENT_KEY, url.getParameter(RemotingConstants.SERVER_KEY, RemotingConstants.DEFAULT_REMOTING_CLIENT)); - url = url.addParameter(Constants.CODEC_KEY, DubboCodec.NAME); + url = url.addParameter(RemotingConstants.CODEC_KEY, DubboCodec.NAME); // enable heartbeat by default - url = url.addParameterIfAbsent(Constants.HEARTBEAT_KEY, String.valueOf(Constants.DEFAULT_HEARTBEAT)); + url = url.addParameterIfAbsent(RemotingConstants.HEARTBEAT_KEY, String.valueOf(RemotingConstants.DEFAULT_HEARTBEAT)); // BIO is not allowed since it has severe performance issue. if (str != null && str.length() > 0 && !ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str)) { diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java index f2bc4534fdc..c0111a38b20 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java @@ -19,6 +19,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.Parameters; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NetUtils; @@ -59,7 +60,7 @@ final class LazyConnectExchangeClient implements ExchangeClient { public LazyConnectExchangeClient(URL url, ExchangeHandler requestHandler) { // lazy connect, need set send.reconnect = true, to avoid channel bad status. - this.url = url.addParameter(Constants.SEND_RECONNECT_KEY, Boolean.TRUE.toString()); + this.url = url.addParameter(RemotingConstants.SEND_RECONNECT_KEY, Boolean.TRUE.toString()); this.requestHandler = requestHandler; this.initialState = url.getParameter(Constants.LAZY_CONNECT_INITIAL_STATE_KEY, Constants.DEFAULT_LAZY_CONNECT_INITIAL_STATE); this.requestWithWarning = url.getParameter(REQUEST_WITH_WARNING_KEY, false); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java index faafe082852..5befa5f2ee7 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java @@ -20,6 +20,7 @@ import org.apache.dubbo.common.Parameters; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeClient; @@ -168,8 +169,8 @@ private void replaceWithLazyClient() { // this is a defensive operation to avoid client is closed by accident, the initial state of the client is false URL lazyUrl = URLBuilder.from(url) .addParameter(Constants.LAZY_CONNECT_INITIAL_STATE_KEY, Boolean.FALSE) - .addParameter(Constants.RECONNECT_KEY, Boolean.FALSE) - .addParameter(Constants.SEND_RECONNECT_KEY, Boolean.TRUE.toString()) + .addParameter(RemotingConstants.RECONNECT_KEY, Boolean.FALSE) + .addParameter(RemotingConstants.SEND_RECONNECT_KEY, Boolean.TRUE.toString()) .addParameter("warning", Boolean.TRUE.toString()) .addParameter(LazyConnectExchangeClient.REQUEST_WITH_WARNING_KEY, true) .addParameter("_client_memo", "referencecounthandler.replacewithlazyclient") diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java index 1249c93e2c8..004e47f1588 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java @@ -17,6 +17,7 @@ package org.apache.dubbo.rpc.protocol.dubbo.filter; import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -103,7 +104,7 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept } count = c.getAndIncrement(); if (count < max) { - String prompt = channel.getUrl().getParameter(Constants.PROMPT_KEY, Constants.DEFAULT_PROMPT); + String prompt = channel.getUrl().getParameter(RemotingConstants.PROMPT_KEY, RemotingConstants.DEFAULT_PROMPT); channel.send("\r\n" + RpcContext.getContext().getRemoteAddress() + " -> " + invoker.getInterface().getName() + "." + invocation.getMethodName() diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/status/ThreadPoolStatusChecker.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/status/ThreadPoolStatusChecker.java index 1e88c15b34b..6797782f3a5 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/status/ThreadPoolStatusChecker.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/status/ThreadPoolStatusChecker.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.rpc.protocol.dubbo.status; -import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.status.Status; @@ -36,7 +36,7 @@ public class ThreadPoolStatusChecker implements StatusChecker { @Override public Status check() { DataStore dataStore = ExtensionLoader.getExtensionLoader(DataStore.class).getDefaultExtension(); - Map executors = dataStore.get(Constants.EXECUTOR_SERVICE_COMPONENT_KEY); + Map executors = dataStore.get(RemotingConstants.EXECUTOR_SERVICE_COMPONENT_KEY); StringBuilder msg = new StringBuilder(); Status.Level level = Status.Level.OK; diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java index e2b71d05432..b63a3584652 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java @@ -20,6 +20,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.exchange.ExchangeClient; @@ -76,12 +77,12 @@ public void test_Normal_ChannelReadOnly() throws Exception { DubboInvoker invoker = (DubboInvoker) protocol.refer(IDemoService.class, url); Assertions.assertEquals(true, invoker.isAvailable()); - getClients(invoker)[0].setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); + getClients(invoker)[0].setAttribute(RemotingConstants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); Assertions.assertEquals(false, invoker.isAvailable()); // reset status since connection is shared among invokers - getClients(invoker)[0].removeAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY); + getClients(invoker)[0].removeAttribute(RemotingConstants.CHANNEL_ATTRIBUTE_READONLY_KEY); } @Disabled @@ -130,7 +131,7 @@ public void test_Lazy_ChannelReadOnly() throws Exception { Assertions.assertEquals(true, invoker.isAvailable()); try { - getClients(invoker)[0].setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); + getClients(invoker)[0].setAttribute(RemotingConstants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); fail(); } catch (IllegalStateException e) { @@ -140,7 +141,7 @@ public void test_Lazy_ChannelReadOnly() throws Exception { Assertions.assertEquals("ok", service.get()); Assertions.assertEquals(true, invoker.isAvailable()); - getClients(invoker)[0].setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); + getClients(invoker)[0].setAttribute(RemotingConstants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); Assertions.assertEquals(false, invoker.isAvailable()); } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocolTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocolTest.java index 61d9b6cc148..b5df719f3ea 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocolTest.java @@ -17,8 +17,8 @@ package org.apache.dubbo.rpc.protocol.dubbo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; @@ -96,8 +96,8 @@ public void testDubboProtocol() throws Exception { @Test public void testDubboProtocolWithMina() throws Exception { DemoService service = new DemoServiceImpl(); - protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:9011/" + DemoService.class.getName()).addParameter(Constants.SERVER_KEY, "mina"))); - service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:9011/" + DemoService.class.getName()).addParameter(Constants.CLIENT_KEY, "mina").addParameter("timeout", 3000l))); + protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:9011/" + DemoService.class.getName()).addParameter(RemotingConstants.SERVER_KEY, "mina"))); + service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:9011/" + DemoService.class.getName()).addParameter(RemotingConstants.CLIENT_KEY, "mina").addParameter("timeout", 3000l))); for (int i = 0; i < 10; i++) { assertEquals(service.enumlength(new Type[]{}), Type.Lower); assertEquals(service.getSize(null), -1); diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/DubboHessianURLConnectionFactory.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/DubboHessianURLConnectionFactory.java index 21c566fe0fb..10d1a1bffe3 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/DubboHessianURLConnectionFactory.java +++ b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/DubboHessianURLConnectionFactory.java @@ -17,7 +17,7 @@ package org.apache.dubbo.rpc.protocol.hessian; -import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.rpc.RpcContext; import com.caucho.hessian.client.HessianConnection; @@ -33,7 +33,7 @@ public HessianConnection open(URL url) throws IOException { HessianConnection connection = super.open(url); RpcContext context = RpcContext.getContext(); for (String key : context.getAttachments().keySet()) { - connection.addHeader(Constants.DEFAULT_EXCHANGER + key, context.getAttachment(key)); + connection.addHeader(RemotingConstants.DEFAULT_EXCHANGER + key, context.getAttachment(key)); } return connection; diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocol.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocol.java index 3b9239171a9..0c76e1e7662 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocol.java +++ b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocol.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.remoting.http.HttpBinder; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.remoting.http.HttpServer; @@ -107,7 +108,7 @@ protected T doRefer(Class serviceType, URL url) throws RpcException { hessianProxyFactory.setHessian2Request(isHessian2Request); boolean isOverloadEnabled = url.getParameter(Constants.HESSIAN_OVERLOAD_METHOD_KEY, Constants.DEFAULT_HESSIAN_OVERLOAD_METHOD); hessianProxyFactory.setOverloadEnabled(isOverloadEnabled); - String client = url.getParameter(Constants.CLIENT_KEY, Constants.DEFAULT_HTTP_CLIENT); + String client = url.getParameter(RemotingConstants.CLIENT_KEY, Constants.DEFAULT_HTTP_CLIENT); if ("httpclient".equals(client)) { HessianConnectionFactory factory = new HttpClientConnectionFactory(); factory.setHessianProxyFactory(hessianProxyFactory); @@ -174,8 +175,8 @@ public void handle(HttpServletRequest request, HttpServletResponse response) Enumeration enumeration = request.getHeaderNames(); while (enumeration.hasMoreElements()) { String key = enumeration.nextElement(); - if (key.startsWith(Constants.DEFAULT_EXCHANGER)) { - RpcContext.getContext().setAttachment(key.substring(Constants.DEFAULT_EXCHANGER.length()), + if (key.startsWith(RemotingConstants.DEFAULT_EXCHANGER)) { + RpcContext.getContext().setAttachment(key.substring(RemotingConstants.DEFAULT_EXCHANGER.length()), request.getHeader(key)); } } diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HttpClientConnectionFactory.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HttpClientConnectionFactory.java index 2c6f6db890b..b5bec3e2c5e 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HttpClientConnectionFactory.java +++ b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HttpClientConnectionFactory.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.rpc.protocol.hessian; -import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.rpc.RpcContext; import com.caucho.hessian.client.HessianConnection; @@ -49,7 +49,7 @@ public HessianConnection open(URL url) { HttpClientConnection httpClientConnection = new HttpClientConnection(httpClient, url); RpcContext context = RpcContext.getContext(); for (String key : context.getAttachments().keySet()) { - httpClientConnection.addHeader(Constants.DEFAULT_EXCHANGER + key, context.getAttachment(key)); + httpClientConnection.addHeader(RemotingConstants.DEFAULT_EXCHANGER + key, context.getAttachment(key)); } return httpClientConnection; } diff --git a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java b/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java index 0188a0fe329..d744ebfc0e8 100644 --- a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java +++ b/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.Version; import org.apache.dubbo.remoting.http.HttpBinder; @@ -153,7 +154,7 @@ public RemoteInvocation createRemoteInvocation(MethodInvocation methodInvocation httpProxyFactoryBean.setServiceUrl(key); httpProxyFactoryBean.setServiceInterface(serviceType); - String client = url.getParameter(Constants.CLIENT_KEY); + String client = url.getParameter(RemotingConstants.CLIENT_KEY); if (StringUtils.isEmpty(client) || "simple".equals(client)) { SimpleHttpInvokerRequestExecutor httpInvokerRequestExecutor = new SimpleHttpInvokerRequestExecutor() { @Override @@ -161,14 +162,14 @@ protected void prepareConnection(HttpURLConnection con, int contentLength) throws IOException { super.prepareConnection(con, contentLength); con.setReadTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); - con.setConnectTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT)); + con.setConnectTimeout(url.getParameter(RemotingConstants.CONNECT_TIMEOUT_KEY, RemotingConstants.DEFAULT_CONNECT_TIMEOUT)); } }; httpProxyFactoryBean.setHttpInvokerRequestExecutor(httpInvokerRequestExecutor); } else if ("commons".equals(client)) { HttpComponentsHttpInvokerRequestExecutor httpInvokerRequestExecutor = new HttpComponentsHttpInvokerRequestExecutor(); httpInvokerRequestExecutor.setReadTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); - httpInvokerRequestExecutor.setConnectTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT)); + httpInvokerRequestExecutor.setConnectTimeout(url.getParameter(RemotingConstants.CONNECT_TIMEOUT_KEY, RemotingConstants.DEFAULT_CONNECT_TIMEOUT)); httpProxyFactoryBean.setHttpInvokerRequestExecutor(httpInvokerRequestExecutor); } else { throw new IllegalStateException("Unsupported http protocol client " + client + ", only supported: simple, commons"); diff --git a/dubbo-rpc/dubbo-rpc-memcached/src/main/java/org/apache/dubbo/rpc/protocol/memcached/MemcachedProtocol.java b/dubbo-rpc/dubbo-rpc-memcached/src/main/java/org/apache/dubbo/rpc/protocol/memcached/MemcachedProtocol.java index 8fa088bb95f..2633e961d85 100644 --- a/dubbo-rpc/dubbo-rpc-memcached/src/main/java/org/apache/dubbo/rpc/protocol/memcached/MemcachedProtocol.java +++ b/dubbo-rpc/dubbo-rpc-memcached/src/main/java/org/apache/dubbo/rpc/protocol/memcached/MemcachedProtocol.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.rpc.protocol.memcached; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -59,7 +59,7 @@ public Exporter export(final Invoker invoker) throws RpcException { public Invoker refer(final Class type, final URL url) throws RpcException { try { String address = url.getAddress(); - String backup = url.getParameter(Constants.BACKUP_KEY); + String backup = url.getParameter(RemotingConstants.BACKUP_KEY); if (backup != null && backup.length() > 0) { address += "," + backup; } diff --git a/dubbo-rpc/dubbo-rpc-redis/src/main/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocol.java b/dubbo-rpc/dubbo-rpc-redis/src/main/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocol.java index ba35c298ec4..f93b4447920 100644 --- a/dubbo-rpc/dubbo-rpc-redis/src/main/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocol.java +++ b/dubbo-rpc/dubbo-rpc-redis/src/main/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocol.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -64,7 +65,7 @@ public Exporter export(final Invoker invoker) throws RpcException { } private Serialization getSerialization(URL url) { - return ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(url.getParameter(Constants.SERIALIZATION_KEY, "java")); + return ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(url.getParameter(RemotingConstants.SERIALIZATION_KEY, "java")); } @Override diff --git a/dubbo-rpc/dubbo-rpc-redis/src/test/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocolTest.java b/dubbo-rpc/dubbo-rpc-redis/src/test/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocolTest.java index 9abada0a49e..f42cc821b87 100644 --- a/dubbo-rpc/dubbo-rpc-redis/src/test/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-redis/src/test/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocolTest.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.rpc.protocol.redis; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.Serialization; @@ -177,7 +177,7 @@ public void testAuthRedis() { JedisPool pool = new JedisPool(new GenericObjectPoolConfig(), "localhost", registryUrl.getPort(), 2000, password, database, (String) null); try (Jedis jedis = pool.getResource()) { byte[] valueByte = jedis.get("key".getBytes()); - Serialization serialization = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(this.registryUrl.getParameter(Constants.SERIALIZATION_KEY, "java")); + Serialization serialization = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(this.registryUrl.getParameter(RemotingConstants.SERIALIZATION_KEY, "java")); ObjectInput oin = serialization.deserialize(this.registryUrl, new ByteArrayInputStream(valueByte)); String actual = (String) oin.readObject(); assertThat(value, is(actual)); diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/NettyServer.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/NettyServer.java index 7ee4a8f8641..d8380f54b8c 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/NettyServer.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/NettyServer.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.NetUtils; import io.netty.channel.ChannelOption; @@ -37,17 +38,17 @@ public class NettyServer extends BaseRestServer { @Override protected void doStart(URL url) { - String bindIp = url.getParameter(Constants.BIND_IP_KEY, url.getHost()); + String bindIp = url.getParameter(RemotingConstants.BIND_IP_KEY, url.getHost()); if (!url.isAnyHost() && NetUtils.isValidLocalHost(bindIp)) { server.setHostname(bindIp); } - server.setPort(url.getParameter(Constants.BIND_PORT_KEY, url.getPort())); + server.setPort(url.getParameter(RemotingConstants.BIND_PORT_KEY, url.getPort())); Map channelOption = new HashMap(); channelOption.put(ChannelOption.SO_KEEPALIVE, url.getParameter(Constants.KEEP_ALIVE_KEY, Constants.DEFAULT_KEEP_ALIVE)); server.setChildChannelOptions(channelOption); server.setExecutorThreadCount(url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS)); - server.setIoWorkerCount(url.getParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS)); - server.setMaxRequestSize(url.getParameter(Constants.PAYLOAD_KEY, Constants.DEFAULT_PAYLOAD)); + server.setIoWorkerCount(url.getParameter(Constants.IO_THREADS_KEY, RemotingConstants.DEFAULT_IO_THREADS)); + server.setMaxRequestSize(url.getParameter(RemotingConstants.PAYLOAD_KEY, RemotingConstants.DEFAULT_PAYLOAD)); server.start(); } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java index 6265254d4c6..4934ca50ba6 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.http.HttpBinder; import org.apache.dubbo.remoting.http.servlet.BootstrapListener; @@ -89,13 +90,13 @@ protected Runnable doExport(T impl, Class type, URL url) throws RpcExcept String addr = getAddr(url); Class implClass = ApplicationModel.getProviderModel(url.getPathKey()).getServiceInstance().getClass(); RestServer server = servers.computeIfAbsent(addr, restServer -> { - RestServer s = serverFactory.createServer(url.getParameter(Constants.SERVER_KEY, DEFAULT_SERVER)); + RestServer s = serverFactory.createServer(url.getParameter(RemotingConstants.SERVER_KEY, DEFAULT_SERVER)); s.start(url); return s; }); String contextPath = getContextPath(url); - if ("servlet".equalsIgnoreCase(url.getParameter(Constants.SERVER_KEY, DEFAULT_SERVER))) { + if ("servlet".equalsIgnoreCase(url.getParameter(RemotingConstants.SERVER_KEY, DEFAULT_SERVER))) { ServletContext servletContext = ServletManager.getInstance().getServletContext(ServletManager.EXTERNAL_SERVER_PORT); if (servletContext == null) { throw new RpcException("No servlet context found. Since you are using server='servlet', " + @@ -142,7 +143,7 @@ protected T doRefer(Class serviceType, URL url) throws RpcException { } connectionMonitor.addConnectionManager(connectionManager); RequestConfig requestConfig = RequestConfig.custom() - .setConnectTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT)) + .setConnectTimeout(url.getParameter(RemotingConstants.CONNECT_TIMEOUT_KEY, RemotingConstants.DEFAULT_CONNECT_TIMEOUT)) .setSocketTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)) .build(); diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/RestProtocolTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/RestProtocolTest.java index d1d3295d7cb..aa850301427 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/RestProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/RestProtocolTest.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.Exporter; @@ -112,7 +113,7 @@ public void testNettyServer() { ProviderModel providerModel = new ProviderModel(exportUrl.getServiceKey(), server, DemoService.class); ApplicationModel.initProviderModel(exportUrl.getServiceKey(), providerModel); - URL nettyUrl = exportUrl.addParameter(Constants.SERVER_KEY, "netty"); + URL nettyUrl = exportUrl.addParameter(RemotingConstants.SERVER_KEY, "netty"); Exporter exporter = protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); @@ -130,7 +131,7 @@ public void testServletWithoutWebConfig() { ProviderModel providerModel = new ProviderModel(exportUrl.getServiceKey(), server, DemoService.class); ApplicationModel.initProviderModel(exportUrl.getPathKey(), providerModel); - URL servletUrl = exportUrl.addParameter(Constants.SERVER_KEY, "servlet"); + URL servletUrl = exportUrl.addParameter(RemotingConstants.SERVER_KEY, "servlet"); protocol.export(proxy.getInvoker(server, DemoService.class, servletUrl)); }); @@ -143,7 +144,7 @@ public void testErrorHandler() { ProviderModel providerModel = new ProviderModel(exportUrl.getServiceKey(), server, DemoService.class); ApplicationModel.initProviderModel(exportUrl.getServiceKey(), providerModel); - URL nettyUrl = exportUrl.addParameter(Constants.SERVER_KEY, "netty"); + URL nettyUrl = exportUrl.addParameter(RemotingConstants.SERVER_KEY, "netty"); Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); @@ -173,7 +174,7 @@ public void testFilter() { ProviderModel providerModel = new ProviderModel(exportUrl.getServiceKey(), server, DemoService.class); ApplicationModel.initProviderModel(exportUrl.getServiceKey(), providerModel); - URL nettyUrl = exportUrl.addParameter(Constants.SERVER_KEY, "netty") + URL nettyUrl = exportUrl.addParameter(RemotingConstants.SERVER_KEY, "netty") .addParameter(Constants.EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.support.LoggingFilter"); Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); @@ -193,7 +194,7 @@ public void testRpcContextFilter() { ApplicationModel.initProviderModel(exportUrl.getServiceKey(), providerModel); // use RpcContextFilter - URL nettyUrl = exportUrl.addParameter(Constants.SERVER_KEY, "netty") + URL nettyUrl = exportUrl.addParameter(RemotingConstants.SERVER_KEY, "netty") .addParameter(Constants.EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.RpcContextFilter"); Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java index fa123e232a5..a6aeba1ebed 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.AtomicPositiveInteger; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.TimeoutException; @@ -106,7 +107,7 @@ public boolean isAvailable() { for (ExchangeClient client : clients) { if (client.isConnected() - && !client.hasAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY)) { + && !client.hasAttribute(RemotingConstants.CHANNEL_ATTRIBUTE_READONLY_KEY)) { //cannot write == not Available ? return true; } diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java index 055af6f8bb3..ec6370938c4 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java @@ -19,6 +19,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.RemotingException; @@ -116,7 +117,7 @@ public int getDefaultPort() { public Exporter export(Invoker invoker) throws RpcException { // can use thrift codec only - URL url = invoker.getUrl().addParameter(Constants.CODEC_KEY, ThriftCodec.NAME); + URL url = invoker.getUrl().addParameter(RemotingConstants.CODEC_KEY, ThriftCodec.NAME); // find server. String key = url.getAddress(); // client can expose a service for server to invoke only. @@ -183,7 +184,7 @@ private ExchangeClient initClient(URL url) { ExchangeClient client; - url = url.addParameter(Constants.CODEC_KEY, ThriftCodec.NAME); + url = url.addParameter(RemotingConstants.CODEC_KEY, ThriftCodec.NAME); try { client = Exchangers.connect(url); @@ -198,8 +199,8 @@ private ExchangeClient initClient(URL url) { private ExchangeServer getServer(URL url) { // enable sending readonly event when server closes by default - url = url.addParameterIfAbsent(Constants.CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString()); - String str = url.getParameter(Constants.SERVER_KEY, Constants.DEFAULT_REMOTING_SERVER); + url = url.addParameterIfAbsent(RemotingConstants.CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString()); + String str = url.getParameter(RemotingConstants.SERVER_KEY, RemotingConstants.DEFAULT_REMOTING_SERVER); if (str != null && str.length() > 0 && !ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str)) { throw new RpcException("Unsupported server type: " + str + ", url: " + url); @@ -211,7 +212,7 @@ private ExchangeServer getServer(URL url) { } catch (RemotingException e) { throw new RpcException("Fail to start server(url: " + url + ") " + e.getMessage(), e); } - str = url.getParameter(Constants.CLIENT_KEY); + str = url.getParameter(RemotingConstants.CLIENT_KEY); if (str != null && str.length() > 0) { Set supportedTypes = ExtensionLoader.getExtensionLoader(Transporter.class).getSupportedExtensions(); if (!supportedTypes.contains(str)) { diff --git a/dubbo-rpc/dubbo-rpc-webservice/src/main/java/org/apache/dubbo/rpc/protocol/webservice/WebServiceProtocol.java b/dubbo-rpc/dubbo-rpc-webservice/src/main/java/org/apache/dubbo/rpc/protocol/webservice/WebServiceProtocol.java index ddb270def40..62215aa6d27 100644 --- a/dubbo-rpc/dubbo-rpc-webservice/src/main/java/org/apache/dubbo/rpc/protocol/webservice/WebServiceProtocol.java +++ b/dubbo-rpc/dubbo-rpc-webservice/src/main/java/org/apache/dubbo/rpc/protocol/webservice/WebServiceProtocol.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.remoting.http.HttpBinder; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.remoting.http.HttpServer; @@ -116,7 +117,7 @@ protected T doRefer(final Class serviceType, final URL url) throws RpcExc Client proxy = ClientProxy.getClient(ref); HTTPConduit conduit = (HTTPConduit) proxy.getConduit(); HTTPClientPolicy policy = new HTTPClientPolicy(); - policy.setConnectionTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT)); + policy.setConnectionTimeout(url.getParameter(RemotingConstants.CONNECT_TIMEOUT_KEY, RemotingConstants.DEFAULT_CONNECT_TIMEOUT)); policy.setReceiveTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); conduit.setClient(policy); return ref; From a1e5c8e76d30e1a8ed7e43c87a94077d0b87c9a8 Mon Sep 17 00:00:00 2001 From: jimin Date: Sun, 12 May 2019 10:35:27 +0800 Subject: [PATCH 042/115] optimize some code style (#4006) * optimize constant naming style * optimize some code style Signed-off-by: jimin.jm --- .../java/org/apache/dubbo/common/utils/NetUtils.java | 10 +++++----- .../dubbo/metadata/support/AbstractMetadataReport.java | 4 ++-- .../org/apache/dubbo/monitor/dubbo/MetricsFilter.java | 3 ++- .../java/org/apache/dubbo/qos/command/impl/Ls.java | 4 ++-- .../dubbo/registry/integration/RegistryProtocol.java | 10 +++++----- .../dubbo/registry/nacos/NacosRegistryFactory.java | 1 + .../dubbo/remoting/etcd/jetcd/JEtcdClientWrapper.java | 4 +++- .../org/apache/dubbo/rpc/filter/ActiveLimitFilter.java | 6 +++--- .../common/serialize/gson/GsonJsonObjectInput.java | 4 +++- 9 files changed, 26 insertions(+), 20 deletions(-) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java index e5b85ecd577..828a97e7d36 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java @@ -428,7 +428,7 @@ public static boolean matchIpRange(String pattern, String host, int port) throws host = inetAddress.getHostAddress(); - String[] ip_address = host.split(splitCharacter); + String[] ipAddress = host.split(splitCharacter); if (pattern.equals(host)) { return true; } @@ -442,7 +442,7 @@ public static boolean matchIpRange(String pattern, String host, int port) throws } } for (int i = 0; i < mask.length; i++) { - if (mask[i].equals("*") || mask[i].equals(ip_address[i])) { + if (mask[i].equals("*") || mask[i].equals(ipAddress[i])) { continue; } else if (mask[i].contains("-")) { String[] rangeNumStrs = mask[i].split("-"); @@ -451,13 +451,13 @@ public static boolean matchIpRange(String pattern, String host, int port) throws } Integer min = getNumOfIpSegment(rangeNumStrs[0], isIpv4); Integer max = getNumOfIpSegment(rangeNumStrs[1], isIpv4); - Integer ip = getNumOfIpSegment(ip_address[i], isIpv4); + Integer ip = getNumOfIpSegment(ipAddress[i], isIpv4); if (ip < min || ip > max) { return false; } - } else if ("0".equals(ip_address[i]) && ("0".equals(mask[i]) || "00".equals(mask[i]) || "000".equals(mask[i]) || "0000".equals(mask[i]))) { + } else if ("0".equals(ipAddress[i]) && ("0".equals(mask[i]) || "00".equals(mask[i]) || "000".equals(mask[i]) || "0000".equals(mask[i]))) { continue; - } else if (!mask[i].equals(ip_address[i])) { + } else if (!mask[i].equals(ipAddress[i])) { return false; } } diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java index 16daa2eeb50..49b4b8f7dcc 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java +++ b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java @@ -74,7 +74,7 @@ public abstract class AbstractMetadataReport implements MetadataReport { boolean syncReport; // Local disk cache file File file; - private AtomicBoolean INIT = new AtomicBoolean(false); + private AtomicBoolean initialized = new AtomicBoolean(false); public MetadataReportRetry metadataReportRetry; public AbstractMetadataReport(URL reportServerURL) { @@ -90,7 +90,7 @@ public AbstractMetadataReport(URL reportServerURL) { } } // if this file exist, firstly delete it. - if (!INIT.getAndSet(true) && file.exists()) { + if (!initialized.getAndSet(true) && file.exists()) { file.delete(); } } diff --git a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java index a05c510de71..52bec170f4e 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java +++ b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java @@ -186,8 +186,9 @@ private List getThreadPoolMessage() { } private MetricObject value2MetricObject(String metric, Integer value, MetricLevel level) { - if (metric == null || value == null || level == null) + if (metric == null || value == null || level == null) { return null; + } return new MetricObject .Builder(metric) diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Ls.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Ls.java index 4777727c59a..469a40a3391 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Ls.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Ls.java @@ -45,7 +45,7 @@ public String execute(CommandContext commandContext, String[] args) { public String listProvider() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("As Provider side:" + System.lineSeparator()); - Collection ProviderModelList = ApplicationModel.allProviderModels(); + Collection providerModelList = ApplicationModel.allProviderModels(); TTable tTable = new TTable(new TTable.ColumnDefine[]{ new TTable.ColumnDefine(TTable.Align.MIDDLE), @@ -56,7 +56,7 @@ public String listProvider() { tTable.addRow("Provider Service Name", "PUB"); //Content - for (ProviderModel providerModel : ProviderModelList) { + for (ProviderModel providerModel : providerModelList) { tTable.addRow(providerModel.getServiceName(), isRegistered(providerModel.getServiceName()) ? "Y" : "N"); } stringBuilder.append(tTable.rendering()); diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java index b1b3393b1cf..c70be0b92ce 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java @@ -295,18 +295,18 @@ private URL getRegisteredProviderUrl(final URL providerUrl, final URL registryUr MONITOR_KEY, BIND_IP_KEY, BIND_PORT_KEY, QOS_ENABLE, QOS_PORT, ACCEPT_FOREIGN_IP, VALIDATION_KEY, INTERFACES); } else { - String extra_keys = registryUrl.getParameter(EXTRA_KEYS_KEY, ""); + String extraKeys = registryUrl.getParameter(EXTRA_KEYS_KEY, ""); // if path is not the same as interface name then we should keep INTERFACE_KEY, // otherwise, the registry structure of zookeeper would be '/dubbo/path/providers', // but what we expect is '/dubbo/interface/providers' if (!providerUrl.getPath().equals(providerUrl.getParameter(Constants.INTERFACE_KEY))) { - if (StringUtils.isNotEmpty(extra_keys)) { - extra_keys += ","; + if (StringUtils.isNotEmpty(extraKeys)) { + extraKeys += ","; } - extra_keys += Constants.INTERFACE_KEY; + extraKeys += Constants.INTERFACE_KEY; } String[] paramsToRegistry = getParamsToRegistry(DEFAULT_REGISTER_PROVIDER_KEYS - , Constants.COMMA_SPLIT_PATTERN.split(extra_keys)); + , Constants.COMMA_SPLIT_PATTERN.split(extraKeys)); return URL.valueOf(providerUrl, paramsToRegistry, providerUrl.getParameter(METHODS_KEY, (String[]) null)); } diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistryFactory.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistryFactory.java index d0e508d4533..2b66fb1e95b 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistryFactory.java +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistryFactory.java @@ -48,6 +48,7 @@ public class NacosRegistryFactory extends AbstractRegistryFactory { private final Logger logger = LoggerFactory.getLogger(getClass()); + @Override protected Registry createRegistry(URL url) { return new NacosRegistry(url, buildNamingService(url)); } diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapper.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapper.java index c27fb56b07d..01bf17d264d 100644 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapper.java +++ b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapper.java @@ -186,7 +186,9 @@ public List getChildren(String path) { int index = len, count = 0; if (key.length() > len) { for (; (index = key.indexOf(Constants.PATH_SEPARATOR, index)) != -1; ++index) { - if (count++ > 1) break; + if (count++ > 1) { + break; + } } } return count == 1; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java index 1c2f69fecb9..926fd019425 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java @@ -47,12 +47,12 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept String methodName = invocation.getMethodName(); int max = invoker.getUrl().getMethodParameter(methodName, Constants.ACTIVES_KEY, 0); RpcStatus count = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName()); - if (!count.beginCount(url, methodName, max)) { + if (!RpcStatus.beginCount(url, methodName, max)) { long timeout = invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.TIMEOUT_KEY, 0); long start = System.currentTimeMillis(); long remain = timeout; synchronized (count) { - while (!count.beginCount(url, methodName, max)) { + while (!RpcStatus.beginCount(url, methodName, max)) { try { count.wait(remain); } catch (InterruptedException e) { @@ -79,7 +79,7 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept isSuccess = false; throw t; } finally { - count.endCount(url, methodName, System.currentTimeMillis() - begin, isSuccess); + RpcStatus.endCount(url, methodName, System.currentTimeMillis() - begin, isSuccess); if (max > 0) { synchronized (count) { count.notifyAll(); diff --git a/dubbo-serialization/dubbo-serialization-gson/src/main/java/org/apache/dubbo/common/serialize/gson/GsonJsonObjectInput.java b/dubbo-serialization/dubbo-serialization-gson/src/main/java/org/apache/dubbo/common/serialize/gson/GsonJsonObjectInput.java index 94014f2d4a8..056d719dd28 100644 --- a/dubbo-serialization/dubbo-serialization-gson/src/main/java/org/apache/dubbo/common/serialize/gson/GsonJsonObjectInput.java +++ b/dubbo-serialization/dubbo-serialization-gson/src/main/java/org/apache/dubbo/common/serialize/gson/GsonJsonObjectInput.java @@ -107,7 +107,9 @@ public T readObject(Class cls, Type type) throws IOException, ClassNotFou private String readLine() throws IOException { String line = reader.readLine(); - if (line == null || line.trim().length() == 0) throw new EOFException(); + if (line == null || line.trim().length() == 0) { + throw new EOFException(); + } return line; } From 309b69432800cf5ecb342fef8f6484c849739bd6 Mon Sep 17 00:00:00 2001 From: jimin Date: Sun, 12 May 2019 10:44:08 +0800 Subject: [PATCH 043/115] optimize array code style (#4031) Signed-off-by: jimin.jm --- .../apache/dubbo/common/io/StreamUtils.java | 2 +- .../common/io/UnsafeByteArrayInputStream.java | 10 ++-- .../io/UnsafeByteArrayOutputStream.java | 4 +- .../common/json/GenericJSONConverter.java | 2 +- .../apache/dubbo/common/json/J2oVisitor.java | 2 +- .../org/apache/dubbo/common/json/Yylex.java | 10 ++-- .../support/AbortPolicyWithReport.java | 49 ++++++++++++------- .../support/command/LogTelnetHandler.java | 2 +- .../remoting/transport/AbstractCodec.java | 33 +++++++------ .../dubbo/telnet/LogTelnetHandler.java | 2 +- .../io/RandomAccessByteArrayOutputStream.java | 4 +- 11 files changed, 69 insertions(+), 51 deletions(-) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/io/StreamUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/io/StreamUtils.java index 2a463c3e098..ab2836ef913 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/io/StreamUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/io/StreamUtils.java @@ -40,7 +40,7 @@ public int read() throws IOException { } @Override - public int read(byte b[], int off, int len) throws IOException { + public int read(byte[] b, int off, int len) throws IOException { if (b == null) { throw new NullPointerException(); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeByteArrayInputStream.java b/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeByteArrayInputStream.java index c5b72bdc199..df96a1c1d01 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeByteArrayInputStream.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeByteArrayInputStream.java @@ -23,19 +23,19 @@ * UnsafeByteArrayInputStream. */ public class UnsafeByteArrayInputStream extends InputStream { - protected byte mData[]; + protected byte[] mData; protected int mPosition, mLimit, mMark = 0; - public UnsafeByteArrayInputStream(byte buf[]) { + public UnsafeByteArrayInputStream(byte[] buf) { this(buf, 0, buf.length); } - public UnsafeByteArrayInputStream(byte buf[], int offset) { + public UnsafeByteArrayInputStream(byte[] buf, int offset) { this(buf, offset, buf.length - offset); } - public UnsafeByteArrayInputStream(byte buf[], int offset, int length) { + public UnsafeByteArrayInputStream(byte[] buf, int offset, int length) { mData = buf; mPosition = mMark = offset; mLimit = Math.min(offset + length, buf.length); @@ -47,7 +47,7 @@ public int read() { } @Override - public int read(byte b[], int off, int len) { + public int read(byte[] b, int off, int len) { if (b == null) { throw new NullPointerException(); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeByteArrayOutputStream.java b/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeByteArrayOutputStream.java index 1ac43c893dd..6e75eb83109 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeByteArrayOutputStream.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeByteArrayOutputStream.java @@ -25,7 +25,7 @@ * UnsafeByteArrayOutputStream. */ public class UnsafeByteArrayOutputStream extends OutputStream { - protected byte mBuffer[]; + protected byte[] mBuffer; protected int mCount; @@ -51,7 +51,7 @@ public void write(int b) { } @Override - public void write(byte b[], int off, int len) { + public void write(byte[] b, int off, int len) { if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/json/GenericJSONConverter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/json/GenericJSONConverter.java index 74cf09a142b..9082eb155cb 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/json/GenericJSONConverter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/json/GenericJSONConverter.java @@ -474,7 +474,7 @@ public void writeValue(Object obj, JSONWriter jb, boolean writeClass) throws IOE jb.objectBegin(); Wrapper w = Wrapper.getWrapper(c); - String pns[] = w.getPropertyNames(); + String[] pns = w.getPropertyNames(); for (String pn : pns) { if ((obj instanceof Throwable) && ( diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/json/J2oVisitor.java b/dubbo-common/src/main/java/org/apache/dubbo/common/json/J2oVisitor.java index fdcf674c590..3aa3fd9ed1c 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/json/J2oVisitor.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/json/J2oVisitor.java @@ -83,7 +83,7 @@ private static Object toArray(Class c, Stack list, int len) throws Pa return EMPTY_STRING_ARRAY; } else { Object o; - String ss[] = new String[len]; + String[] ss = new String[len]; for (int i = len - 1; i >= 0; i--) { o = list.pop(); ss[i] = (o == null ? null : o.toString()); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/json/Yylex.java b/dubbo-common/src/main/java/org/apache/dubbo/common/json/Yylex.java index 822175e6031..32a73a7589e 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/json/Yylex.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/json/Yylex.java @@ -45,7 +45,7 @@ public class Yylex { * at the beginning of a line * l is of the form l = 2*k, k a non negative integer */ - private static final int ZZ_LEXSTATE[] = { + private static final int[] ZZ_LEXSTATE = { 0, 0, 1, 1, 2, 2 }; @@ -92,7 +92,7 @@ public class Yylex { /** * The transition table of the DFA */ - private static final int ZZ_TRANS[] = { + private static final int[] ZZ_TRANS = { 3, 4, 5, 5, 6, 3, 5, 3, 7, 8, 3, 9, 3, 5, 10, 11, 5, 12, 5, 5, 13, 5, 5, 5, 5, 5, 14, 5, 5, 5, @@ -247,7 +247,7 @@ public class Yylex { private static final int ZZ_NO_MATCH = 1; private static final int ZZ_PUSHBACK_2BIG = 2; /* error messages for the codes above */ - private static final String ZZ_ERROR_MSG[] = { + private static final String[] ZZ_ERROR_MSG = { "Unkown internal scanner error", "Error: could not match input", "Error: pushback value was too large" @@ -276,7 +276,7 @@ public class Yylex { * this buffer contains the current text to be matched and is * the source of the yytext() string */ - private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; + private char[] zzBuffer = new char[ZZ_BUFFERSIZE]; /** * the textposition at the last accepting state */ @@ -447,7 +447,7 @@ private boolean zzRefill() throws java.io.IOException { /* is the buffer big enough? */ if (zzCurrentPos >= zzBuffer.length) { /* if not: blow it up */ - char newBuffer[] = new char[zzCurrentPos * 2]; + char[] newBuffer = new char[zzCurrentPos * 2]; System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); zzBuffer = newBuffer; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/AbortPolicyWithReport.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/AbortPolicyWithReport.java index 8a137613f17..cb368db895c 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/AbortPolicyWithReport.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/AbortPolicyWithReport.java @@ -16,21 +16,21 @@ */ package org.apache.dubbo.common.threadpool.support; -import org.apache.dubbo.common.Constants; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.JVMUtil; - import java.io.File; import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.Date; +import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.ExecutorService; + +import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.common.utils.JVMUtil; /** * Abort Policy. @@ -46,6 +46,16 @@ public class AbortPolicyWithReport extends ThreadPoolExecutor.AbortPolicy { private static volatile long lastPrintTime = 0; + private static final long TEN_MINUTES_MILLS = 10 * 60 * 1000; + + private static final String OS_WIN_PREFIX = "win"; + + private static final String OS_NAME_KEY = "os.name"; + + private static final String WIN_DATETIME_FORMAT = "yyyy-MM-dd_HH-mm-ss"; + + private static final String DEFAULT_DATETIME_FORMAT = "yyyy-MM-dd_HH:mm:ss"; + private static Semaphore guard = new Semaphore(1); public AbortPolicyWithReport(String threadName, URL url) { @@ -56,11 +66,13 @@ public AbortPolicyWithReport(String threadName, URL url) { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { String msg = String.format("Thread pool is EXHAUSTED!" + - " Thread Name: %s, Pool Size: %d (active: %d, core: %d, max: %d, largest: %d), Task: %d (completed: %d)," + - " Executor status:(isShutdown:%s, isTerminated:%s, isTerminating:%s), in %s://%s:%d!", - threadName, e.getPoolSize(), e.getActiveCount(), e.getCorePoolSize(), e.getMaximumPoolSize(), e.getLargestPoolSize(), - e.getTaskCount(), e.getCompletedTaskCount(), e.isShutdown(), e.isTerminated(), e.isTerminating(), - url.getProtocol(), url.getIp(), url.getPort()); + " Thread Name: %s, Pool Size: %d (active: %d, core: %d, max: %d, largest: %d), Task: %d (completed: " + + "%d)," + + " Executor status:(isShutdown:%s, isTerminated:%s, isTerminating:%s), in %s://%s:%d!", + threadName, e.getPoolSize(), e.getActiveCount(), e.getCorePoolSize(), e.getMaximumPoolSize(), + e.getLargestPoolSize(), + e.getTaskCount(), e.getCompletedTaskCount(), e.isShutdown(), e.isTerminated(), e.isTerminating(), + url.getProtocol(), url.getIp(), url.getPort()); logger.warn(msg); dumpJStack(); throw new RejectedExecutionException(msg); @@ -70,7 +82,7 @@ private void dumpJStack() { long now = System.currentTimeMillis(); //dump every 10 minutes - if (now - lastPrintTime < 10 * 60 * 1000) { + if (now - lastPrintTime < TEN_MINUTES_MILLS) { return; } @@ -84,18 +96,19 @@ private void dumpJStack() { SimpleDateFormat sdf; - String os = System.getProperty("os.name").toLowerCase(); + String os = System.getProperty(OS_NAME_KEY).toLowerCase(); // window system don't support ":" in file name - if (os.contains("win")) { - sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss"); + if (os.contains(OS_WIN_PREFIX)) { + sdf = new SimpleDateFormat(WIN_DATETIME_FORMAT); } else { - sdf = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss"); + sdf = new SimpleDateFormat(DEFAULT_DATETIME_FORMAT); } String dateStr = sdf.format(new Date()); //try-with-resources - try (FileOutputStream jStackStream = new FileOutputStream(new File(dumpPath, "Dubbo_JStack.log" + "." + dateStr))) { + try (FileOutputStream jStackStream = new FileOutputStream( + new File(dumpPath, "Dubbo_JStack.log" + "." + dateStr))) { JVMUtil.jstack(jStackStream); } catch (Throwable t) { logger.error("dump jStack error", t); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/LogTelnetHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/LogTelnetHandler.java index db531dc626f..2d39c23b73b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/LogTelnetHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/LogTelnetHandler.java @@ -48,7 +48,7 @@ public String telnet(Channel channel, String message) { if (message == null || message.trim().length() == 0) { buf.append("EXAMPLE: log error / log 100"); } else { - String str[] = message.split(" "); + String[] str = message.split(" "); if (!StringUtils.isInteger(str[0])) { LoggerFactory.setLevel(Level.valueOf(message.toUpperCase())); } else { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractCodec.java index 346f54ca320..e5f76964370 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractCodec.java @@ -16,6 +16,9 @@ */ package org.apache.dubbo.remoting.transport; +import java.io.IOException; +import java.net.InetSocketAddress; + import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; @@ -26,9 +29,6 @@ import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Codec2; -import java.io.IOException; -import java.net.InetSocketAddress; - /** * AbstractCodec */ @@ -36,13 +36,18 @@ public abstract class AbstractCodec implements Codec2 { private static final Logger logger = LoggerFactory.getLogger(AbstractCodec.class); + private static final String CLIENT_SIDE = "client"; + + private static final String SERVER_SIDE = "server"; + protected static void checkPayload(Channel channel, long size) throws IOException { int payload = RemotingConstants.DEFAULT_PAYLOAD; if (channel != null && channel.getUrl() != null) { payload = channel.getUrl().getParameter(RemotingConstants.PAYLOAD_KEY, RemotingConstants.DEFAULT_PAYLOAD); } if (payload > 0 && size > payload) { - ExceedPayloadLimitException e = new ExceedPayloadLimitException("Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel); + ExceedPayloadLimitException e = new ExceedPayloadLimitException( + "Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel); logger.error(e); throw e; } @@ -53,21 +58,21 @@ protected Serialization getSerialization(Channel channel) { } protected boolean isClientSide(Channel channel) { - String side = (String) channel.getAttribute(Constants.SIDE_KEY); - if ("client".equals(side)) { + String side = (String)channel.getAttribute(Constants.SIDE_KEY); + if (CLIENT_SIDE.equals(side)) { return true; - } else if ("server".equals(side)) { + } else if (SERVER_SIDE.equals(side)) { return false; } else { InetSocketAddress address = channel.getRemoteAddress(); URL url = channel.getUrl(); - boolean client = url.getPort() == address.getPort() - && NetUtils.filterLocalHost(url.getIp()).equals( - NetUtils.filterLocalHost(address.getAddress() - .getHostAddress())); - channel.setAttribute(Constants.SIDE_KEY, client ? "client" - : "server"); - return client; + boolean isClient = url.getPort() == address.getPort() + && NetUtils.filterLocalHost(url.getIp()).equals( + NetUtils.filterLocalHost(address.getAddress() + .getHostAddress())); + channel.setAttribute(Constants.SIDE_KEY, isClient ? CLIENT_SIDE + : SERVER_SIDE); + return isClient; } } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/telnet/LogTelnetHandler.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/telnet/LogTelnetHandler.java index b62198d11d4..86bcd9b26a8 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/telnet/LogTelnetHandler.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/telnet/LogTelnetHandler.java @@ -48,7 +48,7 @@ public String telnet(Channel channel, String message) { if (message == null || message.trim().length() == 0) { buf.append("EXAMPLE: log error / log 100"); } else { - String str[] = message.split(" "); + String[] str = message.split(" "); if (!StringUtils.isInteger(str[0])) { LoggerFactory.setLevel(Level.valueOf(message.toUpperCase())); } else { diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/io/RandomAccessByteArrayOutputStream.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/io/RandomAccessByteArrayOutputStream.java index a5d0d119370..660dd8031db 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/io/RandomAccessByteArrayOutputStream.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/io/RandomAccessByteArrayOutputStream.java @@ -25,7 +25,7 @@ @Deprecated public class RandomAccessByteArrayOutputStream extends OutputStream { - protected byte buffer[]; + protected byte[] buffer; protected int count; @@ -54,7 +54,7 @@ public void write(int b) { } @Override - public void write(byte b[], int off, int len) { + public void write(byte[] b, int off, int len) { if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); From 6a3f4c75bd99a50e23d447174170c5867c17821f Mon Sep 17 00:00:00 2001 From: Taosheng Wei Date: Sun, 12 May 2019 10:47:31 +0800 Subject: [PATCH 044/115] use equal explicit class to replace anonymous class (#4027) --- .../rpc/cluster/support/AvailableCluster.java | 19 +------------------ 1 file changed, 1 insertion(+), 18 deletions(-) diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AvailableCluster.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AvailableCluster.java index 85e91e0527f..a2e353b4e4c 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AvailableCluster.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AvailableCluster.java @@ -16,15 +16,10 @@ */ package org.apache.dubbo.rpc.cluster.support; -import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.cluster.Cluster; import org.apache.dubbo.rpc.cluster.Directory; -import org.apache.dubbo.rpc.cluster.LoadBalance; - -import java.util.List; /** * AvailableCluster @@ -36,19 +31,7 @@ public class AvailableCluster implements Cluster { @Override public Invoker join(Directory directory) throws RpcException { - - return new AbstractClusterInvoker(directory) { - @Override - public Result doInvoke(Invocation invocation, List> invokers, LoadBalance loadbalance) throws RpcException { - for (Invoker invoker : invokers) { - if (invoker.isAvailable()) { - return invoker.invoke(invocation); - } - } - throw new RpcException("No provider available in " + invokers); - } - }; - + return new AvailableClusterInvoker<>(directory); } } From fe3d34588348122c2cb5af36541251b51d67e751 Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Sun, 12 May 2019 16:33:35 +0800 Subject: [PATCH 045/115] [DUBBO-3137]: step3 - start using CommonConstants (#4030) * [DUBBO-3137]: start to use org.apache.dubbo.common.constants.CommonConstants * remove useless imports * remove useless imports * remove unused imports * remove unused imports * remove unused imports * remove unused imports * remove unused imports * use static import --- .../dubbo/rpc/cluster/Configurator.java | 4 +- .../configurator/AbstractConfigurator.java | 50 +++--- .../configurator/parser/ConfigParser.java | 4 +- .../ConsistentHashLoadBalance.java | 5 +- .../router/condition/ConditionRouter.java | 11 +- .../router/condition/config/AppRouter.java | 4 +- .../rpc/cluster/router/tag/TagRouter.java | 3 +- .../rpc/cluster/support/ClusterUtils.java | 63 +++++--- .../support/ForkingClusterInvoker.java | 5 +- .../support/MergeableClusterInvoker.java | 8 +- .../support/RegistryAwareClusterInvoker.java | 4 +- .../configurator/parser/ConfigParserTest.java | 29 ++-- .../cluster/directory/MockDirInvocation.java | 15 +- .../rpc/cluster/support/ClusterUtilsTest.java | 71 ++++---- .../support/MergeableClusterInvokerTest.java | 9 +- .../org/apache/dubbo/common/Constants.java | 151 +----------------- .../org/apache/dubbo/common/Parameters.java | 11 +- .../java/org/apache/dubbo/common/URL.java | 37 +++-- .../org/apache/dubbo/common/URLBuilder.java | 4 +- .../apache/dubbo/common/bytecode/Proxy.java | 5 +- .../common/config/ConfigurationUtils.java | 4 +- .../dubbo/common/config/Environment.java | 4 +- .../common/constants/RegistryConstants.java | 25 --- .../common/extension/ExtensionLoader.java | 17 +- .../dubbo/common/threadpool/ThreadPool.java | 7 +- .../support/AbortPolicyWithReport.java | 5 +- .../support/cached/CachedThreadPool.java | 21 ++- .../support/eager/EagerThreadPool.java | 21 ++- .../support/fixed/FixedThreadPool.java | 14 +- .../support/limited/LimitedThreadPool.java | 18 ++- .../dubbo/common/utils/ConfigUtils.java | 24 +-- .../dubbo/common/utils/ExecutorUtil.java | 9 +- .../apache/dubbo/common/utils/NetUtils.java | 18 ++- .../dubbo/common/utils/StringUtils.java | 17 +- .../apache/dubbo/common/utils/UrlUtils.java | 73 +++++---- .../common/extension/ExtensionLoaderTest.java | 12 +- .../support/cached/CachedThreadPoolTest.java | 22 +-- .../support/eager/EagerThreadPoolTest.java | 21 ++- .../support/fixed/FixedThreadPoolTest.java | 19 ++- .../limited/LimitedThreadPoolTest.java | 19 ++- .../dubbo/common/utils/CIDRUtilsTest.java | 3 - .../dubbo/common/utils/ConfigUtilsTest.java | 13 +- .../dubbo/common/utils/ExecutorUtilTest.java | 9 +- .../dubbo/common/utils/StringUtilsTest.java | 13 +- .../dubbo/common/utils/UrlUtilsTest.java | 18 ++- .../cache/support/AbstractCacheFactory.java | 5 +- .../dubbo/config/ApplicationConfigTest.java | 11 +- .../apache/dubbo/filter/LegacyInvocation.java | 18 ++- .../apache/dubbo/service/MockInvocation.java | 15 +- .../apache/dubbo/config/AbstractConfig.java | 13 +- .../dubbo/config/AbstractInterfaceConfig.java | 40 +++-- .../dubbo/config/AbstractReferenceConfig.java | 7 +- .../dubbo/config/AbstractServiceConfig.java | 7 +- .../dubbo/config/ApplicationConfig.java | 9 +- .../dubbo/config/ConfigCenterConfig.java | 12 +- .../dubbo/config/MetadataReportConfig.java | 6 +- .../org/apache/dubbo/config/MethodConfig.java | 3 +- .../apache/dubbo/config/ProtocolConfig.java | 4 +- .../apache/dubbo/config/ProviderConfig.java | 4 +- .../apache/dubbo/config/ReferenceConfig.java | 28 ++-- .../apache/dubbo/config/RegistryConfig.java | 7 +- .../apache/dubbo/config/ServiceConfig.java | 31 ++-- .../dubbo/config/context/ConfigManager.java | 2 +- .../config/AbstractInterfaceConfigTest.java | 7 +- .../dubbo/config/ApplicationConfigTest.java | 8 +- .../dubbo/config/ServiceConfigTest.java | 18 ++- .../dubbo/config/mock/MockRegistry.java | 4 +- .../dubbo/config/spring/ReferenceBean.java | 7 +- .../dubbo/config/spring/ServiceBean.java | 20 +-- .../annotation/AnnotationBeanNameBuilder.java | 8 +- .../schema/DubboBeanDefinitionParser.java | 5 +- .../config/spring/SimpleRegistryExporter.java | 5 +- .../annotation/ReferenceBeanBuilderTest.java | 1 - .../apollo/ApolloDynamicConfiguration.java | 7 +- .../consul/ConsulDynamicConfiguration.java | 2 +- .../etcd/EtcdDynamicConfiguration.java | 2 +- .../nacos/NacosDynamicConfiguration.java | 20 +-- .../NacosDynamicConfigurationFactory.java | 7 +- .../java/org/apache/dubbo/container/Main.java | 5 +- .../dubbo/cache/filter/CacheFilter.java | 19 +-- .../cache/support/AbstractCacheFactory.java | 5 +- .../dubbo/cache/support/jcache/JCache.java | 5 +- .../validation/filter/ValidationFilter.java | 3 +- .../identifier/MetadataIdentifier.java | 24 +-- .../integration/MetadataReportService.java | 26 ++- .../support/AbstractMetadataReport.java | 14 +- .../identifier/MetadataIdentifierTest.java | 16 +- .../store/test/JTestMetadataReport4Test.java | 5 +- .../support/AbstractMetadataReportTest.java | 8 +- .../store/etcd/EtcdMetadataReport.java | 14 +- .../store/etcd/EtcdMetadataReportTest.java | 19 ++- .../store/redis/RedisMetadataReport.java | 6 +- .../store/redis/RedisMetadataReportTest.java | 10 +- .../zookeeper/ZookeeperMetadataReport.java | 14 +- .../ZookeeperMetadataReportTest.java | 8 +- .../support/AbstractMonitorFactory.java | 5 +- .../dubbo/monitor/support/MonitorFilter.java | 25 ++- .../monitor/support/MonitorFilterTest.java | 8 +- .../dubbo/monitor/dubbo/DubboMonitor.java | 7 +- .../monitor/dubbo/DubboMonitorFactory.java | 2 +- .../dubbo/monitor/dubbo/MetricsFilter.java | 30 ++-- .../monitor/dubbo/MetricsFilterTest.java | 63 ++++---- .../AbstractConfiguratorListener.java | 4 +- .../integration/RegistryDirectory.java | 27 ++-- .../integration/RegistryProtocol.java | 48 ++++-- .../registry/support/AbstractRegistry.java | 8 +- .../support/AbstractRegistryFactory.java | 4 +- .../registry/support/FailbackRegistry.java | 4 +- .../dubbo/registry/consul/ConsulRegistry.java | 10 +- .../registry/dubbo/DubboRegistryFactory.java | 15 +- .../registry/dubbo/RegistryDirectoryTest.java | 26 +-- .../registry/dubbo/RegistryProtocolTest.java | 2 +- .../dubbo/SimpleRegistryExporter.java | 5 +- .../dubbo/registry/etcd/EtcdRegistry.java | 41 ++--- .../dubbo/registry/etcd/EtcdRegistryTest.java | 18 ++- .../registry/multicast/MulticastRegistry.java | 12 +- .../dubbo/registry/nacos/NacosRegistry.java | 19 ++- .../dubbo/registry/redis/RedisRegistry.java | 46 +++--- .../dubbo/registry/sofa/SofaRegistry.java | 29 ++-- .../registry/zookeeper/ZookeeperRegistry.java | 38 +++-- .../exchange/support/DefaultFuture.java | 8 +- .../support/header/HeaderExchangeChannel.java | 6 +- .../telnet/support/TelnetHandlerAdapter.java | 4 +- .../support/command/StatusTelnetHandler.java | 5 +- .../remoting/transport/AbstractClient.java | 11 +- .../remoting/transport/AbstractCodec.java | 7 +- .../remoting/transport/AbstractEndpoint.java | 10 +- .../remoting/transport/AbstractServer.java | 13 +- .../dispatcher/WrappedChannelHandler.java | 8 +- .../ConnectionOrderedChannelHandler.java | 6 +- .../dubbo/remoting/ChanelHandlerTest.java | 7 +- .../remoting/PerformanceClientCloseTest.java | 9 +- .../remoting/PerformanceClientFixedTest.java | 8 +- .../dubbo/remoting/PerformanceClientTest.java | 5 +- .../dubbo/remoting/PerformanceServerTest.java | 16 +- .../codec/DeprecatedTelnetCodec.java | 6 +- .../remoting/etcd/jetcd/JEtcdClient.java | 7 +- .../etcd/jetcd/JEtcdClientWrapper.java | 8 +- .../etcd/support/AbstractEtcdClient.java | 4 +- .../transport/grizzly/GrizzlyChannel.java | 6 +- .../transport/grizzly/GrizzlyClient.java | 8 +- .../transport/grizzly/GrizzlyServer.java | 14 +- .../remoting/http/jetty/JettyHttpServer.java | 6 +- .../http/tomcat/TomcatHttpServer.java | 6 +- .../remoting/transport/mina/MinaChannel.java | 6 +- .../remoting/transport/mina/MinaServer.java | 7 +- .../transport/netty/NettyChannel.java | 6 +- .../remoting/transport/netty/NettyServer.java | 5 +- .../transport/netty4/NettyChannel.java | 6 +- .../transport/netty4/NettyServer.java | 4 +- .../curator/CuratorZookeeperClient.java | 5 +- .../support/AbstractZookeeperTransporter.java | 7 +- .../AbstractZookeeperTransporterTest.java | 4 +- .../java/org/apache/dubbo/rpc/RpcContext.java | 6 +- .../org/apache/dubbo/rpc/RpcInvocation.java | 29 ++-- .../dubbo/rpc/filter/AccessLogFilter.java | 10 +- .../dubbo/rpc/filter/ActiveLimitFilter.java | 7 +- .../dubbo/rpc/filter/ClassLoaderFilter.java | 4 +- .../rpc/filter/ConsumerContextFilter.java | 4 +- .../dubbo/rpc/filter/ContextFilter.java | 21 ++- .../dubbo/rpc/filter/DeprecatedFilter.java | 3 +- .../apache/dubbo/rpc/filter/EchoFilter.java | 3 +- .../dubbo/rpc/filter/ExceptionFilter.java | 4 +- .../dubbo/rpc/filter/ExecuteLimitFilter.java | 3 +- .../dubbo/rpc/filter/GenericFilter.java | 3 +- .../dubbo/rpc/filter/GenericImplFilter.java | 3 +- .../dubbo/rpc/filter/TimeoutFilter.java | 4 +- .../apache/dubbo/rpc/filter/TokenFilter.java | 3 +- .../dubbo/rpc/filter/TpsLimitFilter.java | 3 +- .../dubbo/rpc/protocol/AbstractProtocol.java | 7 +- .../rpc/protocol/AbstractProxyProtocol.java | 8 +- .../rpc/protocol/ProtocolFilterWrapper.java | 5 +- .../dubbo/rpc/proxy/AbstractProxyFactory.java | 4 +- .../dubbo/rpc/support/ProtocolUtils.java | 7 +- .../rpc/filter/tps/DefaultTPSLimiterTest.java | 14 +- .../rpc/filter/tps/TpsLimitFilterTest.java | 9 +- .../dubbo/rpc/support/MockInvocation.java | 15 +- .../protocol/dubbo/CallbackServiceCodec.java | 19 ++- .../protocol/dubbo/ChannelWrappedInvoker.java | 11 +- .../dubbo/DecodeableRpcInvocation.java | 6 +- .../dubbo/rpc/protocol/dubbo/DubboCodec.java | 6 +- .../rpc/protocol/dubbo/DubboInvoker.java | 17 +- .../rpc/protocol/dubbo/DubboProtocol.java | 19 ++- .../protocol/dubbo/filter/FutureFilter.java | 3 +- .../protocol/dubbo/filter/TraceFilter.java | 4 +- .../rpc/protocol/hessian/HessianProtocol.java | 5 +- .../dubbo/rpc/protocol/http/HttpProtocol.java | 10 +- .../rpc/protocol/injvm/InjvmInvoker.java | 5 +- .../rpc/protocol/injvm/InjvmProtocolTest.java | 15 +- .../rpc/protocol/redis/RedisProtocol.java | 6 +- .../rpc/protocol/rest/BaseRestServer.java | 4 +- .../dubbo/rpc/protocol/rest/NettyServer.java | 8 +- .../dubbo/rpc/protocol/rest/RestProtocol.java | 17 +- .../dubbo/rpc/protocol/rmi/RmiProtocol.java | 3 +- .../rpc/protocol/thrift/ThriftCodec.java | 15 +- .../rpc/protocol/thrift/ThriftInvoker.java | 16 +- .../rpc/protocol/thrift/ThriftProtocol.java | 5 +- .../rpc/protocol/thrift/ThriftCodecTest.java | 13 +- .../webservice/WebServiceProtocol.java | 6 +- 199 files changed, 1500 insertions(+), 1089 deletions(-) diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Configurator.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Configurator.java index b85a0461312..98760348448 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Configurator.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Configurator.java @@ -28,6 +28,8 @@ import java.util.Map; import java.util.Optional; +import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; + /** * Configurator. (SPI, Prototype, ThreadSafe) * @@ -82,7 +84,7 @@ static Optional> toConfigurators(List urls) { } Map override = new HashMap<>(url.getParameters()); //The anyhost parameter of override may be added automatically, it can't change the judgement of changing url - override.remove(Constants.ANYHOST_KEY); + override.remove(ANYHOST_KEY); if (override.size() == 0) { configurators.clear(); continue; diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java index 15665a5b74e..0ce3e00276b 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java @@ -27,6 +27,16 @@ import java.util.Map; import java.util.Set; +import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; +import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; +import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; + /** * AbstractOverrideConfigurator */ @@ -49,7 +59,7 @@ public URL getUrl() { @Override public URL configure(URL url) { // If override url is not enabled or is invalid, just return. - if (!configuratorUrl.getParameter(Constants.ENABLED_KEY, true) || configuratorUrl.getHost() == null || url == null || url.getHost() == null) { + if (!configuratorUrl.getParameter(ENABLED_KEY, true) || configuratorUrl.getHost() == null || url == null || url.getHost() == null) { return url; } /** @@ -57,11 +67,11 @@ public URL configure(URL url) { */ String apiVersion = configuratorUrl.getParameter(Constants.CONFIG_VERSION_KEY); if (StringUtils.isNotEmpty(apiVersion)) { - String currentSide = url.getParameter(Constants.SIDE_KEY); - String configuratorSide = configuratorUrl.getParameter(Constants.SIDE_KEY); - if (currentSide.equals(configuratorSide) && Constants.CONSUMER.equals(configuratorSide) && 0 == configuratorUrl.getPort()) { + String currentSide = url.getParameter(SIDE_KEY); + String configuratorSide = configuratorUrl.getParameter(SIDE_KEY); + if (currentSide.equals(configuratorSide) && CONSUMER.equals(configuratorSide) && 0 == configuratorUrl.getPort()) { url = configureIfMatch(NetUtils.getLocalHost(), url); - } else if (currentSide.equals(configuratorSide) && Constants.PROVIDER.equals(configuratorSide) && url.getPort() == configuratorUrl.getPort()) { + } else if (currentSide.equals(configuratorSide) && PROVIDER.equals(configuratorSide) && url.getPort() == configuratorUrl.getPort()) { url = configureIfMatch(url.getHost(), url); } } @@ -84,41 +94,41 @@ private URL configureDeprecated(URL url) { } else {// override url don't have a port, means the ip override url specify is a consumer address or 0.0.0.0 // 1.If it is a consumer ip address, the intention is to control a specific consumer instance, it must takes effect at the consumer side, any provider received this override url should ignore; // 2.If the ip is 0.0.0.0, this override url can be used on consumer, and also can be used on provider - if (url.getParameter(Constants.SIDE_KEY, Constants.PROVIDER).equals(Constants.CONSUMER)) { + if (url.getParameter(SIDE_KEY, PROVIDER).equals(CONSUMER)) { return configureIfMatch(NetUtils.getLocalHost(), url);// NetUtils.getLocalHost is the ip address consumer registered to registry. - } else if (url.getParameter(Constants.SIDE_KEY, Constants.CONSUMER).equals(Constants.PROVIDER)) { - return configureIfMatch(Constants.ANYHOST_VALUE, url);// take effect on all providers, so address must be 0.0.0.0, otherwise it won't flow to this if branch + } else if (url.getParameter(SIDE_KEY, CONSUMER).equals(PROVIDER)) { + return configureIfMatch(ANYHOST_VALUE, url);// take effect on all providers, so address must be 0.0.0.0, otherwise it won't flow to this if branch } } return url; } private URL configureIfMatch(String host, URL url) { - if (Constants.ANYHOST_VALUE.equals(configuratorUrl.getHost()) || host.equals(configuratorUrl.getHost())) { + if (ANYHOST_VALUE.equals(configuratorUrl.getHost()) || host.equals(configuratorUrl.getHost())) { // TODO, to support wildcards String providers = configuratorUrl.getParameter(Constants.OVERRIDE_PROVIDERS_KEY); - if (StringUtils.isEmpty(providers) || providers.contains(url.getAddress()) || providers.contains(Constants.ANYHOST_VALUE)) { - String configApplication = configuratorUrl.getParameter(Constants.APPLICATION_KEY, + if (StringUtils.isEmpty(providers) || providers.contains(url.getAddress()) || providers.contains(ANYHOST_VALUE)) { + String configApplication = configuratorUrl.getParameter(APPLICATION_KEY, configuratorUrl.getUsername()); - String currentApplication = url.getParameter(Constants.APPLICATION_KEY, url.getUsername()); - if (configApplication == null || Constants.ANY_VALUE.equals(configApplication) + String currentApplication = url.getParameter(APPLICATION_KEY, url.getUsername()); + if (configApplication == null || ANY_VALUE.equals(configApplication) || configApplication.equals(currentApplication)) { Set conditionKeys = new HashSet(); conditionKeys.add(Constants.CATEGORY_KEY); conditionKeys.add(RemotingConstants.CHECK_KEY); conditionKeys.add(Constants.DYNAMIC_KEY); - conditionKeys.add(Constants.ENABLED_KEY); - conditionKeys.add(Constants.GROUP_KEY); - conditionKeys.add(Constants.VERSION_KEY); - conditionKeys.add(Constants.APPLICATION_KEY); - conditionKeys.add(Constants.SIDE_KEY); + conditionKeys.add(ENABLED_KEY); + conditionKeys.add(GROUP_KEY); + conditionKeys.add(VERSION_KEY); + conditionKeys.add(APPLICATION_KEY); + conditionKeys.add(SIDE_KEY); conditionKeys.add(Constants.CONFIG_VERSION_KEY); for (Map.Entry entry : configuratorUrl.getParameters().entrySet()) { String key = entry.getKey(); String value = entry.getValue(); - if (key.startsWith("~") || Constants.APPLICATION_KEY.equals(key) || Constants.SIDE_KEY.equals(key)) { + if (key.startsWith("~") || APPLICATION_KEY.equals(key) || SIDE_KEY.equals(key)) { conditionKeys.add(key); - if (value != null && !Constants.ANY_VALUE.equals(value) + if (value != null && !ANY_VALUE.equals(value) && !value.equals(url.getParameter(key.startsWith("~") ? key.substring(1) : key))) { return url; } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParser.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParser.java index 76d6f2db3a3..962e52f8876 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParser.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParser.java @@ -31,6 +31,8 @@ import java.util.List; import java.util.Map; +import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; + /** * Config parser */ @@ -194,7 +196,7 @@ private static List parseAddresses(ConfigItem item) { addresses = new ArrayList<>(); } if (addresses.size() == 0) { - addresses.add(Constants.ANYHOST_VALUE); + addresses.add(ANYHOST_VALUE); } return addresses; } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalance.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalance.java index 75ebc8a7682..b48bc4ab32e 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalance.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalance.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.loadbalance; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -31,6 +30,8 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; + /** * ConsistentHashLoadBalance */ @@ -78,7 +79,7 @@ private static final class ConsistentHashSelector { this.identityHashCode = identityHashCode; URL url = invokers.get(0).getUrl(); this.replicaNumber = url.getMethodParameter(methodName, HASH_NODES, 160); - String[] index = Constants.COMMA_SPLIT_PATTERN.split(url.getMethodParameter(methodName, HASH_ARGUMENTS, "0")); + String[] index = COMMA_SPLIT_PATTERN.split(url.getMethodParameter(methodName, HASH_ARGUMENTS, "0")); argumentIndex = new int[index.length]; for (int i = 0; i < index.length; i++) { argumentIndex[i] = Integer.parseInt(index[i]); diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java index 1cd7536a92c..ab75f894d74 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java @@ -39,6 +39,11 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY_PREFIX; +import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; + /** * ConditionRouter * @@ -63,7 +68,7 @@ public ConditionRouter(URL url) { this.url = url; this.priority = url.getParameter(Constants.PRIORITY_KEY, 0); this.force = url.getParameter(Constants.FORCE_KEY, false); - this.enabled = url.getParameter(Constants.ENABLED_KEY, true); + this.enabled = url.getParameter(ENABLED_KEY, true); init(url.getParameterAndDecoded(Constants.RULE_KEY)); } @@ -219,7 +224,7 @@ private boolean matchCondition(Map condition, URL url, URL pa String key = matchPair.getKey(); String sampleValue; //get real invoked method name from invocation - if (invocation != null && (Constants.METHOD_KEY.equals(key) || Constants.METHODS_KEY.equals(key))) { + if (invocation != null && (METHOD_KEY.equals(key) || METHODS_KEY.equals(key))) { sampleValue = invocation.getMethodName(); } else if (Constants.ADDRESS_KEY.equals(key)) { sampleValue = url.getAddress(); @@ -228,7 +233,7 @@ private boolean matchCondition(Map condition, URL url, URL pa } else { sampleValue = sample.get(key); if (sampleValue == null) { - sampleValue = sample.get(Constants.DEFAULT_KEY_PREFIX + key); + sampleValue = sample.get(DEFAULT_KEY_PREFIX + key); } } if (sampleValue != null) { diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppRouter.java index 31a5df174c1..b334e377bb1 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppRouter.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.rpc.cluster.router.condition.config; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.configcenter.DynamicConfiguration; /** @@ -31,7 +31,7 @@ public class AppRouter extends ListenableRouter { private static final int APP_ROUTER_DEFAULT_PRIORITY = 150; public AppRouter(DynamicConfiguration configuration, URL url) { - super(configuration, url, url.getParameter(Constants.APPLICATION_KEY)); + super(configuration, url, url.getParameter(CommonConstants.APPLICATION_KEY)); this.priority = APP_ROUTER_DEFAULT_PRIORITY; } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java index d03efca6e4d..b30f3d5ed26 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; @@ -232,7 +233,7 @@ public void notify(List> invokers) { Invoker invoker = invokers.get(0); URL url = invoker.getUrl(); - String providerApplication = url.getParameter(Constants.REMOTE_APPLICATION_KEY); + String providerApplication = url.getParameter(CommonConstants.REMOTE_APPLICATION_KEY); if (StringUtils.isEmpty(providerApplication)) { logger.error("TagRouter must getConfig from or subscribe to a specific application, but the application " + diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java index 6c58740eb88..b45ad11d508 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java @@ -26,6 +26,21 @@ import java.util.Map; import java.util.Set; +import static org.apache.dubbo.common.constants.CommonConstants.ALIVE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY_PREFIX; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_APPLICATION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; + /** * ClusterUtils */ @@ -42,29 +57,29 @@ public static URL mergeUrl(URL remoteUrl, Map localMap) { map.putAll(remoteMap); // Remove configurations from provider, some items should be affected by provider. - map.remove(Constants.THREAD_NAME_KEY); - map.remove(Constants.DEFAULT_KEY_PREFIX + Constants.THREAD_NAME_KEY); + map.remove(THREAD_NAME_KEY); + map.remove(DEFAULT_KEY_PREFIX + THREAD_NAME_KEY); - map.remove(Constants.THREADPOOL_KEY); - map.remove(Constants.DEFAULT_KEY_PREFIX + Constants.THREADPOOL_KEY); + map.remove(THREADPOOL_KEY); + map.remove(DEFAULT_KEY_PREFIX + THREADPOOL_KEY); - map.remove(Constants.CORE_THREADS_KEY); - map.remove(Constants.DEFAULT_KEY_PREFIX + Constants.CORE_THREADS_KEY); + map.remove(CORE_THREADS_KEY); + map.remove(DEFAULT_KEY_PREFIX + CORE_THREADS_KEY); - map.remove(Constants.THREADS_KEY); - map.remove(Constants.DEFAULT_KEY_PREFIX + Constants.THREADS_KEY); + map.remove(THREADS_KEY); + map.remove(DEFAULT_KEY_PREFIX + THREADS_KEY); - map.remove(Constants.QUEUES_KEY); - map.remove(Constants.DEFAULT_KEY_PREFIX + Constants.QUEUES_KEY); + map.remove(QUEUES_KEY); + map.remove(DEFAULT_KEY_PREFIX + QUEUES_KEY); - map.remove(Constants.ALIVE_KEY); - map.remove(Constants.DEFAULT_KEY_PREFIX + Constants.ALIVE_KEY); + map.remove(ALIVE_KEY); + map.remove(DEFAULT_KEY_PREFIX + ALIVE_KEY); map.remove(RemotingConstants.TRANSPORTER_KEY); - map.remove(Constants.DEFAULT_KEY_PREFIX + RemotingConstants.TRANSPORTER_KEY); + map.remove(DEFAULT_KEY_PREFIX + RemotingConstants.TRANSPORTER_KEY); map.remove(Constants.ASYNC_KEY); - map.remove(Constants.DEFAULT_KEY_PREFIX + Constants.ASYNC_KEY); + map.remove(DEFAULT_KEY_PREFIX + Constants.ASYNC_KEY); // remove method async entry. Set methodAsyncKey = new HashSet<>(); @@ -82,28 +97,28 @@ public static URL mergeUrl(URL remoteUrl, Map localMap) { // All providers come to here have been filtered by group, which means only those providers that have the exact same group value with the consumer could come to here. // So, generally, we don't need to care about the group value here. // But when comes to group merger, there is an exception, the consumer group may be '*' while the provider group can be empty or any other values. - String remoteGroup = map.get(Constants.GROUP_KEY); - String remoteRelease = map.get(Constants.RELEASE_KEY); + String remoteGroup = map.get(GROUP_KEY); + String remoteRelease = map.get(RELEASE_KEY); map.putAll(localMap); if (StringUtils.isNotEmpty(remoteGroup)) { - map.put(Constants.GROUP_KEY, remoteGroup); + map.put(GROUP_KEY, remoteGroup); } // we should always keep the Provider RELEASE_KEY not overrode by the the value on Consumer side. - map.remove(Constants.RELEASE_KEY); + map.remove(RELEASE_KEY); if (StringUtils.isNotEmpty(remoteRelease)) { - map.put(Constants.RELEASE_KEY, remoteRelease); + map.put(RELEASE_KEY, remoteRelease); } } if (remoteMap != null && remoteMap.size() > 0) { // Use version passed from provider side reserveRemoteValue(Constants.DUBBO_VERSION_KEY, map, remoteMap); - reserveRemoteValue(Constants.VERSION_KEY, map, remoteMap); - reserveRemoteValue(Constants.METHODS_KEY, map, remoteMap); - reserveRemoteValue(Constants.TIMESTAMP_KEY, map, remoteMap); + reserveRemoteValue(VERSION_KEY, map, remoteMap); + reserveRemoteValue(METHODS_KEY, map, remoteMap); + reserveRemoteValue(TIMESTAMP_KEY, map, remoteMap); reserveRemoteValue(Constants.TAG_KEY, map, remoteMap); // TODO, for compatibility consideration, we cannot simply change the value behind APPLICATION_KEY from Consumer to Provider. So just add an extra key here. // Reserve application name from provider. - map.put(Constants.REMOTE_APPLICATION_KEY, remoteMap.get(Constants.APPLICATION_KEY)); + map.put(REMOTE_APPLICATION_KEY, remoteMap.get(APPLICATION_KEY)); // Combine filters and listeners on Provider and Consumer String remoteFilter = remoteMap.get(Constants.REFERENCE_FILTER_KEY); @@ -130,4 +145,4 @@ private static void reserveRemoteValue(String key, Map map, Map< } } -} \ No newline at end of file +} diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvoker.java index 184a7b63df6..4f84196f96f 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvoker.java @@ -35,6 +35,9 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + /** * Invoke a specific number of invokers concurrently, usually used for demanding real-time operations, but need to waste more service resources. * @@ -60,7 +63,7 @@ public Result doInvoke(final Invocation invocation, List> invokers, L checkInvokers(invokers, invocation); final List> selected; final int forks = getUrl().getParameter(Constants.FORKS_KEY, Constants.DEFAULT_FORKS); - final int timeout = getUrl().getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); + final int timeout = getUrl().getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT); if (forks <= 0 || forks >= invokers.size()) { selected = invokers; } else { diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java index 82a0e8a2cb7..51159a99eca 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java @@ -47,6 +47,10 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + @SuppressWarnings("unchecked") public class MergeableClusterInvoker extends AbstractClusterInvoker { @@ -68,7 +72,7 @@ protected Result doInvoke(Invocation invocation, List> invokers, Load return invoker.invoke(invocation); } catch (RpcException e) { if (e.isNoInvokerAvailableAfterFilter()) { - log.debug("No available provider for service" + directory.getUrl().getServiceKey() + " on group " + invoker.getUrl().getParameter(Constants.GROUP_KEY) + ", will continue to try another group."); + log.debug("No available provider for service" + directory.getUrl().getServiceKey() + " on group " + invoker.getUrl().getParameter(GROUP_KEY) + ", will continue to try another group."); } else { throw e; } @@ -101,7 +105,7 @@ public Result call() throws Exception { List resultList = new ArrayList(results.size()); - int timeout = getUrl().getMethodParameter(invocation.getMethodName(), Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); + int timeout = getUrl().getMethodParameter(invocation.getMethodName(), TIMEOUT_KEY, DEFAULT_TIMEOUT); for (Map.Entry> entry : results.entrySet()) { Future future = entry.getValue(); try { diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/RegistryAwareClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/RegistryAwareClusterInvoker.java index 1d5d42b7b4f..6a18cc5b35a 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/RegistryAwareClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/RegistryAwareClusterInvoker.java @@ -28,6 +28,8 @@ import java.util.List; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; + /** * */ @@ -44,7 +46,7 @@ public RegistryAwareClusterInvoker(Directory directory) { public Result doInvoke(Invocation invocation, final List> invokers, LoadBalance loadbalance) throws RpcException { // First, pick the invoker (XXXClusterInvoker) that comes from the local registry, distinguish by a 'default' key. for (Invoker invoker : invokers) { - if (invoker.isAvailable() && invoker.getUrl().getParameter(Constants.REGISTRY_KEY + "." + Constants.DEFAULT_KEY, false)) { + if (invoker.isAvailable() && invoker.getUrl().getParameter(Constants.REGISTRY_KEY + "." + DEFAULT_KEY, false)) { return invoker.invoke(invocation); } } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParserTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParserTest.java index 6bfe3e0c9e1..e066f1cedee 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParserTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParserTest.java @@ -31,6 +31,11 @@ import java.io.InputStream; import java.util.List; +import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; + /** * */ @@ -76,8 +81,8 @@ public void parseConfiguratorsServiceGroupVersionTest() throws Exception { Assertions.assertNotNull(urls); Assertions.assertEquals(1, urls.size()); URL url = urls.get(0); - Assertions.assertEquals("testgroup", url.getParameter(Constants.GROUP_KEY)); - Assertions.assertEquals("1.0.0", url.getParameter(Constants.VERSION_KEY)); + Assertions.assertEquals("testgroup", url.getParameter(GROUP_KEY)); + Assertions.assertEquals("1.0.0", url.getParameter(VERSION_KEY)); } } @@ -89,8 +94,8 @@ public void parseConfiguratorsServiceMultiAppsTest() throws IOException { Assertions.assertEquals(4, urls.size()); URL url = urls.get(0); Assertions.assertEquals("127.0.0.1", url.getAddress()); - Assertions.assertEquals(6666, url.getParameter(Constants.TIMEOUT_KEY, 0)); - Assertions.assertNotNull(url.getParameter(Constants.APPLICATION_KEY)); + Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); + Assertions.assertNotNull(url.getParameter(APPLICATION_KEY)); } } @@ -114,9 +119,9 @@ public void parseConfiguratorsAppMultiServicesTest() throws IOException { URL url = urls.get(0); Assertions.assertEquals("127.0.0.1", url.getAddress()); Assertions.assertEquals("service1", url.getServiceInterface()); - Assertions.assertEquals(6666, url.getParameter(Constants.TIMEOUT_KEY, 0)); + Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); Assertions.assertEquals("random", url.getParameter(Constants.LOADBALANCE_KEY)); - Assertions.assertEquals(url.getParameter(Constants.APPLICATION_KEY), "demo-consumer"); + Assertions.assertEquals(url.getParameter(APPLICATION_KEY), "demo-consumer"); } } @@ -130,9 +135,9 @@ public void parseConfiguratorsAppAnyServicesTest() throws IOException { URL url = urls.get(0); Assertions.assertEquals("127.0.0.1", url.getAddress()); Assertions.assertEquals("*", url.getServiceInterface()); - Assertions.assertEquals(6666, url.getParameter(Constants.TIMEOUT_KEY, 0)); + Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); Assertions.assertEquals("random", url.getParameter(Constants.LOADBALANCE_KEY)); - Assertions.assertEquals(url.getParameter(Constants.APPLICATION_KEY), "demo-consumer"); + Assertions.assertEquals(url.getParameter(APPLICATION_KEY), "demo-consumer"); } } @@ -145,9 +150,9 @@ public void parseConfiguratorsAppNoServiceTest() throws IOException { URL url = urls.get(0); Assertions.assertEquals("127.0.0.1", url.getAddress()); Assertions.assertEquals("*", url.getServiceInterface()); - Assertions.assertEquals(6666, url.getParameter(Constants.TIMEOUT_KEY, 0)); + Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); Assertions.assertEquals("random", url.getParameter(Constants.LOADBALANCE_KEY)); - Assertions.assertEquals(url.getParameter(Constants.APPLICATION_KEY), "demo-consumer"); + Assertions.assertEquals(url.getParameter(APPLICATION_KEY), "demo-consumer"); } } @@ -160,10 +165,10 @@ public void parseConsumerSpecificProvidersTest() throws IOException { URL url = urls.get(0); Assertions.assertEquals("127.0.0.1", url.getAddress()); Assertions.assertEquals("*", url.getServiceInterface()); - Assertions.assertEquals(6666, url.getParameter(Constants.TIMEOUT_KEY, 0)); + Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); Assertions.assertEquals("random", url.getParameter(Constants.LOADBALANCE_KEY)); Assertions.assertEquals("127.0.0.1:20880", url.getParameter(Constants.OVERRIDE_PROVIDERS_KEY)); - Assertions.assertEquals(url.getParameter(Constants.APPLICATION_KEY), "demo-consumer"); + Assertions.assertEquals(url.getParameter(APPLICATION_KEY), "demo-consumer"); } } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java index 279160e7167..14a57db0255 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java @@ -23,6 +23,11 @@ import java.util.HashMap; import java.util.Map; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; + /** * MockInvocation.java */ @@ -42,12 +47,12 @@ public Object[] getArguments() { public Map getAttachments() { Map attachments = new HashMap(); - attachments.put(Constants.PATH_KEY, "dubbo"); - attachments.put(Constants.GROUP_KEY, "dubbo"); - attachments.put(Constants.VERSION_KEY, "1.0.0"); + attachments.put(PATH_KEY, "dubbo"); + attachments.put(GROUP_KEY, "dubbo"); + attachments.put(VERSION_KEY, "1.0.0"); attachments.put(Constants.DUBBO_VERSION_KEY, "1.0.0"); attachments.put(Constants.TOKEN_KEY, "sfag"); - attachments.put(Constants.TIMEOUT_KEY, "1000"); + attachments.put(TIMEOUT_KEY, "1000"); return attachments; } @@ -63,4 +68,4 @@ public String getAttachment(String key, String defaultValue) { return getAttachments().get(key); } -} \ No newline at end of file +} diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ClusterUtilsTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ClusterUtilsTest.java index c010a157dcc..8ee6f3a05e0 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ClusterUtilsTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ClusterUtilsTest.java @@ -18,11 +18,22 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; - import org.apache.dubbo.common.URLBuilder; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import static org.apache.dubbo.common.constants.CommonConstants.ALIVE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY_PREFIX; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PID_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; + public class ClusterUtilsTest { @Test @@ -33,52 +44,52 @@ public void testMergeUrl() throws Exception { .setPassword("password"); providerURL = URLBuilder.from(providerURL) - .addParameter(Constants.GROUP_KEY, "dubbo") - .addParameter(Constants.VERSION_KEY, "1.2.3") + .addParameter(GROUP_KEY, "dubbo") + .addParameter(VERSION_KEY, "1.2.3") .addParameter(Constants.DUBBO_VERSION_KEY, "2.3.7") - .addParameter(Constants.THREADPOOL_KEY, "fixed") - .addParameter(Constants.THREADS_KEY, Integer.MAX_VALUE) - .addParameter(Constants.THREAD_NAME_KEY, "test") - .addParameter(Constants.CORE_THREADS_KEY, Integer.MAX_VALUE) - .addParameter(Constants.QUEUES_KEY, Integer.MAX_VALUE) - .addParameter(Constants.ALIVE_KEY, Integer.MAX_VALUE) - .addParameter(Constants.DEFAULT_KEY_PREFIX + Constants.THREADS_KEY, Integer.MAX_VALUE) - .addParameter(Constants.DEFAULT_KEY_PREFIX + Constants.THREADPOOL_KEY, "fixed") - .addParameter(Constants.DEFAULT_KEY_PREFIX + Constants.CORE_THREADS_KEY, Integer.MAX_VALUE) - .addParameter(Constants.DEFAULT_KEY_PREFIX + Constants.QUEUES_KEY, Integer.MAX_VALUE) - .addParameter(Constants.DEFAULT_KEY_PREFIX + Constants.ALIVE_KEY, Integer.MAX_VALUE) - .addParameter(Constants.DEFAULT_KEY_PREFIX + Constants.THREAD_NAME_KEY, "test") + .addParameter(THREADPOOL_KEY, "fixed") + .addParameter(THREADS_KEY, Integer.MAX_VALUE) + .addParameter(THREAD_NAME_KEY, "test") + .addParameter(CORE_THREADS_KEY, Integer.MAX_VALUE) + .addParameter(QUEUES_KEY, Integer.MAX_VALUE) + .addParameter(ALIVE_KEY, Integer.MAX_VALUE) + .addParameter(DEFAULT_KEY_PREFIX + THREADS_KEY, Integer.MAX_VALUE) + .addParameter(DEFAULT_KEY_PREFIX + THREADPOOL_KEY, "fixed") + .addParameter(DEFAULT_KEY_PREFIX + CORE_THREADS_KEY, Integer.MAX_VALUE) + .addParameter(DEFAULT_KEY_PREFIX + QUEUES_KEY, Integer.MAX_VALUE) + .addParameter(DEFAULT_KEY_PREFIX + ALIVE_KEY, Integer.MAX_VALUE) + .addParameter(DEFAULT_KEY_PREFIX + THREAD_NAME_KEY, "test") .build(); URL consumerURL = new URLBuilder(Constants.DUBBO_PROTOCOL, "localhost", 55555) - .addParameter(Constants.PID_KEY, "1234") - .addParameter(Constants.THREADPOOL_KEY, "foo") + .addParameter(PID_KEY, "1234") + .addParameter(THREADPOOL_KEY, "foo") .build(); URL url = ClusterUtils.mergeUrl(providerURL, consumerURL.getParameters()); - Assertions.assertFalse(url.hasParameter(Constants.THREADS_KEY)); - Assertions.assertFalse(url.hasParameter(Constants.DEFAULT_KEY_PREFIX + Constants.THREADS_KEY)); + Assertions.assertFalse(url.hasParameter(THREADS_KEY)); + Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + THREADS_KEY)); - Assertions.assertFalse(url.hasParameter(Constants.DEFAULT_KEY_PREFIX + Constants.THREADPOOL_KEY)); + Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + THREADPOOL_KEY)); - Assertions.assertFalse(url.hasParameter(Constants.CORE_THREADS_KEY)); - Assertions.assertFalse(url.hasParameter(Constants.DEFAULT_KEY_PREFIX + Constants.CORE_THREADS_KEY)); + Assertions.assertFalse(url.hasParameter(CORE_THREADS_KEY)); + Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + CORE_THREADS_KEY)); - Assertions.assertFalse(url.hasParameter(Constants.QUEUES_KEY)); - Assertions.assertFalse(url.hasParameter(Constants.DEFAULT_KEY_PREFIX + Constants.QUEUES_KEY)); + Assertions.assertFalse(url.hasParameter(QUEUES_KEY)); + Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + QUEUES_KEY)); - Assertions.assertFalse(url.hasParameter(Constants.ALIVE_KEY)); - Assertions.assertFalse(url.hasParameter(Constants.DEFAULT_KEY_PREFIX + Constants.ALIVE_KEY)); + Assertions.assertFalse(url.hasParameter(ALIVE_KEY)); + Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + ALIVE_KEY)); - Assertions.assertFalse(url.hasParameter(Constants.THREAD_NAME_KEY)); - Assertions.assertFalse(url.hasParameter(Constants.DEFAULT_KEY_PREFIX + Constants.THREAD_NAME_KEY)); + Assertions.assertFalse(url.hasParameter(THREAD_NAME_KEY)); + Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + THREAD_NAME_KEY)); Assertions.assertEquals(url.getPath(), "path"); Assertions.assertEquals(url.getUsername(), "username"); Assertions.assertEquals(url.getPassword(), "password"); - Assertions.assertEquals(url.getParameter(Constants.PID_KEY), "1234"); - Assertions.assertEquals(url.getParameter(Constants.THREADPOOL_KEY), "foo"); + Assertions.assertEquals(url.getParameter(PID_KEY), "1234"); + Assertions.assertEquals(url.getParameter(THREADPOOL_KEY), "foo"); } } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.java index 8a4089c9049..1c3260a4fc5 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.java @@ -38,6 +38,7 @@ import java.util.List; import java.util.Map; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -113,7 +114,7 @@ public void testGetMenuSuccessfully() throws Exception { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("getUrl".equals(method.getName())) { - return url.addParameter(Constants.GROUP_KEY, "first"); + return url.addParameter(GROUP_KEY, "first"); } if ("getInterface".equals(method.getName())) { return MenuService.class; @@ -129,7 +130,7 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("getUrl".equals(method.getName())) { - return url.addParameter(Constants.GROUP_KEY, "second"); + return url.addParameter(GROUP_KEY, "second"); } if ("getInterface".equals(method.getName())) { return MenuService.class; @@ -193,14 +194,14 @@ public void testAddMenu() throws Exception { given(invocation.getInvoker()).willReturn(firstInvoker); given(firstInvoker.getUrl()).willReturn( - url.addParameter(Constants.GROUP_KEY, "first")); + url.addParameter(GROUP_KEY, "first")); given(firstInvoker.getInterface()).willReturn(MenuService.class); given(firstInvoker.invoke(invocation)).willReturn(new RpcResult()) ; given(firstInvoker.isAvailable()).willReturn(true); given(secondInvoker.getUrl()).willReturn( - url.addParameter(Constants.GROUP_KEY, "second")); + url.addParameter(GROUP_KEY, "second")); given(secondInvoker.getInterface()).willReturn(MenuService.class); given(secondInvoker.invoke(invocation)).willReturn(new RpcResult()) ; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java index 73c1f21662d..8d78190c50b 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java @@ -17,157 +17,14 @@ package org.apache.dubbo.common; -import org.apache.dubbo.common.constants.RemotingConstants; - import java.util.concurrent.ExecutorService; -import java.util.regex.Pattern; + +import static org.apache.dubbo.common.constants.CommonConstants.DUBBO; /** * Constants */ public class Constants { - - // BEGIN common - public static final String DUBBO = "dubbo"; - - public static final String PROVIDER = "provider"; - - public static final String CONSUMER = "consumer"; - - public static final String APPLICATION_KEY = "application"; - - public static final String REMOTE_APPLICATION_KEY = "remote.application"; - - public static final String ENABLED_KEY = "enabled"; - - public static final String DISABLED_KEY = "disabled"; - - public static final String DUBBO_PROPERTIES_KEY = "dubbo.properties.file"; - - public static final String DEFAULT_DUBBO_PROPERTIES = "dubbo.properties"; - - public static final String ANY_VALUE = "*"; - - public static final String COMMA_SEPARATOR = ","; - - public static final Pattern COMMA_SPLIT_PATTERN = Pattern.compile("\\s*[,]+\\s*"); - - public final static String PATH_SEPARATOR = "/"; - - public final static String PROTOCOL_SEPARATOR = "://"; - - public static final String REGISTRY_SEPARATOR = "|"; - - public static final Pattern REGISTRY_SPLIT_PATTERN = Pattern.compile("\\s*[|;]+\\s*"); - - public static final String SEMICOLON_SEPARATOR = ";"; - - public static final Pattern SEMICOLON_SPLIT_PATTERN = Pattern.compile("\\s*[;]+\\s*"); - - public static final String DEFAULT_PROXY = "javassist"; - - public static final String DEFAULT_DIRECTORY = "dubbo"; - - public static final String PROTOCOL_KEY = "protocol"; - - public static final String DEFAULT_PROTOCOL = "dubbo"; - - public static final String DEFAULT_THREAD_NAME = "Dubbo"; - - public static final int DEFAULT_CORE_THREADS = 0; - - public static final int DEFAULT_THREADS = 200; - - public static final String THREADPOOL_KEY = "threadpool"; - - public static final String THREAD_NAME_KEY = "threadname"; - - public static final String CORE_THREADS_KEY = "corethreads"; - - public static final String THREADS_KEY = "threads"; - - public static final String QUEUES_KEY = "queues"; - - public static final String ALIVE_KEY = "alive"; - - public static final String DEFAULT_THREADPOOL = "limited"; - - public static final String DEFAULT_CLIENT_THREADPOOL = "cached"; - - public static final String IO_THREADS_KEY = "iothreads"; - - public static final int DEFAULT_QUEUES = 0; - - public static final int DEFAULT_ALIVE = 60 * 1000; - - public static final String TIMEOUT_KEY = "timeout"; - - public static final int DEFAULT_TIMEOUT = 1000; - - public static final String REMOVE_VALUE_PREFIX = "-"; - - public static final String PROPERTIES_CHAR_SEPERATOR = "-"; - - public static final String GROUP_CHAR_SEPERATOR = ":"; - - public static final String HIDE_KEY_PREFIX = "."; - - public static final String DEFAULT_KEY_PREFIX = "default."; - - public static final String DEFAULT_KEY = "default"; - - - /** - * Default timeout value in milliseconds for server shutdown - */ - public static final int DEFAULT_SERVER_SHUTDOWN_TIMEOUT = 10000; - - public static final String SIDE_KEY = "side"; - - public static final String PROVIDER_SIDE = "provider"; - - public static final String CONSUMER_SIDE = "consumer"; - - public static final String ANYHOST_KEY = "anyhost"; - - public static final String ANYHOST_VALUE = "0.0.0.0"; - - public static final String LOCALHOST_KEY = "localhost"; - - public static final String LOCALHOST_VALUE = "127.0.0.1"; - - public static final String METHODS_KEY = "methods"; - - public static final String METHOD_KEY = "method"; - - public static final String PID_KEY = "pid"; - - public static final String TIMESTAMP_KEY = "timestamp"; - - public static final String GROUP_KEY = "group"; - - public static final String PATH_KEY = "path"; - - public static final String INTERFACE_KEY = "interface"; - - public static final String FILE_KEY = "file"; - - public static final String DUMP_DIRECTORY = "dump.directory"; - - public static final String CLASSIFIER_KEY = "classifier"; - - public static final String VERSION_KEY = "version"; - - public static final String REVISION_KEY = "revision"; - - /** - * package version in the manifest - */ - public static final String RELEASE_KEY = "release"; - - public static final int MAX_PROXY_COUNT = 65535; - // END common - // BEGIN dubbo-remoting-api public static final String PAYLOAD_KEY = "payload"; /** @@ -791,10 +648,6 @@ public class Constants { public static final String COMPATIBLE_CONFIG_KEY = "compatible_config"; - public static final String[] DEFAULT_REGISTER_PROVIDER_KEYS = {APPLICATION_KEY, RemotingConstants.CODEC_KEY, RemotingConstants.EXCHANGER_KEY, RemotingConstants.SERIALIZATION_KEY, CLUSTER_KEY, CONNECTIONS_KEY, DEPRECATED_KEY, - GROUP_KEY, LOADBALANCE_KEY, MOCK_KEY, PATH_KEY, TIMEOUT_KEY, TOKEN_KEY, VERSION_KEY, WARMUP_KEY, WEIGHT_KEY, TIMESTAMP_KEY, DUBBO_VERSION_KEY, RELEASE_KEY}; - - public static final String[] DEFAULT_REGISTER_CONSUMER_KEYS = {APPLICATION_KEY, VERSION_KEY, GROUP_KEY, DUBBO_VERSION_KEY, RELEASE_KEY}; /** * To decide whether register center saves file synchronously, the default value is asynchronously diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Parameters.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Parameters.java index 333270c9de3..90e3415ed13 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/Parameters.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Parameters.java @@ -28,6 +28,9 @@ import java.util.HashMap; import java.util.Map; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY_PREFIX; +import static org.apache.dubbo.common.constants.CommonConstants.HIDE_KEY_PREFIX; + /** * Parameters for backward compatibility for version prior to 2.0.5 * @@ -97,13 +100,13 @@ public String getDecodedParameter(String key, String defaultValue) { public String getParameter(String key) { String value = parameters.get(key); if (StringUtils.isEmpty(value)) { - value = parameters.get(Constants.HIDE_KEY_PREFIX + key); + value = parameters.get(HIDE_KEY_PREFIX + key); } if (StringUtils.isEmpty(value)) { - value = parameters.get(Constants.DEFAULT_KEY_PREFIX + key); + value = parameters.get(DEFAULT_KEY_PREFIX + key); } if (StringUtils.isEmpty(value)) { - value = parameters.get(Constants.HIDE_KEY_PREFIX + Constants.DEFAULT_KEY_PREFIX + key); + value = parameters.get(HIDE_KEY_PREFIX + DEFAULT_KEY_PREFIX + key); } return value; } @@ -171,7 +174,7 @@ public boolean hasParameter(String key) { public String getMethodParameter(String method, String key) { String value = parameters.get(method + "." + key); if (StringUtils.isEmpty(value)) { - value = parameters.get(Constants.HIDE_KEY_PREFIX + method + "." + key); + value = parameters.get(HIDE_KEY_PREFIX + method + "." + key); } if (StringUtils.isEmpty(value)) { return getParameter(key); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java b/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java index e77e6ff208e..c71bc9055fc 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java @@ -40,6 +40,17 @@ import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; +import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY_PREFIX; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; + /** * URL - Uniform Resource Locator (Immutable, ThreadSafe) *

@@ -479,7 +490,7 @@ public String getParameterAndDecoded(String key, String defaultValue) { public String getParameter(String key) { String value = parameters.get(key); if (StringUtils.isEmpty(value)) { - value = parameters.get(Constants.DEFAULT_KEY_PREFIX + key); + value = parameters.get(DEFAULT_KEY_PREFIX + key); } return value; } @@ -497,7 +508,7 @@ public String[] getParameter(String key, String[] defaultValue) { if (StringUtils.isEmpty(value)) { return defaultValue; } - return Constants.COMMA_SPLIT_PATTERN.split(value); + return COMMA_SPLIT_PATTERN.split(value); } public List getParameter(String key, List defaultValue) { @@ -505,7 +516,7 @@ public List getParameter(String key, List defaultValue) { if (value == null || value.length() == 0) { return defaultValue; } - String[] strArray = Constants.COMMA_SPLIT_PATTERN.split(value); + String[] strArray = COMMA_SPLIT_PATTERN.split(value); return Arrays.asList(strArray); } @@ -928,11 +939,11 @@ public boolean hasMethodParameter(String method, String key) { } public boolean isLocalHost() { - return NetUtils.isLocalHost(host) || getParameter(Constants.LOCALHOST_KEY, false); + return NetUtils.isLocalHost(host) || getParameter(LOCALHOST_KEY, false); } public boolean isAnyHost() { - return Constants.ANYHOST_VALUE.equals(host) || getParameter(Constants.ANYHOST_KEY, false); + return ANYHOST_VALUE.equals(host) || getParameter(ANYHOST_KEY, false); } public URL addParameterAndEncoded(String key, String value) { @@ -1123,7 +1134,7 @@ public URL clearParameters() { } public String getRawParameter(String key) { - if (Constants.PROTOCOL_KEY.equals(key)) { + if (PROTOCOL_KEY.equals(key)) { return protocol; } if (Constants.USERNAME_KEY.equals(key)) { @@ -1138,7 +1149,7 @@ public String getRawParameter(String key) { if (Constants.PORT_KEY.equals(key)) { return String.valueOf(port); } - if (Constants.PATH_KEY.equals(key)) { + if (PATH_KEY.equals(key)) { return path; } return getParameter(key); @@ -1147,7 +1158,7 @@ public String getRawParameter(String key) { public Map toMap() { Map map = new HashMap<>(parameters); if (protocol != null) { - map.put(Constants.PROTOCOL_KEY, protocol); + map.put(PROTOCOL_KEY, protocol); } if (username != null) { map.put(Constants.USERNAME_KEY, username); @@ -1162,7 +1173,7 @@ public Map toMap() { map.put(Constants.PORT_KEY, String.valueOf(port)); } if (path != null) { - map.put(Constants.PATH_KEY, path); + map.put(PATH_KEY, path); } return map; } @@ -1317,7 +1328,7 @@ public String getServiceKey() { if (inf == null) { return null; } - return buildKey(inf, getParameter(Constants.GROUP_KEY), getParameter(Constants.VERSION_KEY)); + return buildKey(inf, getParameter(GROUP_KEY), getParameter(VERSION_KEY)); } /** @@ -1329,7 +1340,7 @@ public String getPathKey() { if (inf == null) { return null; } - return buildKey(inf, getParameter(Constants.GROUP_KEY), getParameter(Constants.VERSION_KEY)); + return buildKey(inf, getParameter(GROUP_KEY), getParameter(VERSION_KEY)); } public static String buildKey(String path, String group, String version) { @@ -1358,11 +1369,11 @@ public String getServiceName() { } public String getServiceInterface() { - return getParameter(Constants.INTERFACE_KEY, path); + return getParameter(INTERFACE_KEY, path); } public URL setServiceInterface(String service) { - return addParameter(Constants.INTERFACE_KEY, service); + return addParameter(INTERFACE_KEY, service); } /** diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/URLBuilder.java b/dubbo-common/src/main/java/org/apache/dubbo/common/URLBuilder.java index c938737811d..5c926f94383 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/URLBuilder.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/URLBuilder.java @@ -24,6 +24,8 @@ import java.util.Map; import java.util.Objects; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY_PREFIX; + public final class URLBuilder { private String protocol; @@ -343,7 +345,7 @@ public boolean hasParameter(String key) { public String getParameter(String key) { String value = parameters.get(key); if (StringUtils.isEmpty(value)) { - value = parameters.get(Constants.DEFAULT_KEY_PREFIX + key); + value = parameters.get(DEFAULT_KEY_PREFIX + key); } return value; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Proxy.java b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Proxy.java index 8486e94b34e..2da28183504 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Proxy.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Proxy.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.bytecode; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.ReflectUtils; @@ -34,6 +33,8 @@ import java.util.WeakHashMap; import java.util.concurrent.atomic.AtomicLong; +import static org.apache.dubbo.common.constants.CommonConstants.MAX_PROXY_COUNT; + /** * Proxy. */ @@ -73,7 +74,7 @@ public static Proxy getProxy(Class... ics) { * @return Proxy instance. */ public static Proxy getProxy(ClassLoader cl, Class... ics) { - if (ics.length > Constants.MAX_PROXY_COUNT) { + if (ics.length > MAX_PROXY_COUNT) { throw new IllegalArgumentException("interface limit exceeded"); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java index e2431f20d24..a9425fafa63 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java @@ -27,6 +27,8 @@ import java.util.Map; import java.util.Properties; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_SERVER_SHUTDOWN_TIMEOUT; + /** * Utilities for manipulating configurations from different sources */ @@ -36,7 +38,7 @@ public class ConfigurationUtils { // FIXME @SuppressWarnings("deprecation") public static int getServerShutdownTimeout() { - int timeout = Constants.DEFAULT_SERVER_SHUTDOWN_TIMEOUT; + int timeout = DEFAULT_SERVER_SHUTDOWN_TIMEOUT; Configuration configuration = Environment.getInstance().getConfiguration(); String value = StringUtils.trim(configuration.getString(Constants.SHUTDOWN_WAIT_KEY)); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/Environment.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/Environment.java index 8369b997a49..b6328082061 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/Environment.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/Environment.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.common.config; -import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.StringUtils; import java.util.HashMap; @@ -141,7 +141,7 @@ private static String toKey(String prefix, String id) { if (sb.length() > 0) { return sb.toString(); } - return Constants.DUBBO; + return CommonConstants.DUBBO; } public boolean isConfigCenterFirst() { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java index 331a67c587c..d8bf70139f7 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java @@ -17,26 +17,6 @@ package org.apache.dubbo.common.constants; -import static org.apache.dubbo.common.Constants.APPLICATION_KEY; -import static org.apache.dubbo.common.Constants.CLUSTER_KEY; -import static org.apache.dubbo.common.constants.RemotingConstants.CODEC_KEY; -import static org.apache.dubbo.common.Constants.CONNECTIONS_KEY; -import static org.apache.dubbo.common.Constants.DEPRECATED_KEY; -import static org.apache.dubbo.common.Constants.DUBBO_VERSION_KEY; -import static org.apache.dubbo.common.constants.RemotingConstants.EXCHANGER_KEY; -import static org.apache.dubbo.common.Constants.GROUP_KEY; -import static org.apache.dubbo.common.Constants.LOADBALANCE_KEY; -import static org.apache.dubbo.common.Constants.MOCK_KEY; -import static org.apache.dubbo.common.Constants.PATH_KEY; -import static org.apache.dubbo.common.Constants.RELEASE_KEY; -import static org.apache.dubbo.common.constants.RemotingConstants.SERIALIZATION_KEY; -import static org.apache.dubbo.common.Constants.TIMEOUT_KEY; -import static org.apache.dubbo.common.Constants.TIMESTAMP_KEY; -import static org.apache.dubbo.common.Constants.TOKEN_KEY; -import static org.apache.dubbo.common.Constants.VERSION_KEY; -import static org.apache.dubbo.common.Constants.WARMUP_KEY; -import static org.apache.dubbo.common.Constants.WEIGHT_KEY; - public interface RegistryConstants { String REGISTER_KEY = "register"; @@ -114,11 +94,6 @@ public interface RegistryConstants { String COMPATIBLE_CONFIG_KEY = "compatible_config"; - String[] DEFAULT_REGISTER_PROVIDER_KEYS = {APPLICATION_KEY, CODEC_KEY, EXCHANGER_KEY, SERIALIZATION_KEY, CLUSTER_KEY, CONNECTIONS_KEY, DEPRECATED_KEY, - GROUP_KEY, LOADBALANCE_KEY, MOCK_KEY, PATH_KEY, TIMEOUT_KEY, TOKEN_KEY, VERSION_KEY, WARMUP_KEY, WEIGHT_KEY, TIMESTAMP_KEY, DUBBO_VERSION_KEY, RELEASE_KEY}; - - String[] DEFAULT_REGISTER_CONSUMER_KEYS = {APPLICATION_KEY, VERSION_KEY, GROUP_KEY, DUBBO_VERSION_KEY, RELEASE_KEY}; - /** * To decide whether register center saves file synchronously, the default value is asynchronously */ diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionLoader.java b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionLoader.java index 9d0b46c4469..18b216ddbf1 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionLoader.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionLoader.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.extension; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.support.ActivateComparator; import org.apache.dubbo.common.logger.Logger; @@ -48,6 +47,10 @@ import java.util.concurrent.ConcurrentMap; import java.util.regex.Pattern; +import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.REMOVE_VALUE_PREFIX; + /** * Load dubbo extensions *

    @@ -190,7 +193,7 @@ public List getActivateExtension(URL url, String[] values) { */ public List getActivateExtension(URL url, String key, String group) { String value = url.getParameter(key); - return getActivateExtension(url, StringUtils.isEmpty(value) ? null : Constants.COMMA_SPLIT_PATTERN.split(value), group); + return getActivateExtension(url, StringUtils.isEmpty(value) ? null : COMMA_SPLIT_PATTERN.split(value), group); } /** @@ -205,7 +208,7 @@ public List getActivateExtension(URL url, String key, String group) { public List getActivateExtension(URL url, String[] values, String group) { List exts = new ArrayList<>(); List names = values == null ? new ArrayList<>(0) : Arrays.asList(values); - if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { + if (!names.contains(REMOVE_VALUE_PREFIX + DEFAULT_KEY)) { getExtensionClasses(); for (Map.Entry entry : cachedActivates.entrySet()) { String name = entry.getKey(); @@ -225,7 +228,7 @@ public List getActivateExtension(URL url, String[] values, String group) { if (isMatchGroup(group, activateGroup)) { T ext = getExtension(name); if (!names.contains(name) - && !names.contains(Constants.REMOVE_VALUE_PREFIX + name) + && !names.contains(REMOVE_VALUE_PREFIX + name) && isActive(activateValue, url)) { exts.add(ext); } @@ -236,9 +239,9 @@ && isActive(activateValue, url)) { List usrs = new ArrayList<>(); for (int i = 0; i < names.size(); i++) { String name = names.get(i); - if (!name.startsWith(Constants.REMOVE_VALUE_PREFIX) - && !names.contains(Constants.REMOVE_VALUE_PREFIX + name)) { - if (Constants.DEFAULT_KEY.equals(name)) { + if (!name.startsWith(REMOVE_VALUE_PREFIX) + && !names.contains(REMOVE_VALUE_PREFIX + name)) { + if (DEFAULT_KEY.equals(name)) { if (!usrs.isEmpty()) { exts.addAll(0, usrs); usrs.clear(); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/ThreadPool.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/ThreadPool.java index 0142dedf5eb..312cd690fff 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/ThreadPool.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/ThreadPool.java @@ -16,13 +16,14 @@ */ package org.apache.dubbo.common.threadpool; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.SPI; import java.util.concurrent.Executor; +import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; + /** * ThreadPool */ @@ -35,7 +36,7 @@ public interface ThreadPool { * @param url URL contains thread parameter * @return thread pool */ - @Adaptive({Constants.THREADPOOL_KEY}) + @Adaptive({THREADPOOL_KEY}) Executor getExecutor(URL url); -} \ No newline at end of file +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/AbortPolicyWithReport.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/AbortPolicyWithReport.java index cb368db895c..0872b5b4d9a 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/AbortPolicyWithReport.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/AbortPolicyWithReport.java @@ -26,12 +26,13 @@ import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadPoolExecutor; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.JVMUtil; +import static org.apache.dubbo.common.constants.CommonConstants.DUMP_DIRECTORY; + /** * Abort Policy. * Log warn info when abort. @@ -92,7 +93,7 @@ private void dumpJStack() { ExecutorService pool = Executors.newSingleThreadExecutor(); pool.execute(() -> { - String dumpPath = url.getParameter(Constants.DUMP_DIRECTORY, System.getProperty("user.home")); + String dumpPath = url.getParameter(DUMP_DIRECTORY, System.getProperty("user.home")); SimpleDateFormat sdf; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/cached/CachedThreadPool.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/cached/CachedThreadPool.java index 51c40742dd2..6dbbced16ff 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/cached/CachedThreadPool.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/cached/CachedThreadPool.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.threadpool.support.cached; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.threadlocal.NamedInternalThreadFactory; import org.apache.dubbo.common.threadpool.ThreadPool; @@ -28,6 +27,16 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.CommonConstants.ALIVE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_ALIVE; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_CORE_THREADS; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_QUEUES; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREAD_NAME; +import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; + /** * This thread pool is self-tuned. Thread will be recycled after idle for one minute, and new thread will be created for * the upcoming request. @@ -38,11 +47,11 @@ public class CachedThreadPool implements ThreadPool { @Override public Executor getExecutor(URL url) { - String name = url.getParameter(Constants.THREAD_NAME_KEY, Constants.DEFAULT_THREAD_NAME); - int cores = url.getParameter(Constants.CORE_THREADS_KEY, Constants.DEFAULT_CORE_THREADS); - int threads = url.getParameter(Constants.THREADS_KEY, Integer.MAX_VALUE); - int queues = url.getParameter(Constants.QUEUES_KEY, Constants.DEFAULT_QUEUES); - int alive = url.getParameter(Constants.ALIVE_KEY, Constants.DEFAULT_ALIVE); + String name = url.getParameter(THREAD_NAME_KEY, DEFAULT_THREAD_NAME); + int cores = url.getParameter(CORE_THREADS_KEY, DEFAULT_CORE_THREADS); + int threads = url.getParameter(THREADS_KEY, Integer.MAX_VALUE); + int queues = url.getParameter(QUEUES_KEY, DEFAULT_QUEUES); + int alive = url.getParameter(ALIVE_KEY, DEFAULT_ALIVE); return new ThreadPoolExecutor(cores, threads, alive, TimeUnit.MILLISECONDS, queues == 0 ? new SynchronousQueue() : (queues < 0 ? new LinkedBlockingQueue() diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPool.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPool.java index 14c9bcf9387..6d126894aa9 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPool.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPool.java @@ -17,7 +17,6 @@ package org.apache.dubbo.common.threadpool.support.eager; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.threadlocal.NamedInternalThreadFactory; import org.apache.dubbo.common.threadpool.ThreadPool; @@ -26,6 +25,16 @@ import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.CommonConstants.ALIVE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_ALIVE; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_CORE_THREADS; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_QUEUES; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREAD_NAME; +import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; + /** * EagerThreadPool * When the core threads are all in busy, @@ -35,11 +44,11 @@ public class EagerThreadPool implements ThreadPool { @Override public Executor getExecutor(URL url) { - String name = url.getParameter(Constants.THREAD_NAME_KEY, Constants.DEFAULT_THREAD_NAME); - int cores = url.getParameter(Constants.CORE_THREADS_KEY, Constants.DEFAULT_CORE_THREADS); - int threads = url.getParameter(Constants.THREADS_KEY, Integer.MAX_VALUE); - int queues = url.getParameter(Constants.QUEUES_KEY, Constants.DEFAULT_QUEUES); - int alive = url.getParameter(Constants.ALIVE_KEY, Constants.DEFAULT_ALIVE); + String name = url.getParameter(THREAD_NAME_KEY, DEFAULT_THREAD_NAME); + int cores = url.getParameter(CORE_THREADS_KEY, DEFAULT_CORE_THREADS); + int threads = url.getParameter(THREADS_KEY, Integer.MAX_VALUE); + int queues = url.getParameter(QUEUES_KEY, DEFAULT_QUEUES); + int alive = url.getParameter(ALIVE_KEY, DEFAULT_ALIVE); // init queue and executor TaskQueue taskQueue = new TaskQueue(queues <= 0 ? 1 : queues); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/fixed/FixedThreadPool.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/fixed/FixedThreadPool.java index 682bf899772..606d7e1f913 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/fixed/FixedThreadPool.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/fixed/FixedThreadPool.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.threadpool.support.fixed; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.threadlocal.NamedInternalThreadFactory; import org.apache.dubbo.common.threadpool.ThreadPool; @@ -28,6 +27,13 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_QUEUES; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREAD_NAME; +import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; + /** * Creates a thread pool that reuses a fixed number of threads * @@ -37,9 +43,9 @@ public class FixedThreadPool implements ThreadPool { @Override public Executor getExecutor(URL url) { - String name = url.getParameter(Constants.THREAD_NAME_KEY, Constants.DEFAULT_THREAD_NAME); - int threads = url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS); - int queues = url.getParameter(Constants.QUEUES_KEY, Constants.DEFAULT_QUEUES); + String name = url.getParameter(THREAD_NAME_KEY, DEFAULT_THREAD_NAME); + int threads = url.getParameter(THREADS_KEY, DEFAULT_THREADS); + int queues = url.getParameter(QUEUES_KEY, DEFAULT_QUEUES); return new ThreadPoolExecutor(threads, threads, 0, TimeUnit.MILLISECONDS, queues == 0 ? new SynchronousQueue() : (queues < 0 ? new LinkedBlockingQueue() diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/limited/LimitedThreadPool.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/limited/LimitedThreadPool.java index 3a7dc46de07..87c46d37423 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/limited/LimitedThreadPool.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/limited/LimitedThreadPool.java @@ -17,7 +17,6 @@ package org.apache.dubbo.common.threadpool.support.limited; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.threadlocal.NamedInternalThreadFactory; import org.apache.dubbo.common.threadpool.ThreadPool; @@ -29,6 +28,15 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_CORE_THREADS; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_QUEUES; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREAD_NAME; +import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; + /** * Creates a thread pool that creates new threads as needed until limits reaches. This thread pool will not shrink * automatically. @@ -37,10 +45,10 @@ public class LimitedThreadPool implements ThreadPool { @Override public Executor getExecutor(URL url) { - String name = url.getParameter(Constants.THREAD_NAME_KEY, Constants.DEFAULT_THREAD_NAME); - int cores = url.getParameter(Constants.CORE_THREADS_KEY, Constants.DEFAULT_CORE_THREADS); - int threads = url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS); - int queues = url.getParameter(Constants.QUEUES_KEY, Constants.DEFAULT_QUEUES); + String name = url.getParameter(THREAD_NAME_KEY, DEFAULT_THREAD_NAME); + int cores = url.getParameter(CORE_THREADS_KEY, DEFAULT_CORE_THREADS); + int threads = url.getParameter(THREADS_KEY, DEFAULT_THREADS); + int queues = url.getParameter(QUEUES_KEY, DEFAULT_QUEUES); return new ThreadPoolExecutor(cores, threads, Long.MAX_VALUE, TimeUnit.MILLISECONDS, queues == 0 ? new SynchronousQueue() : (queues < 0 ? new LinkedBlockingQueue() diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConfigUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConfigUtils.java index 1f26bf035a7..072b456214f 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConfigUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConfigUtils.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.common.utils; -import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -34,6 +34,10 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.REMOVE_VALUE_PREFIX; + public class ConfigUtils { private static final Logger logger = LoggerFactory.getLogger(ConfigUtils.class); @@ -88,7 +92,7 @@ public static List mergeValues(Class type, String cfg, List d List names = new ArrayList(); // add initial values - String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); + String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); @@ -96,22 +100,22 @@ public static List mergeValues(Class type, String cfg, List d } // -default is not included - if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { + if (!names.contains(REMOVE_VALUE_PREFIX + DEFAULT_KEY)) { // add default extension - int i = names.indexOf(Constants.DEFAULT_KEY); + int i = names.indexOf(DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } - names.remove(Constants.DEFAULT_KEY); + names.remove(DEFAULT_KEY); } else { - names.remove(Constants.DEFAULT_KEY); + names.remove(DEFAULT_KEY); } // merge - configuration for (String name : new ArrayList(names)) { - if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { + if (name.startsWith(REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } @@ -144,11 +148,11 @@ public static Properties getProperties() { if (PROPERTIES == null) { synchronized (ConfigUtils.class) { if (PROPERTIES == null) { - String path = System.getProperty(Constants.DUBBO_PROPERTIES_KEY); + String path = System.getProperty(CommonConstants.DUBBO_PROPERTIES_KEY); if (path == null || path.length() == 0) { - path = System.getenv(Constants.DUBBO_PROPERTIES_KEY); + path = System.getenv(CommonConstants.DUBBO_PROPERTIES_KEY); if (path == null || path.length() == 0) { - path = Constants.DEFAULT_DUBBO_PROPERTIES; + path = CommonConstants.DEFAULT_DUBBO_PROPERTIES; } } PROPERTIES = ConfigUtils.loadProperties(path, false, true); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ExecutorUtil.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ExecutorUtil.java index c342ed2e713..93a2a60d7d6 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ExecutorUtil.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ExecutorUtil.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.utils; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -24,9 +23,11 @@ import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import java.util.concurrent.ScheduledFuture; + +import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; public class ExecutorUtil { private static final Logger logger = LoggerFactory.getLogger(ExecutorUtil.class); @@ -128,9 +129,9 @@ public void run() { * @return new url with updated thread name */ public static URL setThreadName(URL url, String defaultName) { - String name = url.getParameter(Constants.THREAD_NAME_KEY, defaultName); + String name = url.getParameter(THREAD_NAME_KEY, defaultName); name = name + "-" + url.getAddress(); - url = url.addParameter(Constants.THREAD_NAME_KEY, name); + url = url.addParameter(THREAD_NAME_KEY, name); return url; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java index 828a97e7d36..b5ca11e8c34 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java @@ -37,6 +37,10 @@ import java.util.concurrent.ThreadLocalRandom; import java.util.regex.Pattern; +import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_KEY; + /** * IP and Port Helper for RPC */ @@ -99,18 +103,18 @@ public static boolean isValidAddress(String address) { public static boolean isLocalHost(String host) { return host != null && (LOCAL_IP_PATTERN.matcher(host).matches() - || host.equalsIgnoreCase(Constants.LOCALHOST_KEY)); + || host.equalsIgnoreCase(LOCALHOST_KEY)); } public static boolean isAnyHost(String host) { - return Constants.ANYHOST_VALUE.equals(host); + return ANYHOST_VALUE.equals(host); } public static boolean isInvalidLocalHost(String host) { return host == null || host.length() == 0 - || host.equalsIgnoreCase(Constants.LOCALHOST_KEY) - || host.equals(Constants.ANYHOST_VALUE) + || host.equalsIgnoreCase(LOCALHOST_KEY) + || host.equals(ANYHOST_VALUE) || (LOCAL_IP_PATTERN.matcher(host).matches()); } @@ -130,8 +134,8 @@ static boolean isValidV4Address(InetAddress address) { String name = address.getHostAddress(); boolean result = (name != null && IP_PATTERN.matcher(name).matches() - && !Constants.ANYHOST_VALUE.equals(name) - && !Constants.LOCALHOST_VALUE.equals(name)); + && !ANYHOST_VALUE.equals(name) + && !LOCALHOST_VALUE.equals(name)); return result; } @@ -178,7 +182,7 @@ static InetAddress normalizeV6Address(Inet6Address address) { public static String getLocalHost() { InetAddress address = getLocalAddress(); - return address == null ? Constants.LOCALHOST_VALUE : address.getHostAddress(); + return address == null ? LOCALHOST_VALUE : address.getHostAddress(); } public static String filterLocalHost(String host) { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/StringUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/StringUtils.java index a351346ef1a..20331e3998a 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/StringUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/StringUtils.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.utils; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.io.UnsafeStringWriter; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -33,6 +32,12 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR; +import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; + /** * StringUtils */ @@ -458,7 +463,7 @@ public static boolean isJavaIdentifier(String s) { } public static boolean isContains(String values, String value) { - return isNotEmpty(values) && isContains(Constants.COMMA_SPLIT_PATTERN.split(values), value); + return isNotEmpty(values) && isContains(COMMA_SPLIT_PATTERN.split(values), value); } /** @@ -714,12 +719,12 @@ public static Map parseQueryString(String qs) { public static String getServiceKey(Map ps) { StringBuilder buf = new StringBuilder(); - String group = ps.get(Constants.GROUP_KEY); + String group = ps.get(GROUP_KEY); if (isNotEmpty(group)) { buf.append(group).append("/"); } - buf.append(ps.get(Constants.INTERFACE_KEY)); - String version = ps.get(Constants.VERSION_KEY); + buf.append(ps.get(INTERFACE_KEY)); + String version = ps.get(VERSION_KEY); if (isNotEmpty(group)) { buf.append(":").append(version); } @@ -774,7 +779,7 @@ public static String toArgumentString(Object[] args) { StringBuilder buf = new StringBuilder(); for (Object arg : args) { if (buf.length() > 0) { - buf.append(Constants.COMMA_SEPARATOR); + buf.append(COMMA_SEPARATOR); } if (arg == null || ReflectUtils.isPrimitives(arg.getClass())) { buf.append(arg); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java index 32ab016af43..2d5e6778078 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java @@ -35,11 +35,22 @@ import static org.apache.dubbo.common.Constants.PROVIDERS_CATEGORY; import static org.apache.dubbo.common.Constants.ROUTERS_CATEGORY; import static org.apache.dubbo.common.Constants.ROUTE_PROTOCOL; +import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.CLASSIFIER_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; +import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_SPLIT_PATTERN; +import static org.apache.dubbo.common.constants.CommonConstants.REMOVE_VALUE_PREFIX; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; public class UrlUtils { /** - * in the url string,mark the param begin + * in the url string,mark the param begin */ private final static String URL_PARAM_STARTING_SYMBOL = "?"; @@ -51,7 +62,7 @@ public static URL parseURL(String address, Map defaults) { if (address.contains("://") || address.contains(URL_PARAM_STARTING_SYMBOL)) { url = address; } else { - String[] addresses = Constants.COMMA_SPLIT_PATTERN.split(address); + String[] addresses = COMMA_SPLIT_PATTERN.split(address); url = addresses[0]; if (addresses.length > 1) { StringBuilder backup = new StringBuilder(); @@ -64,22 +75,22 @@ public static URL parseURL(String address, Map defaults) { url += URL_PARAM_STARTING_SYMBOL + RemotingConstants.BACKUP_KEY + "=" + backup.toString(); } } - String defaultProtocol = defaults == null ? null : defaults.get(Constants.PROTOCOL_KEY); + String defaultProtocol = defaults == null ? null : defaults.get(PROTOCOL_KEY); if (defaultProtocol == null || defaultProtocol.length() == 0) { defaultProtocol = Constants.DUBBO_PROTOCOL; } String defaultUsername = defaults == null ? null : defaults.get(Constants.USERNAME_KEY); String defaultPassword = defaults == null ? null : defaults.get(Constants.PASSWORD_KEY); int defaultPort = StringUtils.parseInteger(defaults == null ? null : defaults.get(Constants.PORT_KEY)); - String defaultPath = defaults == null ? null : defaults.get(Constants.PATH_KEY); + String defaultPath = defaults == null ? null : defaults.get(PATH_KEY); Map defaultParameters = defaults == null ? null : new HashMap(defaults); if (defaultParameters != null) { - defaultParameters.remove(Constants.PROTOCOL_KEY); + defaultParameters.remove(PROTOCOL_KEY); defaultParameters.remove(Constants.USERNAME_KEY); defaultParameters.remove(Constants.PASSWORD_KEY); defaultParameters.remove(Constants.HOST_KEY); defaultParameters.remove(Constants.PORT_KEY); - defaultParameters.remove(Constants.PATH_KEY); + defaultParameters.remove(PATH_KEY); } URL u = URL.valueOf(url); boolean changed = false; @@ -144,7 +155,7 @@ public static List parseURLs(String address, Map defaults) if (address == null || address.length() == 0) { return null; } - String[] addresses = Constants.REGISTRY_SPLIT_PATTERN.split(address); + String[] addresses = REGISTRY_SPLIT_PATTERN.split(address); if (addresses == null || addresses.length == 0) { return null; //here won't be empty } @@ -353,17 +364,17 @@ public static URL getEmptyUrl(String service, String category) { } return URL.valueOf(Constants.EMPTY_PROTOCOL + "://0.0.0.0/" + service + URL_PARAM_STARTING_SYMBOL + CATEGORY_KEY + "=" + category - + (group == null ? "" : "&" + Constants.GROUP_KEY + "=" + group) - + (version == null ? "" : "&" + Constants.VERSION_KEY + "=" + version)); + + (group == null ? "" : "&" + GROUP_KEY + "=" + group) + + (version == null ? "" : "&" + VERSION_KEY + "=" + version)); } public static boolean isMatchCategory(String category, String categories) { if (categories == null || categories.length() == 0) { return DEFAULT_CATEGORY.equals(category); - } else if (categories.contains(Constants.ANY_VALUE)) { + } else if (categories.contains(ANY_VALUE)) { return true; - } else if (categories.contains(Constants.REMOVE_VALUE_PREFIX)) { - return !categories.contains(Constants.REMOVE_VALUE_PREFIX + category); + } else if (categories.contains(REMOVE_VALUE_PREFIX)) { + return !categories.contains(REMOVE_VALUE_PREFIX + category); } else { return categories.contains(category); } @@ -373,8 +384,8 @@ public static boolean isMatch(URL consumerUrl, URL providerUrl) { String consumerInterface = consumerUrl.getServiceInterface(); String providerInterface = providerUrl.getServiceInterface(); //FIXME accept providerUrl with '*' as interface name, after carefully thought about all possible scenarios I think it's ok to add this condition. - if (!(Constants.ANY_VALUE.equals(consumerInterface) - || Constants.ANY_VALUE.equals(providerInterface) + if (!(ANY_VALUE.equals(consumerInterface) + || ANY_VALUE.equals(providerInterface) || StringUtils.isEquals(consumerInterface, providerInterface))) { return false; } @@ -383,21 +394,21 @@ public static boolean isMatch(URL consumerUrl, URL providerUrl) { consumerUrl.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY))) { return false; } - if (!providerUrl.getParameter(Constants.ENABLED_KEY, true) - && !Constants.ANY_VALUE.equals(consumerUrl.getParameter(Constants.ENABLED_KEY))) { + if (!providerUrl.getParameter(ENABLED_KEY, true) + && !ANY_VALUE.equals(consumerUrl.getParameter(ENABLED_KEY))) { return false; } - String consumerGroup = consumerUrl.getParameter(Constants.GROUP_KEY); - String consumerVersion = consumerUrl.getParameter(Constants.VERSION_KEY); - String consumerClassifier = consumerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); + String consumerGroup = consumerUrl.getParameter(GROUP_KEY); + String consumerVersion = consumerUrl.getParameter(VERSION_KEY); + String consumerClassifier = consumerUrl.getParameter(CLASSIFIER_KEY, ANY_VALUE); - String providerGroup = providerUrl.getParameter(Constants.GROUP_KEY); - String providerVersion = providerUrl.getParameter(Constants.VERSION_KEY); - String providerClassifier = providerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); - return (Constants.ANY_VALUE.equals(consumerGroup) || StringUtils.isEquals(consumerGroup, providerGroup) || StringUtils.isContains(consumerGroup, providerGroup)) - && (Constants.ANY_VALUE.equals(consumerVersion) || StringUtils.isEquals(consumerVersion, providerVersion)) - && (consumerClassifier == null || Constants.ANY_VALUE.equals(consumerClassifier) || StringUtils.isEquals(consumerClassifier, providerClassifier)); + String providerGroup = providerUrl.getParameter(GROUP_KEY); + String providerVersion = providerUrl.getParameter(VERSION_KEY); + String providerClassifier = providerUrl.getParameter(CLASSIFIER_KEY, ANY_VALUE); + return (ANY_VALUE.equals(consumerGroup) || StringUtils.isEquals(consumerGroup, providerGroup) || StringUtils.isContains(consumerGroup, providerGroup)) + && (ANY_VALUE.equals(consumerVersion) || StringUtils.isEquals(consumerVersion, providerVersion)) + && (consumerClassifier == null || ANY_VALUE.equals(consumerClassifier) || StringUtils.isEquals(consumerClassifier, providerClassifier)); } public static boolean isMatchGlobPattern(String pattern, String value, URL param) { @@ -440,12 +451,12 @@ else if (i == 0) { } public static boolean isServiceKeyMatch(URL pattern, URL value) { - return pattern.getParameter(Constants.INTERFACE_KEY).equals( - value.getParameter(Constants.INTERFACE_KEY)) - && isItemMatch(pattern.getParameter(Constants.GROUP_KEY), - value.getParameter(Constants.GROUP_KEY)) - && isItemMatch(pattern.getParameter(Constants.VERSION_KEY), - value.getParameter(Constants.VERSION_KEY)); + return pattern.getParameter(INTERFACE_KEY).equals( + value.getParameter(INTERFACE_KEY)) + && isItemMatch(pattern.getParameter(GROUP_KEY), + value.getParameter(GROUP_KEY)) + && isItemMatch(pattern.getParameter(VERSION_KEY), + value.getParameter(VERSION_KEY)); } public static List classifyUrls(List urls, Predicate predicate) { diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoaderTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoaderTest.java index 12d8aa92af7..89312eaf32e 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoaderTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoaderTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.extension; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.activate.ActivateExt1; import org.apache.dubbo.common.extension.activate.impl.ActivateExt1Impl1; @@ -57,6 +56,7 @@ import java.util.List; import java.util.Set; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.anyOf; import static org.hamcrest.CoreMatchers.instanceOf; @@ -376,14 +376,14 @@ public void testLoadActivateExtension() throws Exception { Assertions.assertTrue(list.get(0).getClass() == ActivateExt1Impl1.class); // test group - url = url.addParameter(Constants.GROUP_KEY, "group1"); + url = url.addParameter(GROUP_KEY, "group1"); list = ExtensionLoader.getExtensionLoader(ActivateExt1.class) .getActivateExtension(url, new String[]{}, "group1"); Assertions.assertEquals(1, list.size()); Assertions.assertTrue(list.get(0).getClass() == GroupActivateExtImpl.class); // test old @Activate group - url = url.addParameter(Constants.GROUP_KEY, "old_group"); + url = url.addParameter(GROUP_KEY, "old_group"); list = ExtensionLoader.getExtensionLoader(ActivateExt1.class) .getActivateExtension(url, new String[]{}, "old_group"); Assertions.assertEquals(2, list.size()); @@ -391,8 +391,8 @@ public void testLoadActivateExtension() throws Exception { || list.get(0).getClass() == OldActivateExt1Impl3.class); // test value - url = url.removeParameter(Constants.GROUP_KEY); - url = url.addParameter(Constants.GROUP_KEY, "value"); + url = url.removeParameter(GROUP_KEY); + url = url.addParameter(GROUP_KEY, "value"); url = url.addParameter("value", "value"); list = ExtensionLoader.getExtensionLoader(ActivateExt1.class) .getActivateExtension(url, new String[]{}, "value"); @@ -401,7 +401,7 @@ public void testLoadActivateExtension() throws Exception { // test order url = URL.valueOf("test://localhost/test"); - url = url.addParameter(Constants.GROUP_KEY, "order"); + url = url.addParameter(GROUP_KEY, "order"); list = ExtensionLoader.getExtensionLoader(ActivateExt1.class) .getActivateExtension(url, new String[]{}, "order"); Assertions.assertEquals(2, list.size()); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/cached/CachedThreadPoolTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/cached/CachedThreadPoolTest.java index 763cd0fdfe9..2754635f0ed 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/cached/CachedThreadPoolTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/cached/CachedThreadPoolTest.java @@ -17,11 +17,11 @@ package org.apache.dubbo.common.threadpool.support.cached; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.threadlocal.InternalThread; import org.apache.dubbo.common.threadpool.ThreadPool; import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport; + import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; @@ -31,22 +31,26 @@ import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.CommonConstants.ALIVE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.startsWith; -import static org.hamcrest.MatcherAssert.assertThat; public class CachedThreadPoolTest { @Test public void getExecutor1() throws Exception { URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + - Constants.THREAD_NAME_KEY + "=demo&" + - Constants.CORE_THREADS_KEY + "=1&" + - Constants.THREADS_KEY + "=2&" + - Constants.ALIVE_KEY + "=1000&" + - Constants.QUEUES_KEY + "=0"); + THREAD_NAME_KEY + "=demo&" + + CORE_THREADS_KEY + "=1&" + + THREADS_KEY + "=2&" + + ALIVE_KEY + "=1000&" + + QUEUES_KEY + "=0"); ThreadPool threadPool = new CachedThreadPool(); ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url); assertThat(executor.getCorePoolSize(), is(1)); @@ -72,7 +76,7 @@ public void run() { @Test public void getExecutor2() throws Exception { - URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + Constants.QUEUES_KEY + "=1"); + URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + QUEUES_KEY + "=1"); ThreadPool threadPool = new CachedThreadPool(); ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url); assertThat(executor.getQueue(), Matchers.>instanceOf(LinkedBlockingQueue.class)); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolTest.java index 2884c73e8cd..95e41875bcb 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolTest.java @@ -17,11 +17,11 @@ package org.apache.dubbo.common.threadpool.support.eager; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.threadlocal.InternalThread; import org.apache.dubbo.common.threadpool.ThreadPool; import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport; + import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; @@ -31,20 +31,25 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.CommonConstants.ALIVE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.startsWith; -import static org.hamcrest.MatcherAssert.assertThat; public class EagerThreadPoolTest { @Test public void getExecutor1() throws Exception { URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + - Constants.THREAD_NAME_KEY + "=demo&" + - Constants.CORE_THREADS_KEY + "=1&" + - Constants.THREADS_KEY + "=2&" + - Constants.ALIVE_KEY + "=1000&" + - Constants.QUEUES_KEY + "=0"); + THREAD_NAME_KEY + "=demo&" + + CORE_THREADS_KEY + "=1&" + + THREADS_KEY + "=2&" + + ALIVE_KEY + "=1000&" + + QUEUES_KEY + "=0"); ThreadPool threadPool = new EagerThreadPool(); ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url); assertThat(executor, instanceOf(EagerThreadPoolExecutor.class)); @@ -73,7 +78,7 @@ public void run() { @Test public void getExecutor2() throws Exception { - URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + Constants.QUEUES_KEY + "=2"); + URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + QUEUES_KEY + "=2"); ThreadPool threadPool = new EagerThreadPool(); ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url); assertThat(executor.getQueue().remainingCapacity(), is(2)); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/fixed/FixedThreadPoolTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/fixed/FixedThreadPoolTest.java index f1324b18d89..ff8ac9225f8 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/fixed/FixedThreadPoolTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/fixed/FixedThreadPoolTest.java @@ -17,12 +17,11 @@ package org.apache.dubbo.common.threadpool.support.fixed; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.threadlocal.InternalThread; import org.apache.dubbo.common.threadpool.ThreadPool; import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport; -import org.apache.dubbo.common.threadpool.support.limited.LimitedThreadPool; + import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; @@ -34,19 +33,23 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.startsWith; -import static org.hamcrest.MatcherAssert.assertThat; public class FixedThreadPoolTest { @Test public void getExecutor1() throws Exception { URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + - Constants.THREAD_NAME_KEY + "=demo&" + - Constants.CORE_THREADS_KEY + "=1&" + - Constants.THREADS_KEY + "=2&" + - Constants.QUEUES_KEY + "=0"); + THREAD_NAME_KEY + "=demo&" + + CORE_THREADS_KEY + "=1&" + + THREADS_KEY + "=2&" + + QUEUES_KEY + "=0"); ThreadPool threadPool = new FixedThreadPool(); ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url); assertThat(executor.getCorePoolSize(), is(2)); @@ -73,7 +76,7 @@ public void run() { @Test public void getExecutor2() throws Exception { - URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + Constants.QUEUES_KEY + "=1"); + URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + QUEUES_KEY + "=1"); ThreadPool threadPool = new FixedThreadPool(); ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url); assertThat(executor.getQueue(), Matchers.>instanceOf(LinkedBlockingQueue.class)); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/limited/LimitedThreadPoolTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/limited/LimitedThreadPoolTest.java index bb1465773b7..4878d3546c4 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/limited/LimitedThreadPoolTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/limited/LimitedThreadPoolTest.java @@ -17,11 +17,11 @@ package org.apache.dubbo.common.threadpool.support.limited; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.threadlocal.InternalThread; import org.apache.dubbo.common.threadpool.ThreadPool; import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport; + import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; @@ -31,21 +31,24 @@ import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.startsWith; -import static org.hamcrest.MatcherAssert.assertThat; public class LimitedThreadPoolTest { @Test public void getExecutor1() throws Exception { URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + - Constants.THREAD_NAME_KEY + "=demo&" + - Constants.CORE_THREADS_KEY + "=1&" + - Constants.THREADS_KEY + "=2&" + - Constants.QUEUES_KEY + "=0"); + THREAD_NAME_KEY + "=demo&" + + CORE_THREADS_KEY + "=1&" + + THREADS_KEY + "=2&" + + QUEUES_KEY + "=0"); ThreadPool threadPool = new LimitedThreadPool(); ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url); assertThat(executor.getCorePoolSize(), is(1)); @@ -71,7 +74,7 @@ public void run() { @Test public void getExecutor2() throws Exception { - URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + Constants.QUEUES_KEY + "=1"); + URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + QUEUES_KEY + "=1"); ThreadPool threadPool = new LimitedThreadPool(); ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url); assertThat(executor.getQueue(), Matchers.>instanceOf(LinkedBlockingQueue.class)); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CIDRUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CIDRUtilsTest.java index d0c627d174b..89e023f72b2 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CIDRUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CIDRUtilsTest.java @@ -21,9 +21,6 @@ import java.net.UnknownHostException; -/** - * @author cvictory ON 2019-02-28 - */ public class CIDRUtilsTest { @Test diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ConfigUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ConfigUtilsTest.java index 7e9a4904778..b8c7a737938 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ConfigUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ConfigUtilsTest.java @@ -16,8 +16,9 @@ */ package org.apache.dubbo.common.utils; -import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.threadpool.ThreadPool; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -29,12 +30,12 @@ import java.util.Properties; import static java.util.Arrays.asList; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.hamcrest.MatcherAssert.assertThat; public class ConfigUtilsTest { @BeforeEach @@ -119,19 +120,19 @@ public void testReplaceProperty() throws Exception { @Test public void testGetProperties1() throws Exception { try { - System.setProperty(Constants.DUBBO_PROPERTIES_KEY, "properties.load"); + System.setProperty(CommonConstants.DUBBO_PROPERTIES_KEY, "properties.load"); Properties p = ConfigUtils.getProperties(); assertThat((String) p.get("a"), equalTo("12")); assertThat((String) p.get("b"), equalTo("34")); assertThat((String) p.get("c"), equalTo("56")); } finally { - System.clearProperty(Constants.DUBBO_PROPERTIES_KEY); + System.clearProperty(CommonConstants.DUBBO_PROPERTIES_KEY); } } @Test public void testGetProperties2() throws Exception { - System.clearProperty(Constants.DUBBO_PROPERTIES_KEY); + System.clearProperty(CommonConstants.DUBBO_PROPERTIES_KEY); Properties p = ConfigUtils.getProperties(); assertThat((String) p.get("dubbo"), equalTo("properties")); } @@ -256,4 +257,4 @@ public void testLoadPropertiesMultiFileNotRootPath() throws Exception { public void testGetPid() throws Exception { assertThat(ConfigUtils.getPid(), greaterThan(0)); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ExecutorUtilTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ExecutorUtilTest.java index 2ef0f4a2a40..2653eae4f02 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ExecutorUtilTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ExecutorUtilTest.java @@ -17,8 +17,8 @@ package org.apache.dubbo.common.utils; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; + import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -26,9 +26,10 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -76,8 +77,8 @@ public void testShutdownNow() throws Exception { @Test public void testSetThreadName() throws Exception { - URL url = new URL("dubbo", "localhost", 1234).addParameter(Constants.THREAD_NAME_KEY, "custom-thread"); + URL url = new URL("dubbo", "localhost", 1234).addParameter(THREAD_NAME_KEY, "custom-thread"); url = ExecutorUtil.setThreadName(url, "default-name"); - assertThat(url.getParameter(Constants.THREAD_NAME_KEY), equalTo("custom-thread-localhost:1234")); + assertThat(url.getParameter(THREAD_NAME_KEY), equalTo("custom-thread-localhost:1234")); } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/StringUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/StringUtilsTest.java index 384c957bb23..632c999ae6b 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/StringUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/StringUtilsTest.java @@ -16,8 +16,6 @@ */ package org.apache.dubbo.common.utils; -import org.apache.dubbo.common.Constants; - import org.junit.jupiter.api.Test; import java.util.ArrayList; @@ -26,6 +24,9 @@ import java.util.List; import java.util.Map; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; @@ -193,9 +194,9 @@ public void testParseQueryString() throws Exception { @Test public void testGetServiceKey() throws Exception { Map map = new HashMap(); - map.put(Constants.GROUP_KEY, "dubbo"); - map.put(Constants.INTERFACE_KEY, "a.b.c.Foo"); - map.put(Constants.VERSION_KEY, "1.0.0"); + map.put(GROUP_KEY, "dubbo"); + map.put(INTERFACE_KEY, "a.b.c.Foo"); + map.put(VERSION_KEY, "1.0.0"); assertThat(StringUtils.getServiceKey(map), equalTo("dubbo/a.b.c.Foo:1.0.0")); } @@ -295,4 +296,4 @@ public void testTrim() { assertEquals("bi-side blank", StringUtils.trim(" bi-side blank ")); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/UrlUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/UrlUtilsTest.java index 2da27fea760..70800a71fc6 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/UrlUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/UrlUtilsTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.utils; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.junit.jupiter.api.Test; @@ -28,11 +27,14 @@ import java.util.Map; import java.util.Set; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertTrue; public class UrlUtilsTest { @@ -331,16 +333,16 @@ public void testIsItemMatch() throws Exception { @Test public void testIsServiceKeyMatch() throws Exception { URL url = URL.valueOf("test://127.0.0.1"); - URL pattern = url.addParameter(Constants.GROUP_KEY, "test") - .addParameter(Constants.INTERFACE_KEY, "test") - .addParameter(Constants.VERSION_KEY, "test"); + URL pattern = url.addParameter(GROUP_KEY, "test") + .addParameter(INTERFACE_KEY, "test") + .addParameter(VERSION_KEY, "test"); URL value = pattern; assertTrue(UrlUtils.isServiceKeyMatch(pattern, value)); - pattern = pattern.addParameter(Constants.GROUP_KEY, "*"); + pattern = pattern.addParameter(GROUP_KEY, "*"); assertTrue(UrlUtils.isServiceKeyMatch(pattern, value)); - pattern = pattern.addParameter(Constants.VERSION_KEY, "*"); + pattern = pattern.addParameter(VERSION_KEY, "*"); assertTrue(UrlUtils.isServiceKeyMatch(pattern, value)); } @@ -361,4 +363,4 @@ public void testIsMatchGlobPattern() throws Exception { assertTrue(UrlUtils.isMatchGlobPattern("v*e", "value")); assertTrue(UrlUtils.isMatchGlobPattern("$key", "value", URL.valueOf("dubbo://localhost:8080/Foo?key=v*e"))); } -} \ No newline at end of file +} diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/cache/support/AbstractCacheFactory.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/cache/support/AbstractCacheFactory.java index 26aa6e31606..e7a05fdebbe 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/cache/support/AbstractCacheFactory.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/cache/support/AbstractCacheFactory.java @@ -19,13 +19,14 @@ import com.alibaba.dubbo.cache.Cache; import com.alibaba.dubbo.cache.CacheFactory; -import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.rpc.Invocation; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY; + @Deprecated public abstract class AbstractCacheFactory implements CacheFactory { @@ -33,7 +34,7 @@ public abstract class AbstractCacheFactory implements CacheFactory { @Override public Cache getCache(URL url, Invocation invocation) { - url = url.addParameter(Constants.METHOD_KEY, invocation.getMethodName()); + url = url.addParameter(METHOD_KEY, invocation.getMethodName()); String key = url.toFullString(); Cache cache = caches.get(key); if (cache == null) { diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java index 49966db9e05..c7998b2145f 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java @@ -21,7 +21,6 @@ import com.alibaba.dubbo.config.ApplicationConfig; import com.alibaba.dubbo.config.MonitorConfig; import com.alibaba.dubbo.config.RegistryConfig; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -29,13 +28,15 @@ import java.util.HashMap; import java.util.Map; +import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.DUMP_DIRECTORY; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.sameInstance; import static org.hamcrest.collection.IsCollectionWithSize.hasSize; -import static org.hamcrest.MatcherAssert.assertThat; public class ApplicationConfigTest { @Test @@ -47,7 +48,7 @@ public void testName() throws Exception { assertThat(application.getName(), equalTo("app2")); Map parameters = new HashMap(); ApplicationConfig.appendParameters(parameters, application); - assertThat(parameters, hasEntry(Constants.APPLICATION_KEY, "app2")); + assertThat(parameters, hasEntry(APPLICATION_KEY, "app2")); } @Test @@ -141,7 +142,7 @@ public void testDumpDirectory() throws Exception { assertThat(application.getDumpDirectory(), equalTo("/dump")); Map parameters = new HashMap(); ApplicationConfig.appendParameters(parameters, application); - assertThat(parameters, hasEntry(Constants.DUMP_DIRECTORY, "/dump")); + assertThat(parameters, hasEntry(DUMP_DIRECTORY, "/dump")); } @Test @@ -181,4 +182,4 @@ public void testParameters() throws Exception { assertThat(parameters, hasEntry("k1", "v1")); assertThat(parameters, hasEntry(Constants.ACCEPT_FOREIGN_IP, "true")); } -} \ No newline at end of file +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvocation.java b/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvocation.java index a4b5a28c4aa..97c01af3e07 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvocation.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvocation.java @@ -24,6 +24,12 @@ import java.util.HashMap; import java.util.Map; +import static org.apache.dubbo.common.Constants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; + /** * MockInvocation.java */ @@ -49,12 +55,12 @@ public Object[] getArguments() { public Map getAttachments() { Map attachments = new HashMap(); - attachments.put(Constants.PATH_KEY, "dubbo"); - attachments.put(Constants.GROUP_KEY, "dubbo"); - attachments.put(Constants.VERSION_KEY, "1.0.0"); - attachments.put(Constants.DUBBO_VERSION_KEY, "1.0.0"); + attachments.put(PATH_KEY, "dubbo"); + attachments.put(GROUP_KEY, "dubbo"); + attachments.put(VERSION_KEY, "1.0.0"); + attachments.put(DUBBO_VERSION_KEY, "1.0.0"); attachments.put(Constants.TOKEN_KEY, "sfag"); - attachments.put(Constants.TIMEOUT_KEY, "1000"); + attachments.put(TIMEOUT_KEY, "1000"); return attachments; } @@ -70,4 +76,4 @@ public String getAttachment(String key, String defaultValue) { return getAttachments().get(key); } -} \ No newline at end of file +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java b/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java index 148b5bce5f5..5655f26a7bf 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java @@ -23,6 +23,11 @@ import java.util.HashMap; import java.util.Map; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; + /** * MockInvocation.java */ @@ -48,12 +53,12 @@ public Object[] getArguments() { public Map getAttachments() { Map attachments = new HashMap(); - attachments.put(Constants.PATH_KEY, "dubbo"); - attachments.put(Constants.GROUP_KEY, "dubbo"); - attachments.put(Constants.VERSION_KEY, "1.0.0"); + attachments.put(PATH_KEY, "dubbo"); + attachments.put(GROUP_KEY, "dubbo"); + attachments.put(VERSION_KEY, "1.0.0"); attachments.put(Constants.DUBBO_VERSION_KEY, "1.0.0"); attachments.put(Constants.TOKEN_KEY, "sfag"); - attachments.put(Constants.TIMEOUT_KEY, "1000"); + attachments.put(TIMEOUT_KEY, "1000"); return attachments; } @@ -69,4 +74,4 @@ public String getAttachment(String key, String defaultValue) { return getAttachments().get(key); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractConfig.java index 50fb55ed0ab..246694822a7 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractConfig.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.config; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.CompositeConfiguration; import org.apache.dubbo.common.config.Environment; import org.apache.dubbo.common.config.InmemoryConfiguration; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -42,6 +42,9 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.REMOVE_VALUE_PREFIX; + /** * Utility methods and public methods for parsing configuration * @@ -175,7 +178,7 @@ protected static void appendParameters(Map parameters, Object co str = URL.encode(str); } if (parameter != null && parameter.append()) { - String pre = parameters.get(Constants.DEFAULT_KEY + "." + key); + String pre = parameters.get(DEFAULT_KEY + "." + key); if (pre != null && pre.length() > 0) { str = pre + "," + str; } @@ -314,10 +317,10 @@ protected static void checkMultiExtension(Class type, String property, String if (StringUtils.isNotEmpty(value)) { String[] values = value.split("\\s*[,]+\\s*"); for (String v : values) { - if (v.startsWith(Constants.REMOVE_VALUE_PREFIX)) { + if (v.startsWith(REMOVE_VALUE_PREFIX)) { v = v.substring(1); } - if (Constants.DEFAULT_KEY.equals(v)) { + if (DEFAULT_KEY.equals(v)) { continue; } if (!ExtensionLoader.getExtensionLoader(type).hasExtension(v)) { @@ -529,7 +532,7 @@ public Map getMetaData() { @Parameter(excluded = true) public String getPrefix() { - return StringUtils.isNotEmpty(prefix) ? prefix : (Constants.DUBBO + "." + getTagName(this.getClass())); + return StringUtils.isNotEmpty(prefix) ? prefix : (CommonConstants.DUBBO + "." + getTagName(this.getClass())); } public void setPrefix(String prefix) { diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java index ca21e4b3a74..b571eababd7 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java @@ -54,6 +54,16 @@ import java.util.Set; import static org.apache.dubbo.common.config.ConfigurationUtils.parseProperties; +import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR; +import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; +import static org.apache.dubbo.common.constants.CommonConstants.FILE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PID_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; /** @@ -298,16 +308,16 @@ protected List loadRegistries(boolean provider) { for (RegistryConfig config : registries) { String address = config.getAddress(); if (StringUtils.isEmpty(address)) { - address = Constants.ANYHOST_VALUE; + address = ANYHOST_VALUE; } if (!RegistryConfig.NO_AVAILABLE.equalsIgnoreCase(address)) { Map map = new HashMap(); appendParameters(map, application); appendParameters(map, config); - map.put(Constants.PATH_KEY, RegistryService.class.getName()); + map.put(PATH_KEY, RegistryService.class.getName()); appendRuntimeParameters(map); - if (!map.containsKey(Constants.PROTOCOL_KEY)) { - map.put(Constants.PROTOCOL_KEY, Constants.DUBBO_PROTOCOL); + if (!map.containsKey(PROTOCOL_KEY)) { + map.put(PROTOCOL_KEY, Constants.DUBBO_PROTOCOL); } List urls = UrlUtils.parseURLs(address, map); @@ -337,7 +347,7 @@ protected List loadRegistries(boolean provider) { protected URL loadMonitor(URL registryURL) { checkMonitor(); Map map = new HashMap(); - map.put(Constants.INTERFACE_KEY, MonitorService.class.getName()); + map.put(INTERFACE_KEY, MonitorService.class.getName()); appendRuntimeParameters(map); //set ip String hostToRegistry = ConfigUtils.getSystemProperty(Constants.DUBBO_IP_TO_REGISTRY); @@ -356,18 +366,18 @@ protected URL loadMonitor(URL registryURL) { address = sysaddress; } if (ConfigUtils.isNotEmpty(address)) { - if (!map.containsKey(Constants.PROTOCOL_KEY)) { + if (!map.containsKey(PROTOCOL_KEY)) { if (getExtensionLoader(MonitorFactory.class).hasExtension(Constants.LOGSTAT_PROTOCOL)) { - map.put(Constants.PROTOCOL_KEY, Constants.LOGSTAT_PROTOCOL); + map.put(PROTOCOL_KEY, Constants.LOGSTAT_PROTOCOL); } else { - map.put(Constants.PROTOCOL_KEY, Constants.DUBBO_PROTOCOL); + map.put(PROTOCOL_KEY, Constants.DUBBO_PROTOCOL); } } return UrlUtils.parseURL(address, map); } else if (Constants.REGISTRY_PROTOCOL.equals(monitor.getProtocol()) && registryURL != null) { return URLBuilder.from(registryURL) .setProtocol(Constants.DUBBO_PROTOCOL) - .addParameter(Constants.PROTOCOL_KEY, Constants.REGISTRY_PROTOCOL) + .addParameter(PROTOCOL_KEY, Constants.REGISTRY_PROTOCOL) .addParameterAndEncoded(Constants.REFER_KEY, StringUtils.toQueryString(map)) .build(); } @@ -376,10 +386,10 @@ protected URL loadMonitor(URL registryURL) { static void appendRuntimeParameters(Map map) { map.put(Constants.DUBBO_VERSION_KEY, Version.getProtocolVersion()); - map.put(Constants.RELEASE_KEY, Version.getVersion()); - map.put(Constants.TIMESTAMP_KEY, String.valueOf(System.currentTimeMillis())); + map.put(RELEASE_KEY, Version.getVersion()); + map.put(TIMESTAMP_KEY, String.valueOf(System.currentTimeMillis())); if (ConfigUtils.getPid() > 0) { - map.put(Constants.PID_KEY, String.valueOf(ConfigUtils.getPid())); + map.put(PID_KEY, String.valueOf(ConfigUtils.getPid())); } } @@ -519,7 +529,7 @@ private void convertRegistryIdsToRegistries() { configedRegistries.addAll(getSubProperties(Environment.getInstance().getAppExternalConfigurationMap(), Constants.REGISTRIES_SUFFIX)); - registryIds = String.join(Constants.COMMA_SEPARATOR, configedRegistries); + registryIds = String.join(COMMA_SEPARATOR, configedRegistries); } if (StringUtils.isEmpty(registryIds)) { @@ -535,7 +545,7 @@ private void convertRegistryIdsToRegistries() { ); } } else { - String[] ids = Constants.COMMA_SPLIT_PATTERN.split(registryIds); + String[] ids = COMMA_SPLIT_PATTERN.split(registryIds); List tmpRegistries = CollectionUtils.isNotEmpty(registries) ? registries : new ArrayList<>(); Arrays.stream(ids).forEach(id -> { if (tmpRegistries.stream().noneMatch(reg -> reg.getId().equals(id))) { @@ -678,7 +688,7 @@ public String getFilter() { } public void setFilter(String filter) { - checkMultiExtension(Filter.class, Constants.FILE_KEY, filter); + checkMultiExtension(Filter.class, FILE_KEY, filter); this.filter = filter; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java index 75281e965e1..69f0a69c8e9 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java @@ -22,6 +22,9 @@ import org.apache.dubbo.rpc.InvokerListener; import org.apache.dubbo.rpc.support.ProtocolUtils; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; + /** * AbstractConsumerConfig * @@ -203,7 +206,7 @@ public String getVersion() { } public void setVersion(String version) { - checkKey(Constants.VERSION_KEY, version); + checkKey(VERSION_KEY, version); this.version = version; } @@ -212,7 +215,7 @@ public String getGroup() { } public void setGroup(String group) { - checkKey(Constants.GROUP_KEY, group); + checkKey(GROUP_KEY, group); this.group = group; } } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java index 35607fad2f7..636039ffd7d 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java @@ -26,6 +26,9 @@ import java.util.Arrays; import java.util.List; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; + /** * AbstractServiceConfig * @@ -116,7 +119,7 @@ public String getVersion() { } public void setVersion(String version) { - checkKey(Constants.VERSION_KEY, version); + checkKey(VERSION_KEY, version); this.version = version; } @@ -125,7 +128,7 @@ public String getGroup() { } public void setGroup(String group) { - checkKey(Constants.GROUP_KEY, group); + checkKey(GROUP_KEY, group); this.group = group; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java index 2775d0de514..1aa364a0b74 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java @@ -27,6 +27,9 @@ import java.util.List; import java.util.Map; +import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.DUMP_DIRECTORY; + /** * The application info @@ -130,7 +133,7 @@ public ApplicationConfig(String name) { setName(name); } - @Parameter(key = Constants.APPLICATION_KEY, required = true, useKeyAsProperty = false) + @Parameter(key = APPLICATION_KEY, required = true, useKeyAsProperty = false) public String getName() { return name; } @@ -267,7 +270,7 @@ public void setDefault(Boolean isDefault) { this.isDefault = isDefault; } - @Parameter(key = Constants.DUMP_DIRECTORY) + @Parameter(key = DUMP_DIRECTORY) public String getDumpDirectory() { return dumpDirectory; } @@ -327,4 +330,4 @@ public boolean isValid() { return !StringUtils.isEmpty(name); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java index 45677bf2bdd..6870b1aaa55 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java @@ -26,6 +26,10 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; +import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; + /** * ConfigCenterConfig */ @@ -56,12 +60,12 @@ public ConfigCenterConfig() { public URL toUrl() { Map map = this.getMetaData(); if (StringUtils.isEmpty(address)) { - address = Constants.ANYHOST_VALUE; + address = ANYHOST_VALUE; } - map.put(Constants.PATH_KEY, ConfigCenterConfig.class.getSimpleName()); + map.put(PATH_KEY, ConfigCenterConfig.class.getSimpleName()); // use 'zookeeper' as the default configcenter. - if (StringUtils.isEmpty(map.get(Constants.PROTOCOL_KEY))) { - map.put(Constants.PROTOCOL_KEY, Constants.ZOOKEEPER_PROTOCOL); + if (StringUtils.isEmpty(map.get(PROTOCOL_KEY))) { + map.put(PROTOCOL_KEY, Constants.ZOOKEEPER_PROTOCOL); } return UrlUtils.parseURL(address, map); } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MetadataReportConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MetadataReportConfig.java index e7add0a0e81..a7c72f6f41b 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MetadataReportConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MetadataReportConfig.java @@ -16,13 +16,13 @@ */ package org.apache.dubbo.config; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.support.Parameter; import java.util.Map; -import static org.apache.dubbo.common.Constants.PROPERTIES_CHAR_SEPERATOR; +import static org.apache.dubbo.common.constants.CommonConstants.DUBBO; +import static org.apache.dubbo.common.constants.CommonConstants.PROPERTIES_CHAR_SEPERATOR; /** * MetadataReportConfig @@ -158,7 +158,7 @@ public void setSyncReport(Boolean syncReport) { @Override @Parameter(excluded = true) public String getPrefix() { - return StringUtils.isNotEmpty(prefix) ? prefix : (Constants.DUBBO + "." + PREFIX_TAG); + return StringUtils.isNotEmpty(prefix) ? prefix : (DUBBO + "." + PREFIX_TAG); } @Override diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MethodConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MethodConfig.java index c9478d45cae..0bc989fb3c8 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MethodConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MethodConfig.java @@ -17,6 +17,7 @@ package org.apache.dubbo.config; import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.annotation.Method; import org.apache.dubbo.config.support.Parameter; @@ -318,7 +319,7 @@ public void setServiceId(String serviceId) { @Override @Parameter(excluded = true) public String getPrefix() { - return Constants.DUBBO + "." + service + return CommonConstants.DUBBO + "." + service + (StringUtils.isEmpty(serviceId) ? "" : ("." + serviceId)) + "." + getName(); } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java index 4cb2f7dcdd7..767204e255c 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java @@ -33,6 +33,8 @@ import java.util.Map; +import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; + /** * ProtocolConfig * @@ -269,7 +271,7 @@ public String getThreadpool() { } public void setThreadpool(String threadpool) { - checkExtension(ThreadPool.class, Constants.THREADPOOL_KEY, threadpool); + checkExtension(ThreadPool.class, THREADPOOL_KEY, threadpool); this.threadpool = threadpool; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProviderConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProviderConfig.java index b76ab7958fb..33a88e68642 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProviderConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProviderConfig.java @@ -29,6 +29,8 @@ import java.util.ArrayList; import java.util.Arrays; +import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; + /** * The service provider default configuration * @@ -217,7 +219,7 @@ public String getThreadpool() { } public void setThreadpool(String threadpool) { - checkExtension(ThreadPool.class, Constants.THREADPOOL_KEY, threadpool); + checkExtension(ThreadPool.class, THREADPOOL_KEY, threadpool); this.threadpool = threadpool; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java index 32f5dd14dcd..2842eabd703 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java @@ -56,6 +56,16 @@ import java.util.Map; import java.util.Properties; +import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR; +import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; +import static org.apache.dubbo.common.constants.CommonConstants.DUBBO; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.SEMICOLON_SPLIT_PATTERN; +import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.utils.NetUtils.isInvalidLocalHost; /** @@ -261,24 +271,24 @@ private void init() { checkMock(interfaceClass); Map map = new HashMap(); - map.put(Constants.SIDE_KEY, Constants.CONSUMER_SIDE); + map.put(SIDE_KEY, CONSUMER_SIDE); appendRuntimeParameters(map); if (!isGeneric()) { String revision = Version.getVersion(interfaceClass, version); if (revision != null && revision.length() > 0) { - map.put(Constants.REVISION_KEY, revision); + map.put(REVISION_KEY, revision); } String[] methods = Wrapper.getWrapper(interfaceClass).getMethodNames(); if (methods.length == 0) { logger.warn("No method found in service interface " + interfaceClass.getName()); - map.put(Constants.METHODS_KEY, Constants.ANY_VALUE); + map.put(METHODS_KEY, ANY_VALUE); } else { - map.put(Constants.METHODS_KEY, StringUtils.join(new HashSet(Arrays.asList(methods)), Constants.COMMA_SEPARATOR)); + map.put(METHODS_KEY, StringUtils.join(new HashSet(Arrays.asList(methods)), COMMA_SEPARATOR)); } } - map.put(Constants.INTERFACE_KEY, interfaceName); + map.put(INTERFACE_KEY, interfaceName); appendParameters(map, metrics); appendParameters(map, application); appendParameters(map, module); @@ -333,14 +343,14 @@ private ConsumerModel buildConsumerModel(String serviceKey, Map @SuppressWarnings({"unchecked", "rawtypes", "deprecation"}) private T createProxy(Map map) { if (shouldJvmRefer(map)) { - URL url = new URL(Constants.LOCAL_PROTOCOL, Constants.LOCALHOST_VALUE, 0, interfaceClass.getName()).addParameters(map); + URL url = new URL(Constants.LOCAL_PROTOCOL, LOCALHOST_VALUE, 0, interfaceClass.getName()).addParameters(map); invoker = REF_PROTOCOL.refer(interfaceClass, url); if (logger.isInfoEnabled()) { logger.info("Using injvm service " + interfaceClass.getName()); } } else { if (url != null && url.length() > 0) { // user specified URL, could be peer-to-peer address, or register center's address. - String[] us = Constants.SEMICOLON_SPLIT_PATTERN.split(url); + String[] us = SEMICOLON_SPLIT_PATTERN.split(url); if (us != null && us.length > 0) { for (String u : us) { URL url = URL.valueOf(u); @@ -410,7 +420,7 @@ private T createProxy(Map map) { */ MetadataReportService metadataReportService = null; if ((metadataReportService = getMetadataReportService()) != null) { - URL consumerURL = new URL(Constants.CONSUMER_PROTOCOL, map.remove(Constants.REGISTER_IP_KEY), 0, map.get(Constants.INTERFACE_KEY), map); + URL consumerURL = new URL(Constants.CONSUMER_PROTOCOL, map.remove(Constants.REGISTER_IP_KEY), 0, map.get(INTERFACE_KEY), map); metadataReportService.publishConsumer(consumerURL); } // create service proxy @@ -609,7 +619,7 @@ Invoker getInvoker() { @Override @Parameter(excluded = true) public String getPrefix() { - return Constants.DUBBO + ".reference." + interfaceName; + return DUBBO + ".reference." + interfaceName; } private void resolveFile() { diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java index bb72e218e85..a529fd604a9 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java @@ -23,6 +23,9 @@ import java.util.Map; +import static org.apache.dubbo.common.constants.CommonConstants.FILE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; + /** * RegistryConfig * @@ -158,7 +161,7 @@ public String getProtocol() { } public void setProtocol(String protocol) { - checkName(Constants.PROTOCOL_KEY, protocol); + checkName(PROTOCOL_KEY, protocol); this.protocol = protocol; this.updateIdIfAbsent(protocol); } @@ -240,7 +243,7 @@ public String getFile() { } public void setFile(String file) { - checkPathLength(Constants.FILE_KEY, file); + checkPathLength(FILE_KEY, file); this.file = file; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index 0c755b475bf..d4ef8bb1536 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -62,7 +62,16 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; -import static org.apache.dubbo.common.Constants.LOCALHOST_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; +import static org.apache.dubbo.common.constants.CommonConstants.DUBBO; +import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; +import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.utils.NetUtils.getAvailablePort; import static org.apache.dubbo.common.utils.NetUtils.getLocalHost; import static org.apache.dubbo.common.utils.NetUtils.isInvalidLocalHost; @@ -436,11 +445,11 @@ private void doExportUrls() { private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List registryURLs) { String name = protocolConfig.getName(); if (StringUtils.isEmpty(name)) { - name = Constants.DUBBO; + name = DUBBO; } Map map = new HashMap(); - map.put(Constants.SIDE_KEY, Constants.PROVIDER_SIDE); + map.put(SIDE_KEY, PROVIDER_SIDE); appendRuntimeParameters(map); appendParameters(map, metrics); @@ -509,19 +518,19 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r if (ProtocolUtils.isGeneric(generic)) { map.put(Constants.GENERIC_KEY, generic); - map.put(Constants.METHODS_KEY, Constants.ANY_VALUE); + map.put(METHODS_KEY, ANY_VALUE); } else { String revision = Version.getVersion(interfaceClass, version); if (revision != null && revision.length() > 0) { - map.put(Constants.REVISION_KEY, revision); + map.put(REVISION_KEY, revision); } String[] methods = Wrapper.getWrapper(interfaceClass).getMethodNames(); if (methods.length == 0) { logger.warn("No method found in service interface " + interfaceClass.getName()); - map.put(Constants.METHODS_KEY, Constants.ANY_VALUE); + map.put(METHODS_KEY, ANY_VALUE); } else { - map.put(Constants.METHODS_KEY, StringUtils.join(new HashSet(Arrays.asList(methods)), ",")); + map.put(METHODS_KEY, StringUtils.join(new HashSet(Arrays.asList(methods)), ",")); } } if (!ConfigUtils.isEmpty(token)) { @@ -696,7 +705,7 @@ private String findConfigedHosts(ProtocolConfig protocolConfig, List regist hostToRegistry = hostToBind; } - map.put(Constants.ANYHOST_KEY, String.valueOf(anyhost)); + map.put(ANYHOST_KEY, String.valueOf(anyhost)); return hostToRegistry; } @@ -863,7 +872,7 @@ private void convertProtocolIdsToProtocols() { ); } } else { - String[] arr = Constants.COMMA_SPLIT_PATTERN.split(protocolIds); + String[] arr = COMMA_SPLIT_PATTERN.split(protocolIds); List tmpProtocols = CollectionUtils.isNotEmpty(protocols) ? protocols : new ArrayList<>(); Arrays.stream(arr).forEach(id -> { if (tmpProtocols.stream().noneMatch(prot -> prot.getId().equals(id))) { @@ -943,7 +952,7 @@ public String getPath() { } public void setPath(String path) { - checkPathName(Constants.PATH_KEY, path); + checkPathName(PATH_KEY, path); this.path = path; } @@ -1024,6 +1033,6 @@ public void setProviders(List providers) { @Override @Parameter(excluded = true) public String getPrefix() { - return Constants.DUBBO + ".service." + interfaceName; + return DUBBO + ".service." + interfaceName; } } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/context/ConfigManager.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/context/ConfigManager.java index 808fd9cdc57..79b097a0db8 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/context/ConfigManager.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/context/ConfigManager.java @@ -35,7 +35,7 @@ import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; -import static org.apache.dubbo.common.Constants.DEFAULT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; /** * TODO diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractInterfaceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractInterfaceConfigTest.java index 6f30581b875..004d78006f0 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractInterfaceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractInterfaceConfigTest.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.config.api.Greeting; import org.apache.dubbo.config.context.ConfigManager; @@ -51,13 +52,13 @@ public class AbstractInterfaceConfigTest { @BeforeAll public static void setUp(@TempDir Path folder) { - dubboProperties = folder.resolve(Constants.DUBBO_PROPERTIES_KEY).toFile(); - System.setProperty(Constants.DUBBO_PROPERTIES_KEY, dubboProperties.getAbsolutePath()); + dubboProperties = folder.resolve(CommonConstants.DUBBO_PROPERTIES_KEY).toFile(); + System.setProperty(CommonConstants.DUBBO_PROPERTIES_KEY, dubboProperties.getAbsolutePath()); } @AfterAll public static void tearDown() { - System.clearProperty(Constants.DUBBO_PROPERTIES_KEY); + System.clearProperty(CommonConstants.DUBBO_PROPERTIES_KEY); } @AfterEach diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java index d560921de4b..be140fce8be 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java @@ -26,13 +26,15 @@ import java.util.HashMap; import java.util.Map; +import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.DUMP_DIRECTORY; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.sameInstance; import static org.hamcrest.collection.IsCollectionWithSize.hasSize; -import static org.hamcrest.MatcherAssert.assertThat; public class ApplicationConfigTest { @Test @@ -44,7 +46,7 @@ public void testName() throws Exception { assertThat(application.getName(), equalTo("app2")); Map parameters = new HashMap(); ApplicationConfig.appendParameters(parameters, application); - assertThat(parameters, hasEntry(Constants.APPLICATION_KEY, "app2")); + assertThat(parameters, hasEntry(APPLICATION_KEY, "app2")); } @Test @@ -138,7 +140,7 @@ public void testDumpDirectory() throws Exception { assertThat(application.getDumpDirectory(), equalTo("/dump")); Map parameters = new HashMap(); ApplicationConfig.appendParameters(parameters, application); - assertThat(parameters, hasEntry(Constants.DUMP_DIRECTORY, "/dump")); + assertThat(parameters, hasEntry(DUMP_DIRECTORY, "/dump")); } @Test diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java index 3a54f30c5ff..0bd7068057c 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java @@ -46,6 +46,12 @@ import static org.apache.dubbo.common.Constants.GENERIC_SERIALIZATION_BEAN; import static org.apache.dubbo.common.Constants.GENERIC_SERIALIZATION_DEFAULT; import static org.apache.dubbo.common.Constants.GENERIC_SERIALIZATION_NATIVE_JAVA; +import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; +import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; @@ -131,17 +137,17 @@ public void testExport() throws Exception { URL url = service.toUrl(); assertThat(url.getProtocol(), equalTo("mockprotocol2")); assertThat(url.getPath(), equalTo(DemoService.class.getName())); - assertThat(url.getParameters(), hasEntry(Constants.ANYHOST_KEY, "true")); - assertThat(url.getParameters(), hasEntry(Constants.APPLICATION_KEY, "app")); + assertThat(url.getParameters(), hasEntry(ANYHOST_KEY, "true")); + assertThat(url.getParameters(), hasEntry(APPLICATION_KEY, "app")); assertThat(url.getParameters(), hasKey(RemotingConstants.BIND_IP_KEY)); assertThat(url.getParameters(), hasKey(RemotingConstants.BIND_PORT_KEY)); assertThat(url.getParameters(), hasEntry(Constants.EXPORT_KEY, "true")); assertThat(url.getParameters(), hasEntry("echo.0.callback", "false")); assertThat(url.getParameters(), hasEntry(Constants.GENERIC_KEY, "false")); - assertThat(url.getParameters(), hasEntry(Constants.INTERFACE_KEY, DemoService.class.getName())); - assertThat(url.getParameters(), hasKey(Constants.METHODS_KEY)); - assertThat(url.getParameters().get(Constants.METHODS_KEY), containsString("echo")); - assertThat(url.getParameters(), hasEntry(Constants.SIDE_KEY, Constants.PROVIDER)); + assertThat(url.getParameters(), hasEntry(INTERFACE_KEY, DemoService.class.getName())); + assertThat(url.getParameters(), hasKey(METHODS_KEY)); + assertThat(url.getParameters().get(METHODS_KEY), containsString("echo")); + assertThat(url.getParameters(), hasEntry(SIDE_KEY, PROVIDER)); Mockito.verify(protocolDelegate).export(Mockito.any(Invoker.class)); } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockRegistry.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockRegistry.java index 5632887648d..47ab8e252be 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockRegistry.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockRegistry.java @@ -24,6 +24,8 @@ import java.util.ArrayList; import java.util.List; +import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; + /** * TODO Comment of MockRegistry */ @@ -84,7 +86,7 @@ public void subscribe(URL url, NotifyListener listener) { urls.add(url.setProtocol("mockprotocol") .removeParameter(Constants.CATEGORY_KEY) - .addParameter(Constants.METHODS_KEY, "sayHello")); + .addParameter(METHODS_KEY, "sayHello")); listener.notify(urls); } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ReferenceBean.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ReferenceBean.java index 3c1111ba749..314cdfe2910 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ReferenceBean.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ReferenceBean.java @@ -16,18 +16,17 @@ */ package org.apache.dubbo.config.spring; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ConfigCenterConfig; import org.apache.dubbo.config.ConsumerConfig; import org.apache.dubbo.config.MetadataReportConfig; +import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.ModuleConfig; import org.apache.dubbo.config.MonitorConfig; import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.config.RegistryConfig; -import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.annotation.Reference; import org.apache.dubbo.config.spring.extension.SpringExtensionFactory; import org.apache.dubbo.config.support.Parameter; @@ -44,6 +43,8 @@ import java.util.List; import java.util.Map; +import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; + /** * ReferenceFactoryBean */ @@ -158,7 +159,7 @@ public void afterPropertiesSet() throws Exception { if (registryConfigMap != null && registryConfigMap.size() > 0) { List registryConfigs = new ArrayList<>(); if (StringUtils.isNotEmpty(registryIds)) { - Arrays.stream(Constants.COMMA_SPLIT_PATTERN.split(registryIds)).forEach(id -> { + Arrays.stream(COMMA_SPLIT_PATTERN.split(registryIds)).forEach(id -> { if (registryConfigMap.containsKey(id)) { registryConfigs.add(registryConfigMap.get(id)); } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ServiceBean.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ServiceBean.java index ec132eeab60..40eea8c1aca 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ServiceBean.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ServiceBean.java @@ -16,19 +16,18 @@ */ package org.apache.dubbo.config.spring; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.config.ProtocolConfig; -import org.apache.dubbo.config.ProviderConfig; -import org.apache.dubbo.config.ServiceConfig; -import org.apache.dubbo.config.MetricsConfig; -import org.apache.dubbo.config.RegistryConfig; +import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ConfigCenterConfig; import org.apache.dubbo.config.MetadataReportConfig; -import org.apache.dubbo.config.MonitorConfig; +import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.ModuleConfig; -import org.apache.dubbo.config.ApplicationConfig; +import org.apache.dubbo.config.MonitorConfig; +import org.apache.dubbo.config.ProtocolConfig; +import org.apache.dubbo.config.ProviderConfig; +import org.apache.dubbo.config.RegistryConfig; +import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.annotation.Service; import org.apache.dubbo.config.spring.context.event.ServiceBeanExportedEvent; import org.apache.dubbo.config.spring.extension.SpringExtensionFactory; @@ -50,6 +49,7 @@ import java.util.List; import java.util.Map; +import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; import static org.apache.dubbo.config.spring.util.BeanFactoryUtils.addApplicationListener; /** @@ -200,7 +200,7 @@ public void afterPropertiesSet() throws Exception { if (CollectionUtils.isNotEmptyMap(registryConfigMap)) { List registryConfigs = new ArrayList<>(); if (StringUtils.isNotEmpty(registryIds)) { - Arrays.stream(Constants.COMMA_SPLIT_PATTERN.split(registryIds)).forEach(id -> { + Arrays.stream(COMMA_SPLIT_PATTERN.split(registryIds)).forEach(id -> { if (registryConfigMap.containsKey(id)) { registryConfigs.add(registryConfigMap.get(id)); } @@ -285,7 +285,7 @@ public void afterPropertiesSet() throws Exception { if (protocolConfigMap != null && protocolConfigMap.size() > 0) { List protocolConfigs = new ArrayList(); if (StringUtils.isNotEmpty(getProtocolIds())) { - Arrays.stream(Constants.COMMA_SPLIT_PATTERN.split(getProtocolIds())) + Arrays.stream(COMMA_SPLIT_PATTERN.split(getProtocolIds())) .forEach(id -> { if (protocolConfigMap.containsKey(id)) { protocolConfigs.add(protocolConfigMap.get(id)); diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationBeanNameBuilder.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationBeanNameBuilder.java index 610058acd71..867fb2a182d 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationBeanNameBuilder.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationBeanNameBuilder.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.config.spring.beans.factory.annotation; -import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.config.annotation.Reference; import org.apache.dubbo.config.annotation.Service; import org.apache.dubbo.registry.Registry; @@ -24,8 +24,8 @@ import org.springframework.core.env.Environment; import static org.apache.dubbo.common.Constants.CONSUMERS_CATEGORY; -import static org.apache.dubbo.common.Constants.DEFAULT_PROTOCOL; import static org.apache.dubbo.common.Constants.PROVIDERS_CATEGORY; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_PROTOCOL; import static org.apache.dubbo.config.spring.util.AnnotationUtils.resolveInterfaceName; import static org.springframework.util.StringUtils.arrayToCommaDelimitedString; import static org.springframework.util.StringUtils.hasText; @@ -114,8 +114,8 @@ public AnnotationBeanNameBuilder environment(Environment environment) { * * @param protocols one or more protocols * @return if protocols == null, it will return - * {@link Constants#DEFAULT_PROTOCOL "dubbo"} as the default protocol - * @see Constants#DEFAULT_PROTOCOL + * {@link CommonConstants#DEFAULT_PROTOCOL "dubbo"} as the default protocol + * @see CommonConstants#DEFAULT_PROTOCOL */ private static String resolveProtocol(String... protocols) { String protocol = arrayToCommaDelimitedString(protocols); diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/DubboBeanDefinitionParser.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/DubboBeanDefinitionParser.java index f5c2ab07f93..3ad8243ad37 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/DubboBeanDefinitionParser.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/DubboBeanDefinitionParser.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config.spring.schema; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ReflectUtils; @@ -52,6 +51,8 @@ import java.util.Set; import java.util.regex.Pattern; +import static org.apache.dubbo.common.constants.CommonConstants.HIDE_KEY_PREFIX; + /** * AbstractBeanDefinitionParser * @@ -316,7 +317,7 @@ private static ManagedMap parseParameters(NodeList nodeList, RootBeanDefinition String value = ((Element) node).getAttribute("value"); boolean hide = "true".equals(((Element) node).getAttribute("hide")); if (hide) { - key = Constants.HIDE_KEY_PREFIX + key; + key = HIDE_KEY_PREFIX + key; } parameters.put(key, new TypedStringValue(value, String.class)); } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java index 0db362af074..c3616a7c570 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java @@ -17,7 +17,6 @@ package org.apache.dubbo.config.spring; import org.apache.dubbo.common.Constants; -import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; @@ -29,6 +28,8 @@ import java.io.IOException; import java.net.ServerSocket; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; + /** * SimpleRegistryExporter */ @@ -55,7 +56,7 @@ public static Exporter export(int port, RegistryService registr return protocol.export(proxyFactory.getInvoker(registryService, RegistryService.class, new URLBuilder(Constants.DUBBO_PROTOCOL, NetUtils.getLocalHost(), port, RegistryService.class.getName()) .setPath(RegistryService.class.getName()) - .addParameter(Constants.INTERFACE_KEY, RegistryService.class.getName()) + .addParameter(INTERFACE_KEY, RegistryService.class.getName()) .addParameter(Constants.CLUSTER_STICKY_KEY, "true") .addParameter(Constants.CALLBACK_INSTANCES_LIMIT_KEY, "1000") .addParameter("ondisconnect", "disconnect") diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceBeanBuilderTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceBeanBuilderTest.java index 7dd12663d89..069de915a67 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceBeanBuilderTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceBeanBuilderTest.java @@ -38,7 +38,6 @@ /** * {@link ReferenceBeanBuilder} Test * - * @author Mercy * @see ReferenceBeanBuilder * @see Reference * @since 2.6.4 diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java index ebce3031d73..4df84265d12 100644 --- a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java @@ -41,6 +41,9 @@ import java.util.concurrent.CopyOnWriteArraySet; import java.util.stream.Collectors; +import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; + /** * Apollo implementation, https://github.com/ctripcorp/apollo */ @@ -64,7 +67,7 @@ public class ApolloDynamicConfiguration implements DynamicConfiguration { if (configEnv != null) { System.setProperty(APOLLO_ENV_KEY, configEnv); } - if (StringUtils.isEmpty(System.getProperty(APOLLO_ENV_KEY)) && !Constants.ANYHOST_VALUE.equals(configAddr)) { + if (StringUtils.isEmpty(System.getProperty(APOLLO_ENV_KEY)) && !ANYHOST_VALUE.equals(configAddr)) { System.setProperty(APOLLO_ADDR_KEY, configAddr); } if (configCluster != null) { @@ -89,7 +92,7 @@ public class ApolloDynamicConfiguration implements DynamicConfiguration { private String getAddressWithProtocolPrefix (URL url) { String address = url.getBackupAddress(); if (StringUtils.isNotEmpty(address)) { - address = Arrays.stream(Constants.COMMA_SPLIT_PATTERN.split(address)) + address = Arrays.stream(COMMA_SPLIT_PATTERN.split(address)) .map(addr -> { if (addr.startsWith(APOLLO_PROTOCOL_PREFIX)) { return addr; diff --git a/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfiguration.java index 0168fd12946..d03e0f1c560 100644 --- a/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfiguration.java @@ -40,7 +40,7 @@ import static java.util.concurrent.Executors.newCachedThreadPool; import static org.apache.dubbo.common.Constants.CONFIG_NAMESPACE_KEY; -import static org.apache.dubbo.common.Constants.PATH_SEPARATOR; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; import static org.apache.dubbo.configcenter.ConfigChangeType.ADDED; /** diff --git a/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfiguration.java index 18e90887592..66799b9015f 100644 --- a/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfiguration.java @@ -40,7 +40,7 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.dubbo.common.Constants.CONFIG_NAMESPACE_KEY; -import static org.apache.dubbo.common.Constants.PATH_SEPARATOR; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; /** * The etcd implementation of {@link DynamicConfiguration} diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java index 2d63c99ec29..3baf27c7cc0 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java @@ -17,10 +17,6 @@ package org.apache.dubbo.configcenter.support.nacos; -import com.alibaba.nacos.api.NacosFactory; -import com.alibaba.nacos.api.config.ConfigService; -import com.alibaba.nacos.api.config.listener.AbstractSharedListener; -import com.alibaba.nacos.api.exception.NacosException; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -30,24 +26,30 @@ import org.apache.dubbo.configcenter.ConfigurationListener; import org.apache.dubbo.configcenter.DynamicConfiguration; +import com.alibaba.nacos.api.NacosFactory; +import com.alibaba.nacos.api.config.ConfigService; +import com.alibaba.nacos.api.config.listener.AbstractSharedListener; +import com.alibaba.nacos.api.exception.NacosException; + import java.util.Map; import java.util.Properties; import java.util.Set; -import java.util.concurrent.Executor; -import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArraySet; +import java.util.concurrent.Executor; + import static com.alibaba.nacos.api.PropertyKeyConst.ACCESS_KEY; import static com.alibaba.nacos.api.PropertyKeyConst.CLUSTER_NAME; import static com.alibaba.nacos.api.PropertyKeyConst.ENDPOINT; +import static com.alibaba.nacos.api.PropertyKeyConst.NAMESPACE; import static com.alibaba.nacos.api.PropertyKeyConst.SECRET_KEY; import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; -import static com.alibaba.nacos.api.PropertyKeyConst.NAMESPACE; import static com.alibaba.nacos.client.naming.utils.UtilAndComs.NACOS_NAMING_LOG_NAME; import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; import static org.apache.dubbo.common.Constants.CONFIG_NAMESPACE_KEY; -import static org.apache.dubbo.common.Constants.GROUP_CHAR_SEPERATOR; -import static org.apache.dubbo.common.Constants.PROPERTIES_CHAR_SEPERATOR; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_CHAR_SEPERATOR; +import static org.apache.dubbo.common.constants.CommonConstants.PROPERTIES_CHAR_SEPERATOR; /** * The nacos implementation of {@link DynamicConfiguration} diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationFactory.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationFactory.java index 2246741c1cb..804e216a590 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationFactory.java +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationFactory.java @@ -17,12 +17,13 @@ package org.apache.dubbo.configcenter.support.nacos; -import com.alibaba.nacos.api.PropertyKeyConst; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.configcenter.AbstractDynamicConfigurationFactory; import org.apache.dubbo.configcenter.DynamicConfiguration; +import com.alibaba.nacos.api.PropertyKeyConst; + /** * The nacos implementation of {@link AbstractDynamicConfigurationFactory} */ @@ -31,7 +32,7 @@ public class NacosDynamicConfigurationFactory extends AbstractDynamicConfigurati @Override protected DynamicConfiguration createDynamicConfiguration(URL url) { URL nacosURL = url; - if (Constants.DUBBO.equals(url.getParameter(PropertyKeyConst.NAMESPACE))) { + if (CommonConstants.DUBBO.equals(url.getParameter(PropertyKeyConst.NAMESPACE))) { // Nacos use empty string as default name space, replace default namespace "dubbo" to "" nacosURL = url.removeParameter(PropertyKeyConst.NAMESPACE); } diff --git a/dubbo-container/dubbo-container-api/src/main/java/org/apache/dubbo/container/Main.java b/dubbo-container/dubbo-container-api/src/main/java/org/apache/dubbo/container/Main.java index 5ae08c27af6..967cece1198 100644 --- a/dubbo-container/dubbo-container-api/src/main/java/org/apache/dubbo/container/Main.java +++ b/dubbo-container/dubbo-container-api/src/main/java/org/apache/dubbo/container/Main.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.container; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -31,6 +30,8 @@ import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; +import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; + /** * Main. (API, Static, ThreadSafe) * @@ -54,7 +55,7 @@ public static void main(String[] args) { try { if (ArrayUtils.isEmpty(args)) { String config = ConfigUtils.getProperty(CONTAINER_KEY, loader.getDefaultExtensionName()); - args = Constants.COMMA_SPLIT_PATTERN.split(config); + args = COMMA_SPLIT_PATTERN.split(config); } final List containers = new ArrayList(); diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java index 4de9f5a170c..89463d8e2b4 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java @@ -19,6 +19,7 @@ import org.apache.dubbo.cache.Cache; import org.apache.dubbo.cache.CacheFactory; import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.StringUtils; @@ -45,10 +46,10 @@ * 3)<dubbo:provider cache="expiring" /> * 4)<dubbo:consumer cache="jcache" /> * - *If cache type is defined in method level then method level type will get precedence. According to above provided - *example, if service has two method, method1 and method2, method2 will have cache type as threadlocal where others will - *be backed by lru - * + * If cache type is defined in method level then method level type will get precedence. According to above provided + * example, if service has two method, method1 and method2, method2 will have cache type as threadlocal where others will + * be backed by lru + * * * @see org.apache.dubbo.rpc.Filter * @see org.apache.dubbo.cache.support.lru.LruCacheFactory @@ -59,9 +60,8 @@ * @see org.apache.dubbo.cache.support.threadlocal.ThreadLocalCache * @see org.apache.dubbo.cache.support.expiring.ExpiringCacheFactory * @see org.apache.dubbo.cache.support.expiring.ExpiringCache - * */ -@Activate(group = {Constants.CONSUMER, Constants.PROVIDER}, value = Constants.CACHE_KEY) +@Activate(group = {CommonConstants.CONSUMER, CommonConstants.PROVIDER}, value = Constants.CACHE_KEY) public class CacheFilter implements Filter { private CacheFactory cacheFactory; @@ -81,6 +81,7 @@ public void setCacheFactory(CacheFactory cacheFactory) { * If cache is configured, dubbo will invoke method on each method call. If cache value is returned by cache store * then it will return otherwise call the remote method and return value. If remote method's return valeu has error * then it will not cache the value. + * * @param invoker service * @param invocation invocation. * @return Cache returned value if found by the underlying cache store. If cache miss it will call target method. @@ -95,7 +96,7 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept Object value = cache.get(key); if (value != null) { if (value instanceof ValueWrapper) { - return new RpcResult(((ValueWrapper)value).get()); + return new RpcResult(((ValueWrapper) value).get()); } else { return new RpcResult(value); } @@ -113,13 +114,13 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept /** * Cache value wrapper. */ - static class ValueWrapper implements Serializable{ + static class ValueWrapper implements Serializable { private static final long serialVersionUID = -1777337318019193256L; private final Object value; - public ValueWrapper(Object value){ + public ValueWrapper(Object value) { this.value = value; } diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java index 2522ce775a8..98ca797b248 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java @@ -18,13 +18,14 @@ import org.apache.dubbo.cache.Cache; import org.apache.dubbo.cache.CacheFactory; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY; + /** * AbstractCacheFactory is a default implementation of {@link CacheFactory}. It abstract out the key formation from URL along with * invocation method. It initially check if the value for key already present in own local in-memory store then it won't check underlying storage cache {@link Cache}. @@ -51,7 +52,7 @@ public abstract class AbstractCacheFactory implements CacheFactory { */ @Override public Cache getCache(URL url, Invocation invocation) { - url = url.addParameter(Constants.METHOD_KEY, invocation.getMethodName()); + url = url.addParameter(METHOD_KEY, invocation.getMethodName()); String key = url.toFullString(); Cache cache = caches.get(key); if (cache == null) { diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCache.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCache.java index 0aae511dd62..bf4b3d16467 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCache.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCache.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.cache.support.jcache; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; @@ -30,6 +29,8 @@ import javax.cache.spi.CachingProvider; import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY; + /** * This class store the cache value per thread. If a service,method,consumer or provided is configured with key cache * with value jcache, dubbo initialize the instance of this class using {@link JCacheFactory} to store method's returns value @@ -45,7 +46,7 @@ public class JCache implements org.apache.dubbo.cache.Cache { private final Cache store; public JCache(URL url) { - String method = url.getParameter(Constants.METHOD_KEY, ""); + String method = url.getParameter(METHOD_KEY, ""); String key = url.getAddress() + "." + url.getServiceKey() + "." + method; // jcache parameter is the full-qualified class name of SPI implementation String type = url.getParameter("jcache"); diff --git a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java index 2af761a0958..0aa0e361f0d 100644 --- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java +++ b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java @@ -17,6 +17,7 @@ package org.apache.dubbo.validation.filter; import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.rpc.Filter; @@ -55,7 +56,7 @@ * @see Filter * @see org.apache.dubbo.validation.support.AbstractValidation */ -@Activate(group = {Constants.CONSUMER, Constants.PROVIDER}, value = Constants.VALIDATION_KEY, order = 10000) +@Activate(group = {CommonConstants.CONSUMER, CommonConstants.PROVIDER}, value = Constants.VALIDATION_KEY, order = 10000) public class ValidationFilter implements Filter { private Validation validation; diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/identifier/MetadataIdentifier.java b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/identifier/MetadataIdentifier.java index 457b3b6092b..602e4b298b7 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/identifier/MetadataIdentifier.java +++ b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/identifier/MetadataIdentifier.java @@ -16,9 +16,15 @@ */ package org.apache.dubbo.metadata.identifier; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; +import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; + /** * 2018/10/25 */ @@ -47,15 +53,15 @@ public MetadataIdentifier(String serviceInterface, String version, String group, public MetadataIdentifier(URL url) { this.serviceInterface = url.getServiceInterface(); - this.version = url.getParameter(Constants.VERSION_KEY); - this.group = url.getParameter(Constants.GROUP_KEY); - this.side = url.getParameter(Constants.SIDE_KEY); - setApplication(url.getParameter(Constants.APPLICATION_KEY)); + this.version = url.getParameter(VERSION_KEY); + this.group = url.getParameter(GROUP_KEY); + this.side = url.getParameter(SIDE_KEY); + setApplication(url.getParameter(APPLICATION_KEY)); } public String getUniqueKey(KeyTypeEnum keyType) { if (keyType == KeyTypeEnum.PATH) { - return getFilePathKey() + Constants.PATH_SEPARATOR + DEFAULT_PATH_TAG; + return getFilePathKey() + PATH_SEPARATOR + DEFAULT_PATH_TAG; } return getIdentifierKey() + META_DATA_STORE_TAG; } @@ -69,12 +75,12 @@ private String getFilePathKey() { } private String getFilePathKey(String pathTag) { - return pathTag + Constants.PATH_SEPARATOR + toServicePath() + Constants.PATH_SEPARATOR + (version == null ? "" : (version + Constants.PATH_SEPARATOR)) - + (group == null ? "" : (group + Constants.PATH_SEPARATOR)) + side + Constants.PATH_SEPARATOR + getApplication(); + return pathTag + PATH_SEPARATOR + toServicePath() + PATH_SEPARATOR + (version == null ? "" : (version + PATH_SEPARATOR)) + + (group == null ? "" : (group + PATH_SEPARATOR)) + side + PATH_SEPARATOR + getApplication(); } private String toServicePath() { - if (Constants.ANY_VALUE.equals(serviceInterface)) { + if (ANY_VALUE.equals(serviceInterface)) { return ""; } return URL.encode(serviceInterface); diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/MetadataReportService.java b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/MetadataReportService.java index 832dac62fe8..9bcc541935a 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/MetadataReportService.java +++ b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/MetadataReportService.java @@ -33,6 +33,16 @@ import java.util.function.Supplier; +import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_DIRECTORY; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PID_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; +import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; + /** * @since 2.7.0 */ @@ -49,7 +59,7 @@ public class MetadataReportService { MetadataReportService(URL metadataReportURL) { if (Constants.METADATA_REPORT_KEY.equals(metadataReportURL.getProtocol())) { - String protocol = metadataReportURL.getParameter(Constants.METADATA_REPORT_KEY, Constants.DEFAULT_DIRECTORY); + String protocol = metadataReportURL.getParameter(Constants.METADATA_REPORT_KEY, DEFAULT_DIRECTORY); metadataReportURL = URLBuilder.from(metadataReportURL) .setProtocol(protocol) .removeParameter(Constants.METADATA_REPORT_KEY) @@ -79,16 +89,16 @@ public static MetadataReportService instance(Supplier metadataReportUrl) { public void publishProvider(URL providerUrl) throws RpcException { //first add into the list // remove the individul param - providerUrl = providerUrl.removeParameters(Constants.PID_KEY, Constants.TIMESTAMP_KEY, RemotingConstants.BIND_IP_KEY, RemotingConstants.BIND_PORT_KEY, Constants.TIMESTAMP_KEY); + providerUrl = providerUrl.removeParameters(PID_KEY, TIMESTAMP_KEY, RemotingConstants.BIND_IP_KEY, RemotingConstants.BIND_PORT_KEY, TIMESTAMP_KEY); try { - String interfaceName = providerUrl.getParameter(Constants.INTERFACE_KEY); + String interfaceName = providerUrl.getParameter(INTERFACE_KEY); if (StringUtils.isNotEmpty(interfaceName)) { Class interfaceClass = Class.forName(interfaceName); FullServiceDefinition fullServiceDefinition = ServiceDefinitionBuilder.buildFullDefinition(interfaceClass, providerUrl.getParameters()); metadataReport.storeProviderMetadata(new MetadataIdentifier(providerUrl.getServiceInterface(), - providerUrl.getParameter(Constants.VERSION_KEY), providerUrl.getParameter(Constants.GROUP_KEY), - Constants.PROVIDER_SIDE,providerUrl.getParameter(Constants.APPLICATION_KEY)), fullServiceDefinition); + providerUrl.getParameter(VERSION_KEY), providerUrl.getParameter(GROUP_KEY), + PROVIDER_SIDE, providerUrl.getParameter(APPLICATION_KEY)), fullServiceDefinition); return; } logger.error("publishProvider interfaceName is empty . providerUrl: " + providerUrl.toFullString()); @@ -99,10 +109,10 @@ public void publishProvider(URL providerUrl) throws RpcException { } public void publishConsumer(URL consumerURL) throws RpcException { - consumerURL = consumerURL.removeParameters(Constants.PID_KEY, Constants.TIMESTAMP_KEY, RemotingConstants.BIND_IP_KEY, RemotingConstants.BIND_PORT_KEY, Constants.TIMESTAMP_KEY); + consumerURL = consumerURL.removeParameters(PID_KEY, TIMESTAMP_KEY, RemotingConstants.BIND_IP_KEY, RemotingConstants.BIND_PORT_KEY, TIMESTAMP_KEY); metadataReport.storeConsumerMetadata(new MetadataIdentifier(consumerURL.getServiceInterface(), - consumerURL.getParameter(Constants.VERSION_KEY), consumerURL.getParameter(Constants.GROUP_KEY),Constants.CONSUMER_SIDE, - consumerURL.getParameter(Constants.APPLICATION_KEY)), consumerURL.getParameters()); + consumerURL.getParameter(VERSION_KEY), consumerURL.getParameter(GROUP_KEY), CONSUMER_SIDE, + consumerURL.getParameter(APPLICATION_KEY)), consumerURL.getParameters()); } } diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java index 49b4b8f7dcc..67f06e7bbd0 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java +++ b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java @@ -51,6 +51,12 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; +import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; +import static org.apache.dubbo.common.constants.CommonConstants.FILE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; +import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; + /** * */ @@ -80,7 +86,7 @@ public abstract class AbstractMetadataReport implements MetadataReport { public AbstractMetadataReport(URL reportServerURL) { setUrl(reportServerURL); // Start file save timer - String filename = reportServerURL.getParameter(Constants.FILE_KEY, System.getProperty("user.home") + "/.dubbo/dubbo-metadata-" + reportServerURL.getParameter(Constants.APPLICATION_KEY) + "-" + reportServerURL.getAddress() + ".cache"); + String filename = reportServerURL.getParameter(FILE_KEY, System.getProperty("user.home") + "/.dubbo/dubbo-metadata-" + reportServerURL.getParameter(APPLICATION_KEY) + "-" + reportServerURL.getAddress() + ".cache"); File file = null; if (ConfigUtils.isNotEmpty(filename)) { file = new File(filename); @@ -271,7 +277,7 @@ public void storeConsumerMetadataTask(MetadataIdentifier consumerMetadataIdentif String getProtocol(URL url) { - String protocol = url.getParameter(Constants.SIDE_KEY); + String protocol = url.getParameter(SIDE_KEY); protocol = protocol == null ? url.getProtocol() : protocol; return protocol; } @@ -290,9 +296,9 @@ private boolean doHandleMetadataCollection(Map metad Iterator> iterable = metadataMap.entrySet().iterator(); while (iterable.hasNext()) { Map.Entry item = iterable.next(); - if (Constants.PROVIDER_SIDE.equals(item.getKey().getSide())) { + if (PROVIDER_SIDE.equals(item.getKey().getSide())) { this.storeProviderMetadata(item.getKey(), (FullServiceDefinition) item.getValue()); - } else if (Constants.CONSUMER_SIDE.equals(item.getKey().getSide())) { + } else if (CONSUMER_SIDE.equals(item.getKey().getSide())) { this.storeConsumerMetadata(item.getKey(), (Map) item.getValue()); } diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/identifier/MetadataIdentifierTest.java b/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/identifier/MetadataIdentifierTest.java index ca415b46457..cdb089b83eb 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/identifier/MetadataIdentifierTest.java +++ b/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/identifier/MetadataIdentifierTest.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.metadata.identifier; -import org.apache.dubbo.common.Constants; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.metadata.identifier.MetadataIdentifier.META_DATA_STORE_TAG; /** @@ -34,18 +34,18 @@ public void testGetUniqueKey() { String version = "1.0.0.zk.md"; String group = null; String application = "vic.zk.md"; - MetadataIdentifier providerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, Constants.PROVIDER_SIDE, application); + MetadataIdentifier providerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE, application); System.out.println(providerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.PATH)); Assertions.assertEquals(providerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.PATH), - "metadata" + Constants.PATH_SEPARATOR + interfaceName + Constants.PATH_SEPARATOR + - (version == null ? "" : (version + Constants.PATH_SEPARATOR)) - + (group == null ? "" : (group + Constants.PATH_SEPARATOR)) + Constants.PROVIDER_SIDE - + Constants.PATH_SEPARATOR + application + Constants.PATH_SEPARATOR + "metadata"); + "metadata" + PATH_SEPARATOR + interfaceName + PATH_SEPARATOR + + (version == null ? "" : (version + PATH_SEPARATOR)) + + (group == null ? "" : (group + PATH_SEPARATOR)) + PROVIDER_SIDE + + PATH_SEPARATOR + application + PATH_SEPARATOR + "metadata"); System.out.println(providerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY)); Assertions.assertEquals(providerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY), interfaceName + MetadataIdentifier.SEPARATOR + (version == null ? "" : version + MetadataIdentifier.SEPARATOR) + (group == null ? "" : group + MetadataIdentifier.SEPARATOR) - + Constants.PROVIDER_SIDE + MetadataIdentifier.SEPARATOR + application + META_DATA_STORE_TAG); + + PROVIDER_SIDE + MetadataIdentifier.SEPARATOR + application + META_DATA_STORE_TAG); } } diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store/test/JTestMetadataReport4Test.java b/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store/test/JTestMetadataReport4Test.java index f5c129692e1..e01a71ab5f4 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store/test/JTestMetadataReport4Test.java +++ b/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store/test/JTestMetadataReport4Test.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.store.test; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -26,6 +25,8 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; + /** * ZookeeperRegistry */ @@ -42,7 +43,7 @@ public JTestMetadataReport4Test(URL url) { private static String getProtocol(URL url) { - String protocol = url.getParameter(Constants.SIDE_KEY); + String protocol = url.getParameter(SIDE_KEY); protocol = protocol == null ? url.getProtocol() : protocol; return protocol; } diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportTest.java b/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportTest.java index 9544c18db93..d74c7905437 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportTest.java +++ b/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder; @@ -34,6 +33,9 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; + /** * */ @@ -155,7 +157,7 @@ private MetadataIdentifier storePrivider(AbstractMetadataReport abstractMetadata URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + "?version=" + version + "&application=" + application + (group == null ? "" : "&group=" + group) + "&testPKey=8989"); - MetadataIdentifier providerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, Constants.PROVIDER_SIDE,application); + MetadataIdentifier providerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE,application); Class interfaceClass = Class.forName(interfaceName); FullServiceDefinition fullServiceDefinition = ServiceDefinitionBuilder.buildFullDefinition(interfaceClass, url.getParameters()); @@ -169,7 +171,7 @@ private MetadataIdentifier storeConsumer(AbstractMetadataReport abstractMetadata + application + (group == null ? "" : "&group=" + group) + "&testPKey=9090"); tmp.putAll(url.getParameters()); - MetadataIdentifier consumerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, Constants.CONSUMER_SIDE, application); + MetadataIdentifier consumerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, CONSUMER_SIDE, application); abstractMetadataReport.storeConsumerMetadata(consumerMetadataIdentifier, tmp); diff --git a/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReport.java b/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReport.java index 0a472f55a78..5ee950611a2 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReport.java +++ b/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReport.java @@ -33,7 +33,6 @@ */ package org.apache.dubbo.metadata.store.etcd; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -41,6 +40,9 @@ import org.apache.dubbo.metadata.support.AbstractMetadataReport; import org.apache.dubbo.remoting.etcd.jetcd.JEtcdClient; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; + /** * Report Metadata to Etcd */ @@ -60,9 +62,9 @@ public EtcdMetadataReport(URL url) { if (url.isAnyHost()) { throw new IllegalStateException("registry address == null"); } - String group = url.getParameter(Constants.GROUP_KEY, DEFAULT_ROOT); - if (!group.startsWith(Constants.PATH_SEPARATOR)) { - group = Constants.PATH_SEPARATOR + group; + String group = url.getParameter(GROUP_KEY, DEFAULT_ROOT); + if (!group.startsWith(PATH_SEPARATOR)) { + group = PATH_SEPARATOR + group; } this.root = group; etcdClient = new JEtcdClient(url); @@ -90,9 +92,9 @@ String getNodeKey(MetadataIdentifier identifier) { } String toRootDir() { - if (root.equals(Constants.PATH_SEPARATOR)) { + if (root.equals(PATH_SEPARATOR)) { return root; } - return root + Constants.PATH_SEPARATOR; + return root + PATH_SEPARATOR; } } diff --git a/dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java b/dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java index e6f6b02c522..770b058e070 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java +++ b/dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java @@ -17,18 +17,18 @@ package org.apache.dubbo.metadata.store.etcd; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.utils.NetUtils; +import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder; +import org.apache.dubbo.metadata.definition.model.FullServiceDefinition; +import org.apache.dubbo.metadata.identifier.MetadataIdentifier; + import com.google.gson.Gson; import io.etcd.jetcd.ByteSequence; import io.etcd.jetcd.Client; import io.etcd.jetcd.kv.GetResponse; import io.etcd.jetcd.launcher.EtcdCluster; import io.etcd.jetcd.launcher.EtcdClusterFactory; -import org.apache.dubbo.common.Constants; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder; -import org.apache.dubbo.metadata.definition.model.FullServiceDefinition; -import org.apache.dubbo.metadata.identifier.MetadataIdentifier; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -41,6 +41,9 @@ import java.util.Map; import java.util.concurrent.CompletableFuture; +import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; + /** * Unit test for etcd metadata report */ @@ -109,7 +112,7 @@ private MetadataIdentifier storeProvider(EtcdMetadataReport etcdMetadataReport, + application + (group == null ? "" : "&group=" + group)); MetadataIdentifier providerMetadataIdentifier = - new MetadataIdentifier(interfaceName, version, group, Constants.PROVIDER_SIDE, application); + new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE, application); Class interfaceClass = Class.forName(interfaceName); FullServiceDefinition fullServiceDefinition = ServiceDefinitionBuilder.buildFullDefinition(interfaceClass, url.getParameters()); @@ -122,7 +125,7 @@ private MetadataIdentifier storeProvider(EtcdMetadataReport etcdMetadataReport, private MetadataIdentifier storeConsumer(EtcdMetadataReport etcdMetadataReport, String interfaceName, String version, String group, String application) throws InterruptedException { - MetadataIdentifier consumerIdentifier = new MetadataIdentifier(interfaceName, version, group, Constants.CONSUMER_SIDE, application); + MetadataIdentifier consumerIdentifier = new MetadataIdentifier(interfaceName, version, group, CONSUMER_SIDE, application); Map tmp = new HashMap<>(); tmp.put("paramConsumerTest", "etcdConsumer"); etcdMetadataReport.storeConsumerMetadata(consumerIdentifier, tmp); diff --git a/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java b/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java index b00295c3bdf..c0b992da466 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java +++ b/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.store.redis; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -27,6 +26,9 @@ import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + /** * RedisMetadataReport */ @@ -38,7 +40,7 @@ public class RedisMetadataReport extends AbstractMetadataReport { public RedisMetadataReport(URL url) { super(url); - int timeout = url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); + int timeout = url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT); pool = new JedisPool(new JedisPoolConfig(), url.getHost(), url.getPort(), timeout, url.getPassword()); } diff --git a/dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java b/dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java index 5a6d4f5fcf1..5ec061130d0 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java +++ b/dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java @@ -16,14 +16,14 @@ */ package org.apache.dubbo.metadata.store.redis; -import com.google.gson.Gson; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder; import org.apache.dubbo.metadata.definition.model.FullServiceDefinition; import org.apache.dubbo.metadata.identifier.MetadataIdentifier; import org.apache.dubbo.rpc.RpcException; + +import com.google.gson.Gson; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -39,6 +39,8 @@ import java.util.Map; import static org.apache.dubbo.common.Constants.SYNC_REPORT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; /** * 2018/10/9 @@ -153,7 +155,7 @@ private MetadataIdentifier storePrivider(RedisMetadataReport redisMetadataReport URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + "?paramTest=redisTest&version=" + version + "&application=" + application + (group == null ? "" : "&group=" + group)); - MetadataIdentifier providerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, Constants.PROVIDER_SIDE, application); + MetadataIdentifier providerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE, application); Class interfaceClass = Class.forName(interfaceName); FullServiceDefinition fullServiceDefinition = ServiceDefinitionBuilder.buildFullDefinition(interfaceClass, url.getParameters()); @@ -170,7 +172,7 @@ private MetadataIdentifier storeConsumer(RedisMetadataReport redisMetadataReport URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + "?version=" + version + "&application=" + application + (group == null ? "" : "&group=" + group)); - MetadataIdentifier consumerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, Constants.CONSUMER_SIDE, application); + MetadataIdentifier consumerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, CONSUMER_SIDE, application); Class interfaceClass = Class.forName(interfaceName); Map tmp = new HashMap<>(); diff --git a/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java b/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java index de26faf7c2a..66353f6817d 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java +++ b/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.store.zookeeper; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -25,6 +24,9 @@ import org.apache.dubbo.remoting.zookeeper.ZookeeperClient; import org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; + /** * ZookeeperMetadataReport */ @@ -41,19 +43,19 @@ public ZookeeperMetadataReport(URL url, ZookeeperTransporter zookeeperTransporte if (url.isAnyHost()) { throw new IllegalStateException("registry address == null"); } - String group = url.getParameter(Constants.GROUP_KEY, DEFAULT_ROOT); - if (!group.startsWith(Constants.PATH_SEPARATOR)) { - group = Constants.PATH_SEPARATOR + group; + String group = url.getParameter(GROUP_KEY, DEFAULT_ROOT); + if (!group.startsWith(PATH_SEPARATOR)) { + group = PATH_SEPARATOR + group; } this.root = group; zkClient = zookeeperTransporter.connect(url); } String toRootDir() { - if (root.equals(Constants.PATH_SEPARATOR)) { + if (root.equals(PATH_SEPARATOR)) { return root; } - return root + Constants.PATH_SEPARATOR; + return root + PATH_SEPARATOR; } @Override diff --git a/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportTest.java b/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportTest.java index da1e87b8945..799a1bb04f4 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportTest.java +++ b/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.store.zookeeper; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder; @@ -34,6 +33,9 @@ import java.util.HashMap; import java.util.Map; +import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; + /** * 2018/10/9 */ @@ -122,7 +124,7 @@ private MetadataIdentifier storePrivider(ZookeeperMetadataReport zookeeperMetada URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + "?paramTest=zkTest&version=" + version + "&application=" + application + (group == null ? "" : "&group=" + group)); - MetadataIdentifier providerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, Constants.PROVIDER_SIDE, application); + MetadataIdentifier providerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE, application); Class interfaceClass = Class.forName(interfaceName); FullServiceDefinition fullServiceDefinition = ServiceDefinitionBuilder.buildFullDefinition(interfaceClass, url.getParameters()); @@ -135,7 +137,7 @@ private MetadataIdentifier storeConsumer(ZookeeperMetadataReport zookeeperMetada URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + "?version=" + version + "&application=" + application + (group == null ? "" : "&group=" + group)); - MetadataIdentifier consumerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, Constants.CONSUMER_SIDE, application); + MetadataIdentifier consumerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, CONSUMER_SIDE, application); Class interfaceClass = Class.forName(interfaceName); Map tmp = new HashMap<>(); diff --git a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/AbstractMonitorFactory.java b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/AbstractMonitorFactory.java index 9708e905a49..7b921e6fdf9 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/AbstractMonitorFactory.java +++ b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/AbstractMonitorFactory.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.monitor.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -38,6 +37,8 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; + /** * AbstractMonitorFactory. (SPI, Singleton, ThreadSafe) */ @@ -67,7 +68,7 @@ public static Collection getMonitors() { @Override public Monitor getMonitor(URL url) { - url = url.setPath(MonitorService.class.getName()).addParameter(Constants.INTERFACE_KEY, MonitorService.class.getName()); + url = url.setPath(MonitorService.class.getName()).addParameter(INTERFACE_KEY, MonitorService.class.getName()); String key = url.toServiceStringWithoutResolving(); Monitor monitor = MONITORS.get(key); Future future = FUTURES.get(key); diff --git a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java index 10eb31e42fc..3269b37bb1f 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java +++ b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java @@ -37,10 +37,19 @@ import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; +import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; +import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; +import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; + /** * MonitorFilter. (SPI, Singleton, ThreadSafe) */ -@Activate(group = {Constants.PROVIDER, Constants.CONSUMER}) +@Activate(group = {PROVIDER, CONSUMER}) public class MonitorFilter implements Filter { private static final Logger logger = LoggerFactory.getLogger(MonitorFilter.class); @@ -128,15 +137,15 @@ private URL createStatisticsUrl(Invoker invoker, Invocation invocation, Resul // ---- service statistics ---- long elapsed = System.currentTimeMillis() - start; // invocation cost int concurrent = getConcurrent(invoker, invocation).get(); // current concurrent count - String application = invoker.getUrl().getParameter(Constants.APPLICATION_KEY); + String application = invoker.getUrl().getParameter(APPLICATION_KEY); String service = invoker.getInterface().getName(); // service name String method = RpcUtils.getMethodName(invocation); // method name - String group = invoker.getUrl().getParameter(Constants.GROUP_KEY); - String version = invoker.getUrl().getParameter(Constants.VERSION_KEY); + String group = invoker.getUrl().getParameter(GROUP_KEY); + String version = invoker.getUrl().getParameter(VERSION_KEY); int localPort; String remoteKey, remoteValue; - if (Constants.CONSUMER_SIDE.equals(invoker.getUrl().getParameter(Constants.SIDE_KEY))) { + if (CONSUMER_SIDE.equals(invoker.getUrl().getParameter(SIDE_KEY))) { // ---- for service consumer ---- localPort = 0; remoteKey = MonitorService.PROVIDER; @@ -157,7 +166,7 @@ private URL createStatisticsUrl(Invoker invoker, Invocation invocation, Resul return new URL(Constants.COUNT_PROTOCOL, NetUtils.getLocalHost(), localPort, - service + Constants.PATH_SEPARATOR + method, + service + PATH_SEPARATOR + method, MonitorService.APPLICATION, application, MonitorService.INTERFACE, service, MonitorService.METHOD, method, @@ -167,8 +176,8 @@ private URL createStatisticsUrl(Invoker invoker, Invocation invocation, Resul MonitorService.CONCURRENT, String.valueOf(concurrent), Constants.INPUT_KEY, input, Constants.OUTPUT_KEY, output, - Constants.GROUP_KEY, group, - Constants.VERSION_KEY, version); + GROUP_KEY, group, + VERSION_KEY, version); } // concurrent counter diff --git a/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java b/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java index 01ba57dd7b8..171d087bcec 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java +++ b/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java @@ -28,6 +28,7 @@ import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -37,6 +38,9 @@ import java.util.Arrays; import java.util.List; +import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; +import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -60,7 +64,7 @@ public Class getInterface() { public URL getUrl() { try { - return URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880?" + Constants.APPLICATION_KEY + "=abc&" + Constants.SIDE_KEY + "=" + Constants.CONSUMER_SIDE + "&" + Constants.MONITOR_KEY + "=" + URLEncoder.encode("dubbo://" + NetUtils.getLocalHost() + ":7070", "UTF-8")); + return URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880?" + APPLICATION_KEY + "=abc&" + SIDE_KEY + "=" + CONSUMER_SIDE + "&" + Constants.MONITOR_KEY + "=" + URLEncoder.encode("dubbo://" + NetUtils.getLocalHost() + ":7070", "UTF-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e.getMessage(), e); } @@ -138,7 +142,7 @@ public void testSkipMonitorIfNotHasKey() { monitorFilter.setMonitorFactory(mockMonitorFactory); Invocation invocation = new RpcInvocation("aaa", new Class[0], new Object[0]); Invoker invoker = mock(Invoker.class); - given(invoker.getUrl()).willReturn(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880?" + Constants.APPLICATION_KEY + "=abc&" + Constants.SIDE_KEY + "=" + Constants.CONSUMER_SIDE)); + given(invoker.getUrl()).willReturn(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880?" + APPLICATION_KEY + "=abc&" + SIDE_KEY + "=" + CONSUMER_SIDE)); monitorFilter.invoke(invoker, invocation); diff --git a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitor.java b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitor.java index f7f0d87d8e1..d36ae4cefdd 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitor.java +++ b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitor.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.monitor.dubbo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -36,6 +35,8 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_PROTOCOL; + /** * DubboMonitor */ @@ -102,7 +103,7 @@ public void send() { long maxOutput = numbers[7]; long maxElapsed = numbers[8]; long maxConcurrent = numbers[9]; - String protocol = getUrl().getParameter(Constants.DEFAULT_PROTOCOL); + String protocol = getUrl().getParameter(DEFAULT_PROTOCOL); // send statistics data URL url = statistics.getUrl() @@ -117,7 +118,7 @@ public void send() { MonitorService.MAX_OUTPUT, String.valueOf(maxOutput), MonitorService.MAX_ELAPSED, String.valueOf(maxElapsed), MonitorService.MAX_CONCURRENT, String.valueOf(maxConcurrent), - Constants.DEFAULT_PROTOCOL, protocol + DEFAULT_PROTOCOL, protocol ); monitorService.collect(url); diff --git a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java index 5d73112bfd4..1802fe3fe9e 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java +++ b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java @@ -28,8 +28,8 @@ import static org.apache.dubbo.common.constants.RemotingConstants.CHECK_KEY; import static org.apache.dubbo.common.Constants.DUBBO_PROTOCOL; -import static org.apache.dubbo.common.Constants.PROTOCOL_KEY; import static org.apache.dubbo.common.Constants.REFERENCE_FILTER_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; /** * DefaultMonitorFactory diff --git a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java index 52bec170f4e..78d87e183c7 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java +++ b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java @@ -16,16 +16,6 @@ */ package org.apache.dubbo.monitor.dubbo; -import com.alibaba.fastjson.JSON; -import com.alibaba.metrics.FastCompass; -import com.alibaba.metrics.MetricLevel; -import com.alibaba.metrics.MetricManager; -import com.alibaba.metrics.MetricName; -import com.alibaba.metrics.MetricRegistry; -import com.alibaba.metrics.common.CollectLevel; -import com.alibaba.metrics.common.MetricObject; -import com.alibaba.metrics.common.MetricsCollector; -import com.alibaba.metrics.common.MetricsCollectorFactory; import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; @@ -44,17 +34,31 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.support.RpcUtils; -import java.util.Collections; -import java.util.SortedMap; + +import com.alibaba.fastjson.JSON; +import com.alibaba.metrics.FastCompass; +import com.alibaba.metrics.MetricLevel; +import com.alibaba.metrics.MetricManager; +import com.alibaba.metrics.MetricName; +import com.alibaba.metrics.MetricRegistry; +import com.alibaba.metrics.common.CollectLevel; +import com.alibaba.metrics.common.MetricObject; +import com.alibaba.metrics.common.MetricsCollector; +import com.alibaba.metrics.common.MetricsCollectorFactory; + import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.SortedMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_PROTOCOL; + public class MetricsFilter implements Filter { private static final Logger logger = LoggerFactory.getLogger(MetricsFilter.class); @@ -66,7 +70,7 @@ public class MetricsFilter implements Filter { public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { if (exported.compareAndSet(false, true)) { this.protocolName = invoker.getUrl().getParameter(Constants.METRICS_PROTOCOL) == null ? - Constants.DEFAULT_PROTOCOL : invoker.getUrl().getParameter(Constants.METRICS_PROTOCOL); + DEFAULT_PROTOCOL : invoker.getUrl().getParameter(Constants.METRICS_PROTOCOL); Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(protocolName); diff --git a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/MetricsFilterTest.java b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/MetricsFilterTest.java index bca62f4aab8..23bb1341cdd 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/MetricsFilterTest.java +++ b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/MetricsFilterTest.java @@ -16,14 +16,6 @@ */ package org.apache.dubbo.monitor.dubbo; -import com.alibaba.metrics.FastCompass; -import com.alibaba.metrics.IMetricManager; -import com.alibaba.metrics.MetricLevel; -import com.alibaba.metrics.MetricManager; -import com.alibaba.metrics.MetricName; -import com.alibaba.metrics.common.MetricObject; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; @@ -37,6 +29,15 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; + +import com.alibaba.metrics.FastCompass; +import com.alibaba.metrics.IMetricManager; +import com.alibaba.metrics.MetricLevel; +import com.alibaba.metrics.MetricManager; +import com.alibaba.metrics.MetricName; +import com.alibaba.metrics.common.MetricObject; +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -44,6 +45,12 @@ import java.util.List; import java.util.Map; +import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; +import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + public class MetricsFilterTest { private final Invoker serviceInvoker = new Invoker() { @@ -99,9 +106,9 @@ public void testConsumerSuccess() throws Exception { IMetricManager metricManager = MetricManager.getIMetricManager(); metricManager.clear(); MetricsFilter metricsFilter = new MetricsFilter(); - Invocation invocation = new RpcInvocation("sayName", new Class[] {Integer.class}, new Object[0]); + Invocation invocation = new RpcInvocation("sayName", new Class[]{Integer.class}, new Object[0]); RpcContext.getContext().setRemoteAddress(NetUtils.getLocalHost(), 20880).setLocalAddress(NetUtils.getLocalHost(), 2345); - RpcContext.getContext().setUrl(serviceInvoker.getUrl().addParameter(Constants.SIDE_KEY, Constants.CONSUMER_SIDE)); + RpcContext.getContext().setUrl(serviceInvoker.getUrl().addParameter(SIDE_KEY, CONSUMER_SIDE)); for (int i = 0; i < 100; i++) { metricsFilter.invoke(serviceInvoker, invocation); } @@ -126,8 +133,8 @@ public void testConsumerTimeout() { MetricsFilter metricsFilter = new MetricsFilter(); Invocation invocation = new RpcInvocation("timeoutException", null, null); RpcContext.getContext().setRemoteAddress(NetUtils.getLocalHost(), 20880).setLocalAddress(NetUtils.getLocalHost(), 2345); - RpcContext.getContext().setUrl(timeoutInvoker.getUrl().addParameter(Constants.SIDE_KEY, Constants.CONSUMER_SIDE) - .addParameter(Constants.TIMEOUT_KEY, 300)); + RpcContext.getContext().setUrl(timeoutInvoker.getUrl().addParameter(SIDE_KEY, CONSUMER_SIDE) + .addParameter(TIMEOUT_KEY, 300)); for (int i = 0; i < 10; i++) { try { metricsFilter.invoke(timeoutInvoker, invocation); @@ -156,7 +163,7 @@ public void testProviderSuccess() throws Exception { MetricsFilter metricsFilter = new MetricsFilter(); Invocation invocation = new RpcInvocation("sayName", new Class[0], new Object[0]); RpcContext.getContext().setRemoteAddress(NetUtils.getLocalHost(), 20880).setLocalAddress(NetUtils.getLocalHost(), 2345); - RpcContext.getContext().setUrl(serviceInvoker.getUrl().addParameter(Constants.SIDE_KEY, Constants.PROVIDER)); + RpcContext.getContext().setUrl(serviceInvoker.getUrl().addParameter(SIDE_KEY, PROVIDER)); for (int i = 0; i < 100; i++) { metricsFilter.invoke(serviceInvoker, invocation); } @@ -180,8 +187,8 @@ public void testInvokeMetricsService() { MetricsFilter metricsFilter = new MetricsFilter(); Invocation invocation = new RpcInvocation("sayName", new Class[0], new Object[0]); RpcContext.getContext().setRemoteAddress(NetUtils.getLocalHost(), 20880).setLocalAddress(NetUtils.getLocalHost(), 2345); - RpcContext.getContext().setUrl(serviceInvoker.getUrl().addParameter(Constants.SIDE_KEY, Constants.PROVIDER_SIDE) - .addParameter(Constants.TIMEOUT_KEY, 300)); + RpcContext.getContext().setUrl(serviceInvoker.getUrl().addParameter(SIDE_KEY, PROVIDER_SIDE) + .addParameter(TIMEOUT_KEY, 300)); for (int i = 0; i < 50; i++) { try { metricsFilter.invoke(serviceInvoker, invocation); @@ -194,18 +201,19 @@ public void testInvokeMetricsService() { URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":20880/" + MetricsService.class.getName()); Invoker invoker = protocol.refer(MetricsService.class, url); invocation = new RpcInvocation("getMetricsByGroup", new Class[]{String.class}, new Object[]{Constants.DUBBO_GROUP}); - try{ + try { Thread.sleep(5000); } catch (Exception e) { // ignore } String resStr = invoker.invoke(invocation).getValue().toString(); - List metricObjectList = new Gson().fromJson(resStr, new TypeToken>(){}.getType()); + List metricObjectList = new Gson().fromJson(resStr, new TypeToken>() { + }.getType()); Map metricMap = new HashMap<>(); - for(int i = 0; i < metricObjectList.size(); i++) { + for (int i = 0; i < metricObjectList.size(); i++) { MetricObject object = metricObjectList.get(i); String metric = object.getMetric().substring(object.getMetric().lastIndexOf(".") + 1); - if((double)object.getValue() > 0.0 && object.getMetricLevel().equals(MetricLevel.MAJOR)) + if ((double) object.getValue() > 0.0 && object.getMetricLevel().equals(MetricLevel.MAJOR)) metricMap.put(metric, object.getValue()); } @@ -224,11 +232,11 @@ public void testInvokeMetricsMethodService() { Invocation sayNameInvocation = new RpcInvocation("sayName", new Class[0], new Object[0]); Invocation echoInvocation = new RpcInvocation("echo", new Class[]{Integer.class}, new Integer[]{1}); RpcContext.getContext().setRemoteAddress(NetUtils.getLocalHost(), 20880).setLocalAddress(NetUtils.getLocalHost(), 2345); - RpcContext.getContext().setUrl(serviceInvoker.getUrl().addParameter(Constants.SIDE_KEY, Constants.PROVIDER_SIDE) - .addParameter(Constants.TIMEOUT_KEY, 300)); + RpcContext.getContext().setUrl(serviceInvoker.getUrl().addParameter(SIDE_KEY, PROVIDER_SIDE) + .addParameter(TIMEOUT_KEY, 300)); for (int i = 0; i < 50; i++) { - metricsFilter.invoke(serviceInvoker, sayNameInvocation); - metricsFilter.invoke(serviceInvoker, echoInvocation); + metricsFilter.invoke(serviceInvoker, sayNameInvocation); + metricsFilter.invoke(serviceInvoker, echoInvocation); try { metricsFilter.invoke(timeoutInvoker, sayNameInvocation); } catch (RpcException e) { @@ -245,21 +253,22 @@ public void testInvokeMetricsMethodService() { URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":20880/" + MetricsService.class.getName()); Invoker invoker = protocol.refer(MetricsService.class, url); Invocation invocation = new RpcInvocation("getMetricsByGroup", new Class[]{String.class}, new Object[]{Constants.DUBBO_GROUP}); - try{ + try { Thread.sleep(15000); } catch (Exception e) { // ignore } String resStr = invoker.invoke(invocation).getValue().toString(); - List metricObjectList = new Gson().fromJson(resStr, new TypeToken>(){}.getType()); + List metricObjectList = new Gson().fromJson(resStr, new TypeToken>() { + }.getType()); Map> methodMetricMap = new HashMap<>(); - for(int i = 0; i < metricObjectList.size(); i++) { + for (int i = 0; i < metricObjectList.size(); i++) { MetricObject object = metricObjectList.get(i); String service = object.getTags().get("service"); String method = service + "." + object.getTags().get("method"); String metric = object.getMetric().substring(object.getMetric().lastIndexOf(".") + 1); Map map = methodMetricMap.get(method); - if(map == null) { + if (map == null) { map = new HashMap(); methodMetricMap.put(method, map); } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java index 3aea7e6177e..46beabd0e89 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.registry.integration; -import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; @@ -42,7 +42,7 @@ public abstract class AbstractConfiguratorListener implements ConfigurationListe protected final void initWith(String key) { DynamicConfiguration dynamicConfiguration = DynamicConfiguration.getDynamicConfiguration(); dynamicConfiguration.addListener(key, this); - String rawConfig = dynamicConfiguration.getConfig(key, Constants.DUBBO); + String rawConfig = dynamicConfiguration.getConfig(key, CommonConstants.DUBBO); if (!StringUtils.isEmpty(rawConfig)) { process(new ConfigChangeEvent(key, rawConfig)); } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java index 9538742ede1..a28383fade7 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java @@ -67,6 +67,13 @@ import static org.apache.dubbo.common.Constants.PROVIDERS_CATEGORY; import static org.apache.dubbo.common.Constants.ROUTERS_CATEGORY; import static org.apache.dubbo.common.Constants.ROUTE_PROTOCOL; +import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.DISABLED_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; /** @@ -125,15 +132,15 @@ public RegistryDirectory(Class serviceType, URL url) { this.serviceKey = url.getServiceKey(); this.queryMap = StringUtils.parseQueryString(url.getParameterAndDecoded(Constants.REFER_KEY)); this.overrideDirectoryUrl = this.directoryUrl = turnRegistryUrlToConsumerUrl(url); - String group = directoryUrl.getParameter(Constants.GROUP_KEY, ""); - this.multiGroup = group != null && (Constants.ANY_VALUE.equals(group) || group.contains(",")); + String group = directoryUrl.getParameter(GROUP_KEY, ""); + this.multiGroup = group != null && (ANY_VALUE.equals(group) || group.contains(",")); } private URL turnRegistryUrlToConsumerUrl(URL url) { // save any parameter in registry that will be useful to the new url. - String isDefault = url.getParameter(Constants.DEFAULT_KEY); + String isDefault = url.getParameter(DEFAULT_KEY); if (StringUtils.isNotEmpty(isDefault)) { - queryMap.put(Constants.REGISTRY_KEY + "." + Constants.DEFAULT_KEY, isDefault); + queryMap.put(Constants.REGISTRY_KEY + "." + DEFAULT_KEY, isDefault); } return URLBuilder.from(url) .setPath(url.getServiceInterface()) @@ -298,7 +305,7 @@ private List> toMergeInvokerList(List> invokers) { List> mergedInvokers = new ArrayList<>(); Map>> groupMap = new HashMap<>(); for (Invoker invoker : invokers) { - String group = invoker.getUrl().getParameter(Constants.GROUP_KEY, ""); + String group = invoker.getUrl().getParameter(GROUP_KEY, ""); groupMap.computeIfAbsent(group, k -> new ArrayList<>()); groupMap.get(group).add(invoker); } @@ -361,7 +368,7 @@ private Map> toInvokers(List urls) { return newUrlInvokerMap; } Set keys = new HashSet<>(); - String queryProtocols = this.queryMap.get(Constants.PROTOCOL_KEY); + String queryProtocols = this.queryMap.get(PROTOCOL_KEY); for (URL providerUrl : urls) { // If protocol is configured at the reference side, only the matching protocol is selected if (queryProtocols != null && queryProtocols.length() > 0) { @@ -400,10 +407,10 @@ private Map> toInvokers(List urls) { if (invoker == null) { // Not in the cache, refer again try { boolean enabled = true; - if (url.hasParameter(Constants.DISABLED_KEY)) { - enabled = !url.getParameter(Constants.DISABLED_KEY, false); + if (url.hasParameter(DISABLED_KEY)) { + enabled = !url.getParameter(DISABLED_KEY, false); } else { - enabled = url.getParameter(Constants.ENABLED_KEY, true); + enabled = url.getParameter(ENABLED_KEY, true); } if (enabled) { invoker = new InvokerDelegate<>(protocol.refer(serviceType, url), url, providerUrl); @@ -441,7 +448,7 @@ private URL mergeUrl(URL providerUrl) { if ((providerUrl.getPath() == null || providerUrl.getPath() .length() == 0) && Constants.DUBBO_PROTOCOL.equals(providerUrl.getProtocol())) { // Compatible version 1.0 //fix by tony.chenl DUBBO-44 - String path = directoryUrl.getParameter(Constants.INTERFACE_KEY); + String path = directoryUrl.getParameter(INTERFACE_KEY); if (path != null) { int i = path.indexOf('/'); if (i >= 0) { diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java index c70be0b92ce..fcd0de288bf 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.registry.integration; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.config.ConfigurationUtils; @@ -54,24 +53,18 @@ import static java.util.concurrent.Executors.newSingleThreadExecutor; import static org.apache.dubbo.common.Constants.ACCEPT_FOREIGN_IP; -import static org.apache.dubbo.common.Constants.ANY_VALUE; import static org.apache.dubbo.common.constants.RemotingConstants.BIND_IP_KEY; import static org.apache.dubbo.common.constants.RemotingConstants.BIND_PORT_KEY; import static org.apache.dubbo.common.Constants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.RemotingConstants.CHECK_KEY; -import static org.apache.dubbo.common.Constants.COMMA_SPLIT_PATTERN; import static org.apache.dubbo.common.Constants.CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.Constants.CONFIGURATORS_SUFFIX; import static org.apache.dubbo.common.Constants.CONSUMERS_CATEGORY; import static org.apache.dubbo.common.Constants.CONSUMER_PROTOCOL; -import static org.apache.dubbo.common.Constants.DEFAULT_REGISTER_CONSUMER_KEYS; -import static org.apache.dubbo.common.Constants.DEFAULT_REGISTER_PROVIDER_KEYS; import static org.apache.dubbo.common.Constants.DEFAULT_REGISTRY; import static org.apache.dubbo.common.Constants.EXPORT_KEY; import static org.apache.dubbo.common.Constants.EXTRA_KEYS_KEY; -import static org.apache.dubbo.common.Constants.HIDE_KEY_PREFIX; import static org.apache.dubbo.common.Constants.INTERFACES; -import static org.apache.dubbo.common.Constants.METHODS_KEY; import static org.apache.dubbo.common.Constants.MONITOR_KEY; import static org.apache.dubbo.common.Constants.OVERRIDE_PROTOCOL; import static org.apache.dubbo.common.Constants.PROVIDERS_CATEGORY; @@ -86,12 +79,45 @@ import static org.apache.dubbo.common.Constants.ROUTERS_CATEGORY; import static org.apache.dubbo.common.Constants.SIMPLIFIED_KEY; import static org.apache.dubbo.common.Constants.VALIDATION_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.LOADBALANCE_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.WARMUP_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.WEIGHT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.HIDE_KEY_PREFIX; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.CLUSTER_KEY; +import static org.apache.dubbo.common.constants.RemotingConstants.CODEC_KEY; +import static org.apache.dubbo.common.constants.RemotingConstants.EXCHANGER_KEY; +import static org.apache.dubbo.common.constants.RemotingConstants.SERIALIZATION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.CONNECTIONS_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.DEPRECATED_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.MOCK_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; import static org.apache.dubbo.common.utils.UrlUtils.classifyUrls; /** * RegistryProtocol */ public class RegistryProtocol implements Protocol { + public static final String[] DEFAULT_REGISTER_PROVIDER_KEYS = { + APPLICATION_KEY, CODEC_KEY, EXCHANGER_KEY, SERIALIZATION_KEY, CLUSTER_KEY, CONNECTIONS_KEY, DEPRECATED_KEY, + GROUP_KEY, LOADBALANCE_KEY, MOCK_KEY, PATH_KEY, TIMEOUT_KEY, TOKEN_KEY, VERSION_KEY, WARMUP_KEY, + WEIGHT_KEY, TIMESTAMP_KEY, DUBBO_VERSION_KEY, RELEASE_KEY + }; + + public static final String[] DEFAULT_REGISTER_CONSUMER_KEYS = { + APPLICATION_KEY, VERSION_KEY, GROUP_KEY, DUBBO_VERSION_KEY, RELEASE_KEY + }; private final static Logger logger = LoggerFactory.getLogger(RegistryProtocol.class); private static RegistryProtocol INSTANCE; @@ -299,14 +325,14 @@ private URL getRegisteredProviderUrl(final URL providerUrl, final URL registryUr // if path is not the same as interface name then we should keep INTERFACE_KEY, // otherwise, the registry structure of zookeeper would be '/dubbo/path/providers', // but what we expect is '/dubbo/interface/providers' - if (!providerUrl.getPath().equals(providerUrl.getParameter(Constants.INTERFACE_KEY))) { + if (!providerUrl.getPath().equals(providerUrl.getParameter(INTERFACE_KEY))) { if (StringUtils.isNotEmpty(extraKeys)) { extraKeys += ","; } - extraKeys += Constants.INTERFACE_KEY; + extraKeys += INTERFACE_KEY; } String[] paramsToRegistry = getParamsToRegistry(DEFAULT_REGISTER_PROVIDER_KEYS - , Constants.COMMA_SPLIT_PATTERN.split(extraKeys)); + , COMMA_SPLIT_PATTERN.split(extraKeys)); return URL.valueOf(providerUrl, paramsToRegistry, providerUrl.getParameter(METHODS_KEY, (String[]) null)); } @@ -357,7 +383,7 @@ public Invoker refer(Class type, URL url) throws RpcException { // group="a,b" or group="*" Map qs = StringUtils.parseQueryString(url.getParameterAndDecoded(REFER_KEY)); - String group = qs.get(Constants.GROUP_KEY); + String group = qs.get(GROUP_KEY); if (group != null && group.length() > 0) { if ((COMMA_SPLIT_PATTERN.split(group)).length > 1 || "*".equals(group)) { return doRefer(getMergeableCluster(), registry, type, url); diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.java index cfe3299eb89..5d2f0e386e5 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.java @@ -52,6 +52,10 @@ import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; +import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.FILE_KEY; + /** * AbstractRegistry. (SPI, Prototype, ThreadSafe) */ @@ -84,7 +88,7 @@ public AbstractRegistry(URL url) { setUrl(url); // Start file save timer syncSaveFile = url.getParameter(Constants.REGISTRY_FILESAVE_SYNC_KEY, false); - String filename = url.getParameter(Constants.FILE_KEY, System.getProperty("user.home") + "/.dubbo/dubbo-registry-" + url.getParameter(Constants.APPLICATION_KEY) + "-" + url.getAddress() + ".cache"); + String filename = url.getParameter(FILE_KEY, System.getProperty("user.home") + "/.dubbo/dubbo-registry-" + url.getParameter(APPLICATION_KEY) + "-" + url.getAddress() + ".cache"); File file = null; if (ConfigUtils.isNotEmpty(filename)) { file = new File(filename); @@ -383,7 +387,7 @@ protected void notify(URL url, NotifyListener listener, List urls) { throw new IllegalArgumentException("notify listener == null"); } if ((CollectionUtils.isEmpty(urls)) - && !Constants.ANY_VALUE.equals(url.getServiceInterface())) { + && !ANY_VALUE.equals(url.getServiceInterface())) { logger.warn("Ignore empty notify urls for subscribe url " + url); return; } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.java index 4ef392ef42a..1819a09640e 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.java @@ -31,6 +31,8 @@ import java.util.Map; import java.util.concurrent.locks.ReentrantLock; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; + /** * AbstractRegistryFactory. (SPI, Singleton, ThreadSafe) * @@ -85,7 +87,7 @@ public static void destroyAll() { public Registry getRegistry(URL url) { url = URLBuilder.from(url) .setPath(RegistryService.class.getName()) - .addParameter(Constants.INTERFACE_KEY, RegistryService.class.getName()) + .addParameter(INTERFACE_KEY, RegistryService.class.getName()) .removeParameters(Constants.EXPORT_KEY, Constants.REFER_KEY) .build(); String key = url.toServiceStringWithoutResolving(); diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java index 1132ad8b60f..ef24676c3a3 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java @@ -38,6 +38,8 @@ import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.CommonConstants.FILE_KEY; + /** * FailbackRegistry. (SPI, Prototype, ThreadSafe) */ @@ -295,7 +297,7 @@ public void subscribe(URL url, NotifyListener listener) { List urls = getCacheUrls(url); if (CollectionUtils.isNotEmpty(urls)) { notify(url, listener, urls); - logger.error("Failed to subscribe " + url + ", Using cached list: " + urls + " from cache file: " + getUrl().getParameter(Constants.FILE_KEY, System.getProperty("user.home") + "/dubbo-registry-" + url.getHost() + ".cache") + ", cause: " + t.getMessage(), t); + logger.error("Failed to subscribe " + url + ", Using cached list: " + urls + " from cache file: " + getUrl().getParameter(FILE_KEY, System.getProperty("user.home") + "/dubbo-registry-" + url.getHost() + ".cache") + ", cause: " + t.getMessage(), t); } else { // If the startup detection is opened, the Exception is thrown directly. boolean check = getUrl().getParameter(RemotingConstants.CHECK_KEY, true) diff --git a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java b/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java index 7bcd6b00afb..968e75b3ea5 100644 --- a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java +++ b/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java @@ -24,6 +24,7 @@ import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.support.FailbackRegistry; +import org.apache.dubbo.rpc.RpcException; import com.ecwid.consul.v1.ConsulClient; import com.ecwid.consul.v1.QueryParams; @@ -32,24 +33,23 @@ import com.ecwid.consul.v1.catalog.CatalogServicesRequest; import com.ecwid.consul.v1.health.HealthServicesRequest; import com.ecwid.consul.v1.health.model.HealthService; -import org.apache.dubbo.rpc.RpcException; +import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; -import java.util.ArrayList; import java.util.Map; import java.util.Objects; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.Executors; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static java.util.concurrent.Executors.newCachedThreadPool; -import static org.apache.dubbo.common.Constants.ANY_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; /** * registry center implementation for consul diff --git a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java index c199774b391..68b37c92914 100644 --- a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java +++ b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java @@ -38,6 +38,11 @@ import java.util.HashSet; import java.util.List; +import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + /** * DubboRegistryFactory * @@ -52,14 +57,14 @@ private static URL getRegistryURL(URL url) { return URLBuilder.from(url) .setPath(RegistryService.class.getName()) .removeParameter(Constants.EXPORT_KEY).removeParameter(Constants.REFER_KEY) - .addParameter(Constants.INTERFACE_KEY, RegistryService.class.getName()) + .addParameter(INTERFACE_KEY, RegistryService.class.getName()) .addParameter(Constants.CLUSTER_STICKY_KEY, "true") .addParameter(Constants.LAZY_CONNECT_KEY, "true") .addParameter(RemotingConstants.RECONNECT_KEY, "false") - .addParameterIfAbsent(Constants.TIMEOUT_KEY, "10000") + .addParameterIfAbsent(TIMEOUT_KEY, "10000") .addParameterIfAbsent(Constants.CALLBACK_INSTANCES_LIMIT_KEY, "10000") .addParameterIfAbsent(RemotingConstants.CONNECT_TIMEOUT_KEY, "10000") - .addParameter(Constants.METHODS_KEY, StringUtils.join(new HashSet<>(Arrays.asList(Wrapper.getWrapper(RegistryService.class).getDeclaredMethodNames())), ",")) + .addParameter(METHODS_KEY, StringUtils.join(new HashSet<>(Arrays.asList(Wrapper.getWrapper(RegistryService.class).getDeclaredMethodNames())), ",")) //.addParameter(Constants.STUB_KEY, RegistryServiceStub.class.getName()) //.addParameter(Constants.STUB_EVENT_KEY, Boolean.TRUE.toString()) //for event dispatch //.addParameter(Constants.ON_DISCONNECT_KEY, "disconnect") @@ -87,12 +92,12 @@ public Registry createRegistry(URL url) { urls.add(url.removeParameter(RemotingConstants.BACKUP_KEY)); String backup = url.getParameter(RemotingConstants.BACKUP_KEY); if (backup != null && backup.length() > 0) { - String[] addresses = Constants.COMMA_SPLIT_PATTERN.split(backup); + String[] addresses = COMMA_SPLIT_PATTERN.split(backup); for (String address : addresses) { urls.add(url.setAddress(address)); } } - RegistryDirectory directory = new RegistryDirectory<>(RegistryService.class, url.addParameter(Constants.INTERFACE_KEY, RegistryService.class.getName()).addParameterAndEncoded(Constants.REFER_KEY, url.toParameterString())); + RegistryDirectory directory = new RegistryDirectory<>(RegistryService.class, url.addParameter(INTERFACE_KEY, RegistryService.class.getName()).addParameterAndEncoded(Constants.REFER_KEY, url.toParameterString())); Invoker registryInvoker = cluster.join(directory); RegistryService registryService = proxyFactory.getProxy(registryInvoker); DubboRegistry registry = new DubboRegistry(registryInvoker, registryService); diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java index e6911fd8347..4bf7e2a8835 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java @@ -50,6 +50,12 @@ import java.util.Map; import java.util.concurrent.CountDownLatch; +import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; +import static org.apache.dubbo.common.constants.CommonConstants.DISABLED_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.junit.jupiter.api.Assertions.fail; @SuppressWarnings({"rawtypes", "unchecked"}) @@ -183,7 +189,7 @@ public void testNotified_WithDuplicateUrls() { private void testforbid(RegistryDirectory registryDirectory) { invocation = new RpcInvocation(); List serviceUrls = new ArrayList(); - serviceUrls.add(new URL(Constants.EMPTY_PROTOCOL, Constants.ANYHOST_VALUE, 0, service, Constants.CATEGORY_KEY, Constants.PROVIDERS_CATEGORY)); + serviceUrls.add(new URL(Constants.EMPTY_PROTOCOL, ANYHOST_VALUE, 0, service, Constants.CATEGORY_KEY, Constants.PROVIDERS_CATEGORY)); registryDirectory.notify(serviceUrls); Assertions.assertEquals(false, registryDirectory.isAvailable(), "invokers size=0 ,then the registry directory is not available"); @@ -228,7 +234,7 @@ private void test_Notified_only_routers(RegistryDirectory registryDirectory) { private void test_Notified1invokers(RegistryDirectory registryDirectory) { List serviceUrls = new ArrayList(); - serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1").addParameter(Constants.APPLICATION_KEY, "mockApplicationName"));// .addParameter("refer.autodestroy", "true") + serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1").addParameter(APPLICATION_KEY, "mockApplicationName"));// .addParameter("refer.autodestroy", "true") registryDirectory.notify(serviceUrls); Assertions.assertEquals(true, registryDirectory.isAvailable()); @@ -711,8 +717,8 @@ public void testNofityOverrideUrls_Provider() { invocation = new RpcInvocation(); List durls = new ArrayList(); - durls.add(SERVICEURL.setHost("10.20.30.140").addParameter("timeout", "1").addParameter(Constants.SIDE_KEY, Constants.CONSUMER_SIDE));//One is the same, one is different - durls.add(SERVICEURL2.setHost("10.20.30.141").addParameter("timeout", "2").addParameter(Constants.SIDE_KEY, Constants.CONSUMER_SIDE)); + durls.add(SERVICEURL.setHost("10.20.30.140").addParameter("timeout", "1").addParameter(SIDE_KEY, CONSUMER_SIDE));//One is the same, one is different + durls.add(SERVICEURL2.setHost("10.20.30.141").addParameter("timeout", "2").addParameter(SIDE_KEY, CONSUMER_SIDE)); registryDirectory.notify(durls); durls = new ArrayList(); @@ -829,7 +835,7 @@ public void testNofityOverrideUrls_disabled_allProvider() { registryDirectory.notify(durls); durls = new ArrayList(); - durls.add(URL.valueOf("override://0.0.0.0?" + Constants.ENABLED_KEY + "=false")); + durls.add(URL.valueOf("override://0.0.0.0?" + ENABLED_KEY + "=false")); registryDirectory.notify(durls); List> invokers = registryDirectory.list(invocation); @@ -852,7 +858,7 @@ public void testNofityOverrideUrls_disabled_specifiedProvider() { registryDirectory.notify(durls); durls = new ArrayList(); - durls.add(URL.valueOf("override://10.20.30.140:9091?" + Constants.DISABLED_KEY + "=true")); + durls.add(URL.valueOf("override://10.20.30.140:9091?" + DISABLED_KEY + "=true")); registryDirectory.notify(durls); List> invokers = registryDirectory.list(invocation); @@ -860,7 +866,7 @@ public void testNofityOverrideUrls_disabled_specifiedProvider() { Assertions.assertEquals("10.20.30.141", invokers.get(0).getUrl().getHost()); durls = new ArrayList(); - durls.add(URL.valueOf("empty://0.0.0.0?" + Constants.DISABLED_KEY + "=true&" + Constants.CATEGORY_KEY + "=" + Constants.CONFIGURATORS_CATEGORY)); + durls.add(URL.valueOf("empty://0.0.0.0?" + DISABLED_KEY + "=true&" + Constants.CATEGORY_KEY + "=" + Constants.CONFIGURATORS_CATEGORY)); registryDirectory.notify(durls); List> invokers2 = registryDirectory.list(invocation); Assertions.assertEquals(2, invokers2.size()); @@ -891,7 +897,7 @@ public void testNofity_To_Decrease_provider() { Assertions.assertEquals("10.20.30.140", invokers2.get(0).getUrl().getHost()); durls = new ArrayList(); - durls.add(URL.valueOf("empty://0.0.0.0?" + Constants.DISABLED_KEY + "=true&" + Constants.CATEGORY_KEY + "=" + Constants.CONFIGURATORS_CATEGORY)); + durls.add(URL.valueOf("empty://0.0.0.0?" + DISABLED_KEY + "=true&" + Constants.CATEGORY_KEY + "=" + Constants.CONFIGURATORS_CATEGORY)); registryDirectory.notify(durls); List> invokers3 = registryDirectory.list(invocation); Assertions.assertEquals(1, invokers3.size()); @@ -908,7 +914,7 @@ public void testNofity_disabled_specifiedProvider() { // Initially disable List durls = new ArrayList(); - durls.add(SERVICEURL.setHost("10.20.30.140").addParameter(Constants.ENABLED_KEY, "false")); + durls.add(SERVICEURL.setHost("10.20.30.140").addParameter(ENABLED_KEY, "false")); durls.add(SERVICEURL.setHost("10.20.30.141")); registryDirectory.notify(durls); @@ -918,7 +924,7 @@ public void testNofity_disabled_specifiedProvider() { //Enabled by override rule durls = new ArrayList(); - durls.add(URL.valueOf("override://10.20.30.140:9091?" + Constants.DISABLED_KEY + "=false")); + durls.add(URL.valueOf("override://10.20.30.140:9091?" + DISABLED_KEY + "=false")); registryDirectory.notify(durls); List> invokers2 = registryDirectory.list(invocation); Assertions.assertEquals(2, invokers2.size()); diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java index f1669d3462e..40d5cb4ea02 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java @@ -42,7 +42,7 @@ import java.util.ArrayList; import java.util.List; -import static org.apache.dubbo.common.Constants.DEFAULT_REGISTER_PROVIDER_KEYS; +import static org.apache.dubbo.registry.integration.RegistryProtocol.DEFAULT_REGISTER_PROVIDER_KEYS; import static org.junit.jupiter.api.Assertions.assertEquals; /** diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java index 2b67e634143..92f5fb49131 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java @@ -17,7 +17,6 @@ package org.apache.dubbo.registry.dubbo; import org.apache.dubbo.common.Constants; -import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; @@ -29,6 +28,8 @@ import java.io.IOException; import java.net.ServerSocket; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; + /** * SimpleRegistryExporter * @@ -56,7 +57,7 @@ public static Exporter export(int port, RegistryService registr return protocol.export(proxyFactory.getInvoker(registryService, RegistryService.class, new URLBuilder(Constants.DUBBO_PROTOCOL, NetUtils.getLocalHost(), port, RegistryService.class.getName()) .setPath(RegistryService.class.getName()) - .addParameter(Constants.INTERFACE_KEY, RegistryService.class.getName()) + .addParameter(INTERFACE_KEY, RegistryService.class.getName()) .addParameter(Constants.CLUSTER_STICKY_KEY, "true") .addParameter(Constants.CALLBACK_INSTANCES_LIMIT_KEY, "1000") .addParameter("ondisconnect", "disconnect") diff --git a/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistry.java b/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistry.java index 1f70044c164..93612b5457f 100644 --- a/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistry.java +++ b/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistry.java @@ -57,6 +57,11 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; + /** * Support for ectd3 registry. @@ -81,9 +86,9 @@ public EtcdRegistry(URL url, EtcdTransporter etcdTransporter) { if (url.isAnyHost()) { throw new IllegalStateException("registry address is invalid, actual: '" + url.getHost() + "'"); } - String group = url.getParameter(Constants.GROUP_KEY, DEFAULT_ROOT); - if (!group.startsWith(Constants.PATH_SEPARATOR)) { - group = Constants.PATH_SEPARATOR + group; + String group = url.getParameter(GROUP_KEY, DEFAULT_ROOT); + if (!group.startsWith(PATH_SEPARATOR)) { + group = PATH_SEPARATOR + group; } this.root = group; etcdClient = etcdTransporter.connect(url); @@ -141,7 +146,7 @@ public void doUnregister(URL url) { @Override public void doSubscribe(URL url, NotifyListener listener) { try { - if (Constants.ANY_VALUE.equals(url.getServiceInterface())) { + if (ANY_VALUE.equals(url.getServiceInterface())) { String root = toRootPath(); /* @@ -179,7 +184,7 @@ public void doSubscribe(URL url, NotifyListener listener) { * if new interface event arrived, we watch their direct children, * eg: /dubbo/interface, /dubbo/interface and so on. */ - subscribe(url.setPath(child).addParameters(Constants.INTERFACE_KEY, child, + subscribe(url.setPath(child).addParameters(INTERFACE_KEY, child, RemotingConstants.CHECK_KEY, String.valueOf(false)), listener); } } @@ -196,7 +201,7 @@ public void doSubscribe(URL url, NotifyListener listener) { for (String service : services) { service = URL.decode(service); anyServices.add(service); - subscribe(url.setPath(service).addParameters(Constants.INTERFACE_KEY, service, + subscribe(url.setPath(service).addParameters(INTERFACE_KEY, service, RemotingConstants.CHECK_KEY, String.valueOf(false)), listener); } } else { @@ -279,10 +284,10 @@ public void destroy() { } protected String toRootDir() { - if (root.startsWith(Constants.PATH_SEPARATOR)) { + if (root.startsWith(PATH_SEPARATOR)) { return root; } - return Constants.PATH_SEPARATOR + root; + return PATH_SEPARATOR + root; } protected String toRootPath() { @@ -291,15 +296,15 @@ protected String toRootPath() { protected String toServicePath(URL url) { String name = url.getServiceInterface(); - if (Constants.ANY_VALUE.equals(name)) { + if (ANY_VALUE.equals(name)) { return toRootPath(); } - return toRootDir() + Constants.PATH_SEPARATOR + URL.encode(name); + return toRootDir() + PATH_SEPARATOR + URL.encode(name); } protected String[] toCategoriesPath(URL url) { String[] categories; - if (Constants.ANY_VALUE.equals(url.getParameter(Constants.CATEGORY_KEY))) { + if (ANY_VALUE.equals(url.getParameter(Constants.CATEGORY_KEY))) { categories = new String[]{Constants.PROVIDERS_CATEGORY, Constants.CONSUMERS_CATEGORY, Constants.ROUTERS_CATEGORY, Constants.CONFIGURATORS_CATEGORY}; } else { @@ -307,25 +312,25 @@ protected String[] toCategoriesPath(URL url) { } String[] paths = new String[categories.length]; for (int i = 0; i < categories.length; i++) { - paths[i] = toServicePath(url) + Constants.PATH_SEPARATOR + categories[i]; + paths[i] = toServicePath(url) + PATH_SEPARATOR + categories[i]; } return paths; } protected String toCategoryPath(URL url) { - return toServicePath(url) + Constants.PATH_SEPARATOR + url.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY); + return toServicePath(url) + PATH_SEPARATOR + url.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY); } protected String toUrlPath(URL url) { - return toCategoryPath(url) + Constants.PATH_SEPARATOR + URL.encode(url.toFullString()); + return toCategoryPath(url) + PATH_SEPARATOR + URL.encode(url.toFullString()); } protected List toUnsubscribedPath(URL url) { List categories = new ArrayList<>(); - if (Constants.ANY_VALUE.equals(url.getServiceInterface())) { - String group = url.getParameter(Constants.GROUP_KEY, DEFAULT_ROOT); - if (!group.startsWith(Constants.PATH_SEPARATOR)) { - group = Constants.PATH_SEPARATOR + group; + if (ANY_VALUE.equals(url.getServiceInterface())) { + String group = url.getParameter(GROUP_KEY, DEFAULT_ROOT); + if (!group.startsWith(PATH_SEPARATOR)) { + group = PATH_SEPARATOR + group; } categories.add(group); return categories; diff --git a/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java b/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java index 7de75411791..f972242a1d6 100644 --- a/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java +++ b/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java @@ -58,6 +58,7 @@ import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.RegistryFactory; import org.apache.dubbo.registry.support.AbstractRegistryFactory; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -73,6 +74,13 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; +import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.CLASSIFIER_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; + @Disabled public class EtcdRegistryTest { @@ -87,15 +95,15 @@ public class EtcdRegistryTest { EtcdRegistry registry; 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, + INTERFACE_KEY, ANY_VALUE, + GROUP_KEY, ANY_VALUE, + VERSION_KEY, ANY_VALUE, + CLASSIFIER_KEY, ANY_VALUE, Constants.CATEGORY_KEY, Constants.PROVIDERS_CATEGORY + "," + Constants.CONSUMERS_CATEGORY + "," + Constants.ROUTERS_CATEGORY + "," + Constants.CONFIGURATORS_CATEGORY, - Constants.ENABLED_KEY, Constants.ANY_VALUE, + ENABLED_KEY, ANY_VALUE, RemotingConstants.CHECK_KEY, String.valueOf(false)); @Test diff --git a/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java b/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java index 3223532c07f..ae7b004ab38 100644 --- a/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java +++ b/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java @@ -49,6 +49,10 @@ import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; + /** * MulticastRegistry */ @@ -249,13 +253,13 @@ public void doUnregister(URL url) { @Override public void doSubscribe(URL url, NotifyListener listener) { - if (Constants.ANY_VALUE.equals(url.getServiceInterface())) { + if (ANY_VALUE.equals(url.getServiceInterface())) { admin = true; } multicast(Constants.SUBSCRIBE + " " + url.toFullString()); synchronized (listener) { try { - listener.wait(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); + listener.wait(url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT)); } catch (InterruptedException e) { } } @@ -263,7 +267,7 @@ public void doSubscribe(URL url, NotifyListener listener) { @Override public void doUnsubscribe(URL url, NotifyListener listener) { - if (!Constants.ANY_VALUE.equals(url.getServiceInterface()) && url.getParameter(Constants.REGISTER_KEY, true)) { + if (!ANY_VALUE.equals(url.getServiceInterface()) && url.getParameter(Constants.REGISTER_KEY, true)) { unregister(url); } multicast(Constants.UNSUBSCRIBE + " " + url.toFullString()); @@ -403,7 +407,7 @@ public List lookup(URL url) { } } } - if (Constants.ANY_VALUE.equals(url.getServiceInterface())) { + if (ANY_VALUE.equals(url.getServiceInterface())) { for (URL u : getSubscribed().keySet()) { if (UrlUtils.isMatch(url, u)) { urls.add(u); diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java index da00a9d35eb..40d4a1355bd 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java @@ -52,11 +52,14 @@ import static org.apache.dubbo.common.Constants.CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.Constants.CONSUMERS_CATEGORY; import static org.apache.dubbo.common.Constants.DEFAULT_CATEGORY; -import static org.apache.dubbo.common.Constants.GROUP_KEY; -import static org.apache.dubbo.common.Constants.INTERFACE_KEY; import static org.apache.dubbo.common.Constants.PROVIDERS_CATEGORY; import static org.apache.dubbo.common.Constants.ROUTERS_CATEGORY; -import static org.apache.dubbo.common.Constants.VERSION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; /** * Nacos {@link Registry} @@ -381,14 +384,14 @@ private void notifySubscriber(URL url, NotifyListener listener, Collection metadata = instance.getMetadata(); - String protocol = metadata.get(Constants.PROTOCOL_KEY); - String path = metadata.get(Constants.PATH_KEY); + String protocol = metadata.get(PROTOCOL_KEY); + String path = metadata.get(PATH_KEY); return new URL(protocol, instance.getIp(), instance.getPort(), @@ -400,8 +403,8 @@ private Instance createInstance(URL url) { // Append default category if absent String category = url.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY); URL newURL = url.addParameter(Constants.CATEGORY_KEY, category); - newURL = newURL.addParameter(Constants.PROTOCOL_KEY, url.getProtocol()); - newURL = newURL.addParameter(Constants.PATH_KEY, url.getPath()); + newURL = newURL.addParameter(PROTOCOL_KEY, url.getProtocol()); + newURL = newURL.addParameter(PATH_KEY, url.getPath()); String ip = url.getHost(); int port = url.getPort(); Instance instance = new Instance(); diff --git a/dubbo-registry/dubbo-registry-redis/src/main/java/org/apache/dubbo/registry/redis/RedisRegistry.java b/dubbo-registry/dubbo-registry-redis/src/main/java/org/apache/dubbo/registry/redis/RedisRegistry.java index 5303ddc495a..03a8131b22a 100644 --- a/dubbo-registry/dubbo-registry-redis/src/main/java/org/apache/dubbo/registry/redis/RedisRegistry.java +++ b/dubbo-registry/dubbo-registry-redis/src/main/java/org/apache/dubbo/registry/redis/RedisRegistry.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.registry.redis; -import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; @@ -32,6 +31,8 @@ import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.support.FailbackRegistry; import org.apache.dubbo.rpc.RpcException; + +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPubSub; @@ -55,6 +56,13 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + /** * RedisRegistry */ @@ -143,17 +151,17 @@ public RedisRegistry(URL url) { port = DEFAULT_REDIS_PORT; } this.jedisPools.put(address, new JedisPool(config, host, port, - url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT), StringUtils.isEmpty(url.getPassword()) ? null : url.getPassword(), + url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT), StringUtils.isEmpty(url.getPassword()) ? null : url.getPassword(), url.getParameter("db.index", 0))); } this.reconnectPeriod = url.getParameter(Constants.REGISTRY_RECONNECT_PERIOD_KEY, Constants.DEFAULT_REGISTRY_RECONNECT_PERIOD); - String group = url.getParameter(Constants.GROUP_KEY, DEFAULT_ROOT); - if (!group.startsWith(Constants.PATH_SEPARATOR)) { - group = Constants.PATH_SEPARATOR + group; + String group = url.getParameter(GROUP_KEY, DEFAULT_ROOT); + if (!group.startsWith(PATH_SEPARATOR)) { + group = PATH_SEPARATOR + group; } - if (!group.endsWith(Constants.PATH_SEPARATOR)) { - group = group + Constants.PATH_SEPARATOR; + if (!group.endsWith(PATH_SEPARATOR)) { + group = group + PATH_SEPARATOR; } this.root = group; @@ -195,7 +203,7 @@ private void deferExpired() { // The monitoring center is responsible for deleting outdated dirty data private void clean(Jedis jedis) { - Set keys = jedis.keys(root + Constants.ANY_VALUE); + Set keys = jedis.keys(root + ANY_VALUE); if (CollectionUtils.isNotEmpty(keys)) { for (String key : keys) { Map values = jedis.hgetAll(key); @@ -341,7 +349,7 @@ public void doSubscribe(final URL url, final NotifyListener listener) { JedisPool jedisPool = entry.getValue(); try { try (Jedis jedis = jedisPool.getResource()) { - if (service.endsWith(Constants.ANY_VALUE)) { + if (service.endsWith(ANY_VALUE)) { admin = true; Set keys = jedis.keys(service); if (CollectionUtils.isNotEmpty(keys)) { @@ -356,7 +364,7 @@ public void doSubscribe(final URL url, final NotifyListener listener) { } } } else { - doNotify(jedis, jedis.keys(service + Constants.PATH_SEPARATOR + Constants.ANY_VALUE), url, Collections.singletonList(listener)); + doNotify(jedis, jedis.keys(service + PATH_SEPARATOR + ANY_VALUE), url, Collections.singletonList(listener)); } success = true; break; // Just read one server's data @@ -394,14 +402,14 @@ private void doNotify(Jedis jedis, Collection keys, URL url, Collection< List categories = Arrays.asList(url.getParameter(Constants.CATEGORY_KEY, new String[0])); String consumerService = url.getServiceInterface(); for (String key : keys) { - if (!Constants.ANY_VALUE.equals(consumerService)) { + if (!ANY_VALUE.equals(consumerService)) { String providerService = toServiceName(key); if (!providerService.equals(consumerService)) { continue; } } String category = toCategoryName(key); - if (!categories.contains(Constants.ANY_VALUE) && !categories.contains(category)) { + if (!categories.contains(ANY_VALUE) && !categories.contains(category)) { continue; } List urls = new ArrayList<>(); @@ -420,7 +428,7 @@ private void doNotify(Jedis jedis, Collection keys, URL url, Collection< if (urls.isEmpty()) { urls.add(URLBuilder.from(url) .setProtocol(Constants.EMPTY_PROTOCOL) - .setAddress(Constants.ANYHOST_VALUE) + .setAddress(ANYHOST_VALUE) .setPath(toServiceName(key)) .addParameter(Constants.CATEGORY_KEY, category) .build()); @@ -444,16 +452,16 @@ private String toServiceName(String categoryPath) { } private String toCategoryName(String categoryPath) { - int i = categoryPath.lastIndexOf(Constants.PATH_SEPARATOR); + int i = categoryPath.lastIndexOf(PATH_SEPARATOR); return i > 0 ? categoryPath.substring(i + 1) : categoryPath; } private String toServicePath(String categoryPath) { int i; if (categoryPath.startsWith(root)) { - i = categoryPath.indexOf(Constants.PATH_SEPARATOR, root.length()); + i = categoryPath.indexOf(PATH_SEPARATOR, root.length()); } else { - i = categoryPath.indexOf(Constants.PATH_SEPARATOR); + i = categoryPath.indexOf(PATH_SEPARATOR); } return i > 0 ? categoryPath.substring(0, i) : categoryPath; } @@ -463,7 +471,7 @@ private String toServicePath(URL url) { } private String toCategoryPath(URL url) { - return toServicePath(url) + Constants.PATH_SEPARATOR + url.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY); + return toServicePath(url) + PATH_SEPARATOR + url.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY); } private class NotifySub extends JedisPubSub { @@ -567,7 +575,7 @@ public void run() { try { jedis = jedisPool.getResource(); try { - if (service.endsWith(Constants.ANY_VALUE)) { + if (service.endsWith(ANY_VALUE)) { if (first) { first = false; Set keys = jedis.keys(service); @@ -585,7 +593,7 @@ public void run() { doNotify(jedis, service); resetSkip(); } - jedis.psubscribe(new NotifySub(jedisPool), service + Constants.PATH_SEPARATOR + Constants.ANY_VALUE); // blocking + jedis.psubscribe(new NotifySub(jedisPool), service + PATH_SEPARATOR + ANY_VALUE); // blocking } break; } finally { diff --git a/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistry.java b/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistry.java index a514d7a2517..f83e0e6dada 100644 --- a/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistry.java +++ b/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistry.java @@ -16,6 +16,15 @@ */ package org.apache.dubbo.registry.sofa; +import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.common.utils.ConfigUtils; +import org.apache.dubbo.common.utils.StringUtils; +import org.apache.dubbo.registry.NotifyListener; +import org.apache.dubbo.registry.support.FailbackRegistry; + import com.alipay.sofa.registry.client.api.RegistryClient; import com.alipay.sofa.registry.client.api.RegistryClientConfig; import com.alipay.sofa.registry.client.api.Subscriber; @@ -26,14 +35,6 @@ import com.alipay.sofa.registry.client.provider.DefaultRegistryClient; import com.alipay.sofa.registry.client.provider.DefaultRegistryClientConfigBuilder; import com.alipay.sofa.registry.core.model.ScopeEnum; -import org.apache.dubbo.common.Constants; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.ConfigUtils; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.registry.NotifyListener; -import org.apache.dubbo.registry.support.FailbackRegistry; import java.util.ArrayList; import java.util.List; @@ -42,6 +43,10 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.DUBBO; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.registry.sofa.SofaRegistryConstants.ADDRESS_WAIT_TIME_KEY; import static org.apache.dubbo.registry.sofa.SofaRegistryConstants.DEFAULT_GROUP; import static org.apache.dubbo.registry.sofa.SofaRegistryConstants.LOCAL_DATA_CENTER; @@ -208,7 +213,7 @@ private void handleRegistryData(UserData data, NotifyListener notifyListener, List datas = flatUserData(data); for (String serviceUrl : datas) { URL url = URL.valueOf(serviceUrl); - String serverApplication = url.getParameter(Constants.APPLICATION_KEY); + String serverApplication = url.getParameter(APPLICATION_KEY); if (StringUtils.isNotEmpty(serverApplication)) { url = url.addParameter("dstApp", serverApplication); } @@ -225,15 +230,15 @@ private String buildServiceName(URL url) { // return url.getServiceKey(); StringBuilder buf = new StringBuilder(); buf.append(url.getServiceInterface()); - String version = url.getParameter(Constants.VERSION_KEY); + String version = url.getParameter(VERSION_KEY); if (StringUtils.isNotEmpty(version)) { buf.append(":").append(version); } - String group = url.getParameter(Constants.GROUP_KEY); + String group = url.getParameter(GROUP_KEY); if (StringUtils.isNotEmpty(group)) { buf.append(":").append(group); } - buf.append("@").append(Constants.DUBBO); + buf.append("@").append(DUBBO); return buf.toString(); } diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.java index 102d5881af2..74ed7215e20 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.java @@ -39,6 +39,12 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; +import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_SEPARATOR; + /** * ZookeeperRegistry * @@ -64,9 +70,9 @@ public ZookeeperRegistry(URL url, ZookeeperTransporter zookeeperTransporter) { if (url.isAnyHost()) { throw new IllegalStateException("registry address == null"); } - String group = url.getParameter(Constants.GROUP_KEY, DEFAULT_ROOT); - if (!group.startsWith(Constants.PATH_SEPARATOR)) { - group = Constants.PATH_SEPARATOR + group; + String group = url.getParameter(GROUP_KEY, DEFAULT_ROOT); + if (!group.startsWith(PATH_SEPARATOR)) { + group = PATH_SEPARATOR + group; } this.root = group; zkClient = zookeeperTransporter.connect(url); @@ -117,7 +123,7 @@ public void doUnregister(URL url) { @Override public void doSubscribe(final URL url, final NotifyListener listener) { try { - if (Constants.ANY_VALUE.equals(url.getServiceInterface())) { + if (ANY_VALUE.equals(url.getServiceInterface())) { String root = toRootPath(); ConcurrentMap listeners = zkListeners.get(url); if (listeners == null) { @@ -131,7 +137,7 @@ public void doSubscribe(final URL url, final NotifyListener listener) { child = URL.decode(child); if (!anyServices.contains(child)) { anyServices.add(child); - subscribe(url.setPath(child).addParameters(Constants.INTERFACE_KEY, child, + subscribe(url.setPath(child).addParameters(INTERFACE_KEY, child, RemotingConstants.CHECK_KEY, String.valueOf(false)), listener); } } @@ -144,7 +150,7 @@ public void doSubscribe(final URL url, final NotifyListener listener) { for (String service : services) { service = URL.decode(service); anyServices.add(service); - subscribe(url.setPath(service).addParameters(Constants.INTERFACE_KEY, service, + subscribe(url.setPath(service).addParameters(INTERFACE_KEY, service, RemotingConstants.CHECK_KEY, String.valueOf(false)), listener); } } @@ -180,7 +186,7 @@ public void doUnsubscribe(URL url, NotifyListener listener) { if (listeners != null) { ChildListener zkListener = listeners.get(listener); if (zkListener != null) { - if (Constants.ANY_VALUE.equals(url.getServiceInterface())) { + if (ANY_VALUE.equals(url.getServiceInterface())) { String root = toRootPath(); zkClient.removeChildListener(root, zkListener); } else { @@ -212,10 +218,10 @@ public List lookup(URL url) { } private String toRootDir() { - if (root.equals(Constants.PATH_SEPARATOR)) { + if (root.equals(PATH_SEPARATOR)) { return root; } - return root + Constants.PATH_SEPARATOR; + return root + PATH_SEPARATOR; } private String toRootPath() { @@ -224,7 +230,7 @@ private String toRootPath() { private String toServicePath(URL url) { String name = url.getServiceInterface(); - if (Constants.ANY_VALUE.equals(name)) { + if (ANY_VALUE.equals(name)) { return toRootPath(); } return toRootDir() + URL.encode(name); @@ -232,7 +238,7 @@ private String toServicePath(URL url) { private String[] toCategoriesPath(URL url) { String[] categories; - if (Constants.ANY_VALUE.equals(url.getParameter(Constants.CATEGORY_KEY))) { + if (ANY_VALUE.equals(url.getParameter(Constants.CATEGORY_KEY))) { categories = new String[]{Constants.PROVIDERS_CATEGORY, Constants.CONSUMERS_CATEGORY, Constants.ROUTERS_CATEGORY, Constants.CONFIGURATORS_CATEGORY}; } else { @@ -240,17 +246,17 @@ private String[] toCategoriesPath(URL url) { } String[] paths = new String[categories.length]; for (int i = 0; i < categories.length; i++) { - paths[i] = toServicePath(url) + Constants.PATH_SEPARATOR + categories[i]; + paths[i] = toServicePath(url) + PATH_SEPARATOR + categories[i]; } return paths; } private String toCategoryPath(URL url) { - return toServicePath(url) + Constants.PATH_SEPARATOR + url.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY); + return toServicePath(url) + PATH_SEPARATOR + url.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY); } private String toUrlPath(URL url) { - return toCategoryPath(url) + Constants.PATH_SEPARATOR + URL.encode(url.toFullString()); + return toCategoryPath(url) + PATH_SEPARATOR + URL.encode(url.toFullString()); } private List toUrlsWithoutEmpty(URL consumer, List providers) { @@ -258,7 +264,7 @@ private List toUrlsWithoutEmpty(URL consumer, List providers) { if (CollectionUtils.isNotEmpty(providers)) { for (String provider : providers) { provider = URL.decode(provider); - if (provider.contains(Constants.PROTOCOL_SEPARATOR)) { + if (provider.contains(PROTOCOL_SEPARATOR)) { URL url = URL.valueOf(provider); if (UrlUtils.isMatch(consumer, url)) { urls.add(url); @@ -272,7 +278,7 @@ private List toUrlsWithoutEmpty(URL consumer, List providers) { private List toUrlsWithEmpty(URL consumer, String path, List providers) { List urls = toUrlsWithoutEmpty(consumer, providers); if (urls == null || urls.isEmpty()) { - int i = path.lastIndexOf(Constants.PATH_SEPARATOR); + int i = path.lastIndexOf(PATH_SEPARATOR); String category = i < 0 ? path : path.substring(i + 1); URL empty = URLBuilder.from(consumer) .setProtocol(Constants.EMPTY_PROTOCOL) diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture.java index 290d668241a..6a554469845 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.exchange.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.timer.HashedWheelTimer; @@ -41,6 +40,9 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + /** * DefaultFuture. */ @@ -73,7 +75,7 @@ private DefaultFuture(Channel channel, Request request, int timeout) { this.channel = channel; this.request = request; this.id = request.getId(); - this.timeout = timeout > 0 ? timeout : channel.getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); + this.timeout = timeout > 0 ? timeout : channel.getUrl().getPositiveParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT); // put into waiting map. FUTURES.put(id, this); CHANNELS.put(id, channel); @@ -167,7 +169,7 @@ public Object get() throws RemotingException { @Override public Object get(int timeout) throws RemotingException { if (timeout <= 0) { - timeout = Constants.DEFAULT_TIMEOUT; + timeout = DEFAULT_TIMEOUT; } if (!isDone()) { long start = System.currentTimeMillis(); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java index 4aef993a2e2..f9193de3e41 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.exchange.support.header; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.logger.Logger; @@ -33,6 +32,9 @@ import java.net.InetSocketAddress; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + /** * ExchangeReceiver */ @@ -98,7 +100,7 @@ public void send(Object message, boolean sent) throws RemotingException { @Override public ResponseFuture request(Object request) throws RemotingException { - return request(request, channel.getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); + return request(request, channel.getUrl().getPositiveParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT)); } @Override diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java index 89a781c5bef..1dec8162b31 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java @@ -26,6 +26,8 @@ import org.apache.dubbo.remoting.telnet.TelnetHandler; import org.apache.dubbo.remoting.transport.ChannelHandlerAdapter; +import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; + public class TelnetHandlerAdapter extends ChannelHandlerAdapter implements TelnetHandler { private final ExtensionLoader extensionLoader = ExtensionLoader.getExtensionLoader(TelnetHandler.class); @@ -86,7 +88,7 @@ private boolean commandEnabled(URL url, String command) { if (StringUtils.isEmpty(supportCommands)) { return true; } - String[] commands = Constants.COMMA_SPLIT_PATTERN.split(supportCommands); + String[] commands = COMMA_SPLIT_PATTERN.split(supportCommands); for (String c : commands) { if (command.equals(c)) { return true; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/StatusTelnetHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/StatusTelnetHandler.java index 69611f60a0e..12fbf989dcc 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/StatusTelnetHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/StatusTelnetHandler.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.telnet.support.command; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.status.Status; @@ -33,6 +32,8 @@ import java.util.List; import java.util.Map; +import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; + /** * StatusTelnetHandler */ @@ -81,7 +82,7 @@ public String telnet(Channel channel, String message) { String status = channel.getUrl().getParameter("status"); Map statuses = new HashMap(); if (CollectionUtils.isNotEmptyMap(statuses)) { - String[] ss = Constants.COMMA_SPLIT_PATTERN.split(status); + String[] ss = COMMA_SPLIT_PATTERN.split(status); for (String s : ss) { StatusChecker handler = extensionLoader.getExtension(s); Status stat; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractClient.java index aa10dd819f5..876b5208ed9 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractClient.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.transport; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.constants.RemotingConstants; @@ -37,6 +36,10 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; +import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_CLIENT_THREADPOOL; +import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; + /** * AbstractClient */ @@ -83,14 +86,14 @@ public AbstractClient(URL url, ChannelHandler handler) throws RemotingException } executor = (ExecutorService) ExtensionLoader.getExtensionLoader(DataStore.class) - .getDefaultExtension().get(Constants.CONSUMER_SIDE, Integer.toString(url.getPort())); + .getDefaultExtension().get(CONSUMER_SIDE, Integer.toString(url.getPort())); ExtensionLoader.getExtensionLoader(DataStore.class) - .getDefaultExtension().remove(Constants.CONSUMER_SIDE, Integer.toString(url.getPort())); + .getDefaultExtension().remove(CONSUMER_SIDE, Integer.toString(url.getPort())); } protected static ChannelHandler wrapChannelHandler(URL url, ChannelHandler handler) { url = ExecutorUtil.setThreadName(url, CLIENT_THREAD_POOL_NAME); - url = url.addParameterIfAbsent(Constants.THREADPOOL_KEY, Constants.DEFAULT_CLIENT_THREADPOOL); + url = url.addParameterIfAbsent(THREADPOOL_KEY, DEFAULT_CLIENT_THREADPOOL); return ChannelHandlers.wrap(handler, url); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractCodec.java index e5f76964370..04f700a97c4 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractCodec.java @@ -19,7 +19,6 @@ import java.io.IOException; import java.net.InetSocketAddress; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; @@ -29,6 +28,8 @@ import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Codec2; +import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; + /** * AbstractCodec */ @@ -58,7 +59,7 @@ protected Serialization getSerialization(Channel channel) { } protected boolean isClientSide(Channel channel) { - String side = (String)channel.getAttribute(Constants.SIDE_KEY); + String side = (String)channel.getAttribute(SIDE_KEY); if (CLIENT_SIDE.equals(side)) { return true; } else if (SERVER_SIDE.equals(side)) { @@ -70,7 +71,7 @@ protected boolean isClientSide(Channel channel) { && NetUtils.filterLocalHost(url.getIp()).equals( NetUtils.filterLocalHost(address.getAddress() .getHostAddress())); - channel.setAttribute(Constants.SIDE_KEY, isClient ? CLIENT_SIDE + channel.setAttribute(SIDE_KEY, isClient ? CLIENT_SIDE : SERVER_SIDE); return isClient; } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractEndpoint.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractEndpoint.java index 0a438bf7491..f366e7ce7b7 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractEndpoint.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractEndpoint.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.transport; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.Resetable; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; @@ -28,6 +27,9 @@ import org.apache.dubbo.remoting.Codec2; import org.apache.dubbo.remoting.transport.codec.CodecAdapter; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + /** * AbstractEndpoint */ @@ -44,7 +46,7 @@ public abstract class AbstractEndpoint extends AbstractPeer implements Resetable public AbstractEndpoint(URL url, ChannelHandler handler) { super(url, handler); this.codec = getChannelCodec(url); - this.timeout = url.getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); + this.timeout = url.getPositiveParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT); this.connectTimeout = url.getPositiveParameter(RemotingConstants.CONNECT_TIMEOUT_KEY, RemotingConstants.DEFAULT_CONNECT_TIMEOUT); } @@ -65,8 +67,8 @@ public void reset(URL url) { + url + ", cause: Channel closed. channel: " + getLocalAddress()); } try { - if (url.hasParameter(Constants.TIMEOUT_KEY)) { - int t = url.getParameter(Constants.TIMEOUT_KEY, 0); + if (url.hasParameter(TIMEOUT_KEY)) { + int t = url.getParameter(TIMEOUT_KEY, 0); if (t > 0) { this.timeout = t; } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractServer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractServer.java index 0af47a63c3e..a252ca46d34 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractServer.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.transport; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; @@ -35,6 +34,10 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; +import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; + /** * AbstractServer */ @@ -54,8 +57,8 @@ public AbstractServer(URL url, ChannelHandler handler) throws RemotingException String bindIp = getUrl().getParameter(RemotingConstants.BIND_IP_KEY, getUrl().getHost()); int bindPort = getUrl().getParameter(RemotingConstants.BIND_PORT_KEY, getUrl().getPort()); - if (url.getParameter(Constants.ANYHOST_KEY, false) || NetUtils.isInvalidLocalHost(bindIp)) { - bindIp = Constants.ANYHOST_VALUE; + if (url.getParameter(ANYHOST_KEY, false) || NetUtils.isInvalidLocalHost(bindIp)) { + bindIp = ANYHOST_VALUE; } bindAddress = new InetSocketAddress(bindIp, bindPort); this.accepts = url.getParameter(RemotingConstants.ACCEPTS_KEY, RemotingConstants.DEFAULT_ACCEPTS); @@ -104,10 +107,10 @@ public void reset(URL url) { logger.error(t.getMessage(), t); } try { - if (url.hasParameter(Constants.THREADS_KEY) + if (url.hasParameter(THREADS_KEY) && executor instanceof ThreadPoolExecutor && !executor.isShutdown()) { ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor; - int threads = url.getParameter(Constants.THREADS_KEY, 0); + int threads = url.getParameter(THREADS_KEY, 0); int max = threadPoolExecutor.getMaximumPoolSize(); int core = threadPoolExecutor.getCorePoolSize(); if (threads > 0 && (threads != max || threads != core)) { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java index f545a413d3f..bd41ca25ac2 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.transport.dispatcher; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; @@ -33,6 +32,9 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; +import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; + public class WrappedChannelHandler implements ChannelHandlerDelegate { protected static final Logger logger = LoggerFactory.getLogger(WrappedChannelHandler.class); @@ -51,8 +53,8 @@ public WrappedChannelHandler(ChannelHandler handler, URL url) { executor = (ExecutorService) ExtensionLoader.getExtensionLoader(ThreadPool.class).getAdaptiveExtension().getExecutor(url); String componentKey = RemotingConstants.EXECUTOR_SERVICE_COMPONENT_KEY; - if (Constants.CONSUMER_SIDE.equalsIgnoreCase(url.getParameter(Constants.SIDE_KEY))) { - componentKey = Constants.CONSUMER_SIDE; + if (CONSUMER_SIDE.equalsIgnoreCase(url.getParameter(SIDE_KEY))) { + componentKey = CONSUMER_SIDE; } DataStore dataStore = ExtensionLoader.getExtensionLoader(DataStore.class).getDefaultExtension(); dataStore.put(componentKey, Integer.toString(url.getPort()), executor); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java index 79465e68679..91310ef0f86 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.transport.dispatcher.connection; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport; @@ -37,6 +36,9 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREAD_NAME; + public class ConnectionOrderedChannelHandler extends WrappedChannelHandler { protected final ThreadPoolExecutor connectionExecutor; @@ -44,7 +46,7 @@ public class ConnectionOrderedChannelHandler extends WrappedChannelHandler { public ConnectionOrderedChannelHandler(ChannelHandler handler, URL url) { super(handler, url); - String threadName = url.getParameter(Constants.THREAD_NAME_KEY, Constants.DEFAULT_THREAD_NAME); + String threadName = url.getParameter(THREAD_NAME_KEY, DEFAULT_THREAD_NAME); connectionExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(url.getPositiveParameter(RemotingConstants.CONNECT_QUEUE_CAPACITY, Integer.MAX_VALUE)), diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/ChanelHandlerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/ChanelHandlerTest.java index 2d87e54ed1b..d4cd13a79c8 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/ChanelHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/ChanelHandlerTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -24,9 +23,11 @@ import org.apache.dubbo.remoting.exchange.Exchangers; import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerAdapter; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + /** * ChanelHandlerTest *

    @@ -82,7 +83,7 @@ public void testClient() throws Throwable { final String server = System.getProperty("server", "127.0.0.1:9911"); final String transporter = PerformanceUtils.getProperty(RemotingConstants.TRANSPORTER_KEY, RemotingConstants.DEFAULT_TRANSPORTER); final String serialization = PerformanceUtils.getProperty(RemotingConstants.SERIALIZATION_KEY, RemotingConstants.DEFAULT_REMOTING_SERIALIZATION); - final int timeout = PerformanceUtils.getIntProperty(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); + final int timeout = PerformanceUtils.getIntProperty(TIMEOUT_KEY, DEFAULT_TIMEOUT); int sleep = PerformanceUtils.getIntProperty("sleep", 60 * 1000 * 60); final String url = "exchange://" + server + "?transporter=" + transporter + "&serialization=" + serialization + "&timeout=" + timeout; diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientCloseTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientCloseTest.java index d92648ac7d8..46e1a10c016 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientCloseTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientCloseTest.java @@ -16,18 +16,19 @@ */ package org.apache.dubbo.remoting; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.remoting.exchange.Exchangers; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.concurrent.atomic.AtomicInteger; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + /** * ProformanceClient * The test class will report abnormal thread pool, because the judgment on the thread pool concurrency problems produced in DefaultChannelHandler (connected event has been executed asynchronously, judgment, then closed the thread pool, thread pool and execution error, this problem can be specified through the Constants.CHANNEL_HANDLER_KEY=connection.) @@ -46,7 +47,7 @@ public void testClient() throws Throwable { final String server = System.getProperty("server", "127.0.0.1:9911"); final String transporter = PerformanceUtils.getProperty(RemotingConstants.TRANSPORTER_KEY, RemotingConstants.DEFAULT_TRANSPORTER); final String serialization = PerformanceUtils.getProperty(RemotingConstants.SERIALIZATION_KEY, RemotingConstants.DEFAULT_REMOTING_SERIALIZATION); - final int timeout = PerformanceUtils.getIntProperty(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); + final int timeout = PerformanceUtils.getIntProperty(TIMEOUT_KEY, DEFAULT_TIMEOUT); final int concurrent = PerformanceUtils.getIntProperty("concurrent", 1); final int runs = PerformanceUtils.getIntProperty("runs", Integer.MAX_VALUE); final String onerror = PerformanceUtils.getProperty("onerror", "continue"); @@ -102,4 +103,4 @@ public void run() { } } -} \ No newline at end of file +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java index ae2aecc77be..d0bbfd7af8b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java @@ -23,12 +23,14 @@ import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.remoting.exchange.Exchangers; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Random; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + public class PerformanceClientFixedTest { private static final Logger logger = LoggerFactory.getLogger(PerformanceClientTest.class); @@ -43,7 +45,7 @@ public void testClient() throws Exception { final String server = System.getProperty("server", "127.0.0.1:9911"); final String transporter = PerformanceUtils.getProperty(RemotingConstants.TRANSPORTER_KEY, RemotingConstants.DEFAULT_TRANSPORTER); final String serialization = PerformanceUtils.getProperty(RemotingConstants.SERIALIZATION_KEY, RemotingConstants.DEFAULT_REMOTING_SERIALIZATION); - final int timeout = PerformanceUtils.getIntProperty(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); + final int timeout = PerformanceUtils.getIntProperty(TIMEOUT_KEY, DEFAULT_TIMEOUT); //final int length = PerformanceUtils.getIntProperty("length", 1024); final int connectionCount = PerformanceUtils.getIntProperty(Constants.CONNECTIONS_KEY, 1); //final int concurrent = PerformanceUtils.getIntProperty("concurrent", 100); @@ -134,4 +136,4 @@ public void testClient() throws Exception { } } -} \ No newline at end of file +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java index 43570b6c5a7..acf1353bb3a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java @@ -34,6 +34,9 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + /** * PerformanceClientTest *

    @@ -54,7 +57,7 @@ public void testClient() throws Throwable { final String server = System.getProperty("server", "127.0.0.1:9911"); final String transporter = PerformanceUtils.getProperty(RemotingConstants.TRANSPORTER_KEY, RemotingConstants.DEFAULT_TRANSPORTER); final String serialization = PerformanceUtils.getProperty(RemotingConstants.SERIALIZATION_KEY, RemotingConstants.DEFAULT_REMOTING_SERIALIZATION); - final int timeout = PerformanceUtils.getIntProperty(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); + final int timeout = PerformanceUtils.getIntProperty(TIMEOUT_KEY, DEFAULT_TIMEOUT); final int length = PerformanceUtils.getIntProperty("length", 1024); final int connections = PerformanceUtils.getIntProperty(Constants.CONNECTIONS_KEY, 1); final int concurrent = PerformanceUtils.getIntProperty("concurrent", 100); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.java index 580dbb3e980..04c9c673426 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -26,13 +25,18 @@ import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerAdapter; import org.apache.dubbo.remoting.transport.dispatcher.execution.ExecutionDispatcher; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; +import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADPOOL; +import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS; + /** * PerformanceServer *

    @@ -64,9 +68,9 @@ private static ExchangeServer statServer() throws Exception { final int port = PerformanceUtils.getIntProperty("port", 9911); final String transporter = PerformanceUtils.getProperty(RemotingConstants.TRANSPORTER_KEY, RemotingConstants.DEFAULT_TRANSPORTER); final String serialization = PerformanceUtils.getProperty(RemotingConstants.SERIALIZATION_KEY, RemotingConstants.DEFAULT_REMOTING_SERIALIZATION); - final String threadpool = PerformanceUtils.getProperty(Constants.THREADPOOL_KEY, Constants.DEFAULT_THREADPOOL); - final int threads = PerformanceUtils.getIntProperty(Constants.THREADS_KEY, Constants.DEFAULT_THREADS); - final int iothreads = PerformanceUtils.getIntProperty(Constants.IO_THREADS_KEY, RemotingConstants.DEFAULT_IO_THREADS); + final String threadpool = PerformanceUtils.getProperty(THREADPOOL_KEY, DEFAULT_THREADPOOL); + final int threads = PerformanceUtils.getIntProperty(THREADS_KEY, DEFAULT_THREADS); + final int iothreads = PerformanceUtils.getIntProperty(IO_THREADS_KEY, RemotingConstants.DEFAULT_IO_THREADS); final int buffer = PerformanceUtils.getIntProperty(RemotingConstants.BUFFER_KEY, RemotingConstants.DEFAULT_BUFFER_SIZE); final String channelHandler = PerformanceUtils.getProperty(RemotingConstants.DISPATCHER_KEY, ExecutionDispatcher.NAME); @@ -163,4 +167,4 @@ public void testServer() throws Exception { } } -} \ No newline at end of file +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java index 5b30d5cbabb..7342b9c233f 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java @@ -39,6 +39,8 @@ import java.util.LinkedList; import java.util.List; +import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; + public class DeprecatedTelnetCodec implements Codec { private static final Logger logger = LoggerFactory.getLogger(DeprecatedTelnetCodec.class); @@ -152,7 +154,7 @@ private static boolean endsWith(byte[] message, byte[] command) throws IOExcepti } protected boolean isClientSide(Channel channel) { - String side = (String) channel.getAttribute(Constants.SIDE_KEY); + String side = (String) channel.getAttribute(SIDE_KEY); if ("client".equals(side)) { return true; } else if ("server".equals(side)) { @@ -164,7 +166,7 @@ protected boolean isClientSide(Channel channel) { && NetUtils.filterLocalHost(url.getIp()).equals( NetUtils.filterLocalHost(address.getAddress() .getHostAddress())); - channel.setAttribute(Constants.SIDE_KEY, client ? "client" + channel.setAttribute(SIDE_KEY, client ? "client" : "server"); return client; } diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java index c1f8e2cb936..bb994e6ca70 100644 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java +++ b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java @@ -17,7 +17,6 @@ package org.apache.dubbo.remoting.etcd.jetcd; -import io.grpc.ManagedChannel; import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; @@ -39,6 +38,7 @@ import io.etcd.jetcd.api.WatchRequest; import io.etcd.jetcd.api.WatchResponse; import io.etcd.jetcd.common.exception.ClosedClientException; +import io.grpc.ManagedChannel; import io.grpc.Status; import io.grpc.stub.StreamObserver; import io.netty.util.internal.ConcurrentSet; @@ -60,6 +60,7 @@ import java.util.concurrent.locks.ReentrantLock; import static java.util.stream.Collectors.toList; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; import static org.apache.dubbo.remoting.etcd.Constants.DEFAULT_ETCD3_NOTIFY_QUEUES_KEY; import static org.apache.dubbo.remoting.etcd.Constants.DEFAULT_ETCD3_NOTIFY_THREADS; import static org.apache.dubbo.remoting.etcd.Constants.DEFAULT_GRPC_QUEUES; @@ -338,7 +339,7 @@ private String find(Event event) { int len = path.length(), index = len, count = 0; if (key.length() >= index) { - for (; (index = key.indexOf(Constants.PATH_SEPARATOR, index)) != -1; ++index) { + for (; (index = key.indexOf(PATH_SEPARATOR, index)) != -1; ++index) { if (count++ > 1) { break; } @@ -370,7 +371,7 @@ private List filterChildren(List children) { .filter(child -> { int index = len, count = 0; if (child.length() > len) { - for (; (index = child.indexOf(Constants.PATH_SEPARATOR, index)) != -1; ++index) { + for (; (index = child.indexOf(PATH_SEPARATOR, index)) != -1; ++index) { if (count++ > 1) { break; } diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapper.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapper.java index 01bf17d264d..7bfb12120d3 100644 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapper.java +++ b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapper.java @@ -17,7 +17,6 @@ package org.apache.dubbo.remoting.etcd.jetcd; -import io.etcd.jetcd.kv.PutResponse; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -37,6 +36,7 @@ import io.etcd.jetcd.common.exception.ErrorCode; import io.etcd.jetcd.common.exception.EtcdException; import io.etcd.jetcd.kv.GetResponse; +import io.etcd.jetcd.kv.PutResponse; import io.etcd.jetcd.lease.LeaseKeepAliveResponse; import io.etcd.jetcd.options.GetOption; import io.etcd.jetcd.options.PutOption; @@ -66,6 +66,8 @@ import java.util.function.Consumer; import static java.util.stream.Collectors.toList; +import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; public class JEtcdClientWrapper { @@ -185,7 +187,7 @@ public List getChildren(String path) { String key = pair.getKey().toString(UTF_8); int index = len, count = 0; if (key.length() > len) { - for (; (index = key.indexOf(Constants.PATH_SEPARATOR, index)) != -1; ++index) { + for (; (index = key.indexOf(PATH_SEPARATOR, index)) != -1; ++index) { if (count++ > 1) { break; } @@ -479,7 +481,7 @@ public void delete(String path) { } public String[] endPoints(String backupAddress) { - String[] endpoints = backupAddress.split(Constants.COMMA_SEPARATOR); + String[] endpoints = backupAddress.split(COMMA_SEPARATOR); List addresses = Arrays.stream(endpoints) .map(address -> address.contains(Constants.HTTP_SUBFIX_KEY) ? address diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/support/AbstractEtcdClient.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/support/AbstractEtcdClient.java index 0a6d26f90e9..cdc7ed5056d 100644 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/support/AbstractEtcdClient.java +++ b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/support/AbstractEtcdClient.java @@ -49,6 +49,8 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; + public abstract class AbstractEtcdClient implements EtcdClient { protected static final Logger logger = LoggerFactory.getLogger(AbstractEtcdClient.class); @@ -151,7 +153,7 @@ protected String fixNamespace(String path) { if (StringUtils.isEmpty(path)) { throw new IllegalArgumentException("path is required, actual null or ''"); } - return (path.charAt(0) != '/') ? (Constants.PATH_SEPARATOR + path) : path; + return (path.charAt(0) != '/') ? (PATH_SEPARATOR + path) : path; } protected void createParentIfAbsent(String fixedPath) { diff --git a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyChannel.java b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyChannel.java index 4732676a082..02caca61c93 100644 --- a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyChannel.java +++ b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyChannel.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.transport.grizzly; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -33,6 +32,9 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + /** * GrizzlyChannel * @@ -105,7 +107,7 @@ public void send(Object message, boolean sent) throws RemotingException { try { GrizzlyFuture future = connection.write(message); if (sent) { - timeout = getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); + timeout = getUrl().getPositiveParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT); future.get(timeout, TimeUnit.MILLISECONDS); } } catch (TimeoutException e) { diff --git a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyClient.java b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyClient.java index 2753d215262..e4a0e345d81 100644 --- a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyClient.java +++ b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyClient.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.transport.grizzly; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -35,6 +34,9 @@ import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + /** * GrizzlyClient * @@ -77,7 +79,7 @@ protected void doOpen() throws Throwable { @Override protected void doConnect() throws Throwable { connection = transport.connect(getConnectAddress()) - .get(getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT), TimeUnit.MILLISECONDS); + .get(getUrl().getPositiveParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT), TimeUnit.MILLISECONDS); } @Override @@ -107,4 +109,4 @@ protected Channel getChannel() { return GrizzlyChannel.getOrAddChannel(c, getUrl(), this); } -} \ No newline at end of file +} diff --git a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyServer.java b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyServer.java index 65a8726305a..38608603a50 100644 --- a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyServer.java +++ b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyServer.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.transport.grizzly; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -39,6 +38,11 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADPOOL; +import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS; + /** * GrizzlyServer */ @@ -64,13 +68,13 @@ protected void doOpen() throws Throwable { TCPNIOTransportBuilder builder = TCPNIOTransportBuilder.newInstance(); ThreadPoolConfig config = builder.getWorkerThreadPoolConfig(); config.setPoolName(SERVER_THREAD_POOL_NAME).setQueueLimit(-1); - String threadpool = getUrl().getParameter(Constants.THREADPOOL_KEY, Constants.DEFAULT_THREADPOOL); - if (Constants.DEFAULT_THREADPOOL.equals(threadpool)) { - int threads = getUrl().getPositiveParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS); + String threadpool = getUrl().getParameter(THREADPOOL_KEY, DEFAULT_THREADPOOL); + if (DEFAULT_THREADPOOL.equals(threadpool)) { + int threads = getUrl().getPositiveParameter(THREADS_KEY, DEFAULT_THREADS); config.setCorePoolSize(threads).setMaxPoolSize(threads) .setKeepAliveTime(0L, TimeUnit.SECONDS); } else if ("cached".equals(threadpool)) { - int threads = getUrl().getPositiveParameter(Constants.THREADS_KEY, Integer.MAX_VALUE); + int threads = getUrl().getPositiveParameter(THREADS_KEY, Integer.MAX_VALUE); config.setCorePoolSize(0).setMaxPoolSize(threads) .setKeepAliveTime(60L, TimeUnit.SECONDS); } else { diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpServer.java index 0274271b85b..77442e29dec 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpServer.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpServer.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.http.jetty; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; @@ -36,6 +35,9 @@ import org.eclipse.jetty.util.log.StdErrLog; import org.eclipse.jetty.util.thread.QueuedThreadPool; +import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS; + public class JettyHttpServer extends AbstractHttpServer { private static final Logger logger = LoggerFactory.getLogger(JettyHttpServer.class); @@ -54,7 +56,7 @@ public JettyHttpServer(URL url, final HttpHandler handler) { DispatcherServlet.addHttpHandler(url.getParameter(RemotingConstants.BIND_PORT_KEY, url.getPort()), handler); - int threads = url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS); + int threads = url.getParameter(THREADS_KEY, DEFAULT_THREADS); QueuedThreadPool threadPool = new QueuedThreadPool(); threadPool.setDaemon(true); threadPool.setMaxThreads(threads); diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java index 901d5880471..e59f8f6bd95 100755 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.http.tomcat; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; @@ -32,6 +31,9 @@ import java.io.File; +import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS; + public class TomcatHttpServer extends AbstractHttpServer { private static final Logger logger = LoggerFactory.getLogger(TomcatHttpServer.class); @@ -50,7 +52,7 @@ public TomcatHttpServer(URL url, final HttpHandler handler) { tomcat.setBaseDir(baseDir); tomcat.setPort(url.getPort()); tomcat.getConnector().setProperty( - "maxThreads", String.valueOf(url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS))); + "maxThreads", String.valueOf(url.getParameter(THREADS_KEY, DEFAULT_THREADS))); // tomcat.getConnector().setProperty( // "minSpareThreads", String.valueOf(url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS))); diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaChannel.java b/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaChannel.java index 093ce216940..7229cb16074 100644 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaChannel.java +++ b/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaChannel.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.transport.mina; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -29,6 +28,9 @@ import java.net.InetSocketAddress; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + /** * MinaChannel */ @@ -96,7 +98,7 @@ public void send(Object message, boolean sent) throws RemotingException { try { WriteFuture future = session.write(message); if (sent) { - timeout = getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); + timeout = getUrl().getPositiveParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT); success = future.join(timeout); } } catch (Throwable e) { diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaServer.java b/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaServer.java index 4937944eccb..2a6af51a874 100644 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaServer.java +++ b/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaServer.java @@ -16,9 +16,7 @@ */ package org.apache.dubbo.remoting.transport.mina; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ExecutorUtil; @@ -41,6 +39,9 @@ import java.util.Set; import java.util.concurrent.Executors; +import static org.apache.dubbo.common.Constants.DEFAULT_IO_THREADS; +import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY; + /** * MinaServer */ @@ -57,7 +58,7 @@ public MinaServer(URL url, ChannelHandler handler) throws RemotingException { @Override protected void doOpen() throws Throwable { // set thread pool. - acceptor = new SocketAcceptor(getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, RemotingConstants.DEFAULT_IO_THREADS), + acceptor = new SocketAcceptor(getUrl().getPositiveParameter(IO_THREADS_KEY, DEFAULT_IO_THREADS), Executors.newCachedThreadPool(new NamedThreadFactory("MinaServerWorker", true))); // config diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyChannel.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyChannel.java index f5e02131a36..45633b9e645 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyChannel.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyChannel.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.transport.netty; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -31,6 +30,9 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + /** * NettyChannel. */ @@ -99,7 +101,7 @@ public void send(Object message, boolean sent) throws RemotingException { try { ChannelFuture future = channel.write(message); if (sent) { - timeout = getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); + timeout = getUrl().getPositiveParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT); success = future.await(timeout); } Throwable cause = future.getCause(); diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyServer.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyServer.java index b25461e0f14..9e782ccfbea 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyServer.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyServer.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.transport.netty; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; @@ -46,6 +45,8 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY; + /** * NettyServer */ @@ -68,7 +69,7 @@ protected void doOpen() throws Throwable { NettyHelper.setNettyLoggerFactory(); ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerBoss", true)); ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true)); - ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, RemotingConstants.DEFAULT_IO_THREADS)); + ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(IO_THREADS_KEY, RemotingConstants.DEFAULT_IO_THREADS)); bootstrap = new ServerBootstrap(channelFactory); final NettyHandler nettyHandler = new NettyHandler(getUrl(), this); diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java index 21bf2419487..b4202e1a219 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.transport.netty4; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -32,6 +31,9 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + /** * NettyChannel. */ @@ -100,7 +102,7 @@ public void send(Object message, boolean sent) throws RemotingException { try { ChannelFuture future = channel.writeAndFlush(message); if (sent) { - timeout = getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); + timeout = getUrl().getPositiveParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT); success = future.await(timeout); } Throwable cause = future.cause(); diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java index ad952a75ce1..6bc5f895731 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.transport.netty4; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; @@ -49,6 +48,7 @@ import java.util.Map; import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY; /** * NettyServer @@ -75,7 +75,7 @@ protected void doOpen() throws Throwable { bootstrap = new ServerBootstrap(); bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss", true)); - workerGroup = new NioEventLoopGroup(getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, RemotingConstants.DEFAULT_IO_THREADS), + workerGroup = new NioEventLoopGroup(getUrl().getPositiveParameter(IO_THREADS_KEY, RemotingConstants.DEFAULT_IO_THREADS), new DefaultThreadFactory("NettyServerWorker", true)); final NettyServerHandler nettyServerHandler = new NettyServerHandler(getUrl(), this); diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java index a97eb7e5f22..e3a06e59980 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.zookeeper.curator; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.zookeeper.ChildListener; @@ -46,6 +45,8 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + public class CuratorZookeeperClient extends AbstractZookeeperClient { static final Charset CHARSET = Charset.forName("UTF-8"); @@ -56,7 +57,7 @@ public class CuratorZookeeperClient extends AbstractZookeeperClient @@ -136,8 +137,8 @@ void writeToClientMap(List addressList, ZookeeperClient zookeeperClient) URL toClientURL(URL url) { Map parameterMap = new HashMap<>(); // for CuratorZookeeperClient - if (url.getParameter(Constants.TIMEOUT_KEY) != null) { - parameterMap.put(Constants.TIMEOUT_KEY, url.getParameter(Constants.TIMEOUT_KEY)); + if (url.getParameter(TIMEOUT_KEY) != null) { + parameterMap.put(TIMEOUT_KEY, url.getParameter(TIMEOUT_KEY)); } if (url.getParameter(RemotingConstants.BACKUP_KEY) != null) { parameterMap.put(RemotingConstants.BACKUP_KEY, url.getParameter(RemotingConstants.BACKUP_KEY)); diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/support/AbstractZookeeperTransporterTest.java b/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/support/AbstractZookeeperTransporterTest.java index eb6965a0c65..a1644a359e5 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/support/AbstractZookeeperTransporterTest.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/support/AbstractZookeeperTransporterTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.zookeeper.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.zookeeper.ZookeeperClient; @@ -31,6 +30,7 @@ import java.util.List; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.IsNull.nullValue; @@ -74,7 +74,7 @@ public void testCreateServerURL() { Assertions.assertEquals(newUrl.getPort(), zkServerPort); Assertions.assertNull(newUrl.getUsername()); Assertions.assertNull(newUrl.getPassword()); - Assertions.assertEquals(newUrl.getParameter(Constants.TIMEOUT_KEY, 5000), 2300); + Assertions.assertEquals(newUrl.getParameter(TIMEOUT_KEY, 5000), 2300); Assertions.assertEquals(newUrl.getParameters().size(), 1); Assertions.assertEquals(newUrl.getPath(), ZookeeperTransporter.class.getName()); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java index fa63b7e4c1a..3378e198877 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java @@ -36,6 +36,10 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; +import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; + /** * Thread local context. (API, ThreadLocal, ThreadSafe) @@ -235,7 +239,7 @@ public boolean isProviderSide() { * @return consumer side. */ public boolean isConsumerSide() { - return getUrl().getParameter(Constants.SIDE_KEY, Constants.PROVIDER_SIDE).equals(Constants.CONSUMER_SIDE); + return getUrl().getParameter(SIDE_KEY, PROVIDER_SIDE).equals(CONSUMER_SIDE); } /** diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.java index 707bf3b77ad..7688705c352 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.java @@ -26,6 +26,13 @@ import java.util.HashMap; import java.util.Map; +import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; + /** * RPC Invocation. * @@ -54,24 +61,24 @@ public RpcInvocation(Invocation invocation, Invoker invoker) { invocation.getInvoker()); if (invoker != null) { URL url = invoker.getUrl(); - setAttachment(Constants.PATH_KEY, url.getPath()); - if (url.hasParameter(Constants.INTERFACE_KEY)) { - setAttachment(Constants.INTERFACE_KEY, url.getParameter(Constants.INTERFACE_KEY)); + setAttachment(PATH_KEY, url.getPath()); + if (url.hasParameter(INTERFACE_KEY)) { + setAttachment(INTERFACE_KEY, url.getParameter(INTERFACE_KEY)); } - if (url.hasParameter(Constants.GROUP_KEY)) { - setAttachment(Constants.GROUP_KEY, url.getParameter(Constants.GROUP_KEY)); + if (url.hasParameter(GROUP_KEY)) { + setAttachment(GROUP_KEY, url.getParameter(GROUP_KEY)); } - if (url.hasParameter(Constants.VERSION_KEY)) { - setAttachment(Constants.VERSION_KEY, url.getParameter(Constants.VERSION_KEY, "0.0.0")); + if (url.hasParameter(VERSION_KEY)) { + setAttachment(VERSION_KEY, url.getParameter(VERSION_KEY, "0.0.0")); } - if (url.hasParameter(Constants.TIMEOUT_KEY)) { - setAttachment(Constants.TIMEOUT_KEY, url.getParameter(Constants.TIMEOUT_KEY)); + if (url.hasParameter(TIMEOUT_KEY)) { + setAttachment(TIMEOUT_KEY, url.getParameter(TIMEOUT_KEY)); } if (url.hasParameter(Constants.TOKEN_KEY)) { setAttachment(Constants.TOKEN_KEY, url.getParameter(Constants.TOKEN_KEY)); } - if (url.hasParameter(Constants.APPLICATION_KEY)) { - setAttachment(Constants.APPLICATION_KEY, url.getParameter(Constants.APPLICATION_KEY)); + if (url.hasParameter(APPLICATION_KEY)) { + setAttachment(APPLICATION_KEY, url.getParameter(APPLICATION_KEY)); } } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java index 23fa1ea52cb..0990daf2ebc 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java @@ -45,6 +45,10 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; + /** * Record access log for the service. *

    @@ -59,7 +63,7 @@ * </logger> * */ -@Activate(group = Constants.PROVIDER, value = Constants.ACCESS_LOG_KEY) +@Activate(group = PROVIDER, value = Constants.ACCESS_LOG_KEY) public class AccessLogFilter implements Filter { private static final Logger logger = LoggerFactory.getLogger(AccessLogFilter.class); @@ -162,8 +166,8 @@ private AccessLogData buildAccessLogData(Invoker invoker, Invocation inv) { AccessLogData logData = AccessLogData.newLogData(); logData.setServiceName(invoker.getInterface().getName()); logData.setMethodName(inv.getMethodName()); - logData.setVersion(invoker.getUrl().getParameter(Constants.VERSION_KEY)); - logData.setGroup(invoker.getUrl().getParameter(Constants.GROUP_KEY)); + logData.setVersion(invoker.getUrl().getParameter(VERSION_KEY)); + logData.setGroup(invoker.getUrl().getParameter(GROUP_KEY)); logData.setInvocationTime(new Date()); logData.setTypes(inv.getParameterTypes()); logData.setArguments(inv.getArguments()); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java index 926fd019425..143544bbf50 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java @@ -26,6 +26,9 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcStatus; +import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + /** * ActiveLimitFilter restrict the concurrent client invocation for a service or service's method from client side. * To use active limit filter, configured url with actives and provide valid >0 integer value. @@ -38,7 +41,7 @@ * * @see Filter */ -@Activate(group = Constants.CONSUMER, value = Constants.ACTIVES_KEY) +@Activate(group = CONSUMER, value = Constants.ACTIVES_KEY) public class ActiveLimitFilter implements Filter { @Override @@ -48,7 +51,7 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept int max = invoker.getUrl().getMethodParameter(methodName, Constants.ACTIVES_KEY, 0); RpcStatus count = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName()); if (!RpcStatus.beginCount(url, methodName, max)) { - long timeout = invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.TIMEOUT_KEY, 0); + long timeout = invoker.getUrl().getMethodParameter(invocation.getMethodName(), TIMEOUT_KEY, 0); long start = System.currentTimeMillis(); long remain = timeout; synchronized (count) { diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ClassLoaderFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ClassLoaderFilter.java index 17d265ef6bb..62ba78598ba 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ClassLoaderFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ClassLoaderFilter.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.rpc.filter; -import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; @@ -27,7 +27,7 @@ /** * Set the current execution thread class loader to service interface's class loader. */ -@Activate(group = Constants.PROVIDER, order = -30000) +@Activate(group = CommonConstants.PROVIDER, order = -30000) public class ClassLoaderFilter implements Filter { @Override diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ConsumerContextFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ConsumerContextFilter.java index 5db6b889d35..f1696f4a077 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ConsumerContextFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ConsumerContextFilter.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.rpc.filter; -import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.Filter; @@ -34,7 +34,7 @@ * @see org.apache.dubbo.rpc.Filter * @see RpcContext */ -@Activate(group = Constants.CONSUMER, order = -10000) +@Activate(group = CommonConstants.CONSUMER, order = -10000) public class ConsumerContextFilter implements Filter { @Override diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java index fe85da0386a..1fcb52c929e 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java @@ -29,7 +29,14 @@ import java.util.HashMap; import java.util.Map; -import static org.apache.dubbo.common.Constants.REMOTE_APPLICATION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; +import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_APPLICATION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; + /** * ContextFilter set the provider RpcContext with invoker, invocation, local port it is using and host for @@ -37,7 +44,7 @@ * * @see RpcContext */ -@Activate(group = Constants.PROVIDER, order = -10000) +@Activate(group = PROVIDER, order = -10000) public class ContextFilter implements Filter { @Override @@ -45,13 +52,13 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept Map attachments = invocation.getAttachments(); if (attachments != null) { attachments = new HashMap<>(attachments); - attachments.remove(Constants.PATH_KEY); - attachments.remove(Constants.INTERFACE_KEY); - attachments.remove(Constants.GROUP_KEY); - attachments.remove(Constants.VERSION_KEY); + attachments.remove(PATH_KEY); + attachments.remove(INTERFACE_KEY); + attachments.remove(GROUP_KEY); + attachments.remove(VERSION_KEY); attachments.remove(Constants.DUBBO_VERSION_KEY); attachments.remove(Constants.TOKEN_KEY); - attachments.remove(Constants.TIMEOUT_KEY); + attachments.remove(TIMEOUT_KEY); // Remove async property to avoid being passed to the following invoke chain. attachments.remove(Constants.ASYNC_KEY); attachments.remove(Constants.TAG_KEY); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java index 95803cbd1a7..c373e79eb4d 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java @@ -17,6 +17,7 @@ package org.apache.dubbo.rpc.filter; import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -35,7 +36,7 @@ * * @see Filter */ -@Activate(group = Constants.CONSUMER, value = Constants.DEPRECATED_KEY) +@Activate(group = CommonConstants.CONSUMER, value = Constants.DEPRECATED_KEY) public class DeprecatedFilter implements Filter { private static final Logger LOGGER = LoggerFactory.getLogger(DeprecatedFilter.class); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/EchoFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/EchoFilter.java index cba9e7f4f46..9df24c4cd07 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/EchoFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/EchoFilter.java @@ -17,6 +17,7 @@ package org.apache.dubbo.rpc.filter; import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; @@ -28,7 +29,7 @@ /** * Dubbo provided default Echo echo service, which is available for all dubbo provider service interface. */ -@Activate(group = Constants.PROVIDER, order = -110000) +@Activate(group = CommonConstants.PROVIDER, order = -110000) public class EchoFilter implements Filter { @Override diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExceptionFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExceptionFilter.java index 7715348f827..bc4018513fc 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExceptionFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExceptionFilter.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.rpc.filter; -import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -44,7 +44,7 @@ *

  • Wrap the exception not introduced in API package into RuntimeException. Framework will serialize the outer exception but stringnize its cause in order to avoid of possible serialization problem on client side
  • * */ -@Activate(group = Constants.PROVIDER) +@Activate(group = CommonConstants.PROVIDER) public class ExceptionFilter implements Filter { private final Logger logger; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java index b335a4141ff..42298e7c9ea 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; @@ -32,7 +33,7 @@ * continue the same behaviour un till it is <10. * */ -@Activate(group = Constants.PROVIDER, value = Constants.EXECUTES_KEY) +@Activate(group = CommonConstants.PROVIDER, value = Constants.EXECUTES_KEY) public class ExecuteLimitFilter implements Filter { @Override diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java index fdbfdef275e..be629a5a540 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java @@ -20,6 +20,7 @@ import org.apache.dubbo.common.beanutil.JavaBeanAccessor; import org.apache.dubbo.common.beanutil.JavaBeanDescriptor; import org.apache.dubbo.common.beanutil.JavaBeanSerializeUtil; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.io.UnsafeByteArrayInputStream; @@ -46,7 +47,7 @@ /** * GenericInvokerFilter. */ -@Activate(group = Constants.PROVIDER, order = -20000) +@Activate(group = CommonConstants.PROVIDER, order = -20000) public class GenericFilter implements Filter { @Override diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java index 6df1262fbef..8c23043c3fe 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java @@ -20,6 +20,7 @@ import org.apache.dubbo.common.beanutil.JavaBeanAccessor; import org.apache.dubbo.common.beanutil.JavaBeanDescriptor; import org.apache.dubbo.common.beanutil.JavaBeanSerializeUtil; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -42,7 +43,7 @@ /** * GenericImplInvokerFilter */ -@Activate(group = Constants.CONSUMER, value = Constants.GENERIC_KEY, order = 20000) +@Activate(group = CommonConstants.CONSUMER, value = Constants.GENERIC_KEY, order = 20000) public class GenericImplFilter implements Filter { private static final Logger logger = LoggerFactory.getLogger(GenericImplFilter.class); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TimeoutFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TimeoutFilter.java index c00689fc1c8..d0f7b572497 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TimeoutFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TimeoutFilter.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.rpc.filter; -import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -32,7 +32,7 @@ /** * Log any invocation timeout, but don't stop server from running */ -@Activate(group = Constants.PROVIDER) +@Activate(group = CommonConstants.PROVIDER) public class TimeoutFilter implements Filter { private static final Logger logger = LoggerFactory.getLogger(TimeoutFilter.class); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TokenFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TokenFilter.java index 35ef2aca526..7ac23b0b226 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TokenFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TokenFilter.java @@ -17,6 +17,7 @@ package org.apache.dubbo.rpc.filter; import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.rpc.Filter; @@ -34,7 +35,7 @@ * * @see Filter */ -@Activate(group = Constants.PROVIDER, value = Constants.TOKEN_KEY) +@Activate(group = CommonConstants.PROVIDER, value = Constants.TOKEN_KEY) public class TokenFilter implements Filter { @Override diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TpsLimitFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TpsLimitFilter.java index 5ce78d141ee..bf05dad3524 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TpsLimitFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TpsLimitFilter.java @@ -18,6 +18,7 @@ package org.apache.dubbo.rpc.filter; import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; @@ -34,7 +35,7 @@ * if invocation count exceed the configured tps value (default is -1 which means unlimited) then invocation will get * RpcException. * */ -@Activate(group = Constants.PROVIDER, value = Constants.TPS_LIMIT_RATE_KEY) +@Activate(group = CommonConstants.PROVIDER, value = Constants.TPS_LIMIT_RATE_KEY) public class TpsLimitFilter implements Filter { private final TPSLimiter tpsLimiter = new DefaultTPSLimiter(); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java index afac729e266..5c1b780dc5c 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; @@ -32,6 +31,9 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; + /** * abstract ProtocolSupport. */ @@ -46,8 +48,7 @@ public abstract class AbstractProtocol implements Protocol { protected static String serviceKey(URL url) { int port = url.getParameter(RemotingConstants.BIND_PORT_KEY, url.getPort()); - return serviceKey(port, url.getPath(), url.getParameter(Constants.VERSION_KEY), - url.getParameter(Constants.GROUP_KEY)); + return serviceKey(port, url.getPath(), url.getParameter(VERSION_KEY), url.getParameter(GROUP_KEY)); } protected static String serviceKey(int port, String serviceName, String serviceVersion, String serviceGroup) { diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java index ef9ab321cb4..dafbd328516 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java @@ -17,7 +17,6 @@ package org.apache.dubbo.rpc.protocol; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.NetUtils; @@ -32,6 +31,9 @@ import java.util.Objects; import java.util.concurrent.CopyOnWriteArrayList; +import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; + /** * AbstractProxyProtocol */ @@ -132,8 +134,8 @@ protected RpcException getRpcException(Class type, URL url, Invocation invoca protected String getAddr(URL url) { String bindIp = url.getParameter(RemotingConstants.BIND_IP_KEY, url.getHost()); - if (url.getParameter(Constants.ANYHOST_KEY, false)) { - bindIp = Constants.ANYHOST_VALUE; + if (url.getParameter(ANYHOST_KEY, false)) { + bindIp = ANYHOST_VALUE; } return NetUtils.getIpByHost(bindIp) + ":" + url.getParameter(RemotingConstants.BIND_PORT_KEY, url.getPort()); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolFilterWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolFilterWrapper.java index c5ed5943cd0..766971c4ebe 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolFilterWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolFilterWrapper.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Exporter; @@ -105,7 +106,7 @@ public Exporter export(Invoker invoker) throws RpcException { if (Constants.REGISTRY_PROTOCOL.equals(invoker.getUrl().getProtocol())) { return protocol.export(invoker); } - return protocol.export(buildInvokerChain(invoker, Constants.SERVICE_FILTER_KEY, Constants.PROVIDER)); + return protocol.export(buildInvokerChain(invoker, Constants.SERVICE_FILTER_KEY, CommonConstants.PROVIDER)); } @Override @@ -113,7 +114,7 @@ public Invoker refer(Class type, URL url) throws RpcException { if (Constants.REGISTRY_PROTOCOL.equals(url.getProtocol())) { return protocol.refer(type, url); } - return buildInvokerChain(protocol.refer(type, url), Constants.REFERENCE_FILTER_KEY, Constants.CONSUMER); + return buildInvokerChain(protocol.refer(type, url), Constants.REFERENCE_FILTER_KEY, CommonConstants.CONSUMER); } @Override diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.java index c46aada701d..b2d48916fb8 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.java @@ -25,6 +25,8 @@ import com.alibaba.dubbo.rpc.service.EchoService; +import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; + /** * AbstractProxyFactory */ @@ -40,7 +42,7 @@ public T getProxy(Invoker invoker, boolean generic) throws RpcException { Class[] interfaces = null; String config = invoker.getUrl().getParameter(Constants.INTERFACES); if (config != null && config.length() > 0) { - String[] types = Constants.COMMA_SPLIT_PATTERN.split(config); + String[] types = COMMA_SPLIT_PATTERN.split(config); if (types != null && types.length > 0) { interfaces = new Class[types.length + 2]; interfaces[0] = invoker.getInterface(); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/ProtocolUtils.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/ProtocolUtils.java index a64717c26c4..75b77f81857 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/ProtocolUtils.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/ProtocolUtils.java @@ -20,14 +20,17 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; + public class ProtocolUtils { private ProtocolUtils() { } public static String serviceKey(URL url) { - return serviceKey(url.getPort(), url.getPath(), url.getParameter(Constants.VERSION_KEY), - url.getParameter(Constants.GROUP_KEY)); + return serviceKey(url.getPort(), url.getPath(), url.getParameter(VERSION_KEY), + url.getParameter(GROUP_KEY)); } public static String serviceKey(int port, String serviceName, String serviceVersion, String serviceGroup) { diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiterTest.java index 7852e42e8dc..cd1e9be3d23 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiterTest.java @@ -20,14 +20,12 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.support.MockInvocation; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -/** - * @author: lizhen - * @since: 2019-03-19 - * @description: - */ +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; + public class DefaultTPSLimiterTest { private DefaultTPSLimiter defaultTPSLimiter = new DefaultTPSLimiter(); @@ -36,7 +34,7 @@ public class DefaultTPSLimiterTest { public void testIsAllowable() throws Exception { Invocation invocation = new MockInvocation(); URL url = URL.valueOf("test://test"); - url = url.addParameter(Constants.INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService"); + url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService"); url = url.addParameter(Constants.TPS_LIMIT_RATE_KEY, 2); url = url.addParameter(Constants.TPS_LIMIT_INTERVAL_KEY, 1000); for (int i = 0; i < 3; i++) { @@ -48,7 +46,7 @@ public void testIsAllowable() throws Exception { public void testIsNotAllowable() throws Exception { Invocation invocation = new MockInvocation(); URL url = URL.valueOf("test://test"); - url = url.addParameter(Constants.INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService"); + url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService"); url = url.addParameter(Constants.TPS_LIMIT_RATE_KEY, 2); url = url.addParameter(Constants.TPS_LIMIT_INTERVAL_KEY, 1000); for (int i = 0; i < 4; i++) { @@ -65,7 +63,7 @@ public void testIsNotAllowable() throws Exception { public void testConfigChange() throws Exception { Invocation invocation = new MockInvocation(); URL url = URL.valueOf("test://test"); - url = url.addParameter(Constants.INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService"); + url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService"); url = url.addParameter(Constants.TPS_LIMIT_RATE_KEY, 2); url = url.addParameter(Constants.TPS_LIMIT_INTERVAL_KEY, 1000); for (int i = 0; i < 3; i++) { diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/TpsLimitFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/TpsLimitFilterTest.java index 235eeddd6e2..44662241721 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/TpsLimitFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/TpsLimitFilterTest.java @@ -28,6 +28,7 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.junit.jupiter.api.Assertions.assertTrue; public class TpsLimitFilterTest { @@ -37,8 +38,7 @@ public class TpsLimitFilterTest { @Test public void testWithoutCount() throws Exception { URL url = URL.valueOf("test://test"); - url = url.addParameter(Constants.INTERFACE_KEY, - "org.apache.dubbo.rpc.file.TpsService"); + url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService"); url = url.addParameter(Constants.TPS_LIMIT_RATE_KEY, 5); Invoker invoker = new MyInvoker(url); Invocation invocation = new MockInvocation(); @@ -49,8 +49,7 @@ public void testWithoutCount() throws Exception { public void testFail() throws Exception { Assertions.assertThrows(RpcException.class, () -> { URL url = URL.valueOf("test://test"); - url = url.addParameter(Constants.INTERFACE_KEY, - "org.apache.dubbo.rpc.file.TpsService"); + url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService"); url = url.addParameter(Constants.TPS_LIMIT_RATE_KEY, 5); Invoker invoker = new MyInvoker(url); Invocation invocation = new MockInvocation(); @@ -65,4 +64,4 @@ public void testFail() throws Exception { }); } -} \ No newline at end of file +} diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java index 5b7261de7b4..b017ed6ea8a 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java @@ -23,6 +23,11 @@ import java.util.HashMap; import java.util.Map; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; + /** * MockInvocation.java */ @@ -42,12 +47,12 @@ public Object[] getArguments() { public Map getAttachments() { Map attachments = new HashMap(); - attachments.put(Constants.PATH_KEY, "dubbo"); - attachments.put(Constants.GROUP_KEY, "dubbo"); - attachments.put(Constants.VERSION_KEY, "1.0.0"); + attachments.put(PATH_KEY, "dubbo"); + attachments.put(GROUP_KEY, "dubbo"); + attachments.put(VERSION_KEY, "1.0.0"); attachments.put(Constants.DUBBO_VERSION_KEY, "1.0.0"); attachments.put(Constants.TOKEN_KEY, "sfag"); - attachments.put(Constants.TIMEOUT_KEY, "1000"); + attachments.put(TIMEOUT_KEY, "1000"); return attachments; } @@ -63,4 +68,4 @@ public String getAttachment(String key, String defaultValue) { return getAttachments().get(key); } -} \ No newline at end of file +} diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java index 5eb4dd9205f..dadd4a43eae 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java @@ -37,6 +37,11 @@ import java.util.Map; import java.util.Set; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; + /** * callback service helper */ @@ -85,17 +90,17 @@ private static String exportOrUnexportCallbackService(Channel channel, URL url, params.put(Constants.IS_SERVER_KEY, Boolean.FALSE.toString()); // mark it's a callback, for troubleshooting params.put(Constants.IS_CALLBACK_SERVICE, Boolean.TRUE.toString()); - String group = (url == null ? null : url.getParameter(Constants.GROUP_KEY)); + String group = (url == null ? null : url.getParameter(GROUP_KEY)); if (group != null && group.length() > 0) { - params.put(Constants.GROUP_KEY, group); + params.put(GROUP_KEY, group); } // add method, for verifying against method, automatic fallback (see dubbo protocol) - params.put(Constants.METHODS_KEY, StringUtils.join(Wrapper.getWrapper(clazz).getDeclaredMethodNames(), ",")); + params.put(METHODS_KEY, StringUtils.join(Wrapper.getWrapper(clazz).getDeclaredMethodNames(), ",")); Map tmpMap = new HashMap<>(url.getParameters()); tmpMap.putAll(params); - tmpMap.remove(Constants.VERSION_KEY);// doesn't need to distinguish version for callback - tmpMap.put(Constants.INTERFACE_KEY, clazz.getName()); + tmpMap.remove(VERSION_KEY);// doesn't need to distinguish version for callback + tmpMap.put(INTERFACE_KEY, clazz.getName()); URL exportUrl = new URL(DubboProtocol.NAME, channel.getLocalAddress().getAddress().getHostAddress(), channel.getLocalAddress().getPort(), clazz.getName() + "." + instid, tmpMap); // no need to generate multiple exporters for different channel in the same JVM, cache key cannot collide. @@ -139,8 +144,8 @@ private static Object referOrDestroyCallbackService(Channel channel, URL url, Cl String countkey = getServerSideCountKey(channel, clazz.getName()); if (isRefer) { if (proxy == null) { - URL referurl = URL.valueOf("callback://" + url.getAddress() + "/" + clazz.getName() + "?" + Constants.INTERFACE_KEY + "=" + clazz.getName()); - referurl = referurl.addParametersIfAbsent(url.getParameters()).removeParameter(Constants.METHODS_KEY); + URL referurl = URL.valueOf("callback://" + url.getAddress() + "/" + clazz.getName() + "?" + INTERFACE_KEY + "=" + clazz.getName()); + referurl = referurl.addParametersIfAbsent(url.getParameters()).removeParameter(METHODS_KEY); if (!isInstancesOverLimit(channel, referurl, clazz.getName(), instid, true)) { @SuppressWarnings("rawtypes") Invoker invoker = new ChannelWrappedInvoker(clazz, channel, referurl, String.valueOf(instid)); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java index 14c76446143..02fc3d9a14c 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java @@ -35,6 +35,11 @@ import java.net.InetSocketAddress; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + /** * Wrap the existing invoker on the channel. */ @@ -45,7 +50,7 @@ class ChannelWrappedInvoker extends AbstractInvoker { private final ExchangeClient currentClient; ChannelWrappedInvoker(Class serviceType, Channel channel, URL url, String serviceKey) { - super(serviceType, url, new String[]{Constants.GROUP_KEY, Constants.TOKEN_KEY, Constants.TIMEOUT_KEY}); + super(serviceType, url, new String[]{GROUP_KEY, Constants.TOKEN_KEY, TIMEOUT_KEY}); this.channel = channel; this.serviceKey = serviceKey; this.currentClient = new HeaderExchangeClient(new ChannelWrapper(this.channel), false); @@ -55,7 +60,7 @@ class ChannelWrappedInvoker extends AbstractInvoker { protected Result doInvoke(Invocation invocation) throws Throwable { RpcInvocation inv = (RpcInvocation) invocation; // use interface's name as service path to export if it's not found on client side - inv.setAttachment(Constants.PATH_KEY, getInterface().getName()); + inv.setAttachment(PATH_KEY, getInterface().getName()); inv.setAttachment(Constants.CALLBACK_SERVICE_KEY, serviceKey); try { @@ -63,7 +68,7 @@ protected Result doInvoke(Invocation invocation) throws Throwable { currentClient.send(inv, getUrl().getMethodParameter(invocation.getMethodName(), RemotingConstants.SENT_KEY, false)); return new RpcResult(); } - int timeout = getUrl().getMethodParameter(invocation.getMethodName(), Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); + int timeout = getUrl().getMethodParameter(invocation.getMethodName(), TIMEOUT_KEY, DEFAULT_TIMEOUT); if (timeout > 0) { return (Result) currentClient.request(inv, timeout).get(); } else { diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java index fdf541b35d8..9f3a367c8b5 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java @@ -37,6 +37,8 @@ import java.util.HashMap; import java.util.Map; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.CallbackServiceCodec.decodeInvocationArgument; public class DecodeableRpcInvocation extends RpcInvocation implements Codec, Decodeable { @@ -94,8 +96,8 @@ public Object decode(Channel channel, InputStream input) throws IOException { request.setVersion(dubboVersion); setAttachment(Constants.DUBBO_VERSION_KEY, dubboVersion); - setAttachment(Constants.PATH_KEY, in.readUTF()); - setAttachment(Constants.VERSION_KEY, in.readUTF()); + setAttachment(PATH_KEY, in.readUTF()); + setAttachment(VERSION_KEY, in.readUTF()); setMethodName(in.readUTF()); try { diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java index bc8c7470184..1685f06fbc5 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java @@ -39,6 +39,8 @@ import java.io.IOException; import java.io.InputStream; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.CallbackServiceCodec.encodeInvocationArgument; /** @@ -175,8 +177,8 @@ protected void encodeRequestData(Channel channel, ObjectOutput out, Object data, RpcInvocation inv = (RpcInvocation) data; out.writeUTF(version); - out.writeUTF(inv.getAttachment(Constants.PATH_KEY)); - out.writeUTF(inv.getAttachment(Constants.VERSION_KEY)); + out.writeUTF(inv.getAttachment(PATH_KEY)); + out.writeUTF(inv.getAttachment(VERSION_KEY)); out.writeUTF(inv.getMethodName()); out.writeUTF(ReflectUtils.getDesc(inv.getParameterTypes())); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java index 0bddaf16384..823c5610788 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java @@ -40,6 +40,13 @@ import java.util.Set; import java.util.concurrent.locks.ReentrantLock; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; + /** * DubboInvoker */ @@ -60,10 +67,10 @@ public DubboInvoker(Class serviceType, URL url, ExchangeClient[] clients) { } public DubboInvoker(Class serviceType, URL url, ExchangeClient[] clients, Set> invokers) { - super(serviceType, url, new String[]{Constants.INTERFACE_KEY, Constants.GROUP_KEY, Constants.TOKEN_KEY, Constants.TIMEOUT_KEY}); + super(serviceType, url, new String[]{INTERFACE_KEY, GROUP_KEY, Constants.TOKEN_KEY, TIMEOUT_KEY}); this.clients = clients; // get version. - this.version = url.getParameter(Constants.VERSION_KEY, "0.0.0"); + this.version = url.getParameter(VERSION_KEY, "0.0.0"); this.invokers = invokers; } @@ -71,8 +78,8 @@ public DubboInvoker(Class serviceType, URL url, ExchangeClient[] clients, Set protected Result doInvoke(final Invocation invocation) throws Throwable { RpcInvocation inv = (RpcInvocation) invocation; final String methodName = RpcUtils.getMethodName(invocation); - inv.setAttachment(Constants.PATH_KEY, getUrl().getPath()); - inv.setAttachment(Constants.VERSION_KEY, version); + inv.setAttachment(PATH_KEY, getUrl().getPath()); + inv.setAttachment(VERSION_KEY, version); ExchangeClient currentClient; if (clients.length == 1) { @@ -84,7 +91,7 @@ protected Result doInvoke(final Invocation invocation) throws Throwable { boolean isAsync = RpcUtils.isAsync(getUrl(), invocation); boolean isAsyncFuture = RpcUtils.isReturnTypeFuture(inv); boolean isOneway = RpcUtils.isOneway(getUrl(), invocation); - int timeout = getUrl().getMethodParameter(methodName, Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); + int timeout = getUrl().getMethodParameter(methodName, TIMEOUT_KEY, DEFAULT_TIMEOUT); if (isOneway) { boolean isSent = getUrl().getMethodParameter(methodName, RemotingConstants.SENT_KEY, false); currentClient.send(inv, isSent); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java index 9d881d08f0e..52c64c3aedd 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java @@ -61,6 +61,11 @@ import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; + /** * dubbo protocol support. */ @@ -177,10 +182,10 @@ private Invocation createInvocation(Channel channel, URL url, String methodKey) } RpcInvocation invocation = new RpcInvocation(method, new Class[0], new Object[0]); - invocation.setAttachment(Constants.PATH_KEY, url.getPath()); - invocation.setAttachment(Constants.GROUP_KEY, url.getParameter(Constants.GROUP_KEY)); - invocation.setAttachment(Constants.INTERFACE_KEY, url.getParameter(Constants.INTERFACE_KEY)); - invocation.setAttachment(Constants.VERSION_KEY, url.getParameter(Constants.VERSION_KEY)); + invocation.setAttachment(PATH_KEY, url.getPath()); + invocation.setAttachment(GROUP_KEY, url.getParameter(GROUP_KEY)); + invocation.setAttachment(INTERFACE_KEY, url.getParameter(INTERFACE_KEY)); + invocation.setAttachment(VERSION_KEY, url.getParameter(VERSION_KEY)); if (url.getParameter(Constants.STUB_EVENT_KEY, false)) { invocation.setAttachment(Constants.STUB_EVENT_KEY, Boolean.TRUE.toString()); } @@ -226,7 +231,7 @@ Invoker getInvoker(Channel channel, Invocation inv) throws RemotingException boolean isCallBackServiceInvoke = false; boolean isStubServiceInvoke = false; int port = channel.getLocalAddress().getPort(); - String path = inv.getAttachments().get(Constants.PATH_KEY); + String path = inv.getAttachments().get(PATH_KEY); // if it's callback service on client side isStubServiceInvoke = Boolean.TRUE.toString().equals(inv.getAttachments().get(Constants.STUB_EVENT_KEY)); @@ -241,7 +246,7 @@ Invoker getInvoker(Channel channel, Invocation inv) throws RemotingException inv.getAttachments().put(IS_CALLBACK_SERVICE_INVOKE, Boolean.TRUE.toString()); } - String serviceKey = serviceKey(port, path, inv.getAttachments().get(Constants.VERSION_KEY), inv.getAttachments().get(Constants.GROUP_KEY)); + String serviceKey = serviceKey(port, path, inv.getAttachments().get(VERSION_KEY), inv.getAttachments().get(GROUP_KEY)); DubboExporter exporter = (DubboExporter) exporterMap.get(serviceKey); if (exporter == null) { @@ -277,7 +282,7 @@ public Exporter export(Invoker invoker) throws RpcException { String stubServiceMethods = url.getParameter(Constants.STUB_EVENT_METHODS_KEY); if (stubServiceMethods == null || stubServiceMethods.length() == 0) { if (logger.isWarnEnabled()) { - logger.warn(new IllegalStateException("consumer [" + url.getParameter(Constants.INTERFACE_KEY) + + logger.warn(new IllegalStateException("consumer [" + url.getParameter(INTERFACE_KEY) + "], has set stubproxy support event ,but no stub methods founded.")); } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java index 98283f450c8..24e72d607a2 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java @@ -17,6 +17,7 @@ package org.apache.dubbo.rpc.protocol.dubbo.filter; import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -36,7 +37,7 @@ /** * EventFilter */ -@Activate(group = Constants.CONSUMER) +@Activate(group = CommonConstants.CONSUMER) public class FutureFilter implements Filter { protected static final Logger logger = LoggerFactory.getLogger(FutureFilter.class); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java index 004e47f1588..b2aae4496d6 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.rpc.protocol.dubbo.filter; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.constants.RemotingConstants; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -42,7 +42,7 @@ /** * TraceFilter */ -@Activate(group = Constants.PROVIDER) +@Activate(group = CommonConstants.PROVIDER) public class TraceFilter implements Filter { private static final Logger logger = LoggerFactory.getLogger(TraceFilter.class); diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocol.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocol.java index 0c76e1e7662..caa5b597eb3 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocol.java +++ b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocol.java @@ -45,6 +45,9 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + /** * http rpc support. */ @@ -120,7 +123,7 @@ protected T doRefer(Class serviceType, URL url) throws RpcException { factory.setHessianProxyFactory(hessianProxyFactory); hessianProxyFactory.setConnectionFactory(factory); } - int timeout = url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); + int timeout = url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT); hessianProxyFactory.setConnectTimeout(timeout); hessianProxyFactory.setReadTimeout(timeout); return (T) hessianProxyFactory.create(serviceType, url.setProtocol("http").toJavaURL(), Thread.currentThread().getContextClassLoader()); diff --git a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java b/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java index d744ebfc0e8..a3c91d0af47 100644 --- a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java +++ b/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java @@ -48,6 +48,10 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + /** * HttpProtocol */ @@ -124,7 +128,7 @@ public RemoteInvocation createRemoteInvocation(MethodInvocation methodInvocation package was renamed to 'org.apache.dubbo' in v2.7.0, so only provider versions after v2.7.0 can recognize org.apache.xxx.HttpRemoteInvocation'. */ - if (Version.isRelease270OrHigher(url.getParameter(Constants.RELEASE_KEY))) { + if (Version.isRelease270OrHigher(url.getParameter(RELEASE_KEY))) { invocation = new HttpRemoteInvocation(methodInvocation); } else { /* @@ -161,14 +165,14 @@ public RemoteInvocation createRemoteInvocation(MethodInvocation methodInvocation protected void prepareConnection(HttpURLConnection con, int contentLength) throws IOException { super.prepareConnection(con, contentLength); - con.setReadTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); + con.setReadTimeout(url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT)); con.setConnectTimeout(url.getParameter(RemotingConstants.CONNECT_TIMEOUT_KEY, RemotingConstants.DEFAULT_CONNECT_TIMEOUT)); } }; httpProxyFactoryBean.setHttpInvokerRequestExecutor(httpInvokerRequestExecutor); } else if ("commons".equals(client)) { HttpComponentsHttpInvokerRequestExecutor httpInvokerRequestExecutor = new HttpComponentsHttpInvokerRequestExecutor(); - httpInvokerRequestExecutor.setReadTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); + httpInvokerRequestExecutor.setReadTimeout(url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT)); httpInvokerRequestExecutor.setConnectTimeout(url.getParameter(RemotingConstants.CONNECT_TIMEOUT_KEY, RemotingConstants.DEFAULT_CONNECT_TIMEOUT)); httpProxyFactoryBean.setHttpInvokerRequestExecutor(httpInvokerRequestExecutor); } else { diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmInvoker.java b/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmInvoker.java index 37d23d5bdf7..480014a091c 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmInvoker.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmInvoker.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.injvm; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invocation; @@ -27,6 +26,8 @@ import java.util.Map; +import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_VALUE; + /** * InjvmInvoker */ @@ -58,7 +59,7 @@ public Result doInvoke(Invocation invocation) throws Throwable { if (exporter == null) { throw new RpcException("Service [" + key + "] not found."); } - RpcContext.getContext().setRemoteAddress(Constants.LOCALHOST_VALUE, 0); + RpcContext.getContext().setRemoteAddress(LOCALHOST_VALUE, 0); return exporter.getInvoker().invoke(invocation); } } diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocolTest.java b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocolTest.java index 5285e92507f..cd19b8fcb06 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocolTest.java @@ -32,6 +32,9 @@ import java.util.HashMap; import java.util.List; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -61,11 +64,11 @@ public void after() throws Exception { @Test public void testLocalProtocol() throws Exception { DemoService service = new DemoServiceImpl(); - Invoker invoker = proxy.getInvoker(service, DemoService.class, URL.valueOf("injvm://127.0.0.1/TestService").addParameter(Constants.INTERFACE_KEY, DemoService.class.getName())); + Invoker invoker = proxy.getInvoker(service, DemoService.class, URL.valueOf("injvm://127.0.0.1/TestService").addParameter(INTERFACE_KEY, DemoService.class.getName())); assertTrue(invoker.isAvailable()); Exporter exporter = protocol.export(invoker); exporters.add(exporter); - service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("injvm://127.0.0.1/TestService").addParameter(Constants.INTERFACE_KEY, DemoService.class.getName()))); + service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("injvm://127.0.0.1/TestService").addParameter(INTERFACE_KEY, DemoService.class.getName()))); assertEquals(service.getSize(new String[]{"", "", ""}), 3); service.invoke("injvm://127.0.0.1/TestService", "invoke"); @@ -78,15 +81,15 @@ public void testLocalProtocol() throws Exception { public void testIsInjvmRefer() throws Exception { DemoService service = new DemoServiceImpl(); URL url = URL.valueOf("injvm://127.0.0.1/TestService") - .addParameter(Constants.INTERFACE_KEY, DemoService.class.getName()); + .addParameter(INTERFACE_KEY, DemoService.class.getName()); Exporter exporter = protocol.export(proxy.getInvoker(service, DemoService.class, url)); exporters.add(exporter); url = url.setProtocol("dubbo"); assertTrue(InjvmProtocol.getInjvmProtocol().isInjvmRefer(url)); - url = url.addParameter(Constants.GROUP_KEY, "*") - .addParameter(Constants.VERSION_KEY, "*"); + url = url.addParameter(GROUP_KEY, "*") + .addParameter(VERSION_KEY, "*"); assertTrue(InjvmProtocol.getInjvmProtocol().isInjvmRefer(url)); url = URL.valueOf("fake://127.0.0.1/TestService").addParameter(Constants.SCOPE_KEY, Constants.SCOPE_LOCAL); @@ -103,4 +106,4 @@ public void testIsInjvmRefer() throws Exception { } -} \ No newline at end of file +} diff --git a/dubbo-rpc/dubbo-rpc-redis/src/main/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocol.java b/dubbo-rpc/dubbo-rpc-redis/src/main/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocol.java index f93b4447920..5678beb979c 100644 --- a/dubbo-rpc/dubbo-rpc-redis/src/main/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocol.java +++ b/dubbo-rpc/dubbo-rpc-redis/src/main/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocol.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.redis; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; @@ -46,6 +45,9 @@ import java.util.Map; import java.util.concurrent.TimeoutException; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + /** * RedisProtocol @@ -100,7 +102,7 @@ public Invoker refer(final Class type, final URL url) throws RpcExcept config.setMinEvictableIdleTimeMillis(url.getParameter("min.evictable.idle.time.millis", 0)); } final JedisPool jedisPool = new JedisPool(config, url.getHost(), url.getPort(DEFAULT_PORT), - url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT), + url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT), StringUtils.isBlank(url.getPassword()) ? null : url.getPassword(), url.getParameter("db.index", 0)); final int expiry = url.getParameter("expiry", 0); diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/BaseRestServer.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/BaseRestServer.java index 50648e6fb98..f10abdd7976 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/BaseRestServer.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/BaseRestServer.java @@ -22,6 +22,8 @@ import org.jboss.resteasy.spi.ResteasyDeployment; +import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; + public abstract class BaseRestServer implements RestServer { @Override @@ -53,7 +55,7 @@ public void undeploy(Class resourceDef) { } protected void loadProviders(String value) { - for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(value)) { + for (String clazz : COMMA_SPLIT_PATTERN.split(value)) { if (!StringUtils.isEmpty(clazz)) { getDeployment().getProviderClasses().add(clazz.trim()); } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/NettyServer.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/NettyServer.java index d8380f54b8c..f17f8576fc0 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/NettyServer.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/NettyServer.java @@ -28,6 +28,10 @@ import java.util.HashMap; import java.util.Map; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS; +import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; + /** * Netty server can't support @Context injection of servlet objects since it's not a servlet container * @@ -46,8 +50,8 @@ protected void doStart(URL url) { Map channelOption = new HashMap(); channelOption.put(ChannelOption.SO_KEEPALIVE, url.getParameter(Constants.KEEP_ALIVE_KEY, Constants.DEFAULT_KEEP_ALIVE)); server.setChildChannelOptions(channelOption); - server.setExecutorThreadCount(url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS)); - server.setIoWorkerCount(url.getParameter(Constants.IO_THREADS_KEY, RemotingConstants.DEFAULT_IO_THREADS)); + server.setExecutorThreadCount(url.getParameter(THREADS_KEY, DEFAULT_THREADS)); + server.setIoWorkerCount(url.getParameter(IO_THREADS_KEY, RemotingConstants.DEFAULT_IO_THREADS)); server.setMaxRequestSize(url.getParameter(RemotingConstants.PAYLOAD_KEY, RemotingConstants.DEFAULT_PAYLOAD)); server.start(); } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java index 4934ca50ba6..977bea2daa6 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java @@ -52,6 +52,11 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + public class RestProtocol extends AbstractProxyProtocol { private static final int DEFAULT_PORT = 80; @@ -144,7 +149,7 @@ protected T doRefer(Class serviceType, URL url) throws RpcException { connectionMonitor.addConnectionManager(connectionManager); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(url.getParameter(RemotingConstants.CONNECT_TIMEOUT_KEY, RemotingConstants.DEFAULT_CONNECT_TIMEOUT)) - .setSocketTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)) + .setSocketTimeout(url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT)) .build(); SocketConfig socketConfig = SocketConfig.custom() @@ -159,7 +164,7 @@ protected T doRefer(Class serviceType, URL url) throws RpcException { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); - if (value != null && param.equalsIgnoreCase(Constants.TIMEOUT_KEY)) { + if (value != null && param.equalsIgnoreCase(TIMEOUT_KEY)) { return Long.parseLong(value) * 1000; } } @@ -175,7 +180,7 @@ protected T doRefer(Class serviceType, URL url) throws RpcException { clients.add(client); client.register(RpcContextFilter.class); - for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) { + for (String clazz : COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) { if (!StringUtils.isEmpty(clazz)) { try { client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim())); @@ -239,11 +244,11 @@ public void destroy() { protected String getContextPath(URL url) { String contextPath = url.getPath(); if (contextPath != null) { - if (contextPath.equalsIgnoreCase(url.getParameter(Constants.INTERFACE_KEY))) { + if (contextPath.equalsIgnoreCase(url.getParameter(INTERFACE_KEY))) { return ""; } - if (contextPath.endsWith(url.getParameter(Constants.INTERFACE_KEY))) { - contextPath = contextPath.substring(0, contextPath.lastIndexOf(url.getParameter(Constants.INTERFACE_KEY))); + if (contextPath.endsWith(url.getParameter(INTERFACE_KEY))) { + contextPath = contextPath.substring(0, contextPath.lastIndexOf(url.getParameter(INTERFACE_KEY))); } return contextPath.endsWith("/") ? contextPath.substring(0, contextPath.length() - 1) : contextPath; } else { diff --git a/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocol.java b/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocol.java index 63e9fcdfff1..13d8cae220a 100644 --- a/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocol.java +++ b/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocol.java @@ -31,6 +31,7 @@ import java.net.SocketTimeoutException; import java.rmi.RemoteException; +import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY; import static org.apache.dubbo.common.Version.isRelease263OrHigher; import static org.apache.dubbo.common.Version.isRelease270OrHigher; @@ -82,7 +83,7 @@ protected T doRefer(final Class serviceType, final URL url) throws RpcExc 2. if the provider version is v2.6.3 or higher, send 'com.alibaba.dubbo.rpc.protocol.rmi.RmiRemoteInvocation'. 3. if the provider version is lower than v2.6.3, does not use customized RemoteInvocation. */ - if (isRelease270OrHigher(url.getParameter(Constants.RELEASE_KEY))) { + if (isRelease270OrHigher(url.getParameter(RELEASE_KEY))) { rmiProxyFactoryBean.setRemoteInvocationFactory((methodInvocation) -> { RemoteInvocation invocation = new RmiRemoteInvocation(methodInvocation); if (invocation != null && isGeneric) { diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java index 93a5900d753..e37fab6a68b 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.thrift; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.StringUtils; @@ -30,6 +29,7 @@ import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.protocol.thrift.io.RandomAccessByteArrayOutputStream; + import org.apache.thrift.TApplicationException; import org.apache.thrift.TBase; import org.apache.thrift.TException; @@ -51,6 +51,9 @@ import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; + /** * Thrift framed protocol codec. * @@ -181,8 +184,8 @@ private Object decode(TProtocol protocol) if (message.type == TMessageType.CALL) { RpcInvocation result = new RpcInvocation(); - result.setAttachment(Constants.INTERFACE_KEY, serviceName); - result.setAttachment(Constants.PATH_KEY, path); + result.setAttachment(INTERFACE_KEY, serviceName); + result.setAttachment(PATH_KEY, path); result.setMethodName(message.name); String argsClassName = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class) @@ -401,11 +404,11 @@ private void encodeRequest(Channel channel, ChannelBuffer buffer, Request reques int seqId = nextSeqId(); - String serviceName = inv.getAttachment(Constants.INTERFACE_KEY); + String serviceName = inv.getAttachment(INTERFACE_KEY); if (StringUtils.isEmpty(serviceName)) { throw new IllegalArgumentException("Could not find service name in attachment with key " - + Constants.INTERFACE_KEY); + + INTERFACE_KEY); } TMessage message = new TMessage( @@ -499,7 +502,7 @@ private void encodeRequest(Channel channel, ChannelBuffer buffer, Request reques // service name protocol.writeString(serviceName); // path - protocol.writeString(inv.getAttachment(Constants.PATH_KEY)); + protocol.writeString(inv.getAttachment(PATH_KEY)); // dubbo request id protocol.writeI64(request.getId()); protocol.getTransport().flush(); diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java index a6aeba1ebed..8b79c2ac6c7 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java @@ -33,6 +33,13 @@ import java.util.Set; import java.util.concurrent.locks.ReentrantLock; + +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + /** * @since 2.7.0, use https://github.com/dubbo/dubbo-rpc-native-thrift instead */ @@ -52,9 +59,7 @@ public ThriftInvoker(Class service, URL url, ExchangeClient[] clients) { } public ThriftInvoker(Class type, URL url, ExchangeClient[] clients, Set> invokers) { - super(type, url, - new String[]{Constants.INTERFACE_KEY, Constants.GROUP_KEY, - Constants.TOKEN_KEY, Constants.TIMEOUT_KEY}); + super(type, url, new String[]{INTERFACE_KEY, GROUP_KEY, Constants.TOKEN_KEY, TIMEOUT_KEY}); this.clients = clients; this.invokers = invokers; } @@ -68,7 +73,7 @@ protected Result doInvoke(Invocation invocation) throws Throwable { methodName = invocation.getMethodName(); - inv.setAttachment(Constants.PATH_KEY, getUrl().getPath()); + inv.setAttachment(PATH_KEY, getUrl().getPath()); // for thrift codec inv.setAttachment(ThriftCodec.PARAMETER_CLASS_NAME_GENERATOR, getUrl().getParameter( @@ -83,8 +88,7 @@ protected Result doInvoke(Invocation invocation) throws Throwable { } try { - int timeout = getUrl().getMethodParameter( - methodName, Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); + int timeout = getUrl().getMethodParameter(methodName, TIMEOUT_KEY, DEFAULT_TIMEOUT); RpcContext.getContext().setFuture(null); diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java index ec6370938c4..d5fc0b3a4b7 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java @@ -43,6 +43,9 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; + +import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; + /** * @since 2.7.0, use https://github.com/dubbo/dubbo-rpc-native-thrift instead */ @@ -64,7 +67,7 @@ public CompletableFuture reply(ExchangeChannel channel, Object msg) thro if (msg instanceof Invocation) { Invocation inv = (Invocation) msg; - String path = inv.getAttachments().get(Constants.PATH_KEY); + String path = inv.getAttachments().get(PATH_KEY); String serviceKey = serviceKey(channel.getLocalAddress().getPort(), path, null, null); DubboExporter exporter = (DubboExporter) exporterMap.get(serviceKey); diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodecTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodecTest.java index a1d5daadea8..93421c4bcfb 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodecTest.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodecTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.thrift; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.buffer.ChannelBuffer; @@ -29,6 +28,7 @@ import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.gen.thrift.Demo; import org.apache.dubbo.rpc.protocol.thrift.io.RandomAccessByteArrayOutputStream; + import org.apache.thrift.TApplicationException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TMessage; @@ -41,6 +41,9 @@ import java.io.ByteArrayInputStream; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; + public class ThriftCodecTest { private ThriftCodec codec = new ThriftCodec(); @@ -400,10 +403,10 @@ public void testDecodeRequest() throws Exception { protocol.writeByte(ThriftCodec.VERSION); protocol.writeString( ((RpcInvocation) request.getData()) - .getAttachment(Constants.INTERFACE_KEY)); + .getAttachment(INTERFACE_KEY)); protocol.writeString( ((RpcInvocation) request.getData()) - .getAttachment(Constants.PATH_KEY)); + .getAttachment(PATH_KEY)); protocol.writeI64(request.getId()); protocol.getTransport().flush(); headerLength = bos.size(); @@ -455,8 +458,8 @@ private Request createRequest() { invocation.setParameterTypes(new Class[]{String.class}); - invocation.setAttachment(Constants.INTERFACE_KEY, Demo.Iface.class.getName()); - invocation.setAttachment(Constants.PATH_KEY, Demo.Iface.class.getName()); + invocation.setAttachment(INTERFACE_KEY, Demo.Iface.class.getName()); + invocation.setAttachment(PATH_KEY, Demo.Iface.class.getName()); Request request = new Request(1L); diff --git a/dubbo-rpc/dubbo-rpc-webservice/src/main/java/org/apache/dubbo/rpc/protocol/webservice/WebServiceProtocol.java b/dubbo-rpc/dubbo-rpc-webservice/src/main/java/org/apache/dubbo/rpc/protocol/webservice/WebServiceProtocol.java index 62215aa6d27..928b01c45ff 100644 --- a/dubbo-rpc/dubbo-rpc-webservice/src/main/java/org/apache/dubbo/rpc/protocol/webservice/WebServiceProtocol.java +++ b/dubbo-rpc/dubbo-rpc-webservice/src/main/java/org/apache/dubbo/rpc/protocol/webservice/WebServiceProtocol.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.webservice; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.remoting.http.HttpBinder; @@ -49,6 +48,9 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; +import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; + /** * WebServiceProtocol. */ @@ -118,7 +120,7 @@ protected T doRefer(final Class serviceType, final URL url) throws RpcExc HTTPConduit conduit = (HTTPConduit) proxy.getConduit(); HTTPClientPolicy policy = new HTTPClientPolicy(); policy.setConnectionTimeout(url.getParameter(RemotingConstants.CONNECT_TIMEOUT_KEY, RemotingConstants.DEFAULT_CONNECT_TIMEOUT)); - policy.setReceiveTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); + policy.setReceiveTimeout(url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT)); conduit.setClient(policy); return ref; } From 805f7c764d2f82607c61a94cea1bb37f0062f3b5 Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Mon, 13 May 2019 13:42:39 +0800 Subject: [PATCH 046/115] [DUBBO-3137]: step3 - start to use RegistryConstants (#4035) --- .../dubbo/rpc/cluster/Configurator.java | 3 +- .../configurator/AbstractConfigurator.java | 6 +- .../configurator/parser/ConfigParser.java | 8 +- .../cluster/directory/AbstractDirectory.java | 4 +- .../support/RegistryAwareClusterInvoker.java | 4 +- .../org/apache/dubbo/common/Constants.java | 114 ------------------ .../apache/dubbo/common/utils/UrlUtils.java | 17 +-- .../dubbo/config/AbstractInterfaceConfig.java | 16 ++- .../apache/dubbo/config/ReferenceConfig.java | 8 +- .../apache/dubbo/config/RegistryConfig.java | 3 +- .../apache/dubbo/config/ServiceConfig.java | 3 +- .../dubbo/config/mock/MockRegistry.java | 4 +- .../annotation/AnnotationBeanNameBuilder.java | 4 +- .../etcd/EtcdDynamicConfigurationTest.java | 11 +- .../nacos/NacosDynamicConfigurationTest.java | 10 +- .../qos/protocol/QosProtocolWrapper.java | 6 +- .../qos/protocol/QosProtocolWrapperTest.java | 6 +- .../integration/RegistryDirectory.java | 34 +++--- .../integration/RegistryProtocol.java | 36 +++--- .../registry/retry/AbstractRetryTask.java | 10 +- .../registry/support/AbstractRegistry.java | 18 +-- .../registry/support/FailbackRegistry.java | 10 +- .../support/AbstractRegistryTest.java | 5 +- .../support/FailbackRegistryTest.java | 14 ++- .../dubbo/registry/consul/ConsulRegistry.java | 7 +- .../dubbo/registry/dubbo/DubboRegistry.java | 5 +- .../registry/dubbo/DubboRegistryFactory.java | 3 +- .../registry/dubbo/DubboRegistryTest.java | 7 +- .../registry/dubbo/RegistryDirectoryTest.java | 22 ++-- .../dubbo/registry/etcd/EtcdRegistry.java | 21 ++-- .../dubbo/registry/etcd/EtcdRegistryTest.java | 14 ++- .../registry/multicast/MulticastRegistry.java | 47 +++++--- .../dubbo/registry/nacos/NacosRegistry.java | 21 ++-- .../dubbo/registry/redis/RedisRegistry.java | 41 ++++--- .../dubbo/registry/sofa/SofaRegistry.java | 21 ++-- .../registry/zookeeper/ZookeeperRegistry.java | 24 ++-- .../remoting/etcd/jetcd/JEtcdClient.java | 8 +- .../etcd/jetcd/JEtcdClientWrapper.java | 13 +- .../dubbo/remoting/etcd/option/Constants.java | 10 +- .../etcd/support/AbstractEtcdClient.java | 11 +- .../remoting/etcd/jetcd/JEtcdClientTest.java | 9 +- .../etcd/jetcd/JEtcdClientWrapperTest.java | 5 +- .../rpc/protocol/ProtocolFilterWrapper.java | 6 +- .../rpc/protocol/ProtocolListenerWrapper.java | 6 +- 44 files changed, 320 insertions(+), 335 deletions(-) diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Configurator.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Configurator.java index 98760348448..b86409d8d13 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Configurator.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Configurator.java @@ -29,6 +29,7 @@ import java.util.Optional; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; /** * Configurator. (SPI, Prototype, ThreadSafe) @@ -78,7 +79,7 @@ static Optional> toConfigurators(List urls) { List configurators = new ArrayList<>(urls.size()); for (URL url : urls) { - if (Constants.EMPTY_PROTOCOL.equals(url.getProtocol())) { + if (EMPTY_PROTOCOL.equals(url.getProtocol())) { configurators.clear(); break; } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java index 0ce3e00276b..5fdefb83e3f 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java @@ -36,6 +36,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; /** * AbstractOverrideConfigurator @@ -114,9 +116,9 @@ private URL configureIfMatch(String host, URL url) { if (configApplication == null || ANY_VALUE.equals(configApplication) || configApplication.equals(currentApplication)) { Set conditionKeys = new HashSet(); - conditionKeys.add(Constants.CATEGORY_KEY); + conditionKeys.add(CATEGORY_KEY); conditionKeys.add(RemotingConstants.CHECK_KEY); - conditionKeys.add(Constants.DYNAMIC_KEY); + conditionKeys.add(DYNAMIC_KEY); conditionKeys.add(ENABLED_KEY); conditionKeys.add(GROUP_KEY); conditionKeys.add(VERSION_KEY); diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParser.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParser.java index 962e52f8876..b16783303db 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParser.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParser.java @@ -32,6 +32,8 @@ import java.util.Map; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; +import static org.apache.dubbo.common.constants.RegistryConstants.APP_DYNAMIC_CONFIGURATORS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_CONFIGURATORS_CATEGORY; /** * Config parser @@ -77,7 +79,7 @@ private static List serviceItemToUrls(ConfigItem item, ConfiguratorConfig c parseEnabled(item, config, urlBuilder); - urlBuilder.append("&category=").append(Constants.DYNAMIC_CONFIGURATORS_CATEGORY); + urlBuilder.append("&category=").append(DYNAMIC_CONFIGURATORS_CATEGORY); urlBuilder.append("&configVersion=").append(config.getConfigVersion()); List apps = item.getApplications(); @@ -114,7 +116,7 @@ private static List appItemToUrls(ConfigItem item, ConfiguratorConfig confi parseEnabled(item, config, urlBuilder); - urlBuilder.append("&category=").append(Constants.APP_DYNAMIC_CONFIGURATORS_CATEGORY); + urlBuilder.append("&category=").append(APP_DYNAMIC_CONFIGURATORS_CATEGORY); urlBuilder.append("&configVersion=").append(config.getConfigVersion()); urls.add(URL.valueOf(urlBuilder.toString())); @@ -126,7 +128,7 @@ private static List appItemToUrls(ConfigItem item, ConfiguratorConfig confi private static String toParameterString(ConfigItem item) { StringBuilder sb = new StringBuilder(); sb.append("category="); - sb.append(Constants.DYNAMIC_CONFIGURATORS_CATEGORY); + sb.append(DYNAMIC_CONFIGURATORS_CATEGORY); if (item.getSide() != null) { sb.append("&side="); sb.append(item.getSide()); diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java index c6a01e8ec43..f9677b970ed 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java @@ -32,6 +32,8 @@ import java.util.List; import java.util.Map; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; + /** * Abstract implementation of Directory: Invoker list returned from this Directory's list method have been filtered by Routers * @@ -62,7 +64,7 @@ public AbstractDirectory(URL url, URL consumerUrl, RouterChain routerChain) { throw new IllegalArgumentException("url == null"); } - if (url.getProtocol().equals(Constants.REGISTRY_PROTOCOL)) { + if (url.getProtocol().equals(REGISTRY_PROTOCOL)) { Map queryMap = StringUtils.parseQueryString(url.getParameterAndDecoded(Constants.REFER_KEY)); this.url = url.addParameters(queryMap).removeParameter(Constants.MONITOR_KEY); } else { diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/RegistryAwareClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/RegistryAwareClusterInvoker.java index 6a18cc5b35a..789d850ec1e 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/RegistryAwareClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/RegistryAwareClusterInvoker.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.Invocation; @@ -29,6 +28,7 @@ import java.util.List; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY; /** * @@ -46,7 +46,7 @@ public RegistryAwareClusterInvoker(Directory directory) { public Result doInvoke(Invocation invocation, final List> invokers, LoadBalance loadbalance) throws RpcException { // First, pick the invoker (XXXClusterInvoker) that comes from the local registry, distinguish by a 'default' key. for (Invoker invoker : invokers) { - if (invoker.isAvailable() && invoker.getUrl().getParameter(Constants.REGISTRY_KEY + "." + DEFAULT_KEY, false)) { + if (invoker.isAvailable() && invoker.getUrl().getParameter(REGISTRY_KEY + "." + DEFAULT_KEY, false)) { return invoker.invoke(invocation); } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java index 8d78190c50b..3d571fff18a 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java @@ -571,120 +571,6 @@ public class Constants { public static final String OVERRIDE_PROVIDERS_KEY = "providerAddresses"; // END dubbo-cluster - // BEGIN dubbo-registry-api - public static final String REGISTER_KEY = "register"; - - public static final String SUBSCRIBE_KEY = "subscribe"; - - public static final String REGISTRY_KEY = "registry"; - - public static final String DEFAULT_REGISTRY = "dubbo"; - - public static final String REGISTRY_PROTOCOL = "registry"; - - public static final String DYNAMIC_KEY = "dynamic"; - - public static final String REGISTER = "register"; - - public static final String UNREGISTER = "unregister"; - - public static final String SUBSCRIBE = "subscribe"; - - public static final String UNSUBSCRIBE = "unsubscribe"; - - public static final String CATEGORY_KEY = "category"; - - public static final String PROVIDERS_CATEGORY = "providers"; - - public static final String CONSUMERS_CATEGORY = "consumers"; - - public static final String ROUTERS_CATEGORY = "routers"; - - public static final String DYNAMIC_ROUTERS_CATEGORY = "dynamicrouters"; - - public static final String DEFAULT_CATEGORY = PROVIDERS_CATEGORY; - - public static final String CONFIGURATORS_CATEGORY = "configurators"; - - public static final String DYNAMIC_CONFIGURATORS_CATEGORY = "dynamicconfigurators"; - - public static final String APP_DYNAMIC_CONFIGURATORS_CATEGORY = "appdynamicconfigurators"; - - public static final String CONFIGURATORS_SUFFIX = ".configurators"; - - public static final String ROUTERS_SUFFIX = ".routers"; - - public static final String TRACE_PROTOCOL = "trace"; - - public static final String EMPTY_PROTOCOL = "empty"; - - public static final String ADMIN_PROTOCOL = "admin"; - - public static final String PROVIDER_PROTOCOL = "provider"; - - public static final String CONSUMER_PROTOCOL = "consumer"; - - public static final String ROUTE_PROTOCOL = "route"; - - public static final String SCRIPT_PROTOCOL = "script"; - - public static final String CONDITION_PROTOCOL = "condition"; - - /** - * simple the registry for provider. - * - * @since 2.7.0 - */ - public static final String SIMPLIFIED_KEY = "simplified"; - - /** - * After simplify the registry, should add some paramter individually for provider. - * - * @since 2.7.0 - */ - public static final String EXTRA_KEYS_KEY = "extra-keys"; - - public static final String OVERRIDE_PROTOCOL = "override"; - - public static final String COMPATIBLE_CONFIG_KEY = "compatible_config"; - - - /** - * To decide whether register center saves file synchronously, the default value is asynchronously - */ - public static final String REGISTRY_FILESAVE_SYNC_KEY = "save.file"; - - /** - * Period of registry center's retry interval - */ - public static final String REGISTRY_RETRY_PERIOD_KEY = "retry.period"; - - /** - * Most retry times - */ - public static final String REGISTRY_RETRY_TIMES_KEY = "retry.times"; - - /** - * Default value for the period of retry interval in milliseconds: 5000 - */ - public static final int DEFAULT_REGISTRY_RETRY_PERIOD = 5 * 1000; - - /** - * Default value for the times of retry: 3 - */ - public static final int DEFAULT_REGISTRY_RETRY_TIMES = 3; - - /** - * Reconnection period in milliseconds for register center - */ - public static final String REGISTRY_RECONNECT_PERIOD_KEY = "reconnect.period"; - - public static final int DEFAULT_REGISTRY_RECONNECT_PERIOD = 3 * 1000; - - public static final String SESSION_TIMEOUT_KEY = "session"; - - public static final int DEFAULT_SESSION_TIMEOUT = 60 * 1000; - // END dubbo-registry-api // BEGIN dubbo-monitor-api public static final String MONITOR_KEY = "monitor"; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java index 2d5e6778078..cca3b29b897 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java @@ -28,13 +28,6 @@ import java.util.function.Predicate; import java.util.stream.Collectors; -import static org.apache.dubbo.common.Constants.CATEGORY_KEY; -import static org.apache.dubbo.common.Constants.CONFIGURATORS_CATEGORY; -import static org.apache.dubbo.common.Constants.DEFAULT_CATEGORY; -import static org.apache.dubbo.common.Constants.OVERRIDE_PROTOCOL; -import static org.apache.dubbo.common.Constants.PROVIDERS_CATEGORY; -import static org.apache.dubbo.common.Constants.ROUTERS_CATEGORY; -import static org.apache.dubbo.common.Constants.ROUTE_PROTOCOL; import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.CLASSIFIER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; @@ -46,6 +39,14 @@ import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.REMOVE_VALUE_PREFIX; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.OVERRIDE_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.ROUTE_PROTOCOL; public class UrlUtils { @@ -362,7 +363,7 @@ public static URL getEmptyUrl(String service, String category) { version = service.substring(i + 1); service = service.substring(0, i); } - return URL.valueOf(Constants.EMPTY_PROTOCOL + "://0.0.0.0/" + service + URL_PARAM_STARTING_SYMBOL + return URL.valueOf(EMPTY_PROTOCOL + "://0.0.0.0/" + service + URL_PARAM_STARTING_SYMBOL + CATEGORY_KEY + "=" + category + (group == null ? "" : "&" + GROUP_KEY + "=" + group) + (version == null ? "" : "&" + VERSION_KEY + "=" + version)); diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java index b571eababd7..c3b534d302b 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java @@ -64,6 +64,10 @@ import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.SUBSCRIBE_KEY; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; /** @@ -323,11 +327,11 @@ protected List loadRegistries(boolean provider) { for (URL url : urls) { url = URLBuilder.from(url) - .addParameter(Constants.REGISTRY_KEY, url.getProtocol()) - .setProtocol(Constants.REGISTRY_PROTOCOL) + .addParameter(REGISTRY_KEY, url.getProtocol()) + .setProtocol(REGISTRY_PROTOCOL) .build(); - if ((provider && url.getParameter(Constants.REGISTER_KEY, true)) - || (!provider && url.getParameter(Constants.SUBSCRIBE_KEY, true))) { + if ((provider && url.getParameter(REGISTER_KEY, true)) + || (!provider && url.getParameter(SUBSCRIBE_KEY, true))) { registryList.add(url); } } @@ -374,10 +378,10 @@ protected URL loadMonitor(URL registryURL) { } } return UrlUtils.parseURL(address, map); - } else if (Constants.REGISTRY_PROTOCOL.equals(monitor.getProtocol()) && registryURL != null) { + } else if (REGISTRY_PROTOCOL.equals(monitor.getProtocol()) && registryURL != null) { return URLBuilder.from(registryURL) .setProtocol(Constants.DUBBO_PROTOCOL) - .addParameter(PROTOCOL_KEY, Constants.REGISTRY_PROTOCOL) + .addParameter(PROTOCOL_KEY, REGISTRY_PROTOCOL) .addParameterAndEncoded(Constants.REFER_KEY, StringUtils.toQueryString(map)) .build(); } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java index 2842eabd703..0f6d866802e 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java @@ -66,6 +66,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SEMICOLON_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; import static org.apache.dubbo.common.utils.NetUtils.isInvalidLocalHost; /** @@ -357,7 +359,7 @@ private T createProxy(Map map) { if (StringUtils.isEmpty(url.getPath())) { url = url.setPath(interfaceName); } - if (Constants.REGISTRY_PROTOCOL.equals(url.getProtocol())) { + if (REGISTRY_PROTOCOL.equals(url.getProtocol())) { urls.add(url.addParameterAndEncoded(Constants.REFER_KEY, StringUtils.toQueryString(map))); } else { urls.add(ClusterUtils.mergeUrl(url, map)); @@ -391,7 +393,7 @@ private T createProxy(Map map) { URL registryURL = null; for (URL url : urls) { invokers.add(REF_PROTOCOL.refer(interfaceClass, url)); - if (Constants.REGISTRY_PROTOCOL.equals(url.getProtocol())) { + if (REGISTRY_PROTOCOL.equals(url.getProtocol())) { registryURL = url; // use last registry url } } @@ -420,7 +422,7 @@ private T createProxy(Map map) { */ MetadataReportService metadataReportService = null; if ((metadataReportService = getMetadataReportService()) != null) { - URL consumerURL = new URL(Constants.CONSUMER_PROTOCOL, map.remove(Constants.REGISTER_IP_KEY), 0, map.get(INTERFACE_KEY), map); + URL consumerURL = new URL(CONSUMER_PROTOCOL, map.remove(Constants.REGISTER_IP_KEY), 0, map.get(INTERFACE_KEY), map); metadataReportService.publishConsumer(consumerURL); } // create service proxy diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java index a529fd604a9..dfbf749b16e 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java @@ -25,6 +25,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.FILE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.EXTRA_KEYS_KEY; /** * RegistryConfig @@ -393,7 +394,7 @@ public void setSimplified(Boolean simplified) { this.simplified = simplified; } - @Parameter(key = Constants.EXTRA_KEYS_KEY) + @Parameter(key = EXTRA_KEYS_KEY) public String getExtraKeys() { return extraKeys; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index d4ef8bb1536..07ec5acd845 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -72,6 +72,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; import static org.apache.dubbo.common.utils.NetUtils.getAvailablePort; import static org.apache.dubbo.common.utils.NetUtils.getLocalHost; import static org.apache.dubbo.common.utils.NetUtils.isInvalidLocalHost; @@ -570,7 +571,7 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r if (Constants.LOCAL_PROTOCOL.equalsIgnoreCase(url.getProtocol())) { continue; } - url = url.addParameterIfAbsent(Constants.DYNAMIC_KEY, registryURL.getParameter(Constants.DYNAMIC_KEY)); + url = url.addParameterIfAbsent(DYNAMIC_KEY, registryURL.getParameter(DYNAMIC_KEY)); URL monitorUrl = loadMonitor(registryURL); if (monitorUrl != null) { url = url.addParameterAndEncoded(Constants.MONITOR_KEY, monitorUrl.toFullString()); diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockRegistry.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockRegistry.java index 47ab8e252be..1e72c9784aa 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockRegistry.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockRegistry.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config.mock; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.Registry; @@ -24,6 +23,7 @@ import java.util.ArrayList; import java.util.List; +import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; /** @@ -85,7 +85,7 @@ public void subscribe(URL url, NotifyListener listener) { List urls = new ArrayList(); urls.add(url.setProtocol("mockprotocol") - .removeParameter(Constants.CATEGORY_KEY) + .removeParameter(CATEGORY_KEY) .addParameter(METHODS_KEY, "sayHello")); listener.notify(urls); diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationBeanNameBuilder.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationBeanNameBuilder.java index 867fb2a182d..6e18e2a3471 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationBeanNameBuilder.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationBeanNameBuilder.java @@ -23,9 +23,9 @@ import org.springframework.core.env.Environment; -import static org.apache.dubbo.common.Constants.CONSUMERS_CATEGORY; -import static org.apache.dubbo.common.Constants.PROVIDERS_CATEGORY; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; import static org.apache.dubbo.config.spring.util.AnnotationUtils.resolveInterfaceName; import static org.springframework.util.StringUtils.arrayToCommaDelimitedString; import static org.springframework.util.StringUtils.hasText; diff --git a/dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java index 0f07cab99d9..6e5a3dc3f96 100644 --- a/dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java +++ b/dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java @@ -17,14 +17,14 @@ package org.apache.dubbo.configcenter.support.etcd; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.configcenter.ConfigChangeEvent; +import org.apache.dubbo.configcenter.ConfigurationListener; + import io.etcd.jetcd.ByteSequence; import io.etcd.jetcd.Client; import io.etcd.jetcd.launcher.EtcdCluster; import io.etcd.jetcd.launcher.EtcdClusterFactory; -import org.apache.dubbo.common.Constants; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.configcenter.ConfigChangeEvent; -import org.apache.dubbo.configcenter.ConfigurationListener; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -38,6 +38,7 @@ import java.util.concurrent.TimeUnit; import static java.nio.charset.StandardCharsets.UTF_8; +import static org.apache.dubbo.common.constants.RegistryConstants.SESSION_TIMEOUT_KEY; /** * Unit test for etcd config center support @@ -140,7 +141,7 @@ public void setUp() { // timeout in 15 seconds. URL url = URL.valueOf(urlForDubbo) - .addParameter(Constants.SESSION_TIMEOUT_KEY, 15000); + .addParameter(SESSION_TIMEOUT_KEY, 15000); config = new EtcdDynamicConfiguration(url); } diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java index f5ac1d38ccb..53758a9e288 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java @@ -17,20 +17,22 @@ package org.apache.dubbo.configcenter.support.nacos; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.configcenter.ConfigChangeEvent; import org.apache.dubbo.configcenter.ConfigurationListener; -import org.junit.jupiter.api.Test; + +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; +import static org.apache.dubbo.common.constants.RegistryConstants.SESSION_TIMEOUT_KEY; + /** * Unit test for nacos config center support */ @@ -98,7 +100,7 @@ public static void setUp() { String urlForDubbo = "nacos://" + "127.0.0.1:8848" + "/org.apache.dubbo.nacos.testService"; // timeout in 15 seconds. URL url = URL.valueOf(urlForDubbo) - .addParameter(Constants.SESSION_TIMEOUT_KEY, 15000); + .addParameter(SESSION_TIMEOUT_KEY, 15000); config = new NacosDynamicConfiguration(url); } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/protocol/QosProtocolWrapper.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/protocol/QosProtocolWrapper.java index ae0b22eeeed..03f265e2c65 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/protocol/QosProtocolWrapper.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/protocol/QosProtocolWrapper.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.qos.protocol; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -32,6 +31,7 @@ import static org.apache.dubbo.common.Constants.ACCEPT_FOREIGN_IP; import static org.apache.dubbo.common.Constants.QOS_ENABLE; import static org.apache.dubbo.common.Constants.QOS_PORT; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; public class QosProtocolWrapper implements Protocol { @@ -56,7 +56,7 @@ public int getDefaultPort() { @Override public Exporter export(Invoker invoker) throws RpcException { - if (Constants.REGISTRY_PROTOCOL.equals(invoker.getUrl().getProtocol())) { + if (REGISTRY_PROTOCOL.equals(invoker.getUrl().getProtocol())) { startQosServer(invoker.getUrl()); return protocol.export(invoker); } @@ -65,7 +65,7 @@ public Exporter export(Invoker invoker) throws RpcException { @Override public Invoker refer(Class type, URL url) throws RpcException { - if (Constants.REGISTRY_PROTOCOL.equals(url.getProtocol())) { + if (REGISTRY_PROTOCOL.equals(url.getProtocol())) { startQosServer(url); return protocol.refer(type, url); } diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/protocol/QosProtocolWrapperTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/protocol/QosProtocolWrapperTest.java index cbffcd5ac24..a958d7cbdc1 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/protocol/QosProtocolWrapperTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/protocol/QosProtocolWrapperTest.java @@ -22,13 +22,15 @@ import org.apache.dubbo.qos.server.Server; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import static org.hamcrest.Matchers.is; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -46,7 +48,7 @@ public void setUp() throws Exception { when(url.getParameter(Constants.QOS_PORT, 22222)).thenReturn(12345); when(url.getParameter(Constants.ACCEPT_FOREIGN_IP, true)).thenReturn(false); when(invoker.getUrl()).thenReturn(url); - when(url.getProtocol()).thenReturn(Constants.REGISTRY_PROTOCOL); + when(url.getProtocol()).thenReturn(REGISTRY_PROTOCOL); } @AfterEach diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java index a28383fade7..5b968974d0d 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java @@ -59,14 +59,6 @@ import java.util.Set; import java.util.stream.Collectors; -import static org.apache.dubbo.common.Constants.APP_DYNAMIC_CONFIGURATORS_CATEGORY; -import static org.apache.dubbo.common.Constants.CATEGORY_KEY; -import static org.apache.dubbo.common.Constants.CONFIGURATORS_CATEGORY; -import static org.apache.dubbo.common.Constants.DEFAULT_CATEGORY; -import static org.apache.dubbo.common.Constants.DYNAMIC_CONFIGURATORS_CATEGORY; -import static org.apache.dubbo.common.Constants.PROVIDERS_CATEGORY; -import static org.apache.dubbo.common.Constants.ROUTERS_CATEGORY; -import static org.apache.dubbo.common.Constants.ROUTE_PROTOCOL; import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DISABLED_KEY; @@ -74,6 +66,18 @@ import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.APP_DYNAMIC_CONFIGURATORS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.COMPATIBLE_CONFIG_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_SUFFIX; +import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_CONFIGURATORS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.ROUTE_PROTOCOL; /** @@ -140,7 +144,7 @@ private URL turnRegistryUrlToConsumerUrl(URL url) { // save any parameter in registry that will be useful to the new url. String isDefault = url.getParameter(DEFAULT_KEY); if (StringUtils.isNotEmpty(isDefault)) { - queryMap.put(Constants.REGISTRY_KEY + "." + DEFAULT_KEY, isDefault); + queryMap.put(REGISTRY_KEY + "." + DEFAULT_KEY, isDefault); } return URLBuilder.from(url) .setPath(url.getServiceInterface()) @@ -250,7 +254,7 @@ private void refreshInvoker(List invokerUrls) { if (invokerUrls.size() == 1 && invokerUrls.get(0) != null - && Constants.EMPTY_PROTOCOL.equals(invokerUrls.get(0).getProtocol())) { + && EMPTY_PROTOCOL.equals(invokerUrls.get(0).getProtocol())) { this.forbidden = true; // Forbid to access this.invokers = Collections.emptyList(); routerChain.setInvokers(this.invokers); @@ -336,7 +340,7 @@ private Optional> toRouters(List urls) { List routers = new ArrayList<>(); for (URL url : urls) { - if (Constants.EMPTY_PROTOCOL.equals(url.getProtocol())) { + if (EMPTY_PROTOCOL.equals(url.getProtocol())) { continue; } String routerType = url.getParameter(Constants.ROUTER_KEY); @@ -384,7 +388,7 @@ private Map> toInvokers(List urls) { continue; } } - if (Constants.EMPTY_PROTOCOL.equals(providerUrl.getProtocol())) { + if (EMPTY_PROTOCOL.equals(providerUrl.getProtocol())) { continue; } if (!ExtensionLoader.getExtensionLoader(Protocol.class).hasExtension(providerUrl.getProtocol())) { @@ -655,7 +659,7 @@ private boolean isValidCategory(URL url) { } private boolean isNotCompatibleFor26x(URL url) { - return StringUtils.isEmpty(url.getParameter(Constants.COMPATIBLE_CONFIG_KEY)); + return StringUtils.isEmpty(url.getParameter(COMPATIBLE_CONFIG_KEY)); } private void overrideDirectoryUrl() { @@ -704,7 +708,7 @@ private static class ReferenceConfigurationListener extends AbstractConfigurator ReferenceConfigurationListener(RegistryDirectory directory, URL url) { this.directory = directory; this.url = url; - this.initWith(url.getEncodedServiceKey() + Constants.CONFIGURATORS_SUFFIX); + this.initWith(url.getEncodedServiceKey() + CONFIGURATORS_SUFFIX); } @Override @@ -718,7 +722,7 @@ private static class ConsumerConfigurationListener extends AbstractConfiguratorL List listeners = new ArrayList<>(); ConsumerConfigurationListener() { - this.initWith(ApplicationModel.getApplication() + Constants.CONFIGURATORS_SUFFIX); + this.initWith(ApplicationModel.getApplication() + CONFIGURATORS_SUFFIX); } void addNotifyListener(RegistryDirectory listener) { diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java index fcd0de288bf..c7db7012f77 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java @@ -53,31 +53,13 @@ import static java.util.concurrent.Executors.newSingleThreadExecutor; import static org.apache.dubbo.common.Constants.ACCEPT_FOREIGN_IP; -import static org.apache.dubbo.common.constants.RemotingConstants.BIND_IP_KEY; -import static org.apache.dubbo.common.constants.RemotingConstants.BIND_PORT_KEY; -import static org.apache.dubbo.common.Constants.CATEGORY_KEY; -import static org.apache.dubbo.common.constants.RemotingConstants.CHECK_KEY; -import static org.apache.dubbo.common.Constants.CONFIGURATORS_CATEGORY; -import static org.apache.dubbo.common.Constants.CONFIGURATORS_SUFFIX; -import static org.apache.dubbo.common.Constants.CONSUMERS_CATEGORY; -import static org.apache.dubbo.common.Constants.CONSUMER_PROTOCOL; -import static org.apache.dubbo.common.Constants.DEFAULT_REGISTRY; import static org.apache.dubbo.common.Constants.EXPORT_KEY; -import static org.apache.dubbo.common.Constants.EXTRA_KEYS_KEY; import static org.apache.dubbo.common.Constants.INTERFACES; import static org.apache.dubbo.common.Constants.MONITOR_KEY; -import static org.apache.dubbo.common.Constants.OVERRIDE_PROTOCOL; -import static org.apache.dubbo.common.Constants.PROVIDERS_CATEGORY; -import static org.apache.dubbo.common.Constants.PROVIDER_PROTOCOL; import static org.apache.dubbo.common.Constants.QOS_ENABLE; import static org.apache.dubbo.common.Constants.QOS_PORT; import static org.apache.dubbo.common.Constants.REFER_KEY; import static org.apache.dubbo.common.Constants.REGISTER_IP_KEY; -import static org.apache.dubbo.common.Constants.REGISTER_KEY; -import static org.apache.dubbo.common.Constants.REGISTRY_KEY; -import static org.apache.dubbo.common.Constants.REGISTRY_PROTOCOL; -import static org.apache.dubbo.common.Constants.ROUTERS_CATEGORY; -import static org.apache.dubbo.common.Constants.SIMPLIFIED_KEY; import static org.apache.dubbo.common.Constants.VALIDATION_KEY; import static org.apache.dubbo.common.constants.ClusterConstants.LOADBALANCE_KEY; import static org.apache.dubbo.common.constants.ClusterConstants.WARMUP_KEY; @@ -95,6 +77,24 @@ import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.CLUSTER_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_SUFFIX; +import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTRY; +import static org.apache.dubbo.common.constants.RegistryConstants.EXTRA_KEYS_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.OVERRIDE_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDER_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.SIMPLIFIED_KEY; +import static org.apache.dubbo.common.constants.RemotingConstants.BIND_IP_KEY; +import static org.apache.dubbo.common.constants.RemotingConstants.BIND_PORT_KEY; +import static org.apache.dubbo.common.constants.RemotingConstants.CHECK_KEY; import static org.apache.dubbo.common.constants.RemotingConstants.CODEC_KEY; import static org.apache.dubbo.common.constants.RemotingConstants.EXCHANGER_KEY; import static org.apache.dubbo.common.constants.RemotingConstants.SERIALIZATION_KEY; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/AbstractRetryTask.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/AbstractRetryTask.java index fcbea5fd3c3..f367d17873d 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/AbstractRetryTask.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/AbstractRetryTask.java @@ -17,7 +17,6 @@ package org.apache.dubbo.registry.retry; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -29,6 +28,11 @@ import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTRY_RETRY_PERIOD; +import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTRY_RETRY_TIMES; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_RETRY_PERIOD_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_RETRY_TIMES_KEY; + /** * AbstractRetryTask */ @@ -77,8 +81,8 @@ public abstract class AbstractRetryTask implements TimerTask { this.registry = registry; this.taskName = taskName; cancel = false; - this.retryPeriod = url.getParameter(Constants.REGISTRY_RETRY_PERIOD_KEY, Constants.DEFAULT_REGISTRY_RETRY_PERIOD); - this.retryTimes = url.getParameter(Constants.REGISTRY_RETRY_TIMES_KEY, Constants.DEFAULT_REGISTRY_RETRY_TIMES); + this.retryPeriod = url.getParameter(REGISTRY_RETRY_PERIOD_KEY, DEFAULT_REGISTRY_RETRY_PERIOD); + this.retryTimes = url.getParameter(REGISTRY_RETRY_TIMES_KEY, DEFAULT_REGISTRY_RETRY_TIMES); } public void cancel() { diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.java index 5d2f0e386e5..27a6b1a6c70 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.registry.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -55,6 +54,11 @@ import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.FILE_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_FILESAVE_SYNC_KEY; /** * AbstractRegistry. (SPI, Prototype, ThreadSafe) @@ -87,7 +91,7 @@ public abstract class AbstractRegistry implements Registry { public AbstractRegistry(URL url) { setUrl(url); // Start file save timer - syncSaveFile = url.getParameter(Constants.REGISTRY_FILESAVE_SYNC_KEY, false); + syncSaveFile = url.getParameter(REGISTRY_FILESAVE_SYNC_KEY, false); String filename = url.getParameter(FILE_KEY, System.getProperty("user.home") + "/.dubbo/dubbo-registry-" + url.getParameter(APPLICATION_KEY) + "-" + url.getAddress() + ".cache"); File file = null; if (ConfigUtils.isNotEmpty(filename)) { @@ -108,7 +112,7 @@ public AbstractRegistry(URL url) { protected static List filterEmpty(URL url, List urls) { if (CollectionUtils.isEmpty(urls)) { List result = new ArrayList<>(1); - result.add(url.setProtocol(Constants.EMPTY_PROTOCOL)); + result.add(url.setProtocol(EMPTY_PROTOCOL)); return result; } return urls; @@ -246,7 +250,7 @@ public List lookup(URL url) { if (notifiedUrls != null && notifiedUrls.size() > 0) { for (List urls : notifiedUrls.values()) { for (URL u : urls) { - if (!Constants.EMPTY_PROTOCOL.equals(u.getProtocol())) { + if (!EMPTY_PROTOCOL.equals(u.getProtocol())) { result.add(u); } } @@ -258,7 +262,7 @@ public List lookup(URL url) { List urls = reference.get(); if (CollectionUtils.isNotEmpty(urls)) { for (URL u : urls) { - if (!Constants.EMPTY_PROTOCOL.equals(u.getProtocol())) { + if (!EMPTY_PROTOCOL.equals(u.getProtocol())) { result.add(u); } } @@ -398,7 +402,7 @@ protected void notify(URL url, NotifyListener listener, List urls) { Map> result = new HashMap<>(); for (URL u : urls) { if (UrlUtils.isMatch(url, u)) { - String category = u.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY); + String category = u.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY); List categoryList = result.computeIfAbsent(category, k -> new ArrayList<>()); categoryList.add(u); } @@ -456,7 +460,7 @@ public void destroy() { Set destroyRegistered = new HashSet<>(getRegistered()); if (!destroyRegistered.isEmpty()) { for (URL url : new HashSet<>(getRegistered())) { - if (url.getParameter(Constants.DYNAMIC_KEY, true)) { + if (url.getParameter(DYNAMIC_KEY, true)) { try { unregister(url); if (logger.isInfoEnabled()) { diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java index ef24676c3a3..293bf461d28 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.registry.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.timer.HashedWheelTimer; @@ -39,6 +38,9 @@ import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.FILE_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTRY_RETRY_PERIOD; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_RETRY_PERIOD_KEY; /** * FailbackRegistry. (SPI, Prototype, ThreadSafe) @@ -67,7 +69,7 @@ public abstract class FailbackRegistry extends AbstractRegistry { public FailbackRegistry(URL url) { super(url); - this.retryPeriod = url.getParameter(Constants.REGISTRY_RETRY_PERIOD_KEY, Constants.DEFAULT_REGISTRY_RETRY_PERIOD); + this.retryPeriod = url.getParameter(REGISTRY_RETRY_PERIOD_KEY, DEFAULT_REGISTRY_RETRY_PERIOD); // since the retry task will not be very much. 128 ticks is enough. retryTimer = new HashedWheelTimer(new NamedThreadFactory("DubboRegistryRetryTimer", true), retryPeriod, TimeUnit.MILLISECONDS, 128); @@ -238,7 +240,7 @@ public void register(URL url) { // If the startup detection is opened, the Exception is thrown directly. boolean check = getUrl().getParameter(RemotingConstants.CHECK_KEY, true) && url.getParameter(RemotingConstants.CHECK_KEY, true) - && !Constants.CONSUMER_PROTOCOL.equals(url.getProtocol()); + && !CONSUMER_PROTOCOL.equals(url.getProtocol()); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { @@ -268,7 +270,7 @@ public void unregister(URL url) { // If the startup detection is opened, the Exception is thrown directly. boolean check = getUrl().getParameter(RemotingConstants.CHECK_KEY, true) && url.getParameter(RemotingConstants.CHECK_KEY, true) - && !Constants.CONSUMER_PROTOCOL.equals(url.getProtocol()); + && !CONSUMER_PROTOCOL.equals(url.getProtocol()); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryTest.java index 8c959ebe8a0..6f42a8d4fcf 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.registry.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.NotifyListener; @@ -35,6 +34,8 @@ import java.util.Set; import java.util.concurrent.atomic.AtomicReference; +import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; + /** * AbstractRegistryTest */ @@ -465,7 +466,7 @@ public void filterEmptyTest() throws Exception { } // check if the output is generated by a fixed way - urls.add(testUrl.setProtocol(Constants.EMPTY_PROTOCOL)); + urls.add(testUrl.setProtocol(EMPTY_PROTOCOL)); Assertions.assertEquals(AbstractRegistry.filterEmpty(testUrl, null), urls); List testUrls = new ArrayList<>(); diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/FailbackRegistryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/FailbackRegistryTest.java index dbd7db30d5d..e6ceb6b2c5c 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/FailbackRegistryTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/FailbackRegistryTest.java @@ -16,10 +16,10 @@ */ package org.apache.dubbo.registry.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.registry.NotifyListener; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -30,6 +30,8 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_RETRY_PERIOD_KEY; import static org.junit.jupiter.api.Assertions.assertEquals; public class FailbackRegistryTest { @@ -48,7 +50,7 @@ public class FailbackRegistryTest { public void setUp() throws Exception { service = "org.apache.dubbo.test.DemoService"; serviceUrl = URL.valueOf("remote://127.0.0.1/demoservice?method=get"); - registryUrl = URL.valueOf("http://1.2.3.4:9090/registry?check=false&file=N/A").addParameter(Constants.REGISTRY_RETRY_PERIOD_KEY, String.valueOf(FAILED_PERIOD)); + registryUrl = URL.valueOf("http://1.2.3.4:9090/registry?check=false&file=N/A").addParameter(REGISTRY_RETRY_PERIOD_KEY, String.valueOf(FAILED_PERIOD)); } /** @@ -74,8 +76,8 @@ public void notify(List urls) { registry.setBad(true); registry.register(serviceUrl); registry.unregister(serviceUrl); - registry.subscribe(serviceUrl.setProtocol(Constants.CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), listner); - registry.unsubscribe(serviceUrl.setProtocol(Constants.CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), listner); + registry.subscribe(serviceUrl.setProtocol(CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), listner); + registry.unsubscribe(serviceUrl.setProtocol(CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), listner); //Failure can not be called to listener. assertEquals(false, notified.get()); @@ -130,7 +132,7 @@ public void notify(List urls) { }; registry = new MockRegistry(registryUrl, latch); registry.setBad(true); - registry.subscribe(serviceUrl.setProtocol(Constants.CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), listner); + registry.subscribe(serviceUrl.setProtocol(CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), listner); //Failure can not be called to listener. assertEquals(false, notified.get()); @@ -168,7 +170,7 @@ public void notify(List urls) { } }; registry = new MockRegistry(registryUrl, new CountDownLatch(0)); - registry.subscribe(serviceUrl.setProtocol(Constants.CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), listner); + registry.subscribe(serviceUrl.setProtocol(CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), listner); assertEquals(1, count.get()); //Make sure that the subscribe call has just been called once count.incrementAndGet after the call is completed //Wait for the timer. diff --git a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java b/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java index 968e75b3ea5..e79dac7a2a4 100644 --- a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java +++ b/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java @@ -17,7 +17,6 @@ package org.apache.dubbo.registry.consul; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -50,6 +49,8 @@ import static java.util.concurrent.Executors.newCachedThreadPool; import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; +import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDER_PROTOCOL; /** * registry center implementation for consul @@ -233,11 +234,11 @@ private List getHealthServices(Map> services private boolean isConsumerSide(URL url) { - return url.getProtocol().equals(Constants.CONSUMER_PROTOCOL); + return url.getProtocol().equals(CONSUMER_PROTOCOL); } private boolean isProviderSide(URL url) { - return url.getProtocol().equals(Constants.PROVIDER_PROTOCOL); + return url.getProtocol().equals(PROVIDER_PROTOCOL); } private List convert(List services) { diff --git a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistry.java b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistry.java index 05c785a7e23..86d77a1f42b 100644 --- a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistry.java +++ b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistry.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.registry.dubbo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.constants.RemotingConstants; @@ -37,6 +36,8 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_RECONNECT_PERIOD_KEY; + /** * DubboRegistry */ @@ -70,7 +71,7 @@ public DubboRegistry(Invoker registryInvoker, RegistryService r this.registryInvoker = registryInvoker; this.registryService = registryService; // Start reconnection timer - this.reconnectPeriod = registryInvoker.getUrl().getParameter(Constants.REGISTRY_RECONNECT_PERIOD_KEY, RECONNECT_PERIOD_DEFAULT); + this.reconnectPeriod = registryInvoker.getUrl().getParameter(REGISTRY_RECONNECT_PERIOD_KEY, RECONNECT_PERIOD_DEFAULT); reconnectFuture = reconnectTimer.scheduleWithFixedDelay(() -> { // Check and connect to the registry try { diff --git a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java index 68b37c92914..c2768c724dc 100644 --- a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java +++ b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java @@ -42,6 +42,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; /** * DubboRegistryFactory @@ -105,7 +106,7 @@ public Registry createRegistry(URL url) { directory.setProtocol(protocol); directory.setRouterChain(RouterChain.buildChain(url)); directory.notify(urls); - directory.subscribe(new URL(Constants.CONSUMER_PROTOCOL, NetUtils.getLocalHost(), 0, RegistryService.class.getName(), url.getParameters())); + directory.subscribe(new URL(CONSUMER_PROTOCOL, NetUtils.getLocalHost(), 0, RegistryService.class.getName(), url.getParameters())); return registry; } } diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DubboRegistryTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DubboRegistryTest.java index 336383f5c99..74994b347ad 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DubboRegistryTest.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DubboRegistryTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.registry.dubbo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; @@ -29,11 +28,11 @@ import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; -import static org.junit.jupiter.api.Assertions.assertEquals; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.mock; @@ -55,7 +54,7 @@ public class DubboRegistryTest { @BeforeEach public void setUp() { - registryURL = new URL(Constants.REGISTRY_PROTOCOL, NetUtils.getLocalHost(), NetUtils.getAvailablePort()) + registryURL = new URL(REGISTRY_PROTOCOL, NetUtils.getLocalHost(), NetUtils.getAvailablePort()) .addParameter(RemotingConstants.CHECK_KEY, false) .setServiceInterface(RegistryService.class.getName()); serviceURL = new URL(DubboProtocol.NAME, NetUtils.getLocalHost(), NetUtils.getAvailablePort()) diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java index 4bf7e2a8835..1f82c73982f 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java @@ -56,6 +56,12 @@ import static org.apache.dubbo.common.constants.CommonConstants.DISABLED_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.ROUTE_PROTOCOL; import static org.junit.jupiter.api.Assertions.fail; @SuppressWarnings({"rawtypes", "unchecked"}) @@ -189,7 +195,7 @@ public void testNotified_WithDuplicateUrls() { private void testforbid(RegistryDirectory registryDirectory) { invocation = new RpcInvocation(); List serviceUrls = new ArrayList(); - serviceUrls.add(new URL(Constants.EMPTY_PROTOCOL, ANYHOST_VALUE, 0, service, Constants.CATEGORY_KEY, Constants.PROVIDERS_CATEGORY)); + serviceUrls.add(new URL(EMPTY_PROTOCOL, ANYHOST_VALUE, 0, service, CATEGORY_KEY, PROVIDERS_CATEGORY)); registryDirectory.notify(serviceUrls); Assertions.assertEquals(false, registryDirectory.isAvailable(), "invokers size=0 ,then the registry directory is not available"); @@ -548,15 +554,15 @@ public void testEmptyNotifyCauseForbidden() { public void testNotifyRouterUrls() { if (isScriptUnsupported) return; RegistryDirectory registryDirectory = getRegistryDirectory(); - URL routerurl = URL.valueOf(Constants.ROUTE_PROTOCOL + "://127.0.0.1:9096/"); - URL routerurl2 = URL.valueOf(Constants.ROUTE_PROTOCOL + "://127.0.0.1:9097/"); + URL routerurl = URL.valueOf(ROUTE_PROTOCOL + "://127.0.0.1:9096/"); + URL routerurl2 = URL.valueOf(ROUTE_PROTOCOL + "://127.0.0.1:9097/"); List serviceUrls = new ArrayList(); // without ROUTER_KEY, the first router should not be created. - serviceUrls.add(routerurl.addParameter(Constants.CATEGORY_KEY, Constants.ROUTERS_CATEGORY).addParameter(Constants.TYPE_KEY, "javascript").addParameter(Constants.ROUTER_KEY, + serviceUrls.add(routerurl.addParameter(CATEGORY_KEY, ROUTERS_CATEGORY).addParameter(Constants.TYPE_KEY, "javascript").addParameter(Constants.ROUTER_KEY, "notsupported").addParameter(Constants.RULE_KEY, "function test1(){}")); - serviceUrls.add(routerurl2.addParameter(Constants.CATEGORY_KEY, Constants.ROUTERS_CATEGORY).addParameter(Constants.TYPE_KEY, "javascript").addParameter(Constants.ROUTER_KEY, + serviceUrls.add(routerurl2.addParameter(CATEGORY_KEY, ROUTERS_CATEGORY).addParameter(Constants.TYPE_KEY, "javascript").addParameter(Constants.ROUTER_KEY, ScriptRouterFactory.NAME).addParameter(Constants.RULE_KEY, "function test1(){}")); @@ -866,7 +872,7 @@ public void testNofityOverrideUrls_disabled_specifiedProvider() { Assertions.assertEquals("10.20.30.141", invokers.get(0).getUrl().getHost()); durls = new ArrayList(); - durls.add(URL.valueOf("empty://0.0.0.0?" + DISABLED_KEY + "=true&" + Constants.CATEGORY_KEY + "=" + Constants.CONFIGURATORS_CATEGORY)); + durls.add(URL.valueOf("empty://0.0.0.0?" + DISABLED_KEY + "=true&" + CATEGORY_KEY + "=" + CONFIGURATORS_CATEGORY)); registryDirectory.notify(durls); List> invokers2 = registryDirectory.list(invocation); Assertions.assertEquals(2, invokers2.size()); @@ -897,7 +903,7 @@ public void testNofity_To_Decrease_provider() { Assertions.assertEquals("10.20.30.140", invokers2.get(0).getUrl().getHost()); durls = new ArrayList(); - durls.add(URL.valueOf("empty://0.0.0.0?" + DISABLED_KEY + "=true&" + Constants.CATEGORY_KEY + "=" + Constants.CONFIGURATORS_CATEGORY)); + durls.add(URL.valueOf("empty://0.0.0.0?" + DISABLED_KEY + "=true&" + CATEGORY_KEY + "=" + CONFIGURATORS_CATEGORY)); registryDirectory.notify(durls); List> invokers3 = registryDirectory.list(invocation); Assertions.assertEquals(1, invokers3.size()); @@ -934,7 +940,7 @@ public void testNofity_disabled_specifiedProvider() { public void testNotifyRouterUrls_Clean() { if (isScriptUnsupported) return; RegistryDirectory registryDirectory = getRegistryDirectory(); - URL routerurl = URL.valueOf(Constants.ROUTE_PROTOCOL + "://127.0.0.1:9096/").addParameter(Constants.ROUTER_KEY, + URL routerurl = URL.valueOf(ROUTE_PROTOCOL + "://127.0.0.1:9096/").addParameter(Constants.ROUTER_KEY, "javascript").addParameter(Constants.RULE_KEY, "function test1(){}").addParameter(Constants.ROUTER_KEY, "script"); // FIX diff --git a/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistry.java b/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistry.java index 93612b5457f..1bb5bb155d7 100644 --- a/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistry.java +++ b/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistry.java @@ -61,6 +61,14 @@ import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; +import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; /** @@ -120,7 +128,7 @@ protected static String appendDefaultPort(String address) { public void doRegister(URL url) { try { String path = toUrlPath(url); - if (url.getParameter(Constants.DYNAMIC_KEY, true)) { + if (url.getParameter(DYNAMIC_KEY, true)) { etcdClient.createEphemeral(path); return; } @@ -304,11 +312,10 @@ protected String toServicePath(URL url) { protected String[] toCategoriesPath(URL url) { String[] categories; - if (ANY_VALUE.equals(url.getParameter(Constants.CATEGORY_KEY))) { - categories = new String[]{Constants.PROVIDERS_CATEGORY, Constants.CONSUMERS_CATEGORY, - Constants.ROUTERS_CATEGORY, Constants.CONFIGURATORS_CATEGORY}; + if (ANY_VALUE.equals(url.getParameter(CATEGORY_KEY))) { + categories = new String[]{PROVIDERS_CATEGORY, CONSUMERS_CATEGORY, ROUTERS_CATEGORY, CONFIGURATORS_CATEGORY}; } else { - categories = url.getParameter(Constants.CATEGORY_KEY, new String[]{Constants.DEFAULT_CATEGORY}); + categories = url.getParameter(CATEGORY_KEY, new String[]{DEFAULT_CATEGORY}); } String[] paths = new String[categories.length]; for (int i = 0; i < categories.length; i++) { @@ -318,7 +325,7 @@ protected String[] toCategoriesPath(URL url) { } protected String toCategoryPath(URL url) { - return toServicePath(url) + PATH_SEPARATOR + url.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY); + return toServicePath(url) + PATH_SEPARATOR + url.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY); } protected String toUrlPath(URL url) { @@ -361,7 +368,7 @@ protected List toUrlsWithEmpty(URL consumer, String path, List prov if (urls == null || urls.isEmpty()) { int i = path.lastIndexOf('/'); String category = i < 0 ? path : path.substring(i + 1); - URL empty = consumer.setProtocol(Constants.EMPTY_PROTOCOL).addParameter(Constants.CATEGORY_KEY, category); + URL empty = consumer.setProtocol(EMPTY_PROTOCOL).addParameter(CATEGORY_KEY, category); urls.add(empty); } return urls; diff --git a/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java b/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java index f972242a1d6..e0514aebd15 100644 --- a/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java +++ b/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java @@ -50,7 +50,6 @@ */ package org.apache.dubbo.registry.etcd; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; @@ -80,6 +79,12 @@ import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.ADMIN_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; @Disabled public class EtcdRegistryTest { @@ -94,15 +99,12 @@ public class EtcdRegistryTest { RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getAdaptiveExtension(); EtcdRegistry registry; URL subscribe = new URL( - Constants.ADMIN_PROTOCOL, NetUtils.getLocalHost(), 0, "", + ADMIN_PROTOCOL, NetUtils.getLocalHost(), 0, "", INTERFACE_KEY, ANY_VALUE, GROUP_KEY, ANY_VALUE, VERSION_KEY, ANY_VALUE, CLASSIFIER_KEY, ANY_VALUE, - Constants.CATEGORY_KEY, Constants.PROVIDERS_CATEGORY + "," - + Constants.CONSUMERS_CATEGORY + "," - + Constants.ROUTERS_CATEGORY + "," - + Constants.CONFIGURATORS_CATEGORY, + CATEGORY_KEY, PROVIDERS_CATEGORY + "," + CONSUMERS_CATEGORY + "," + ROUTERS_CATEGORY + "," + CONFIGURATORS_CATEGORY, ENABLED_KEY, ANY_VALUE, RemotingConstants.CHECK_KEY, String.valueOf(false)); diff --git a/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java b/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java index ae7b004ab38..3f4eb269bc6 100644 --- a/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java +++ b/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.registry.multicast; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -49,9 +48,21 @@ import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; +import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_SESSION_TIMEOUT; +import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.OVERRIDE_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.ROUTE_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.SESSION_TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.SUBSCRIBE; +import static org.apache.dubbo.common.constants.RegistryConstants.UNREGISTER; +import static org.apache.dubbo.common.constants.RegistryConstants.UNSUBSCRIBE; /** * MulticastRegistry @@ -119,7 +130,7 @@ public void run() { } catch (IOException e) { throw new IllegalStateException(e.getMessage(), e); } - this.cleanPeriod = url.getParameter(Constants.SESSION_TIMEOUT_KEY, Constants.DEFAULT_SESSION_TIMEOUT); + this.cleanPeriod = url.getParameter(SESSION_TIMEOUT_KEY, DEFAULT_SESSION_TIMEOUT); if (url.getParameter("clean", true)) { this.cleanFuture = cleanExecutor.scheduleWithFixedDelay(new Runnable() { @Override @@ -168,7 +179,7 @@ private void clean() { } private boolean isExpired(URL url) { - if (!url.getParameter(Constants.DYNAMIC_KEY, true) || url.getPort() <= 0 || Constants.CONSUMER_PROTOCOL.equals(url.getProtocol()) || Constants.ROUTE_PROTOCOL.equals(url.getProtocol()) || Constants.OVERRIDE_PROTOCOL.equals(url.getProtocol())) { + if (!url.getParameter(DYNAMIC_KEY, true) || url.getPort() <= 0 || CONSUMER_PROTOCOL.equals(url.getProtocol()) || ROUTE_PROTOCOL.equals(url.getProtocol()) || OVERRIDE_PROTOCOL.equals(url.getProtocol())) { return false; } try (Socket socket = new Socket(url.getHost(), url.getPort())) { @@ -189,14 +200,14 @@ private void receive(String msg, InetSocketAddress remoteAddress) { if (logger.isInfoEnabled()) { logger.info("Receive multicast message: " + msg + " from " + remoteAddress); } - if (msg.startsWith(Constants.REGISTER)) { - URL url = URL.valueOf(msg.substring(Constants.REGISTER.length()).trim()); + if (msg.startsWith(REGISTER)) { + URL url = URL.valueOf(msg.substring(REGISTER.length()).trim()); registered(url); - } else if (msg.startsWith(Constants.UNREGISTER)) { - URL url = URL.valueOf(msg.substring(Constants.UNREGISTER.length()).trim()); + } else if (msg.startsWith(UNREGISTER)) { + URL url = URL.valueOf(msg.substring(UNREGISTER.length()).trim()); unregistered(url); - } else if (msg.startsWith(Constants.SUBSCRIBE)) { - URL url = URL.valueOf(msg.substring(Constants.SUBSCRIBE.length()).trim()); + } else if (msg.startsWith(SUBSCRIBE)) { + URL url = URL.valueOf(msg.substring(SUBSCRIBE.length()).trim()); Set urls = getRegistered(); if (CollectionUtils.isNotEmpty(urls)) { for (URL u : urls) { @@ -204,9 +215,9 @@ private void receive(String msg, InetSocketAddress remoteAddress) { String host = remoteAddress != null && remoteAddress.getAddress() != null ? remoteAddress.getAddress().getHostAddress() : url.getIp(); if (url.getParameter("unicast", true) // Whether the consumer's machine has only one process && !NetUtils.getLocalHost().equals(host)) { // Multiple processes in the same machine cannot be unicast with unicast or there will be only one process receiving information - unicast(Constants.REGISTER + " " + u.toFullString(), host); + unicast(REGISTER + " " + u.toFullString(), host); } else { - multicast(Constants.REGISTER + " " + u.toFullString()); + multicast(REGISTER + " " + u.toFullString()); } } } @@ -243,12 +254,12 @@ private void unicast(String msg, String host) { @Override public void doRegister(URL url) { - multicast(Constants.REGISTER + " " + url.toFullString()); + multicast(REGISTER + " " + url.toFullString()); } @Override public void doUnregister(URL url) { - multicast(Constants.UNREGISTER + " " + url.toFullString()); + multicast(UNREGISTER + " " + url.toFullString()); } @Override @@ -256,7 +267,7 @@ public void doSubscribe(URL url, NotifyListener listener) { if (ANY_VALUE.equals(url.getServiceInterface())) { admin = true; } - multicast(Constants.SUBSCRIBE + " " + url.toFullString()); + multicast(SUBSCRIBE + " " + url.toFullString()); synchronized (listener) { try { listener.wait(url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT)); @@ -267,10 +278,10 @@ public void doSubscribe(URL url, NotifyListener listener) { @Override public void doUnsubscribe(URL url, NotifyListener listener) { - if (!ANY_VALUE.equals(url.getServiceInterface()) && url.getParameter(Constants.REGISTER_KEY, true)) { + if (!ANY_VALUE.equals(url.getServiceInterface()) && url.getParameter(REGISTER_KEY, true)) { unregister(url); } - multicast(Constants.UNSUBSCRIBE + " " + url.toFullString()); + multicast(UNSUBSCRIBE + " " + url.toFullString()); } @Override @@ -335,7 +346,7 @@ protected void unregistered(URL url) { if (urls == null) { urls = new ConcurrentHashSet(); } - URL empty = url.setProtocol(Constants.EMPTY_PROTOCOL); + URL empty = url.setProtocol(EMPTY_PROTOCOL); urls.add(empty); } List list = toList(urls); diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java index 40d4a1355bd..1af3ec2059c 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.registry.nacos; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -47,19 +46,19 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; -import static org.apache.dubbo.common.Constants.ADMIN_PROTOCOL; -import static org.apache.dubbo.common.Constants.CATEGORY_KEY; -import static org.apache.dubbo.common.Constants.CONFIGURATORS_CATEGORY; -import static org.apache.dubbo.common.Constants.CONSUMERS_CATEGORY; -import static org.apache.dubbo.common.Constants.DEFAULT_CATEGORY; -import static org.apache.dubbo.common.Constants.PROVIDERS_CATEGORY; -import static org.apache.dubbo.common.Constants.ROUTERS_CATEGORY; import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.ADMIN_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; /** * Nacos {@link Registry} @@ -385,7 +384,7 @@ private void notifySubscriber(URL url, NotifyListener listener, Collection { try { deferExpired(); // Extend the expiration time @@ -181,10 +190,10 @@ private void deferExpired() { try { try (Jedis jedis = jedisPool.getResource()) { for (URL url : new HashSet<>(getRegistered())) { - if (url.getParameter(Constants.DYNAMIC_KEY, true)) { + if (url.getParameter(DYNAMIC_KEY, true)) { String key = toCategoryPath(url); if (jedis.hset(key, url.toFullString(), String.valueOf(System.currentTimeMillis() + expirePeriod)) == 1) { - jedis.publish(key, Constants.REGISTER); + jedis.publish(key, REGISTER); } } } @@ -212,7 +221,7 @@ private void clean(Jedis jedis) { long now = System.currentTimeMillis(); for (Map.Entry entry : values.entrySet()) { URL url = URL.valueOf(entry.getKey()); - if (url.getParameter(Constants.DYNAMIC_KEY, true)) { + if (url.getParameter(DYNAMIC_KEY, true)) { long expire = Long.parseLong(entry.getValue()); if (expire < now) { jedis.hdel(key, entry.getKey()); @@ -224,7 +233,7 @@ private void clean(Jedis jedis) { } } if (delete) { - jedis.publish(key, Constants.UNREGISTER); + jedis.publish(key, UNREGISTER); } } } @@ -282,7 +291,7 @@ public void doRegister(URL url) { try { try (Jedis jedis = jedisPool.getResource()) { jedis.hset(key, value, expire); - jedis.publish(key, Constants.REGISTER); + jedis.publish(key, REGISTER); success = true; if (!replicate) { break; //  If the server side has synchronized data, just write a single machine @@ -312,7 +321,7 @@ public void doUnregister(URL url) { try { try (Jedis jedis = jedisPool.getResource()) { jedis.hdel(key, value); - jedis.publish(key, Constants.UNREGISTER); + jedis.publish(key, UNREGISTER); success = true; if (!replicate) { break; //  If the server side has synchronized data, just write a single machine @@ -399,7 +408,7 @@ private void doNotify(Jedis jedis, Collection keys, URL url, Collection< } long now = System.currentTimeMillis(); List result = new ArrayList<>(); - List categories = Arrays.asList(url.getParameter(Constants.CATEGORY_KEY, new String[0])); + List categories = Arrays.asList(url.getParameter(CATEGORY_KEY, new String[0])); String consumerService = url.getServiceInterface(); for (String key : keys) { if (!ANY_VALUE.equals(consumerService)) { @@ -417,7 +426,7 @@ private void doNotify(Jedis jedis, Collection keys, URL url, Collection< if (CollectionUtils.isNotEmptyMap(values)) { for (Map.Entry entry : values.entrySet()) { URL u = URL.valueOf(entry.getKey()); - if (!u.getParameter(Constants.DYNAMIC_KEY, true) + if (!u.getParameter(DYNAMIC_KEY, true) || Long.parseLong(entry.getValue()) >= now) { if (UrlUtils.isMatch(url, u)) { urls.add(u); @@ -427,10 +436,10 @@ private void doNotify(Jedis jedis, Collection keys, URL url, Collection< } if (urls.isEmpty()) { urls.add(URLBuilder.from(url) - .setProtocol(Constants.EMPTY_PROTOCOL) + .setProtocol(EMPTY_PROTOCOL) .setAddress(ANYHOST_VALUE) .setPath(toServiceName(key)) - .addParameter(Constants.CATEGORY_KEY, category) + .addParameter(CATEGORY_KEY, category) .build()); } result.addAll(urls); @@ -471,7 +480,7 @@ private String toServicePath(URL url) { } private String toCategoryPath(URL url) { - return toServicePath(url) + PATH_SEPARATOR + url.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY); + return toServicePath(url) + PATH_SEPARATOR + url.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY); } private class NotifySub extends JedisPubSub { @@ -487,8 +496,8 @@ public void onMessage(String key, String msg) { if (logger.isInfoEnabled()) { logger.info("redis event: " + key + " = " + msg); } - if (msg.equals(Constants.REGISTER) - || msg.equals(Constants.UNREGISTER)) { + if (msg.equals(REGISTER) + || msg.equals(UNREGISTER)) { try { Jedis jedis = jedisPool.getResource(); try { diff --git a/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistry.java b/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistry.java index f83e0e6dada..c708688e6a7 100644 --- a/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistry.java +++ b/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistry.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.registry.sofa; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -47,6 +46,10 @@ import static org.apache.dubbo.common.constants.CommonConstants.DUBBO; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDER_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.SUBSCRIBE_KEY; import static org.apache.dubbo.registry.sofa.SofaRegistryConstants.ADDRESS_WAIT_TIME_KEY; import static org.apache.dubbo.registry.sofa.SofaRegistryConstants.DEFAULT_GROUP; import static org.apache.dubbo.registry.sofa.SofaRegistryConstants.LOCAL_DATA_CENTER; @@ -114,8 +117,8 @@ public boolean isAvailable() { @Override public void doRegister(URL url) { - if (!url.getParameter(Constants.REGISTER_KEY, true) - || Constants.CONSUMER_PROTOCOL.equals(url.getProtocol())) { + if (!url.getParameter(REGISTER_KEY, true) + || CONSUMER_PROTOCOL.equals(url.getProtocol())) { return; } @@ -139,8 +142,8 @@ protected void addAttributesForPub(PublisherRegistration publisherRegistration) @Override public void doUnregister(URL url) { - if (!url.getParameter(Constants.REGISTER_KEY, true) - || Constants.CONSUMER_PROTOCOL.equals(url.getProtocol())) { + if (!url.getParameter(REGISTER_KEY, true) + || CONSUMER_PROTOCOL.equals(url.getProtocol())) { return; } String serviceName = buildServiceName(url); @@ -149,8 +152,8 @@ public void doUnregister(URL url) { @Override public void doSubscribe(URL url, final NotifyListener listener) { - if (!url.getParameter(Constants.SUBSCRIBE_KEY, true) - || Constants.PROVIDER_PROTOCOL.equals(url.getProtocol())) { + if (!url.getParameter(SUBSCRIBE_KEY, true) + || PROVIDER_PROTOCOL.equals(url.getProtocol())) { return; } @@ -195,8 +198,8 @@ private void waitAddress(String serviceName, CountDownLatch countDownLatch) { @Override public void doUnsubscribe(URL url, NotifyListener listener) { - if (!url.getParameter(Constants.SUBSCRIBE_KEY, true) - || Constants.PROVIDER_PROTOCOL.equals(url.getProtocol())) { + if (!url.getParameter(SUBSCRIBE_KEY, true) + || PROVIDER_PROTOCOL.equals(url.getProtocol())) { return; } String serviceName = buildServiceName(url); diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.java index 74ed7215e20..2731ffae116 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.registry.zookeeper; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.constants.RemotingConstants; @@ -44,6 +43,14 @@ import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_SEPARATOR; +import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; /** * ZookeeperRegistry @@ -105,7 +112,7 @@ public void destroy() { @Override public void doRegister(URL url) { try { - zkClient.create(toUrlPath(url), url.getParameter(Constants.DYNAMIC_KEY, true)); + zkClient.create(toUrlPath(url), url.getParameter(DYNAMIC_KEY, true)); } catch (Throwable e) { throw new RpcException("Failed to register " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e); } @@ -238,11 +245,10 @@ private String toServicePath(URL url) { private String[] toCategoriesPath(URL url) { String[] categories; - if (ANY_VALUE.equals(url.getParameter(Constants.CATEGORY_KEY))) { - categories = new String[]{Constants.PROVIDERS_CATEGORY, Constants.CONSUMERS_CATEGORY, - Constants.ROUTERS_CATEGORY, Constants.CONFIGURATORS_CATEGORY}; + if (ANY_VALUE.equals(url.getParameter(CATEGORY_KEY))) { + categories = new String[]{PROVIDERS_CATEGORY, CONSUMERS_CATEGORY, ROUTERS_CATEGORY, CONFIGURATORS_CATEGORY}; } else { - categories = url.getParameter(Constants.CATEGORY_KEY, new String[]{Constants.DEFAULT_CATEGORY}); + categories = url.getParameter(CATEGORY_KEY, new String[]{DEFAULT_CATEGORY}); } String[] paths = new String[categories.length]; for (int i = 0; i < categories.length; i++) { @@ -252,7 +258,7 @@ private String[] toCategoriesPath(URL url) { } private String toCategoryPath(URL url) { - return toServicePath(url) + PATH_SEPARATOR + url.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY); + return toServicePath(url) + PATH_SEPARATOR + url.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY); } private String toUrlPath(URL url) { @@ -281,8 +287,8 @@ private List toUrlsWithEmpty(URL consumer, String path, List provid int i = path.lastIndexOf(PATH_SEPARATOR); String category = i < 0 ? path : path.substring(i + 1); URL empty = URLBuilder.from(consumer) - .setProtocol(Constants.EMPTY_PROTOCOL) - .addParameter(Constants.CATEGORY_KEY, category) + .setProtocol(EMPTY_PROTOCOL) + .addParameter(CATEGORY_KEY, category) .build(); urls.add(empty); } diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java index bb994e6ca70..7e584cc1ed8 100644 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java +++ b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java @@ -17,7 +17,6 @@ package org.apache.dubbo.remoting.etcd.jetcd; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -61,6 +60,9 @@ import static java.util.stream.Collectors.toList; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; +import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTRY_RETRY_PERIOD; +import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_SESSION_TIMEOUT; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_RETRY_PERIOD_KEY; import static org.apache.dubbo.remoting.etcd.Constants.DEFAULT_ETCD3_NOTIFY_QUEUES_KEY; import static org.apache.dubbo.remoting.etcd.Constants.DEFAULT_ETCD3_NOTIFY_THREADS; import static org.apache.dubbo.remoting.etcd.Constants.DEFAULT_GRPC_QUEUES; @@ -91,14 +93,14 @@ public JEtcdClient(URL url) { JEtcdClient.this.stateChanged(StateListener.DISCONNECTED); } }); - delayPeriod = getUrl().getParameter(Constants.REGISTRY_RETRY_PERIOD_KEY, Constants.DEFAULT_REGISTRY_RETRY_PERIOD); + delayPeriod = getUrl().getParameter(REGISTRY_RETRY_PERIOD_KEY, DEFAULT_REGISTRY_RETRY_PERIOD); reconnectSchedule = Executors.newScheduledThreadPool(1, new NamedThreadFactory("etcd3-watch-auto-reconnect")); notifyExecutor = new ThreadPoolExecutor( 1 , url.getParameter(ETCD3_NOTIFY_MAXTHREADS_KEYS, DEFAULT_ETCD3_NOTIFY_THREADS) - , Constants.DEFAULT_SESSION_TIMEOUT + , DEFAULT_SESSION_TIMEOUT , TimeUnit.MILLISECONDS , new LinkedBlockingQueue(url.getParameter(DEFAULT_ETCD3_NOTIFY_QUEUES_KEY, DEFAULT_GRPC_QUEUES * 3)) , new NamedThreadFactory("etcd3-notify", true)); diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapper.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapper.java index 7bfb12120d3..58e0443422d 100644 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapper.java +++ b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapper.java @@ -68,6 +68,11 @@ import static java.util.stream.Collectors.toList; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; +import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTRY_RECONNECT_PERIOD; +import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTRY_RETRY_PERIOD; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_RETRY_PERIOD_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.SESSION_TIMEOUT_KEY; +import static org.apache.dubbo.remoting.etcd.option.Constants.DEFAULT_KEEPALIVE_TIMEOUT; public class JEtcdClientWrapper { @@ -111,9 +116,9 @@ public class JEtcdClientWrapper { public JEtcdClientWrapper(URL url) { this.url = url; - this.expirePeriod = url.getParameter(Constants.SESSION_TIMEOUT_KEY, Constants.DEFAULT_KEEPALIVE_TIMEOUT) / 1000; + this.expirePeriod = url.getParameter(SESSION_TIMEOUT_KEY, DEFAULT_KEEPALIVE_TIMEOUT) / 1000; if (expirePeriod <= 0) { - this.expirePeriod = Constants.DEFAULT_KEEPALIVE_TIMEOUT / 1000; + this.expirePeriod = DEFAULT_KEEPALIVE_TIMEOUT / 1000; } this.channel = new AtomicReference<>(); this.completableFuture = CompletableFuture.supplyAsync(() -> prepareClient(url)); @@ -122,7 +127,7 @@ public JEtcdClientWrapper(URL url) { this.retryPolicy = new RetryNTimes(1, 1000, TimeUnit.MILLISECONDS); this.failed = new IllegalStateException("Etcd3 registry is not connected yet, url:" + url); - int retryPeriod = url.getParameter(Constants.REGISTRY_RETRY_PERIOD_KEY, Constants.DEFAULT_REGISTRY_RETRY_PERIOD); + int retryPeriod = url.getParameter(REGISTRY_RETRY_PERIOD_KEY, DEFAULT_REGISTRY_RETRY_PERIOD); this.retryFuture = retryExecutor.scheduleWithFixedDelay(() -> { try { @@ -531,7 +536,7 @@ public void start() { } connectState = connected; } - }, Constants.DEFAULT_REGISTRY_RECONNECT_PERIOD, Constants.DEFAULT_REGISTRY_RECONNECT_PERIOD, TimeUnit.MILLISECONDS); + }, DEFAULT_REGISTRY_RECONNECT_PERIOD, DEFAULT_REGISTRY_RECONNECT_PERIOD, TimeUnit.MILLISECONDS); } catch (Throwable t) { logger.error("monitor reconnect status failed.", t); } diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/option/Constants.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/option/Constants.java index c935808b095..50af9a6057f 100644 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/option/Constants.java +++ b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/option/Constants.java @@ -16,15 +16,17 @@ */ package org.apache.dubbo.remoting.etcd.option; +import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_SESSION_TIMEOUT; + /** * Etcd registry constants. */ -public class Constants extends org.apache.dubbo.common.Constants { +public interface Constants { - public static final String HTTP_SUBFIX_KEY = "://"; + String HTTP_SUBFIX_KEY = "://"; - public static final String HTTP_KEY = "http://"; + String HTTP_KEY = "http://"; - public static final int DEFAULT_KEEPALIVE_TIMEOUT = DEFAULT_SESSION_TIMEOUT / 2; + int DEFAULT_KEEPALIVE_TIMEOUT = DEFAULT_SESSION_TIMEOUT / 2; } diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/support/AbstractEtcdClient.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/support/AbstractEtcdClient.java index cdc7ed5056d..1f764c60099 100644 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/support/AbstractEtcdClient.java +++ b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/support/AbstractEtcdClient.java @@ -33,7 +33,6 @@ */ package org.apache.dubbo.remoting.etcd.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -50,6 +49,10 @@ import java.util.concurrent.ConcurrentMap; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; +import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; public abstract class AbstractEtcdClient implements EtcdClient { @@ -60,10 +63,8 @@ public abstract class AbstractEtcdClient implements EtcdClient private final Set stateListeners = new ConcurrentHashSet<>(); private final ConcurrentMap> childListeners = new ConcurrentHashMap<>(); - private final List categories = Arrays.asList(Constants.PROVIDERS_CATEGORY - , Constants.CONSUMERS_CATEGORY - , Constants.ROUTERS_CATEGORY - , Constants.CONFIGURATORS_CATEGORY); + private final List categories = Arrays.asList(PROVIDERS_CATEGORY, CONSUMERS_CATEGORY, ROUTERS_CATEGORY, + CONFIGURATORS_CATEGORY); private volatile boolean closed = false; public AbstractEtcdClient(URL url) { diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientTest.java b/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientTest.java index 9674feec35d..743d3fe03e1 100644 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientTest.java +++ b/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientTest.java @@ -33,6 +33,9 @@ */ package org.apache.dubbo.remoting.etcd.jetcd; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.remoting.etcd.ChildListener; + import com.google.protobuf.ByteString; import io.etcd.jetcd.ByteSequence; import io.etcd.jetcd.Client; @@ -48,9 +51,6 @@ import io.grpc.ManagedChannel; import io.grpc.Status; import io.grpc.stub.StreamObserver; -import org.apache.dubbo.common.Constants; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.etcd.ChildListener; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -64,6 +64,7 @@ import java.util.concurrent.atomic.AtomicLong; import static java.nio.charset.StandardCharsets.UTF_8; +import static org.apache.dubbo.common.constants.RegistryConstants.SESSION_TIMEOUT_KEY; @Disabled public class JEtcdClientTest { @@ -386,7 +387,7 @@ public void test_watch_after_client_closed() throws InterruptedException { public void setUp() { // timeout in 15 seconds. URL url = URL.valueOf("etcd3://127.0.0.1:2379/com.alibaba.dubbo.registry.RegistryService") - .addParameter(Constants.SESSION_TIMEOUT_KEY, 15000); + .addParameter(SESSION_TIMEOUT_KEY, 15000); client = new JEtcdClient(url); } diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapperTest.java b/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapperTest.java index b7d2671e435..f76c362a6d5 100644 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapperTest.java +++ b/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapperTest.java @@ -33,8 +33,8 @@ */ package org.apache.dubbo.remoting.etcd.jetcd; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -49,6 +49,7 @@ import java.util.concurrent.TimeoutException; import java.util.concurrent.locks.LockSupport; +import static org.apache.dubbo.common.constants.RegistryConstants.SESSION_TIMEOUT_KEY; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.spy; @@ -91,7 +92,7 @@ public void test_create_emerphal_path_then_timeout() { String path = "/dubbo/org.apache.dubbo.demo.DemoService/providers"; URL url = URL.valueOf("etcd3://127.0.0.1:2379/org.apache.dubbo.registry.RegistryService") - .addParameter(Constants.SESSION_TIMEOUT_KEY, 1000); + .addParameter(SESSION_TIMEOUT_KEY, 1000); JEtcdClientWrapper saved = clientWrapper; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolFilterWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolFilterWrapper.java index 766971c4ebe..e45a84c8912 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolFilterWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolFilterWrapper.java @@ -31,6 +31,8 @@ import java.util.List; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; + /** * ListenerProtocol */ @@ -103,7 +105,7 @@ public int getDefaultPort() { @Override public Exporter export(Invoker invoker) throws RpcException { - if (Constants.REGISTRY_PROTOCOL.equals(invoker.getUrl().getProtocol())) { + if (REGISTRY_PROTOCOL.equals(invoker.getUrl().getProtocol())) { return protocol.export(invoker); } return protocol.export(buildInvokerChain(invoker, Constants.SERVICE_FILTER_KEY, CommonConstants.PROVIDER)); @@ -111,7 +113,7 @@ public Exporter export(Invoker invoker) throws RpcException { @Override public Invoker refer(Class type, URL url) throws RpcException { - if (Constants.REGISTRY_PROTOCOL.equals(url.getProtocol())) { + if (REGISTRY_PROTOCOL.equals(url.getProtocol())) { return protocol.refer(type, url); } return buildInvokerChain(protocol.refer(type, url), Constants.REFERENCE_FILTER_KEY, CommonConstants.CONSUMER); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapper.java index 96e37cc81e4..c12ceca1947 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapper.java @@ -30,6 +30,8 @@ import java.util.Collections; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; + /** * ListenerProtocol */ @@ -51,7 +53,7 @@ public int getDefaultPort() { @Override public Exporter export(Invoker invoker) throws RpcException { - if (Constants.REGISTRY_PROTOCOL.equals(invoker.getUrl().getProtocol())) { + if (REGISTRY_PROTOCOL.equals(invoker.getUrl().getProtocol())) { return protocol.export(invoker); } return new ListenerExporterWrapper(protocol.export(invoker), @@ -61,7 +63,7 @@ public Exporter export(Invoker invoker) throws RpcException { @Override public Invoker refer(Class type, URL url) throws RpcException { - if (Constants.REGISTRY_PROTOCOL.equals(url.getProtocol())) { + if (REGISTRY_PROTOCOL.equals(url.getProtocol())) { return protocol.refer(type, url); } return new ListenerInvokerWrapper(protocol.refer(type, url), From e69086400c188154bd1ac9592df2f7a077d08769 Mon Sep 17 00:00:00 2001 From: huazhongming Date: Mon, 13 May 2019 16:06:15 +0800 Subject: [PATCH 047/115] [DUBBO-3137]: step3 - start to use RpcConstants (#4038) * constants step3 rpc * remove useless import * remove useless import * remove useless import * remove useless import --- .../rpc/cluster/router/tag/TagRouter.java | 2 +- .../rpc/cluster/support/ClusterUtils.java | 24 +- .../support/MergeableClusterInvoker.java | 4 +- .../support/wrapper/MockClusterInvoker.java | 4 +- .../cluster/directory/MockDirInvocation.java | 7 +- .../rpc/cluster/support/ClusterUtilsTest.java | 3 +- .../support/MergeableClusterInvokerTest.java | 4 +- .../wrapper/MockClusterInvokerTest.java | 10 +- .../org/apache/dubbo/common/Constants.java | 300 ------------------ .../apache/dubbo/filter/LegacyInvocation.java | 6 +- .../apache/dubbo/service/MockInvocation.java | 7 +- .../dubbo/config/AbstractInterfaceConfig.java | 25 +- .../dubbo/config/AbstractMethodConfig.java | 16 +- .../dubbo/config/AbstractReferenceConfig.java | 9 +- .../dubbo/config/AbstractServiceConfig.java | 10 +- .../apache/dubbo/config/ProtocolConfig.java | 3 +- .../apache/dubbo/config/ReferenceConfig.java | 5 +- .../apache/dubbo/config/ServiceConfig.java | 20 +- .../dubbo/config/annotation/Reference.java | 6 +- .../dubbo/config/annotation/Service.java | 6 +- .../config/AbstractReferenceConfigTest.java | 10 +- .../config/AbstractServiceConfigTest.java | 12 +- .../dubbo/config/ReferenceConfigTest.java | 5 +- .../dubbo/config/ServiceConfigTest.java | 9 +- .../config/builders/ServiceBuilderTest.java | 6 +- .../dubbo/config/spring/ConfigTest.java | 10 +- .../config/spring/SimpleRegistryExporter.java | 3 +- .../apache/dubbo/monitor/MonitorService.java | 8 +- .../dubbo/monitor/support/MonitorFilter.java | 15 +- .../monitor/dubbo/DubboMonitorFactory.java | 2 +- .../dubbo/DubboMonitorFactoryTest.java | 7 +- .../integration/RegistryProtocol.java | 2 +- .../registry/dubbo/DubboRegistryFactory.java | 3 +- .../registry/dubbo/RegistryDirectoryTest.java | 9 +- .../dubbo/SimpleRegistryExporter.java | 3 +- .../remoting/PerformanceClientFixedTest.java | 4 +- .../dubbo/remoting/PerformanceClientTest.java | 4 +- .../support/header/HeartBeatTaskTest.java | 5 +- .../remoting/transport/mina/MinaServer.java | 2 +- .../org/apache/dubbo/rpc/ProxyFactory.java | 9 +- .../java/org/apache/dubbo/rpc/RpcContext.java | 11 +- .../org/apache/dubbo/rpc/RpcInvocation.java | 6 +- .../dubbo/rpc/filter/AccessLogFilter.java | 6 +- .../dubbo/rpc/filter/ActiveLimitFilter.java | 6 +- .../dubbo/rpc/filter/ContextFilter.java | 12 +- .../dubbo/rpc/filter/DeprecatedFilter.java | 7 +- .../apache/dubbo/rpc/filter/EchoFilter.java | 5 +- .../dubbo/rpc/filter/ExecuteLimitFilter.java | 9 +- .../dubbo/rpc/filter/GenericFilter.java | 31 +- .../dubbo/rpc/filter/GenericImplFilter.java | 17 +- .../apache/dubbo/rpc/filter/TokenFilter.java | 9 +- .../dubbo/rpc/filter/TpsLimitFilter.java | 5 +- .../rpc/filter/tps/DefaultTPSLimiter.java | 9 +- .../listener/DeprecatedInvokerListener.java | 7 +- .../dubbo/rpc/model/ConsumerMethodModel.java | 5 +- .../dubbo/rpc/protocol/AbstractInvoker.java | 7 +- .../rpc/protocol/ProtocolFilterWrapper.java | 8 +- .../rpc/protocol/ProtocolListenerWrapper.java | 8 +- .../dubbo/rpc/proxy/AbstractProxyFactory.java | 4 +- .../rpc/proxy/InvokerInvocationHandler.java | 8 +- .../wrapper/StubProxyFactoryWrapper.java | 18 +- .../apache/dubbo/rpc/support/MockInvoker.java | 34 +- .../dubbo/rpc/support/ProtocolUtils.java | 21 +- .../apache/dubbo/rpc/support/RpcUtils.java | 34 +- .../rpc/filter/DeprecatedFilterTest.java | 6 +- .../dubbo/rpc/filter/GenericFilterTest.java | 12 +- .../rpc/filter/GenericImplFilterTest.java | 8 +- .../dubbo/rpc/filter/TokenFilterTest.java | 7 +- .../rpc/filter/tps/DefaultTPSLimiterTest.java | 17 +- .../rpc/filter/tps/TpsLimitFilterTest.java | 6 +- .../dubbo/rpc/support/MockInvocation.java | 7 +- .../dubbo/rpc/support/RpcUtilsTest.java | 7 +- .../protocol/dubbo/CallbackServiceCodec.java | 28 +- .../protocol/dubbo/ChannelWrappedInvoker.java | 10 +- .../dubbo/DecodeableRpcInvocation.java | 5 +- .../dubbo/rpc/protocol/dubbo/DubboCodec.java | 14 +- .../rpc/protocol/dubbo/DubboCountCodec.java | 10 +- .../rpc/protocol/dubbo/DubboInvoker.java | 4 +- .../rpc/protocol/dubbo/DubboProtocol.java | 36 ++- .../dubbo/LazyConnectExchangeClient.java | 6 +- .../dubbo/ReferenceCountExchangeClient.java | 6 +- .../protocol/dubbo/filter/FutureFilter.java | 5 +- .../protocol/dubbo/ExplicitCallbackTest.java | 7 +- .../ReferenceCountExchangeClientTest.java | 10 +- .../dubbo/rpc/service/GenericServiceTest.java | 8 +- .../rpc/protocol/hessian/HessianProtocol.java | 24 +- .../dubbo/rpc/protocol/http/HttpProtocol.java | 13 +- .../protocol/http/HttpRemoteInvocation.java | 7 +- .../rpc/protocol/injvm/InjvmProtocol.java | 11 +- .../rpc/protocol/injvm/InjvmProtocolTest.java | 7 +- .../rpc/protocol/rest/BaseRestServer.java | 4 +- .../dubbo/rpc/protocol/rest/NettyServer.java | 5 +- .../dubbo/rpc/protocol/rest/RestProtocol.java | 9 +- .../rpc/protocol/rest/RestProtocolTest.java | 9 +- .../dubbo/rpc/protocol/rmi/RmiProtocol.java | 15 +- .../rpc/protocol/rmi/RmiRemoteInvocation.java | 7 +- .../rpc/protocol/thrift/ThriftInvoker.java | 5 +- .../rpc/protocol/thrift/ThriftProtocol.java | 7 +- 98 files changed, 546 insertions(+), 682 deletions(-) diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java index b30f3d5ed26..d4d80d3b075 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java @@ -40,7 +40,7 @@ import java.util.function.Predicate; import java.util.stream.Collectors; -import static org.apache.dubbo.common.Constants.FORCE_USE_TAG; +import static org.apache.dubbo.common.constants.RpcConstants.FORCE_USE_TAG; import static org.apache.dubbo.common.Constants.TAG_KEY; /** diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java index b45ad11d508..13df67a39ce 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java @@ -40,6 +40,10 @@ import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.REFERENCE_FILTER_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.INVOKER_LISTENER_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.ASYNC_KEY; /** * ClusterUtils @@ -78,13 +82,13 @@ public static URL mergeUrl(URL remoteUrl, Map localMap) { map.remove(RemotingConstants.TRANSPORTER_KEY); map.remove(DEFAULT_KEY_PREFIX + RemotingConstants.TRANSPORTER_KEY); - map.remove(Constants.ASYNC_KEY); - map.remove(DEFAULT_KEY_PREFIX + Constants.ASYNC_KEY); + map.remove(ASYNC_KEY); + map.remove(DEFAULT_KEY_PREFIX + ASYNC_KEY); // remove method async entry. Set methodAsyncKey = new HashSet<>(); for (String key : map.keySet()) { - if (key != null && key.endsWith("." + Constants.ASYNC_KEY)) { + if (key != null && key.endsWith("." + ASYNC_KEY)) { methodAsyncKey.add(key); } } @@ -111,7 +115,7 @@ public static URL mergeUrl(URL remoteUrl, Map localMap) { } if (remoteMap != null && remoteMap.size() > 0) { // Use version passed from provider side - reserveRemoteValue(Constants.DUBBO_VERSION_KEY, map, remoteMap); + reserveRemoteValue(DUBBO_VERSION_KEY, map, remoteMap); reserveRemoteValue(VERSION_KEY, map, remoteMap); reserveRemoteValue(METHODS_KEY, map, remoteMap); reserveRemoteValue(TIMESTAMP_KEY, map, remoteMap); @@ -121,17 +125,17 @@ public static URL mergeUrl(URL remoteUrl, Map localMap) { map.put(REMOTE_APPLICATION_KEY, remoteMap.get(APPLICATION_KEY)); // Combine filters and listeners on Provider and Consumer - String remoteFilter = remoteMap.get(Constants.REFERENCE_FILTER_KEY); - String localFilter = localMap.get(Constants.REFERENCE_FILTER_KEY); + String remoteFilter = remoteMap.get(REFERENCE_FILTER_KEY); + String localFilter = localMap.get(REFERENCE_FILTER_KEY); if (remoteFilter != null && remoteFilter.length() > 0 && localFilter != null && localFilter.length() > 0) { - localMap.put(Constants.REFERENCE_FILTER_KEY, remoteFilter + "," + localFilter); + localMap.put(REFERENCE_FILTER_KEY, remoteFilter + "," + localFilter); } - String remoteListener = remoteMap.get(Constants.INVOKER_LISTENER_KEY); - String localListener = localMap.get(Constants.INVOKER_LISTENER_KEY); + String remoteListener = remoteMap.get(INVOKER_LISTENER_KEY); + String localListener = localMap.get(INVOKER_LISTENER_KEY); if (remoteListener != null && remoteListener.length() > 0 && localListener != null && localListener.length() > 0) { - localMap.put(Constants.INVOKER_LISTENER_KEY, remoteListener + "," + localListener); + localMap.put(INVOKER_LISTENER_KEY, remoteListener + "," + localListener); } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java index 51159a99eca..334b6f2c849 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.Logger; @@ -50,6 +49,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.MERGER_KEY; @SuppressWarnings("unchecked") public class MergeableClusterInvoker extends AbstractClusterInvoker { @@ -64,7 +64,7 @@ public MergeableClusterInvoker(Directory directory) { @Override protected Result doInvoke(Invocation invocation, List> invokers, LoadBalance loadbalance) throws RpcException { checkInvokers(invokers, invocation); - String merger = getUrl().getMethodParameter(invocation.getMethodName(), Constants.MERGER_KEY); + String merger = getUrl().getMethodParameter(invocation.getMethodName(), MERGER_KEY); if (ConfigUtils.isEmpty(merger)) { // If a method doesn't have a merger, only invoke one Group for (final Invoker invoker : invokers) { if (invoker.isAvailable()) { diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java index 59303142d85..b78d2c76ce7 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java @@ -31,6 +31,8 @@ import org.apache.dubbo.rpc.cluster.Directory; import org.apache.dubbo.rpc.support.MockInvoker; +import static org.apache.dubbo.common.constants.RpcConstants.MOCK_KEY; + import java.util.List; public class MockClusterInvoker implements Invoker { @@ -70,7 +72,7 @@ public Class getInterface() { public Result invoke(Invocation invocation) throws RpcException { Result result = null; - String value = directory.getUrl().getMethodParameter(invocation.getMethodName(), Constants.MOCK_KEY, Boolean.FALSE.toString()).trim(); + String value = directory.getUrl().getMethodParameter(invocation.getMethodName(), MOCK_KEY, Boolean.FALSE.toString()).trim(); if (value.length() == 0 || value.equalsIgnoreCase("false")) { //no mock result = this.invoker.invoke(invocation); diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java index 14a57db0255..fbe697995cd 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.directory; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -27,6 +26,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; /** * MockInvocation.java @@ -50,8 +51,8 @@ public Map getAttachments() { attachments.put(PATH_KEY, "dubbo"); attachments.put(GROUP_KEY, "dubbo"); attachments.put(VERSION_KEY, "1.0.0"); - attachments.put(Constants.DUBBO_VERSION_KEY, "1.0.0"); - attachments.put(Constants.TOKEN_KEY, "sfag"); + attachments.put(DUBBO_VERSION_KEY, "1.0.0"); + attachments.put(TOKEN_KEY, "sfag"); attachments.put(TIMEOUT_KEY, "1000"); return attachments; } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ClusterUtilsTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ClusterUtilsTest.java index 8ee6f3a05e0..8c093cd6ad7 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ClusterUtilsTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ClusterUtilsTest.java @@ -33,6 +33,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; public class ClusterUtilsTest { @@ -46,7 +47,7 @@ public void testMergeUrl() throws Exception { providerURL = URLBuilder.from(providerURL) .addParameter(GROUP_KEY, "dubbo") .addParameter(VERSION_KEY, "1.2.3") - .addParameter(Constants.DUBBO_VERSION_KEY, "2.3.7") + .addParameter(DUBBO_VERSION_KEY, "2.3.7") .addParameter(THREADPOOL_KEY, "fixed") .addParameter(THREADS_KEY, Integer.MAX_VALUE) .addParameter(THREAD_NAME_KEY, "test") diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.java index 1c3260a4fc5..e80380cbd65 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -39,6 +38,7 @@ import java.util.Map; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.MERGER_KEY; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -101,7 +101,7 @@ public void setUp() throws Exception { public void testGetMenuSuccessfully() throws Exception { // setup - url = url.addParameter(Constants.MERGER_KEY, ".merge"); + url = url.addParameter(MERGER_KEY, ".merge"); given(invocation.getMethodName()).willReturn("getMenu"); given(invocation.getParameterTypes()).willReturn(new Class[]{}); diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java index 618e9705d65..ba9caa8f5d9 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java @@ -39,6 +39,8 @@ import java.util.Arrays; import java.util.List; +import static org.apache.dubbo.common.constants.RpcConstants.MOCK_KEY; + public class MockClusterInvokerTest { List> invokers = new ArrayList>(); @@ -54,7 +56,7 @@ public void beforeMethod() { @Test public void testMockInvokerInvoke_normal() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()); - url = url.addParameter(Constants.MOCK_KEY, "fail"); + url = url.addParameter(MOCK_KEY, "fail"); Invoker cluster = getClusterInvoker(url); URL mockUrl = URL.valueOf("mock://localhost/" + IHelloService.class.getName() + "?getSomething.mock=return aa"); @@ -82,7 +84,7 @@ public void testMockInvokerInvoke_normal() { @Test public void testMockInvokerInvoke_failmock() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(Constants.MOCK_KEY, "fail:return null") + .addParameter(MOCK_KEY, "fail:return null") .addParameter("invoke_return_error", "true"); URL mockUrl = URL.valueOf("mock://localhost/" + IHelloService.class.getName() + "?getSomething.mock=return aa").addParameters(url.getParameters()); @@ -117,7 +119,7 @@ public void testMockInvokerInvoke_failmock() { @Test public void testMockInvokerInvoke_forcemock() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()); - url = url.addParameter(Constants.MOCK_KEY, "force:return null"); + url = url.addParameter(MOCK_KEY, "force:return null"); URL mockUrl = URL.valueOf("mock://localhost/" + IHelloService.class.getName() + "?getSomething.mock=return aa&getSomething3xx.mock=return xx") @@ -149,7 +151,7 @@ public void testMockInvokerInvoke_forcemock() { @Test public void testMockInvokerInvoke_forcemock_defaultreturn() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()); - url = url.addParameter(Constants.MOCK_KEY, "force"); + url = url.addParameter(MOCK_KEY, "force"); Invoker cluster = getClusterInvoker(url); URL mockUrl = URL.valueOf("mock://localhost/" + IHelloService.class.getName() + "?getSomething.mock=return aa&getSomething3xx.mock=return xx&sayHello.mock=return ") diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java index 3d571fff18a..1efe9421dae 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java @@ -17,7 +17,6 @@ package org.apache.dubbo.common; -import java.util.concurrent.ExecutorService; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO; @@ -25,307 +24,8 @@ * Constants */ public class Constants { - // BEGIN dubbo-remoting-api - public static final String PAYLOAD_KEY = "payload"; - /** - * 8M - */ - public static final int DEFAULT_PAYLOAD = 8 * 1024 * 1024; - - public static final String BUFFER_KEY = "buffer"; - - /** - * default buffer size is 8k. - */ - public static final int DEFAULT_BUFFER_SIZE = 8 * 1024; - - public static final int MAX_BUFFER_SIZE = 16 * 1024; - - public static final int MIN_BUFFER_SIZE = 1 * 1024; - - public static final String CONNECT_TIMEOUT_KEY = "connect.timeout"; - - public static final int DEFAULT_CONNECT_TIMEOUT = 3000; - - public static final String HEARTBEAT_KEY = "heartbeat"; - - public static final int DEFAULT_HEARTBEAT = 60 * 1000; - - public static final String IDLE_TIMEOUT_KEY = "idle.timeout"; - - public static final int DEFAULT_IDLE_TIMEOUT = 600 * 1000; - - public static final String ACCEPTS_KEY = "accepts"; - - public static final int DEFAULT_ACCEPTS = 0; - - public static final String SERIALIZATION_KEY = "serialization"; - - public static final String DEFAULT_REMOTING_SERIALIZATION = "hessian2"; - - public static final String CODEC_KEY = "codec"; - - public static final String DEFAULT_REMOTING_CODEC = "dubbo"; - - public static final String SERVER_KEY = "server"; - - public static final String DEFAULT_REMOTING_SERVER = "netty"; - - public static final String CLIENT_KEY = "client"; - - public static final String DEFAULT_REMOTING_CLIENT = "netty"; - - public static final String TRANSPORTER_KEY = "transporter"; - - public static final String DEFAULT_TRANSPORTER = "netty"; - - public static final String EXCHANGER_KEY = "exchanger"; - - public static final String DEFAULT_EXCHANGER = "header"; - - public static final String DISPACTHER_KEY = "dispacther"; - - public static final int DEFAULT_IO_THREADS = Math.min(Runtime.getRuntime().availableProcessors() + 1, 32); - - public static final String BIND_IP_KEY = "bind.ip"; - - public static final String BIND_PORT_KEY = "bind.port"; - - public static final String SENT_KEY = "sent"; - - public static final boolean DEFAULT_SENT = false; - - public static final String DISPATCHER_KEY = "dispatcher"; - - public static final String CHANNEL_HANDLER_KEY = "channel.handler"; - - public static final String DEFAULT_CHANNEL_HANDLER = "default"; - - public static final String SERVICE_DESCIPTOR_KEY = "serviceDescriptor"; - - public static final String CONNECT_QUEUE_CAPACITY = "connect.queue.capacity"; - - public static final String CONNECT_QUEUE_WARNING_SIZE = "connect.queue.warning.size"; - - public static final int DEFAULT_CONNECT_QUEUE_WARNING_SIZE = 1000; - - public static final String CHANNEL_ATTRIBUTE_READONLY_KEY = "channel.readonly"; - - public static final String CHANNEL_READONLYEVENT_SENT_KEY = "channel.readonly.sent"; - - public static final String CHANNEL_SEND_READONLYEVENT_KEY = "channel.readonly.send"; - - public static final String EXECUTOR_SERVICE_COMPONENT_KEY = ExecutorService.class.getName(); - - public static final String CHARSET_KEY = "charset"; - - public static final String DEFAULT_CHARSET = "UTF-8"; - - public static final String BACKUP_KEY = "backup"; - - /** - * Every heartbeat duration / HEATBEAT_CHECK_TICK, check if a heartbeat should be sent. Every heartbeat timeout - * duration / HEATBEAT_CHECK_TICK, check if a connection should be closed on server side, and if reconnect on - * client side - */ - public static final int HEARTBEAT_CHECK_TICK = 3; - - /** - * the least heartbeat during is 1000 ms. - */ - public static final long LEAST_HEARTBEAT_DURATION = 1000; - - /** - * ticks per wheel. - */ - public static final int TICKS_PER_WHEEL = 128; - - public static final String HEARTBEAT_TIMEOUT_KEY = "heartbeat.timeout"; - - public static final String RECONNECT_KEY = "reconnect"; - - public static final int DEFAULT_RECONNECT_PERIOD = 2000; - - public static final String SEND_RECONNECT_KEY = "send.reconnect"; - - public static final String CHECK_KEY = "check"; - - public static final String PROMPT_KEY = "prompt"; - - public static final String DEFAULT_PROMPT = "dubbo>"; - // END dubbo-remoting-api - - // BEGIN dubbo-rpc-hessian - public static final String HESSIAN2_REQUEST_KEY = "hessian2.request"; - - public static final boolean DEFAULT_HESSIAN2_REQUEST = false; - - public static final String HESSIAN_OVERLOAD_METHOD_KEY = "hessian.overload.method"; - - public static final boolean DEFAULT_HESSIAN_OVERLOAD_METHOD = false; - - public static final String DEFAULT_HTTP_CLIENT = "jdk"; - - public static final String DEFAULT_HTTP_SERVER = "servlet"; - - public static final String DEFAULT_HTTP_SERIALIZATION = "json"; - // END dubbo-rpc-hessian - - // BEGIN dubbo-rpc-dubbo - public static final String SHARE_CONNECTIONS_KEY = "shareconnections"; - - /** - * By default, a consumer JVM instance and a provider JVM instance share a long TCP connection (except when connections are set), - * which can set the number of long TCP connections shared to avoid the bottleneck of sharing a single long TCP connection. - */ - public static final String DEFAULT_SHARE_CONNECTIONS = "1"; - - public static final String INPUT_KEY = "input"; - - public static final String OUTPUT_KEY = "output"; - - public static final String DECODE_IN_IO_THREAD_KEY = "decode.in.io"; - - public static final boolean DEFAULT_DECODE_IN_IO_THREAD = true; - - /** - * callback inst id - */ - public static final String CALLBACK_SERVICE_KEY = "callback.service.instid"; - - /** - * The limit of callback service instances for one interface on every client - */ - public static final String CALLBACK_INSTANCES_LIMIT_KEY = "callbacks"; - - /** - * The default limit number for callback service instances - * - * @see #CALLBACK_INSTANCES_LIMIT_KEY - */ - public static final int DEFAULT_CALLBACK_INSTANCES = 1; - - public static final String CALLBACK_SERVICE_PROXY_KEY = "callback.service.proxy"; - - public static final String IS_CALLBACK_SERVICE = "is_callback_service"; - - /** - * Invokers in channel's callback - */ - public static final String CHANNEL_CALLBACK_KEY = "channel.callback.invokers.key"; - - /** - * The initial state for lazy connection - */ - public static final String LAZY_CONNECT_INITIAL_STATE_KEY = "connect.lazy.initial.state"; - - /** - * The default value of lazy connection's initial state: true - * - * @see #LAZY_CONNECT_INITIAL_STATE_KEY - */ - public static final boolean DEFAULT_LAZY_CONNECT_INITIAL_STATE = true; - - public static final String OPTIMIZER_KEY = "optimizer"; - // END dubbo-rpc-dubbo - - - // BEGIN dubbo-rpc-api - public static final String DUBBO_VERSION_KEY = "dubbo"; - - public static final String LOCAL_KEY = "local"; - - public static final String STUB_KEY = "stub"; - - public static final String MOCK_KEY = "mock"; - - public static final String DEPRECATED_KEY = "deprecated"; - - public static final String $INVOKE = "$invoke"; - - public static final String $ECHO = "$echo"; - - public static final String RETURN_PREFIX = "return "; - - public static final String THROW_PREFIX = "throw"; - - public static final String FAIL_PREFIX = "fail:"; - - public static final String FORCE_PREFIX = "force:"; - - public static final String MERGER_KEY = "merger"; - - public static final String IS_SERVER_KEY = "isserver"; - - public static final String FORCE_USE_TAG = "dubbo.force.tag"; - - public static final String GENERIC_SERIALIZATION_NATIVE_JAVA = "nativejava"; - - public static final String GENERIC_SERIALIZATION_DEFAULT = "true"; - - public static final String GENERIC_SERIALIZATION_BEAN = "bean"; - - public static final String GENERIC_SERIALIZATION_PROTOBUF = "protobuf-json"; - - public static final String TPS_LIMIT_RATE_KEY = "tps"; - - public static final String TPS_LIMIT_INTERVAL_KEY = "tps.interval"; - - public static final long DEFAULT_TPS_LIMIT_INTERVAL = 60 * 1000; - - public static final String AUTO_ATTACH_INVOCATIONID_KEY = "invocationid.autoattach"; - - public static final String STUB_EVENT_KEY = "dubbo.stub.event"; - - public static final boolean DEFAULT_STUB_EVENT = false; - - public static final String STUB_EVENT_METHODS_KEY = "dubbo.stub.event.methods"; - - public static final String PROXY_KEY = "proxy"; - - public static final String EXECUTES_KEY = "executes"; - - public static final String REFERENCE_FILTER_KEY = "reference.filter"; - - public static final String INVOKER_LISTENER_KEY = "invoker.listener"; - - public static final String SERVICE_FILTER_KEY = "service.filter"; - - public static final String EXPORTER_LISTENER_KEY = "exporter.listener"; - - public static final String ACCESS_LOG_KEY = "accesslog"; - - public static final String ACTIVES_KEY = "actives"; - - public static final String CONNECTIONS_KEY = "connections"; - - public static final String ID_KEY = "id"; - - public static final String ASYNC_KEY = "async"; - - public static final String FUTURE_GENERATED_KEY = "future_generated"; - - public static final String FUTURE_RETURNTYPE_KEY = "future_returntype"; - - public static final String RETURN_KEY = "return"; - - public static final String TOKEN_KEY = "token"; - - public static final String INTERFACES = "interfaces"; - - public static final String GENERIC_KEY = "generic"; - - public static final String LOCAL_PROTOCOL = "injvm"; - // END dubbo-rpc-api - - - // BEGIN dubbo-rpc-rest - public static final String KEEP_ALIVE_KEY = "keepalive"; - public static final boolean DEFAULT_KEEP_ALIVE = true; - public static final String EXTENSION_KEY = "extension"; - // END dubbo-rpc-rest // BEGIN dubbo-config-api diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvocation.java b/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvocation.java index 97c01af3e07..4f4f1314f69 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvocation.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvocation.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.filter; -import org.apache.dubbo.common.Constants; import com.alibaba.dubbo.rpc.Invocation; import com.alibaba.dubbo.rpc.Invoker; @@ -24,11 +23,12 @@ import java.util.HashMap; import java.util.Map; -import static org.apache.dubbo.common.Constants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; /** * MockInvocation.java @@ -59,7 +59,7 @@ public Map getAttachments() { attachments.put(GROUP_KEY, "dubbo"); attachments.put(VERSION_KEY, "1.0.0"); attachments.put(DUBBO_VERSION_KEY, "1.0.0"); - attachments.put(Constants.TOKEN_KEY, "sfag"); + attachments.put(TOKEN_KEY, "sfag"); attachments.put(TIMEOUT_KEY, "1000"); return attachments; } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java b/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java index 5655f26a7bf..db85951e312 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.service; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -27,6 +26,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; /** * MockInvocation.java @@ -56,8 +57,8 @@ public Map getAttachments() { attachments.put(PATH_KEY, "dubbo"); attachments.put(GROUP_KEY, "dubbo"); attachments.put(VERSION_KEY, "1.0.0"); - attachments.put(Constants.DUBBO_VERSION_KEY, "1.0.0"); - attachments.put(Constants.TOKEN_KEY, "sfag"); + attachments.put(DUBBO_VERSION_KEY, "1.0.0"); + attachments.put(TOKEN_KEY, "sfag"); attachments.put(TIMEOUT_KEY, "1000"); return attachments; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java index c3b534d302b..42063bd1e69 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java @@ -68,6 +68,13 @@ import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.SUBSCRIBE_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.LOCAL_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.RETURN_PREFIX; +import static org.apache.dubbo.common.constants.RpcConstants.THROW_PREFIX; +import static org.apache.dubbo.common.constants.RpcConstants.PROXY_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.REFERENCE_FILTER_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.INVOKER_LISTENER_KEY; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; /** @@ -389,7 +396,7 @@ protected URL loadMonitor(URL registryURL) { } static void appendRuntimeParameters(Map map) { - map.put(Constants.DUBBO_VERSION_KEY, Version.getProtocolVersion()); + map.put(DUBBO_VERSION_KEY, Version.getProtocolVersion()); map.put(RELEASE_KEY, Version.getVersion()); map.put(TIMESTAMP_KEY, String.valueOf(System.currentTimeMillis())); if (ConfigUtils.getPid() > 0) { @@ -465,8 +472,8 @@ void checkMock(Class interfaceClass) { } String normalizedMock = MockInvoker.normalizeMock(mock); - if (normalizedMock.startsWith(Constants.RETURN_PREFIX)) { - normalizedMock = normalizedMock.substring(Constants.RETURN_PREFIX.length()).trim(); + if (normalizedMock.startsWith(RETURN_PREFIX)) { + normalizedMock = normalizedMock.substring(RETURN_PREFIX.length()).trim(); try { //Check whether the mock value is legal, if it is illegal, throw exception MockInvoker.parseMockValue(normalizedMock); @@ -474,8 +481,8 @@ void checkMock(Class interfaceClass) { throw new IllegalStateException("Illegal mock return in "); } - } else if (normalizedMock.startsWith(Constants.THROW_PREFIX)) { - normalizedMock = normalizedMock.substring(Constants.THROW_PREFIX.length()).trim(); + } else if (normalizedMock.startsWith(THROW_PREFIX)) { + normalizedMock = normalizedMock.substring(THROW_PREFIX.length()).trim(); if (ConfigUtils.isNotEmpty(normalizedMock)) { try { //Check whether the mock value is legal @@ -639,7 +646,7 @@ public void setLocal(Boolean local) { */ @Deprecated public void setLocal(String local) { - checkName(Constants.LOCAL_KEY, local); + checkName(LOCAL_KEY, local); this.local = local; } @@ -674,7 +681,7 @@ public String getProxy() { } public void setProxy(String proxy) { - checkExtension(ProxyFactory.class, Constants.PROXY_KEY, proxy); + checkExtension(ProxyFactory.class, PROXY_KEY, proxy); this.proxy = proxy; } @@ -686,7 +693,7 @@ public void setConnections(Integer connections) { this.connections = connections; } - @Parameter(key = Constants.REFERENCE_FILTER_KEY, append = true) + @Parameter(key = REFERENCE_FILTER_KEY, append = true) public String getFilter() { return filter; } @@ -696,7 +703,7 @@ public void setFilter(String filter) { this.filter = filter; } - @Parameter(key = Constants.INVOKER_LISTENER_KEY, append = true) + @Parameter(key = INVOKER_LISTENER_KEY, append = true) public String getListener() { return listener; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractMethodConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractMethodConfig.java index fd751d7515c..a36d8568de2 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractMethodConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractMethodConfig.java @@ -22,6 +22,12 @@ import java.util.Map; +import static org.apache.dubbo.common.constants.RpcConstants.MOCK_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.RETURN_PREFIX; +import static org.apache.dubbo.common.constants.RpcConstants.THROW_PREFIX; +import static org.apache.dubbo.common.constants.RpcConstants.FAIL_PREFIX; +import static org.apache.dubbo.common.constants.RpcConstants.FORCE_PREFIX; + /** * AbstractMethodConfig * @@ -164,12 +170,12 @@ public void setMock(String mock) { return; } - if (mock.startsWith(Constants.RETURN_PREFIX) || mock.startsWith(Constants.THROW_PREFIX + " ")) { - checkLength(Constants.MOCK_KEY, mock); - } else if (mock.startsWith(Constants.FAIL_PREFIX) || mock.startsWith(Constants.FORCE_PREFIX)) { - checkNameHasSymbol(Constants.MOCK_KEY, mock); + if (mock.startsWith(RETURN_PREFIX) || mock.startsWith(THROW_PREFIX + " ")) { + checkLength(MOCK_KEY, mock); + } else if (mock.startsWith(FAIL_PREFIX) || mock.startsWith(FORCE_PREFIX)) { + checkNameHasSymbol(MOCK_KEY, mock); } else { - checkName(Constants.MOCK_KEY, mock); + checkName(MOCK_KEY, mock); } this.mock = mock; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java index 69f0a69c8e9..2062a0094e2 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java @@ -24,6 +24,9 @@ import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.STUB_EVENT_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.REFERENCE_FILTER_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.INVOKER_LISTENER_KEY; /** * AbstractConsumerConfig @@ -136,13 +139,13 @@ public void setInjvm(Boolean injvm) { } @Override - @Parameter(key = Constants.REFERENCE_FILTER_KEY, append = true) + @Parameter(key = REFERENCE_FILTER_KEY, append = true) public String getFilter() { return super.getFilter(); } @Override - @Parameter(key = Constants.INVOKER_LISTENER_KEY, append = true) + @Parameter(key = INVOKER_LISTENER_KEY, append = true) public String getListener() { return super.getListener(); } @@ -178,7 +181,7 @@ public void setOndisconnect(String ondisconnect) { super.setOndisconnect(ondisconnect); } - @Parameter(key = Constants.STUB_EVENT_KEY) + @Parameter(key = STUB_EVENT_KEY) public Boolean getStubevent() { return stubevent; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java index 636039ffd7d..7bf3ccd4d52 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.config.support.Parameter; @@ -28,6 +27,9 @@ import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.SERVICE_FILTER_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.EXPORTER_LISTENER_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; /** * AbstractServiceConfig @@ -178,7 +180,7 @@ public void setToken(Boolean token) { } public void setToken(String token) { - checkName(Constants.TOKEN_KEY, token); + checkName(TOKEN_KEY, token); this.token = token; } @@ -250,13 +252,13 @@ public void setExecutes(Integer executes) { } @Override - @Parameter(key = Constants.SERVICE_FILTER_KEY, append = true) + @Parameter(key = SERVICE_FILTER_KEY, append = true) public String getFilter() { return super.getFilter(); } @Override - @Parameter(key = Constants.EXPORTER_LISTENER_KEY, append = true) + @Parameter(key = EXPORTER_LISTENER_KEY, append = true) public String getListener() { return listener; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java index 767204e255c..a32344125d8 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java @@ -34,6 +34,7 @@ import java.util.Map; import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; /** * ProtocolConfig @@ -539,7 +540,7 @@ public void destroy() { @Override public void refresh() { if (StringUtils.isEmpty(this.getName())) { - this.setName(Constants.DUBBO_VERSION_KEY); + this.setName(DUBBO_VERSION_KEY); } super.refresh(); if (StringUtils.isNotEmpty(this.getId())) { diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java index 0f6d866802e..7ab502cc99b 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java @@ -68,6 +68,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; +import static org.apache.dubbo.common.constants.RpcConstants.LOCAL_PROTOCOL; import static org.apache.dubbo.common.utils.NetUtils.isInvalidLocalHost; /** @@ -345,7 +346,7 @@ private ConsumerModel buildConsumerModel(String serviceKey, Map @SuppressWarnings({"unchecked", "rawtypes", "deprecation"}) private T createProxy(Map map) { if (shouldJvmRefer(map)) { - URL url = new URL(Constants.LOCAL_PROTOCOL, LOCALHOST_VALUE, 0, interfaceClass.getName()).addParameters(map); + URL url = new URL(LOCAL_PROTOCOL, LOCALHOST_VALUE, 0, interfaceClass.getName()).addParameters(map); invoker = REF_PROTOCOL.refer(interfaceClass, url); if (logger.isInfoEnabled()) { logger.info("Using injvm service " + interfaceClass.getName()); @@ -368,7 +369,7 @@ private T createProxy(Map map) { } } else { // assemble URL from register center's configuration // if protocols not injvm checkRegistry - if (!Constants.LOCAL_PROTOCOL.equalsIgnoreCase(getProtocol())){ + if (!LOCAL_PROTOCOL.equalsIgnoreCase(getProtocol())){ checkRegistry(); List us = loadRegistries(false); if (CollectionUtils.isNotEmpty(us)) { diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index 07ec5acd845..54a3a403d35 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -72,6 +72,10 @@ import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.PROXY_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.LOCAL_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; import static org.apache.dubbo.common.utils.NetUtils.getAvailablePort; import static org.apache.dubbo.common.utils.NetUtils.getLocalHost; @@ -347,7 +351,7 @@ public void checkAndUpdateSubConfigs() { * @return */ private boolean isOnlyInJvm() { - return getProtocols().size() == 1 && Constants.LOCAL_PROTOCOL.equalsIgnoreCase(getProtocols().get(0).getName()); + return getProtocols().size() == 1 && LOCAL_PROTOCOL.equalsIgnoreCase(getProtocols().get(0).getName()); } public synchronized void export() { @@ -518,7 +522,7 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r } if (ProtocolUtils.isGeneric(generic)) { - map.put(Constants.GENERIC_KEY, generic); + map.put(GENERIC_KEY, generic); map.put(METHODS_KEY, ANY_VALUE); } else { String revision = Version.getVersion(interfaceClass, version); @@ -536,9 +540,9 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r } if (!ConfigUtils.isEmpty(token)) { if (ConfigUtils.isDefault(token)) { - map.put(Constants.TOKEN_KEY, UUID.randomUUID().toString()); + map.put(TOKEN_KEY, UUID.randomUUID().toString()); } else { - map.put(Constants.TOKEN_KEY, token); + map.put(TOKEN_KEY, token); } } // export service @@ -568,7 +572,7 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r if (CollectionUtils.isNotEmpty(registryURLs)) { for (URL registryURL : registryURLs) { //if protocol is only injvm ,not register - if (Constants.LOCAL_PROTOCOL.equalsIgnoreCase(url.getProtocol())) { + if (LOCAL_PROTOCOL.equalsIgnoreCase(url.getProtocol())) { continue; } url = url.addParameterIfAbsent(DYNAMIC_KEY, registryURL.getParameter(DYNAMIC_KEY)); @@ -581,9 +585,9 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r } // For providers, this is used to enable custom proxy to generate invoker - String proxy = url.getParameter(Constants.PROXY_KEY); + String proxy = url.getParameter(PROXY_KEY); if (StringUtils.isNotEmpty(proxy)) { - registryURL = registryURL.addParameter(Constants.PROXY_KEY, proxy); + registryURL = registryURL.addParameter(PROXY_KEY, proxy); } Invoker invoker = proxyFactory.getInvoker(ref, (Class) interfaceClass, registryURL.addParameterAndEncoded(Constants.EXPORT_KEY, url.toFullString())); @@ -618,7 +622,7 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r */ private void exportLocal(URL url) { URL local = URLBuilder.from(url) - .setProtocol(Constants.LOCAL_PROTOCOL) + .setProtocol(LOCAL_PROTOCOL) .setHost(LOCALHOST_VALUE) .setPort(0) .build(); diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java index 5b22abdbc9b..a849d153ea2 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java @@ -27,6 +27,8 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.apache.dubbo.common.constants.RpcConstants; + /** * Reference * @@ -94,7 +96,7 @@ /** * Export an stub service for event dispatch, default value is false. * - * @see Constants#STUB_EVENT_METHODS_KEY + * @see RpcConstants#STUB_EVENT_METHODS_KEY */ boolean stubevent() default false; @@ -136,7 +138,7 @@ /** * The callback instance limit peer connection * - * @see Constants#DEFAULT_CALLBACK_INSTANCES + * @see RpcConstants#DEFAULT_CALLBACK_INSTANCES */ int callbacks() default 0; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Service.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Service.java index 9db3ffdcdc8..dfb14e77001 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Service.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Service.java @@ -27,6 +27,8 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.apache.dubbo.common.constants.RpcConstants; + /** * Service annotation * @@ -142,9 +144,9 @@ /** * The callback instance limit peer connection * - * @see Constants#DEFAULT_CALLBACK_INSTANCES + * @see RpcConstants#DEFAULT_CALLBACK_INSTANCES */ - int callbacks() default Constants.DEFAULT_CALLBACK_INSTANCES; + int callbacks() default RpcConstants.DEFAULT_CALLBACK_INSTANCES; /** * Callback method name when connected, default value is empty string diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java index 92985b20f7b..6ba9ed7997f 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java @@ -31,6 +31,10 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.MatcherAssert.assertThat; +import static org.apache.dubbo.common.constants.RpcConstants.STUB_EVENT_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.REFERENCE_FILTER_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.INVOKER_LISTENER_KEY; + public class AbstractReferenceConfigTest { @Test @@ -71,7 +75,7 @@ public void testFilter() throws Exception { referenceConfig.setFilter("mockfilter"); assertThat(referenceConfig.getFilter(), equalTo("mockfilter")); Map parameters = new HashMap(); - parameters.put(Constants.REFERENCE_FILTER_KEY, "prefilter"); + parameters.put(REFERENCE_FILTER_KEY, "prefilter"); AbstractInterfaceConfig.appendParameters(parameters, referenceConfig); assertThat(parameters, hasValue("prefilter,mockfilter")); } @@ -82,7 +86,7 @@ public void testListener() throws Exception { referenceConfig.setListener("mockinvokerlistener"); assertThat(referenceConfig.getListener(), equalTo("mockinvokerlistener")); Map parameters = new HashMap(); - parameters.put(Constants.INVOKER_LISTENER_KEY, "prelistener"); + parameters.put(INVOKER_LISTENER_KEY, "prelistener"); AbstractInterfaceConfig.appendParameters(parameters, referenceConfig); assertThat(parameters, hasValue("prelistener,mockinvokerlistener")); } @@ -116,7 +120,7 @@ public void testStubevent() throws Exception { referenceConfig.setOnconnect("onConnect"); Map parameters = new HashMap(); AbstractInterfaceConfig.appendParameters(parameters, referenceConfig); - assertThat(parameters, hasKey(Constants.STUB_EVENT_KEY)); + assertThat(parameters, hasKey(STUB_EVENT_KEY)); } @Test diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractServiceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractServiceConfigTest.java index 00ff8747785..8f0e7171123 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractServiceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractServiceConfigTest.java @@ -17,7 +17,6 @@ package org.apache.dubbo.config; -import org.apache.dubbo.common.Constants; import org.junit.jupiter.api.Test; @@ -34,6 +33,9 @@ import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; +import static org.apache.dubbo.common.constants.RpcConstants.SERVICE_FILTER_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.EXPORTER_LISTENER_KEY; + public class AbstractServiceConfigTest { @Test public void testVersion() throws Exception { @@ -139,9 +141,9 @@ public void testFilter() throws Exception { serviceConfig.setFilter("mockfilter"); assertThat(serviceConfig.getFilter(), equalTo("mockfilter")); Map parameters = new HashMap(); - parameters.put(Constants.SERVICE_FILTER_KEY, "prefilter"); + parameters.put(SERVICE_FILTER_KEY, "prefilter"); AbstractServiceConfig.appendParameters(parameters, serviceConfig); - assertThat(parameters, hasEntry(Constants.SERVICE_FILTER_KEY, "prefilter,mockfilter")); + assertThat(parameters, hasEntry(SERVICE_FILTER_KEY, "prefilter,mockfilter")); } @Test @@ -150,9 +152,9 @@ public void testListener() throws Exception { serviceConfig.setListener("mockexporterlistener"); assertThat(serviceConfig.getListener(), equalTo("mockexporterlistener")); Map parameters = new HashMap(); - parameters.put(Constants.EXPORTER_LISTENER_KEY, "prelistener"); + parameters.put(EXPORTER_LISTENER_KEY, "prelistener"); AbstractServiceConfig.appendParameters(parameters, serviceConfig); - assertThat(parameters, hasEntry(Constants.EXPORTER_LISTENER_KEY, "prelistener,mockexporterlistener")); + assertThat(parameters, hasEntry(EXPORTER_LISTENER_KEY, "prelistener,mockexporterlistener")); } @Test diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java index 8a5cf100ea6..d5941a1b179 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.config.annotation.Argument; import org.apache.dubbo.config.annotation.Method; import org.apache.dubbo.config.annotation.Reference; @@ -29,6 +28,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.apache.dubbo.common.constants.RpcConstants.LOCAL_PROTOCOL; + public class ReferenceConfigTest { @BeforeEach @@ -70,7 +71,7 @@ public void testInjvm() throws Exception { System.setProperty("java.net.preferIPv4Stack", "true"); demoService.export(); rc.get(); - Assertions.assertTrue(!Constants.LOCAL_PROTOCOL.equalsIgnoreCase( + Assertions.assertTrue(!LOCAL_PROTOCOL.equalsIgnoreCase( rc.getInvoker().getUrl().getProtocol())); } finally { System.clearProperty("java.net.preferIPv4Stack"); diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java index 0bd7068057c..0a472677ee9 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java @@ -43,15 +43,16 @@ import java.util.Collections; import java.util.concurrent.TimeUnit; -import static org.apache.dubbo.common.Constants.GENERIC_SERIALIZATION_BEAN; -import static org.apache.dubbo.common.Constants.GENERIC_SERIALIZATION_DEFAULT; -import static org.apache.dubbo.common.Constants.GENERIC_SERIALIZATION_NATIVE_JAVA; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_BEAN; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_DEFAULT; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_NATIVE_JAVA; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; @@ -143,7 +144,7 @@ public void testExport() throws Exception { assertThat(url.getParameters(), hasKey(RemotingConstants.BIND_PORT_KEY)); assertThat(url.getParameters(), hasEntry(Constants.EXPORT_KEY, "true")); assertThat(url.getParameters(), hasEntry("echo.0.callback", "false")); - assertThat(url.getParameters(), hasEntry(Constants.GENERIC_KEY, "false")); + assertThat(url.getParameters(), hasEntry(GENERIC_KEY, "false")); assertThat(url.getParameters(), hasEntry(INTERFACE_KEY, DemoService.class.getName())); assertThat(url.getParameters(), hasKey(METHODS_KEY)); assertThat(url.getParameters().get(METHODS_KEY), containsString("echo")); diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/builders/ServiceBuilderTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/builders/ServiceBuilderTest.java index fb1a4cdfd39..0c93ca6d451 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/builders/ServiceBuilderTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/builders/ServiceBuilderTest.java @@ -25,9 +25,9 @@ import java.util.Collections; -import static org.apache.dubbo.common.Constants.GENERIC_SERIALIZATION_BEAN; -import static org.apache.dubbo.common.Constants.GENERIC_SERIALIZATION_DEFAULT; -import static org.apache.dubbo.common.Constants.GENERIC_SERIALIZATION_NATIVE_JAVA; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_BEAN; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_DEFAULT; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_NATIVE_JAVA; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ConfigTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ConfigTest.java index acd75bf98a1..518fedb0161 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ConfigTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ConfigTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config.spring; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; @@ -66,6 +65,9 @@ import static org.junit.Assert.fail; import static org.junit.matchers.JUnitMatchers.containsString; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_BEAN; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; + /** * ConfigTest @@ -988,7 +990,7 @@ public void testGenericServiceConfig() throws Exception { service.setApplication(new ApplicationConfig("test")); service.setRegistry(new RegistryConfig("mock://localhost")); service.setInterface(DemoService.class.getName()); - service.setGeneric(Constants.GENERIC_SERIALIZATION_BEAN); + service.setGeneric(GENERIC_SERIALIZATION_BEAN); service.setRef(new GenericService() { public Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException { @@ -1000,7 +1002,7 @@ public void testGenericServiceConfig() throws Exception { Collection collection = MockRegistryFactory.getCachedRegistry(); MockRegistry registry = (MockRegistry) collection.iterator().next(); URL url = registry.getRegistered().get(0); - Assert.assertEquals(Constants.GENERIC_SERIALIZATION_BEAN, url.getParameter(Constants.GENERIC_KEY)); + Assert.assertEquals(GENERIC_SERIALIZATION_BEAN, url.getParameter(GENERIC_KEY)); } finally { MockRegistryFactory.cleanCachedRegistry(); service.unexport(); @@ -1014,7 +1016,7 @@ public void testGenericServiceConfigThroughSpring() throws Exception { ctx.start(); ServiceConfig serviceConfig = (ServiceConfig) ctx.getBean("dubboDemoService"); URL url = (URL) serviceConfig.getExportedUrls().get(0); - Assert.assertEquals(Constants.GENERIC_SERIALIZATION_BEAN, url.getParameter(Constants.GENERIC_KEY)); + Assert.assertEquals(GENERIC_SERIALIZATION_BEAN, url.getParameter(GENERIC_KEY)); } finally { ctx.destroy(); } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java index c3616a7c570..d239f45227c 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java @@ -29,6 +29,7 @@ import java.net.ServerSocket; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_INSTANCES_LIMIT_KEY; /** * SimpleRegistryExporter @@ -58,7 +59,7 @@ public static Exporter export(int port, RegistryService registr .setPath(RegistryService.class.getName()) .addParameter(INTERFACE_KEY, RegistryService.class.getName()) .addParameter(Constants.CLUSTER_STICKY_KEY, "true") - .addParameter(Constants.CALLBACK_INSTANCES_LIMIT_KEY, "1000") + .addParameter(CALLBACK_INSTANCES_LIMIT_KEY, "1000") .addParameter("ondisconnect", "disconnect") .addParameter("subscribe.1.callback", "true") .addParameter("unsubscribe.1.callback", "false") diff --git a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MonitorService.java b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MonitorService.java index e6b90501264..2221089426c 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MonitorService.java +++ b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MonitorService.java @@ -16,11 +16,13 @@ */ package org.apache.dubbo.monitor; -import org.apache.dubbo.common.Constants; + import org.apache.dubbo.common.URL; import java.util.List; +import static org.apache.dubbo.common.constants.RpcConstants.INPUT_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.OUTPUT_KEY; /** * MonitorService. (SPI, Prototype, ThreadSafe) */ @@ -46,9 +48,9 @@ public interface MonitorService { String FAILURE = "failure"; - String INPUT = Constants.INPUT_KEY; + String INPUT = INPUT_KEY; - String OUTPUT = Constants.OUTPUT_KEY; + String OUTPUT = OUTPUT_KEY; String ELAPSED = "elapsed"; diff --git a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java index 3269b37bb1f..ff7ee989f67 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java +++ b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java @@ -45,7 +45,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; - +import static org.apache.dubbo.common.constants.RpcConstants.INPUT_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.OUTPUT_KEY; /** * MonitorFilter. (SPI, Singleton, ThreadSafe) */ @@ -157,11 +158,11 @@ private URL createStatisticsUrl(Invoker invoker, Invocation invocation, Resul remoteValue = remoteHost; } String input = "", output = ""; - if (invocation.getAttachment(Constants.INPUT_KEY) != null) { - input = invocation.getAttachment(Constants.INPUT_KEY); + if (invocation.getAttachment(INPUT_KEY) != null) { + input = invocation.getAttachment(INPUT_KEY); } - if (result != null && result.getAttachment(Constants.OUTPUT_KEY) != null) { - output = result.getAttachment(Constants.OUTPUT_KEY); + if (result != null && result.getAttachment(OUTPUT_KEY) != null) { + output = result.getAttachment(OUTPUT_KEY); } return new URL(Constants.COUNT_PROTOCOL, @@ -174,8 +175,8 @@ private URL createStatisticsUrl(Invoker invoker, Invocation invocation, Resul error ? MonitorService.FAILURE : MonitorService.SUCCESS, "1", MonitorService.ELAPSED, String.valueOf(elapsed), MonitorService.CONCURRENT, String.valueOf(concurrent), - Constants.INPUT_KEY, input, - Constants.OUTPUT_KEY, output, + INPUT_KEY, input, + OUTPUT_KEY, output, GROUP_KEY, group, VERSION_KEY, version); } diff --git a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java index 1802fe3fe9e..2d2a8af0373 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java +++ b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java @@ -28,7 +28,7 @@ import static org.apache.dubbo.common.constants.RemotingConstants.CHECK_KEY; import static org.apache.dubbo.common.Constants.DUBBO_PROTOCOL; -import static org.apache.dubbo.common.Constants.REFERENCE_FILTER_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.REFERENCE_FILTER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; /** diff --git a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactoryTest.java b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactoryTest.java index a3a1b176602..f96a3ae9281 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactoryTest.java +++ b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactoryTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.monitor.dubbo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.monitor.Monitor; import org.apache.dubbo.rpc.Invoker; @@ -35,6 +34,8 @@ import static org.mockito.Mockito.verify; import static org.mockito.MockitoAnnotations.initMocks; +import static org.apache.dubbo.common.constants.RpcConstants.REFERENCE_FILTER_KEY; + public class DubboMonitorFactoryTest { private DubboMonitorFactory dubboMonitorFactory; @Mock @@ -54,7 +55,7 @@ public void testCreateMonitor() { Monitor monitor = dubboMonitorFactory.createMonitor(urlWithoutPath); assertThat(monitor, not(nullValue())); - URL urlWithFilterKey = URL.valueOf("http://10.10.10.11/").addParameter(Constants.REFERENCE_FILTER_KEY, "testFilter"); + URL urlWithFilterKey = URL.valueOf("http://10.10.10.11/").addParameter(REFERENCE_FILTER_KEY, "testFilter"); monitor = dubboMonitorFactory.createMonitor(urlWithFilterKey); assertThat(monitor, not(nullValue())); @@ -62,6 +63,6 @@ public void testCreateMonitor() { verify(proxyFactory, atLeastOnce()).getProxy(invokerArgumentCaptor.capture()); Invoker invoker = invokerArgumentCaptor.getValue(); - assertThat(invoker.getUrl().getParameter(Constants.REFERENCE_FILTER_KEY), containsString("testFilter")); + assertThat(invoker.getUrl().getParameter(REFERENCE_FILTER_KEY), containsString("testFilter")); } } \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java index c7db7012f77..a94e72f11b4 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java @@ -54,7 +54,7 @@ import static java.util.concurrent.Executors.newSingleThreadExecutor; import static org.apache.dubbo.common.Constants.ACCEPT_FOREIGN_IP; import static org.apache.dubbo.common.Constants.EXPORT_KEY; -import static org.apache.dubbo.common.Constants.INTERFACES; +import static org.apache.dubbo.common.constants.RpcConstants.INTERFACES; import static org.apache.dubbo.common.Constants.MONITOR_KEY; import static org.apache.dubbo.common.Constants.QOS_ENABLE; import static org.apache.dubbo.common.Constants.QOS_PORT; diff --git a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java index c2768c724dc..ca5eb761b37 100644 --- a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java +++ b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java @@ -43,6 +43,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; +import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_INSTANCES_LIMIT_KEY; /** * DubboRegistryFactory @@ -63,7 +64,7 @@ private static URL getRegistryURL(URL url) { .addParameter(Constants.LAZY_CONNECT_KEY, "true") .addParameter(RemotingConstants.RECONNECT_KEY, "false") .addParameterIfAbsent(TIMEOUT_KEY, "10000") - .addParameterIfAbsent(Constants.CALLBACK_INSTANCES_LIMIT_KEY, "10000") + .addParameterIfAbsent(CALLBACK_INSTANCES_LIMIT_KEY, "10000") .addParameterIfAbsent(RemotingConstants.CONNECT_TIMEOUT_KEY, "10000") .addParameter(METHODS_KEY, StringUtils.join(new HashSet<>(Arrays.asList(Wrapper.getWrapper(RegistryService.class).getDeclaredMethodNames())), ",")) //.addParameter(Constants.STUB_KEY, RegistryServiceStub.class.getName()) diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java index 1f82c73982f..3aa1d7dcc00 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java @@ -56,6 +56,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.DISABLED_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.MOCK_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; @@ -403,7 +405,7 @@ public void testParametersMerge() { { Assertions.assertEquals(null, registryDirectory2.getUrl().getParameter("mock")); serviceUrls.clear(); - serviceUrls.add(SERVICEURL.addParameter(Constants.MOCK_KEY, "true")); + serviceUrls.add(SERVICEURL.addParameter(MOCK_KEY, "true")); registryDirectory2.notify(serviceUrls); Assertions.assertEquals("true", registryDirectory2.getUrl().getParameter("mock")); @@ -477,7 +479,7 @@ public void testDubbo1UrlWithGenericInvocation() { registryDirectory.notify(serviceUrls); // Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException; - invocation = new RpcInvocation(Constants.$INVOKE, new Class[]{String.class, String[].class, Object[].class}, + invocation = new RpcInvocation($INVOKE, new Class[]{String.class, String[].class, Object[].class}, new Object[]{"getXXX1", "", new Object[]{}}); List invokers = registryDirectory.list(invocation); @@ -506,8 +508,7 @@ public void testParmeterRoute() { registryDirectory.notify(serviceUrls); - invocation = new RpcInvocation( - Constants.$INVOKE, + invocation = new RpcInvocation($INVOKE, new Class[]{String.class, String[].class, Object[].class}, new Object[]{"getXXX1", new String[]{"Enum"}, new Object[]{Param.MORGAN}}); diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java index 92f5fb49131..f9d9ea0a0a4 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java @@ -29,6 +29,7 @@ import java.net.ServerSocket; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_INSTANCES_LIMIT_KEY; /** * SimpleRegistryExporter @@ -59,7 +60,7 @@ public static Exporter export(int port, RegistryService registr .setPath(RegistryService.class.getName()) .addParameter(INTERFACE_KEY, RegistryService.class.getName()) .addParameter(Constants.CLUSTER_STICKY_KEY, "true") - .addParameter(Constants.CALLBACK_INSTANCES_LIMIT_KEY, "1000") + .addParameter(CALLBACK_INSTANCES_LIMIT_KEY, "1000") .addParameter("ondisconnect", "disconnect") .addParameter("subscribe.1.callback", "true") .addParameter("unsubscribe.1.callback", "false") diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java index d0bbfd7af8b..30be337f1a5 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -30,6 +29,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.CONNECTIONS_KEY; public class PerformanceClientFixedTest { @@ -47,7 +47,7 @@ public void testClient() throws Exception { final String serialization = PerformanceUtils.getProperty(RemotingConstants.SERIALIZATION_KEY, RemotingConstants.DEFAULT_REMOTING_SERIALIZATION); final int timeout = PerformanceUtils.getIntProperty(TIMEOUT_KEY, DEFAULT_TIMEOUT); //final int length = PerformanceUtils.getIntProperty("length", 1024); - final int connectionCount = PerformanceUtils.getIntProperty(Constants.CONNECTIONS_KEY, 1); + final int connectionCount = PerformanceUtils.getIntProperty(CONNECTIONS_KEY, 1); //final int concurrent = PerformanceUtils.getIntProperty("concurrent", 100); //int r = PerformanceUtils.getIntProperty("runs", 10000); //final int runs = r > 0 ? r : Integer.MAX_VALUE; diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java index acf1353bb3a..ebbaae8b37b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -36,6 +35,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.CONNECTIONS_KEY; /** * PerformanceClientTest @@ -59,7 +59,7 @@ public void testClient() throws Throwable { final String serialization = PerformanceUtils.getProperty(RemotingConstants.SERIALIZATION_KEY, RemotingConstants.DEFAULT_REMOTING_SERIALIZATION); final int timeout = PerformanceUtils.getIntProperty(TIMEOUT_KEY, DEFAULT_TIMEOUT); final int length = PerformanceUtils.getIntProperty("length", 1024); - final int connections = PerformanceUtils.getIntProperty(Constants.CONNECTIONS_KEY, 1); + final int connections = PerformanceUtils.getIntProperty(CONNECTIONS_KEY, 1); final int concurrent = PerformanceUtils.getIntProperty("concurrent", 100); int r = PerformanceUtils.getIntProperty("runs", 10000); final int runs = r > 0 ? r : Integer.MAX_VALUE; diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.java index 24a4080c486..23a0e3a4cc6 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.java @@ -17,7 +17,6 @@ package org.apache.dubbo.remoting.exchange.support.header; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.timer.HashedWheelTimer; @@ -31,6 +30,8 @@ import java.util.List; import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; + public class HeartBeatTaskTest { private URL url = URL.valueOf("dubbo://localhost:20880"); @@ -61,7 +62,7 @@ public URL getUrl() { public void testHeartBeat() throws Exception { long now = System.currentTimeMillis(); - url = url.addParameter(Constants.DUBBO_VERSION_KEY, "2.1.1"); + url = url.addParameter(DUBBO_VERSION_KEY, "2.1.1"); channel.setAttribute( HeaderExchangeHandler.KEY_READ_TIMESTAMP, now); channel.setAttribute( diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaServer.java b/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaServer.java index 2a6af51a874..2365ddf56bf 100644 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaServer.java +++ b/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaServer.java @@ -39,7 +39,7 @@ import java.util.Set; import java.util.concurrent.Executors; -import static org.apache.dubbo.common.Constants.DEFAULT_IO_THREADS; +import static org.apache.dubbo.common.constants.RemotingConstants.DEFAULT_IO_THREADS; import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY; /** diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ProxyFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ProxyFactory.java index 50cb62d41d4..1abe78a4126 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ProxyFactory.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ProxyFactory.java @@ -16,11 +16,12 @@ */ package org.apache.dubbo.rpc; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.SPI; +import static org.apache.dubbo.common.constants.RpcConstants.PROXY_KEY; + /** * ProxyFactory. (API/SPI, Singleton, ThreadSafe) */ @@ -33,7 +34,7 @@ public interface ProxyFactory { * @param invoker * @return proxy */ - @Adaptive({Constants.PROXY_KEY}) + @Adaptive({PROXY_KEY}) T getProxy(Invoker invoker) throws RpcException; /** @@ -42,7 +43,7 @@ public interface ProxyFactory { * @param invoker * @return proxy */ - @Adaptive({Constants.PROXY_KEY}) + @Adaptive({PROXY_KEY}) T getProxy(Invoker invoker, boolean generic) throws RpcException; /** @@ -54,7 +55,7 @@ public interface ProxyFactory { * @param url * @return invoker */ - @Adaptive({Constants.PROXY_KEY}) + @Adaptive({PROXY_KEY}) Invoker getInvoker(T proxy, Class type, URL url) throws RpcException; } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java index 3378e198877..233a5844066 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.threadlocal.InternalThreadLocal; import org.apache.dubbo.common.utils.CollectionUtils; @@ -39,6 +38,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.ASYNC_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.RETURN_KEY; /** @@ -677,7 +678,7 @@ public RpcContext setInvocation(Invocation invocation) { public CompletableFuture asyncCall(Callable callable) { try { try { - setAttachment(Constants.ASYNC_KEY, Boolean.TRUE.toString()); + setAttachment(ASYNC_KEY, Boolean.TRUE.toString()); final T o = callable.call(); //local invoke will return directly if (o != null) { @@ -691,7 +692,7 @@ public CompletableFuture asyncCall(Callable callable) { } catch (Exception e) { throw new RpcException(e); } finally { - removeAttachment(Constants.ASYNC_KEY); + removeAttachment(ASYNC_KEY); } } catch (final RpcException e) { return new CompletableFuture() { @@ -733,13 +734,13 @@ public T get(long timeout, TimeUnit unit) */ public void asyncCall(Runnable runnable) { try { - setAttachment(Constants.RETURN_KEY, Boolean.FALSE.toString()); + setAttachment(RETURN_KEY, Boolean.FALSE.toString()); runnable.run(); } catch (Throwable e) { // FIXME should put exception in future? throw new RpcException("oneway call error ." + e.getMessage(), e); } finally { - removeAttachment(Constants.RETURN_KEY); + removeAttachment(RETURN_KEY); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.java index 7688705c352..7c73c825346 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; @@ -32,6 +31,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; /** * RPC Invocation. @@ -74,8 +74,8 @@ public RpcInvocation(Invocation invocation, Invoker invoker) { if (url.hasParameter(TIMEOUT_KEY)) { setAttachment(TIMEOUT_KEY, url.getParameter(TIMEOUT_KEY)); } - if (url.hasParameter(Constants.TOKEN_KEY)) { - setAttachment(Constants.TOKEN_KEY, url.getParameter(Constants.TOKEN_KEY)); + if (url.hasParameter(TOKEN_KEY)) { + setAttachment(TOKEN_KEY, url.getParameter(TOKEN_KEY)); } if (url.hasParameter(APPLICATION_KEY)) { setAttachment(APPLICATION_KEY, url.getParameter(APPLICATION_KEY)); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java index 0990daf2ebc..0e3cfb08cfe 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.filter; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -48,6 +47,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.ACCESS_LOG_KEY; /** * Record access log for the service. @@ -63,7 +63,7 @@ * </logger> * */ -@Activate(group = PROVIDER, value = Constants.ACCESS_LOG_KEY) +@Activate(group = PROVIDER, value = ACCESS_LOG_KEY) public class AccessLogFilter implements Filter { private static final Logger logger = LoggerFactory.getLogger(AccessLogFilter.class); @@ -102,7 +102,7 @@ public AccessLogFilter() { @Override public Result invoke(Invoker invoker, Invocation inv) throws RpcException { try { - String accessLogKey = invoker.getUrl().getParameter(Constants.ACCESS_LOG_KEY); + String accessLogKey = invoker.getUrl().getParameter(ACCESS_LOG_KEY); if (ConfigUtils.isNotEmpty(accessLogKey)) { AccessLogData logData = buildAccessLogData(invoker, inv); log(accessLogKey, logData); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java index 143544bbf50..f0e4f2022d9 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.filter; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.Filter; @@ -28,6 +27,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.ACTIVES_KEY; /** * ActiveLimitFilter restrict the concurrent client invocation for a service or service's method from client side. @@ -41,14 +41,14 @@ * * @see Filter */ -@Activate(group = CONSUMER, value = Constants.ACTIVES_KEY) +@Activate(group = CONSUMER, value = ACTIVES_KEY) public class ActiveLimitFilter implements Filter { @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { URL url = invoker.getUrl(); String methodName = invocation.getMethodName(); - int max = invoker.getUrl().getMethodParameter(methodName, Constants.ACTIVES_KEY, 0); + int max = invoker.getUrl().getMethodParameter(methodName, ACTIVES_KEY, 0); RpcStatus count = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName()); if (!RpcStatus.beginCount(url, methodName, max)) { long timeout = invoker.getUrl().getMethodParameter(invocation.getMethodName(), TIMEOUT_KEY, 0); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java index 1fcb52c929e..802e6d01796 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java @@ -36,6 +36,10 @@ import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.FORCE_USE_TAG; +import static org.apache.dubbo.common.constants.RpcConstants.ASYNC_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; /** @@ -56,13 +60,13 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept attachments.remove(INTERFACE_KEY); attachments.remove(GROUP_KEY); attachments.remove(VERSION_KEY); - attachments.remove(Constants.DUBBO_VERSION_KEY); - attachments.remove(Constants.TOKEN_KEY); + attachments.remove(DUBBO_VERSION_KEY); + attachments.remove(TOKEN_KEY); attachments.remove(TIMEOUT_KEY); // Remove async property to avoid being passed to the following invoke chain. - attachments.remove(Constants.ASYNC_KEY); + attachments.remove(ASYNC_KEY); attachments.remove(Constants.TAG_KEY); - attachments.remove(Constants.FORCE_USE_TAG); + attachments.remove(FORCE_USE_TAG); } RpcContext.getContext() .setInvoker(invoker) diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java index c373e79eb4d..b38babea7fa 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.filter; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.Logger; @@ -30,13 +29,15 @@ import java.util.Set; +import static org.apache.dubbo.common.constants.RpcConstants.DEPRECATED_KEY; + /** * DeprecatedFilter logs error message if a invoked method has been marked as deprecated. To check whether a method * is deprecated or not it looks for deprecated attribute value and consider it is deprecated it value is true * * @see Filter */ -@Activate(group = CommonConstants.CONSUMER, value = Constants.DEPRECATED_KEY) +@Activate(group = CommonConstants.CONSUMER, value = DEPRECATED_KEY) public class DeprecatedFilter implements Filter { private static final Logger LOGGER = LoggerFactory.getLogger(DeprecatedFilter.class); @@ -48,7 +49,7 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept String key = invoker.getInterface().getName() + "." + invocation.getMethodName(); if (!logged.contains(key)) { logged.add(key); - if (invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.DEPRECATED_KEY, false)) { + if (invoker.getUrl().getMethodParameter(invocation.getMethodName(), DEPRECATED_KEY, false)) { LOGGER.error("The service method " + invoker.getInterface().getName() + "." + getMethodSignature(invocation) + " is DEPRECATED! Declare from " + invoker.getUrl()); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/EchoFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/EchoFilter.java index 9df24c4cd07..63d3c9fc4ab 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/EchoFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/EchoFilter.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.filter; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.Filter; @@ -26,6 +25,8 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcResult; +import static org.apache.dubbo.common.constants.RpcConstants.$ECHO; + /** * Dubbo provided default Echo echo service, which is available for all dubbo provider service interface. */ @@ -34,7 +35,7 @@ public class EchoFilter implements Filter { @Override public Result invoke(Invoker invoker, Invocation inv) throws RpcException { - if (inv.getMethodName().equals(Constants.$ECHO) && inv.getArguments() != null && inv.getArguments().length == 1) { + if (inv.getMethodName().equals($ECHO) && inv.getArguments() != null && inv.getArguments().length == 1) { return new RpcResult(inv.getArguments()[0]); } return invoker.invoke(inv); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java index 42298e7c9ea..1eff0635f6e 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.filter; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; @@ -27,20 +26,22 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcStatus; +import static org.apache.dubbo.common.constants.RpcConstants.EXECUTES_KEY; + + /** * The maximum parallel execution request count per method per service for the provider.If the max configured * executes is set to 10 and if invoke request where it is already 10 then it will throws exception. It * continue the same behaviour un till it is <10. - * */ -@Activate(group = CommonConstants.PROVIDER, value = Constants.EXECUTES_KEY) +@Activate(group = CommonConstants.PROVIDER, value = EXECUTES_KEY) public class ExecuteLimitFilter implements Filter { @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { URL url = invoker.getUrl(); String methodName = invocation.getMethodName(); - int max = url.getMethodParameter(methodName, Constants.EXECUTES_KEY, 0); + int max = url.getMethodParameter(methodName, EXECUTES_KEY, 0); if (!RpcStatus.beginCount(url, methodName, max)) { throw new RpcException("Failed to invoke method " + invocation.getMethodName() + " in provider " + url + ", cause: The service using threads greater than invoker, Invocation inv) throws RpcException { - if (inv.getMethodName().equals(Constants.$INVOKE) + if (inv.getMethodName().equals($INVOKE) && inv.getArguments() != null && inv.getArguments().length == 3 && !GenericService.class.isAssignableFrom(invoker.getInterface())) { @@ -65,10 +70,10 @@ public Result invoke(Invoker invoker, Invocation inv) throws RpcException { if (args == null) { args = new Object[params.length]; } - String generic = inv.getAttachment(Constants.GENERIC_KEY); + String generic = inv.getAttachment(GENERIC_KEY); if (StringUtils.isBlank(generic)) { - generic = RpcContext.getContext().getAttachment(Constants.GENERIC_KEY); + generic = RpcContext.getContext().getAttachment(GENERIC_KEY); } if (StringUtils.isEmpty(generic) @@ -79,7 +84,7 @@ public Result invoke(Invoker invoker, Invocation inv) throws RpcException { if (byte[].class == args[i].getClass()) { try (UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream((byte[]) args[i])) { args[i] = ExtensionLoader.getExtensionLoader(Serialization.class) - .getExtension(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA) + .getExtension(GENERIC_SERIALIZATION_NATIVE_JAVA) .deserialize(null, is).readObject(); } catch (Exception e) { throw new RpcException("Deserialize argument [" + (i + 1) + "] failed.", e); @@ -87,7 +92,7 @@ public Result invoke(Invoker invoker, Invocation inv) throws RpcException { } else { throw new RpcException( "Generic serialization [" + - Constants.GENERIC_SERIALIZATION_NATIVE_JAVA + + GENERIC_SERIALIZATION_NATIVE_JAVA + "] only support message type " + byte[].class + " and your message type is " + @@ -101,7 +106,7 @@ public Result invoke(Invoker invoker, Invocation inv) throws RpcException { } else { throw new RpcException( "Generic serialization [" + - Constants.GENERIC_SERIALIZATION_BEAN + + GENERIC_SERIALIZATION_BEAN + "] only support message type " + JavaBeanDescriptor.class.getName() + " and your message type is " + @@ -114,7 +119,7 @@ public Result invoke(Invoker invoker, Invocation inv) throws RpcException { try (UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream(((String) args[0]).getBytes())) { args[0] = ExtensionLoader.getExtensionLoader(Serialization.class) - .getExtension("" + Constants.GENERIC_SERIALIZATION_PROTOBUF) + .getExtension("" + GENERIC_SERIALIZATION_PROTOBUF) .deserialize(null, is).readObject(method.getParameterTypes()[0]); } catch (Exception e) { throw new RpcException("Deserialize argument failed.", e); @@ -122,7 +127,7 @@ public Result invoke(Invoker invoker, Invocation inv) throws RpcException { } else { throw new RpcException( "Generic serialization [" + - Constants.GENERIC_SERIALIZATION_PROTOBUF + + GENERIC_SERIALIZATION_PROTOBUF + "] only support one" + String.class.getName() + " argument and your message size is " + args.length + " and type is" + @@ -138,13 +143,13 @@ public Result invoke(Invoker invoker, Invocation inv) throws RpcException { try { UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(512); ExtensionLoader.getExtensionLoader(Serialization.class) - .getExtension(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA) + .getExtension(GENERIC_SERIALIZATION_NATIVE_JAVA) .serialize(null, os).writeObject(result.getValue()); return new RpcResult(os.toByteArray()); } catch (IOException e) { throw new RpcException( "Generic serialization [" + - Constants.GENERIC_SERIALIZATION_NATIVE_JAVA + + GENERIC_SERIALIZATION_NATIVE_JAVA + "] serialize result failed.", e); } } else if (ProtocolUtils.isBeanGenericSerialization(generic)) { @@ -153,12 +158,12 @@ public Result invoke(Invoker invoker, Invocation inv) throws RpcException { try { UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(512); ExtensionLoader.getExtensionLoader(Serialization.class) - .getExtension(Constants.GENERIC_SERIALIZATION_PROTOBUF) + .getExtension(GENERIC_SERIALIZATION_PROTOBUF) .serialize(null, os).writeObject(result.getValue()); return new RpcResult(os.toString()); } catch (IOException e) { throw new RpcException("Generic serialization [" + - Constants.GENERIC_SERIALIZATION_PROTOBUF + + GENERIC_SERIALIZATION_PROTOBUF + "] serialize result failed.", e); } } else { diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java index 8c23043c3fe..b4b0c6b9e5c 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.filter; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.beanutil.JavaBeanAccessor; import org.apache.dubbo.common.beanutil.JavaBeanDescriptor; import org.apache.dubbo.common.beanutil.JavaBeanSerializeUtil; @@ -40,10 +39,13 @@ import java.lang.reflect.Field; import java.lang.reflect.Method; +import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; + /** * GenericImplInvokerFilter */ -@Activate(group = CommonConstants.CONSUMER, value = Constants.GENERIC_KEY, order = 20000) +@Activate(group = CommonConstants.CONSUMER, value = GENERIC_KEY, order = 20000) public class GenericImplFilter implements Filter { private static final Logger logger = LoggerFactory.getLogger(GenericImplFilter.class); @@ -52,9 +54,9 @@ public class GenericImplFilter implements Filter { @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { - String generic = invoker.getUrl().getParameter(Constants.GENERIC_KEY); + String generic = invoker.getUrl().getParameter(GENERIC_KEY); if (ProtocolUtils.isGeneric(generic) - && !Constants.$INVOKE.equals(invocation.getMethodName()) + && !$INVOKE.equals(invocation.getMethodName()) && invocation instanceof RpcInvocation) { RpcInvocation invocation2 = (RpcInvocation) invocation; String methodName = invocation2.getMethodName(); @@ -76,7 +78,7 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept args = PojoUtils.generalize(arguments); } - invocation2.setMethodName(Constants.$INVOKE); + invocation2.setMethodName($INVOKE); invocation2.setParameterTypes(GENERIC_PARAMETER_TYPES); invocation2.setArguments(new Object[]{methodName, types, args}); Result result = invoker.invoke(invocation2); @@ -146,7 +148,7 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept return result; } - if (invocation.getMethodName().equals(Constants.$INVOKE) + if (invocation.getMethodName().equals($INVOKE) && invocation.getArguments() != null && invocation.getArguments().length == 3 && ProtocolUtils.isGeneric(generic)) { @@ -167,8 +169,7 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept } } - ((RpcInvocation) invocation).setAttachment( - Constants.GENERIC_KEY, invoker.getUrl().getParameter(Constants.GENERIC_KEY)); + ((RpcInvocation) invocation).setAttachment(GENERIC_KEY, invoker.getUrl().getParameter(GENERIC_KEY)); } return invoker.invoke(invocation); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TokenFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TokenFilter.java index 7ac23b0b226..630a866b06d 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TokenFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TokenFilter.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.filter; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.ConfigUtils; @@ -29,23 +28,25 @@ import java.util.Map; +import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; + /** * Perform check whether given provider token is matching with remote token or not. If it does not match * it will not allow to invoke remote method. * * @see Filter */ -@Activate(group = CommonConstants.PROVIDER, value = Constants.TOKEN_KEY) +@Activate(group = CommonConstants.PROVIDER, value = TOKEN_KEY) public class TokenFilter implements Filter { @Override public Result invoke(Invoker invoker, Invocation inv) throws RpcException { - String token = invoker.getUrl().getParameter(Constants.TOKEN_KEY); + String token = invoker.getUrl().getParameter(TOKEN_KEY); if (ConfigUtils.isNotEmpty(token)) { Class serviceType = invoker.getInterface(); Map attachments = inv.getAttachments(); - String remoteToken = attachments == null ? null : attachments.get(Constants.TOKEN_KEY); + String remoteToken = attachments == null ? null : attachments.get(TOKEN_KEY); if (!token.equals(remoteToken)) { throw new RpcException("Invalid token! Forbid invoke remote service " + serviceType + " method " + inv.getMethodName() + "() from consumer " + RpcContext.getContext().getRemoteHost() + " to provider " + RpcContext.getContext().getLocalHost()); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TpsLimitFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TpsLimitFilter.java index bf05dad3524..b6378315615 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TpsLimitFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TpsLimitFilter.java @@ -17,7 +17,6 @@ package org.apache.dubbo.rpc.filter; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.Filter; @@ -28,6 +27,8 @@ import org.apache.dubbo.rpc.filter.tps.DefaultTPSLimiter; import org.apache.dubbo.rpc.filter.tps.TPSLimiter; +import static org.apache.dubbo.common.constants.RpcConstants.TPS_LIMIT_RATE_KEY; + /** * TpsLimitFilter limit the TPS (transaction per second) for all method of a service or a particular method. * Service or method url can define tps or tps.interval to control this control.It use {@link DefaultTPSLimiter} @@ -35,7 +36,7 @@ * if invocation count exceed the configured tps value (default is -1 which means unlimited) then invocation will get * RpcException. * */ -@Activate(group = CommonConstants.PROVIDER, value = Constants.TPS_LIMIT_RATE_KEY) +@Activate(group = CommonConstants.PROVIDER, value = TPS_LIMIT_RATE_KEY) public class TpsLimitFilter implements Filter { private final TPSLimiter tpsLimiter = new DefaultTPSLimiter(); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiter.java index 65985bbf603..496597e5dc8 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiter.java @@ -16,13 +16,16 @@ */ package org.apache.dubbo.rpc.filter.tps; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import static org.apache.dubbo.common.constants.RpcConstants.TPS_LIMIT_RATE_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.TPS_LIMIT_INTERVAL_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_TPS_LIMIT_INTERVAL; + /** * DefaultTPSLimiter is a default implementation for tps filter. It is an in memory based implementation for storing * tps information. It internally use @@ -35,8 +38,8 @@ public class DefaultTPSLimiter implements TPSLimiter { @Override public boolean isAllowable(URL url, Invocation invocation) { - int rate = url.getParameter(Constants.TPS_LIMIT_RATE_KEY, -1); - long interval = url.getParameter(Constants.TPS_LIMIT_INTERVAL_KEY, Constants.DEFAULT_TPS_LIMIT_INTERVAL); + int rate = url.getParameter(TPS_LIMIT_RATE_KEY, -1); + long interval = url.getParameter(TPS_LIMIT_INTERVAL_KEY, DEFAULT_TPS_LIMIT_INTERVAL); String serviceKey = url.getServiceKey(); if (rate > 0) { StatItem statItem = stats.get(serviceKey); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/DeprecatedInvokerListener.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/DeprecatedInvokerListener.java index 2dbbfa96c6f..ce324ebcd07 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/DeprecatedInvokerListener.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/DeprecatedInvokerListener.java @@ -16,24 +16,25 @@ */ package org.apache.dubbo.rpc.listener; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; +import static org.apache.dubbo.common.constants.RpcConstants.DEPRECATED_KEY; + /** * DeprecatedProtocolFilter */ -@Activate(Constants.DEPRECATED_KEY) +@Activate(DEPRECATED_KEY) public class DeprecatedInvokerListener extends InvokerListenerAdapter { private static final Logger LOGGER = LoggerFactory.getLogger(DeprecatedInvokerListener.class); @Override public void referred(Invoker invoker) throws RpcException { - if (invoker.getUrl().getParameter(Constants.DEPRECATED_KEY, false)) { + if (invoker.getUrl().getParameter(DEPRECATED_KEY, false)) { LOGGER.error("The service " + invoker.getInterface().getName() + " is DEPRECATED! Declare from " + invoker.getUrl()); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ConsumerMethodModel.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ConsumerMethodModel.java index 5a871cecc63..2d5352d3040 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ConsumerMethodModel.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ConsumerMethodModel.java @@ -16,11 +16,12 @@ */ package org.apache.dubbo.rpc.model; -import org.apache.dubbo.common.Constants; import java.lang.reflect.Method; import java.util.Map; +import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE; + public class ConsumerMethodModel { private final Method method; // private final boolean isCallBack; @@ -40,7 +41,7 @@ public ConsumerMethodModel(Method method, Map attributes) { this.returnClass = method.getReturnType(); this.parameterTypes = this.createParamSignature(parameterClasses); this.methodName = method.getName(); - this.generic = methodName.equals(Constants.$INVOKE) && parameterTypes != null && parameterTypes.length == 3; + this.generic = methodName.equals($INVOKE) && parameterTypes != null && parameterTypes.length == 3; if (attributes != null) { asyncInfo = (AsyncMethodInfo) attributes.get(methodName); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractInvoker.java index 3df1f1d741e..5cb5c4dfe2d 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractInvoker.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.logger.Logger; @@ -39,6 +38,8 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; +import static org.apache.dubbo.common.constants.RpcConstants.ASYNC_KEY; + /** * AbstractInvoker. */ @@ -148,8 +149,8 @@ public Result invoke(Invocation inv) throws RpcException { */ invocation.addAttachments(contextAttachments); } - if (getUrl().getMethodParameter(invocation.getMethodName(), Constants.ASYNC_KEY, false)) { - invocation.setAttachment(Constants.ASYNC_KEY, Boolean.TRUE.toString()); + if (getUrl().getMethodParameter(invocation.getMethodName(), ASYNC_KEY, false)) { + invocation.setAttachment(ASYNC_KEY, Boolean.TRUE.toString()); } RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolFilterWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolFilterWrapper.java index e45a84c8912..4bd945371a6 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolFilterWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolFilterWrapper.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.ExtensionLoader; @@ -33,6 +32,9 @@ import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; +import static org.apache.dubbo.common.constants.RpcConstants.REFERENCE_FILTER_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.SERVICE_FILTER_KEY; + /** * ListenerProtocol */ @@ -108,7 +110,7 @@ public Exporter export(Invoker invoker) throws RpcException { if (REGISTRY_PROTOCOL.equals(invoker.getUrl().getProtocol())) { return protocol.export(invoker); } - return protocol.export(buildInvokerChain(invoker, Constants.SERVICE_FILTER_KEY, CommonConstants.PROVIDER)); + return protocol.export(buildInvokerChain(invoker, SERVICE_FILTER_KEY, CommonConstants.PROVIDER)); } @Override @@ -116,7 +118,7 @@ public Invoker refer(Class type, URL url) throws RpcException { if (REGISTRY_PROTOCOL.equals(url.getProtocol())) { return protocol.refer(type, url); } - return buildInvokerChain(protocol.refer(type, url), Constants.REFERENCE_FILTER_KEY, CommonConstants.CONSUMER); + return buildInvokerChain(protocol.refer(type, url), REFERENCE_FILTER_KEY, CommonConstants.CONSUMER); } @Override diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapper.java index c12ceca1947..013ffef7e3d 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapper.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.rpc.Exporter; @@ -32,6 +31,9 @@ import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; +import static org.apache.dubbo.common.constants.RpcConstants.INVOKER_LISTENER_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.EXPORTER_LISTENER_KEY; + /** * ListenerProtocol */ @@ -58,7 +60,7 @@ public Exporter export(Invoker invoker) throws RpcException { } return new ListenerExporterWrapper(protocol.export(invoker), Collections.unmodifiableList(ExtensionLoader.getExtensionLoader(ExporterListener.class) - .getActivateExtension(invoker.getUrl(), Constants.EXPORTER_LISTENER_KEY))); + .getActivateExtension(invoker.getUrl(), EXPORTER_LISTENER_KEY))); } @Override @@ -69,7 +71,7 @@ public Invoker refer(Class type, URL url) throws RpcException { return new ListenerInvokerWrapper(protocol.refer(type, url), Collections.unmodifiableList( ExtensionLoader.getExtensionLoader(InvokerListener.class) - .getActivateExtension(url, Constants.INVOKER_LISTENER_KEY))); + .getActivateExtension(url, INVOKER_LISTENER_KEY))); } @Override diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.java index b2d48916fb8..2a792dbbb07 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.proxy; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.ProxyFactory; @@ -26,6 +25,7 @@ import com.alibaba.dubbo.rpc.service.EchoService; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; +import static org.apache.dubbo.common.constants.RpcConstants.INTERFACES; /** * AbstractProxyFactory @@ -40,7 +40,7 @@ public T getProxy(Invoker invoker) throws RpcException { @Override public T getProxy(Invoker invoker, boolean generic) throws RpcException { Class[] interfaces = null; - String config = invoker.getUrl().getParameter(Constants.INTERFACES); + String config = invoker.getUrl().getParameter(INTERFACES); if (config != null && config.length() > 0) { String[] types = COMMA_SPLIT_PATTERN.split(config); if (types != null && types.length > 0) { diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvokerInvocationHandler.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvokerInvocationHandler.java index 3cdb65c742f..fc4e021c9b9 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvokerInvocationHandler.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvokerInvocationHandler.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.proxy; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.Invoker; @@ -26,6 +25,9 @@ import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; +import static org.apache.dubbo.common.constants.RpcConstants.ASYNC_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.FUTURE_RETURNTYPE_KEY; + /** * InvokerHandler */ @@ -60,8 +62,8 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl private RpcInvocation createInvocation(Method method, Object[] args) { RpcInvocation invocation = new RpcInvocation(method, args); if (RpcUtils.hasFutureReturnType(method)) { - invocation.setAttachment(Constants.FUTURE_RETURNTYPE_KEY, "true"); - invocation.setAttachment(Constants.ASYNC_KEY, "true"); + invocation.setAttachment(FUTURE_RETURNTYPE_KEY, "true"); + invocation.setAttachment(ASYNC_KEY, "true"); } return invocation; } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapper.java index e4f7930d505..02addc67ddd 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapper.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.proxy.wrapper; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.Version; @@ -36,6 +35,13 @@ import java.lang.reflect.Constructor; +import static org.apache.dubbo.common.constants.RpcConstants.LOCAL_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.STUB_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.IS_SERVER_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.STUB_EVENT_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_STUB_EVENT; +import static org.apache.dubbo.common.constants.RpcConstants.STUB_EVENT_METHODS_KEY; + /** * StubProxyFactoryWrapper */ @@ -66,11 +72,11 @@ public T getProxy(Invoker invoker) throws RpcException { T proxy = proxyFactory.getProxy(invoker); if (GenericService.class != invoker.getInterface()) { URL url = invoker.getUrl(); - String stub = url.getParameter(Constants.STUB_KEY, url.getParameter(Constants.LOCAL_KEY)); + String stub = url.getParameter(STUB_KEY, url.getParameter(LOCAL_KEY)); if (ConfigUtils.isNotEmpty(stub)) { Class serviceType = invoker.getInterface(); if (ConfigUtils.isDefault(stub)) { - if (url.hasParameter(Constants.STUB_KEY)) { + if (url.hasParameter(STUB_KEY)) { stub = serviceType.getName() + "Stub"; } else { stub = serviceType.getName() + "Local"; @@ -86,9 +92,9 @@ public T getProxy(Invoker invoker) throws RpcException { proxy = (T) constructor.newInstance(new Object[]{proxy}); //export stub service URLBuilder urlBuilder = URLBuilder.from(url); - if (url.getParameter(Constants.STUB_EVENT_KEY, Constants.DEFAULT_STUB_EVENT)) { - urlBuilder.addParameter(Constants.STUB_EVENT_METHODS_KEY, StringUtils.join(Wrapper.getWrapper(proxy.getClass()).getDeclaredMethodNames(), ",")); - urlBuilder.addParameter(Constants.IS_SERVER_KEY, Boolean.FALSE.toString()); + if (url.getParameter(STUB_EVENT_KEY, DEFAULT_STUB_EVENT)) { + urlBuilder.addParameter(STUB_EVENT_METHODS_KEY, StringUtils.join(Wrapper.getWrapper(proxy.getClass()).getDeclaredMethodNames(), ",")); + urlBuilder.addParameter(IS_SERVER_KEY, Boolean.FALSE.toString()); try { export(proxy, (Class) invoker.getInterface(), urlBuilder.build()); } catch (Exception e) { diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java index 923c7cb0fd1..f2f6afb10d9 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.ConfigUtils; @@ -40,6 +39,13 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import static org.apache.dubbo.common.constants.RpcConstants.MOCK_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.RETURN_PREFIX; +import static org.apache.dubbo.common.constants.RpcConstants.THROW_PREFIX; +import static org.apache.dubbo.common.constants.RpcConstants.FAIL_PREFIX; +import static org.apache.dubbo.common.constants.RpcConstants.FORCE_PREFIX; +import static org.apache.dubbo.common.constants.RpcConstants.RETURN_KEY; + final public class MockInvoker implements Invoker { private final static ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); private final static Map> mocks = new ConcurrentHashMap>(); @@ -89,20 +95,20 @@ public static Object parseMockValue(String mock, Type[] returnTypes) throws Exce @Override public Result invoke(Invocation invocation) throws RpcException { - String mock = getUrl().getParameter(invocation.getMethodName() + "." + Constants.MOCK_KEY); + String mock = getUrl().getParameter(invocation.getMethodName() + "." + MOCK_KEY); if (invocation instanceof RpcInvocation) { ((RpcInvocation) invocation).setInvoker(this); } if (StringUtils.isBlank(mock)) { - mock = getUrl().getParameter(Constants.MOCK_KEY); + mock = getUrl().getParameter(MOCK_KEY); } if (StringUtils.isBlank(mock)) { throw new RpcException(new IllegalAccessException("mock can not be null. url :" + url)); } mock = normalizeMock(URL.decode(mock)); - if (mock.startsWith(Constants.RETURN_PREFIX)) { - mock = mock.substring(Constants.RETURN_PREFIX.length()).trim(); + if (mock.startsWith(RETURN_PREFIX)) { + mock = mock.substring(RETURN_PREFIX.length()).trim(); try { Type[] returnTypes = RpcUtils.getReturnTypes(invocation); Object value = parseMockValue(mock, returnTypes); @@ -111,8 +117,8 @@ public Result invoke(Invocation invocation) throws RpcException { throw new RpcException("mock return invoke error. method :" + invocation.getMethodName() + ", mock:" + mock + ", url: " + url, ew); } - } else if (mock.startsWith(Constants.THROW_PREFIX)) { - mock = mock.substring(Constants.THROW_PREFIX.length()).trim(); + } else if (mock.startsWith(THROW_PREFIX)) { + mock = mock.substring(THROW_PREFIX.length()).trim(); if (StringUtils.isBlank(mock)) { throw new RpcException("mocked exception for service degradation."); } else { // user customized class @@ -213,23 +219,23 @@ public static String normalizeMock(String mock) { return mock; } - if (Constants.RETURN_KEY.equalsIgnoreCase(mock)) { - return Constants.RETURN_PREFIX + "null"; + if (RETURN_KEY.equalsIgnoreCase(mock)) { + return RETURN_PREFIX + "null"; } if (ConfigUtils.isDefault(mock) || "fail".equalsIgnoreCase(mock) || "force".equalsIgnoreCase(mock)) { return "default"; } - if (mock.startsWith(Constants.FAIL_PREFIX)) { - mock = mock.substring(Constants.FAIL_PREFIX.length()).trim(); + if (mock.startsWith(FAIL_PREFIX)) { + mock = mock.substring(FAIL_PREFIX.length()).trim(); } - if (mock.startsWith(Constants.FORCE_PREFIX)) { - mock = mock.substring(Constants.FORCE_PREFIX.length()).trim(); + if (mock.startsWith(FORCE_PREFIX)) { + mock = mock.substring(FORCE_PREFIX.length()).trim(); } - if (mock.startsWith(Constants.RETURN_PREFIX) || mock.startsWith(Constants.THROW_PREFIX)) { + if (mock.startsWith(RETURN_PREFIX) || mock.startsWith(THROW_PREFIX)) { mock = mock.replace('`', '"'); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/ProtocolUtils.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/ProtocolUtils.java index 75b77f81857..33e42ca4b41 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/ProtocolUtils.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/ProtocolUtils.java @@ -16,12 +16,15 @@ */ package org.apache.dubbo.rpc.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_NATIVE_JAVA; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_DEFAULT; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_BEAN; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_PROTOBUF; public class ProtocolUtils { @@ -52,27 +55,27 @@ public static String serviceKey(int port, String serviceName, String serviceVers public static boolean isGeneric(String generic) { return generic != null && !"".equals(generic) - && (Constants.GENERIC_SERIALIZATION_DEFAULT.equalsIgnoreCase(generic) /* Normal generalization cal */ - || Constants.GENERIC_SERIALIZATION_NATIVE_JAVA.equalsIgnoreCase(generic) /* Streaming generalization call supporting jdk serialization */ - || Constants.GENERIC_SERIALIZATION_BEAN.equalsIgnoreCase(generic) - || Constants.GENERIC_SERIALIZATION_PROTOBUF.equalsIgnoreCase(generic)); + && (GENERIC_SERIALIZATION_DEFAULT.equalsIgnoreCase(generic) /* Normal generalization cal */ + || GENERIC_SERIALIZATION_NATIVE_JAVA.equalsIgnoreCase(generic) /* Streaming generalization call supporting jdk serialization */ + || GENERIC_SERIALIZATION_BEAN.equalsIgnoreCase(generic) + || GENERIC_SERIALIZATION_PROTOBUF.equalsIgnoreCase(generic)); } public static boolean isDefaultGenericSerialization(String generic) { return isGeneric(generic) - && Constants.GENERIC_SERIALIZATION_DEFAULT.equalsIgnoreCase(generic); + && GENERIC_SERIALIZATION_DEFAULT.equalsIgnoreCase(generic); } public static boolean isJavaGenericSerialization(String generic) { return isGeneric(generic) - && Constants.GENERIC_SERIALIZATION_NATIVE_JAVA.equalsIgnoreCase(generic); + && GENERIC_SERIALIZATION_NATIVE_JAVA.equalsIgnoreCase(generic); } public static boolean isBeanGenericSerialization(String generic) { - return isGeneric(generic) && Constants.GENERIC_SERIALIZATION_BEAN.equals(generic); + return isGeneric(generic) && GENERIC_SERIALIZATION_BEAN.equals(generic); } public static boolean isProtobufGenericSerialization(String generic) { - return isGeneric(generic) && Constants.GENERIC_SERIALIZATION_PROTOBUF.equals(generic); + return isGeneric(generic) && GENERIC_SERIALIZATION_PROTOBUF.equals(generic); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java index a5ae76133cf..86a506afec4 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -34,6 +33,13 @@ import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicLong; +import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE; +import static org.apache.dubbo.common.constants.RpcConstants.AUTO_ATTACH_INVOCATIONID_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.ID_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.ASYNC_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.FUTURE_GENERATED_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.FUTURE_RETURNTYPE_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.RETURN_KEY; /** * RpcUtils */ @@ -107,7 +113,7 @@ public static Type[] getReturnTypes(Invocation invocation) { } public static Long getInvocationId(Invocation inv) { - String id = inv.getAttachment(Constants.ID_KEY); + String id = inv.getAttachment(ID_KEY); return id == null ? null : new Long(id); } @@ -119,12 +125,12 @@ public static Long getInvocationId(Invocation inv) { */ public static void attachInvocationIdIfAsync(URL url, Invocation inv) { if (isAttachInvocationId(url, inv) && getInvocationId(inv) == null && inv instanceof RpcInvocation) { - ((RpcInvocation) inv).setAttachment(Constants.ID_KEY, String.valueOf(INVOKE_ID.getAndIncrement())); + ((RpcInvocation) inv).setAttachment(ID_KEY, String.valueOf(INVOKE_ID.getAndIncrement())); } } private static boolean isAttachInvocationId(URL url, Invocation invocation) { - String value = url.getMethodParameter(invocation.getMethodName(), Constants.AUTO_ATTACH_INVOCATIONID_KEY); + String value = url.getMethodParameter(invocation.getMethodName(), AUTO_ATTACH_INVOCATIONID_KEY); if (value == null) { // add invocationid in async operation by default return isAsync(url, invocation); @@ -136,7 +142,7 @@ private static boolean isAttachInvocationId(URL url, Invocation invocation) { } public static String getMethodName(Invocation invocation) { - if (Constants.$INVOKE.equals(invocation.getMethodName()) + if ($INVOKE.equals(invocation.getMethodName()) && invocation.getArguments() != null && invocation.getArguments().length > 0 && invocation.getArguments()[0] instanceof String) { @@ -146,7 +152,7 @@ public static String getMethodName(Invocation invocation) { } public static Object[] getArguments(Invocation invocation) { - if (Constants.$INVOKE.equals(invocation.getMethodName()) + if ($INVOKE.equals(invocation.getMethodName()) && invocation.getArguments() != null && invocation.getArguments().length > 2 && invocation.getArguments()[2] instanceof Object[]) { @@ -156,7 +162,7 @@ public static Object[] getArguments(Invocation invocation) { } public static Class[] getParameterTypes(Invocation invocation) { - if (Constants.$INVOKE.equals(invocation.getMethodName()) + if ($INVOKE.equals(invocation.getMethodName()) && invocation.getArguments() != null && invocation.getArguments().length > 1 && invocation.getArguments()[1] instanceof String[]) { @@ -175,16 +181,16 @@ public static Class[] getParameterTypes(Invocation invocation) { public static boolean isAsync(URL url, Invocation inv) { boolean isAsync; - if (Boolean.TRUE.toString().equals(inv.getAttachment(Constants.ASYNC_KEY))) { + if (Boolean.TRUE.toString().equals(inv.getAttachment(ASYNC_KEY))) { isAsync = true; } else { - isAsync = url.getMethodParameter(getMethodName(inv), Constants.ASYNC_KEY, false); + isAsync = url.getMethodParameter(getMethodName(inv), ASYNC_KEY, false); } return isAsync; } public static boolean isReturnTypeFuture(Invocation inv) { - return Boolean.TRUE.toString().equals(inv.getAttachment(Constants.FUTURE_RETURNTYPE_KEY)); + return Boolean.TRUE.toString().equals(inv.getAttachment(FUTURE_RETURNTYPE_KEY)); } public static boolean hasFutureReturnType(Method method) { @@ -193,18 +199,18 @@ public static boolean hasFutureReturnType(Method method) { public static boolean isOneway(URL url, Invocation inv) { boolean isOneway; - if (Boolean.FALSE.toString().equals(inv.getAttachment(Constants.RETURN_KEY))) { + if (Boolean.FALSE.toString().equals(inv.getAttachment(RETURN_KEY))) { isOneway = true; } else { - isOneway = !url.getMethodParameter(getMethodName(inv), Constants.RETURN_KEY, true); + isOneway = !url.getMethodParameter(getMethodName(inv), RETURN_KEY, true); } return isOneway; } public static Map getNecessaryAttachments(Invocation inv) { Map attachments = new HashMap<>(inv.getAttachments()); - attachments.remove(Constants.ASYNC_KEY); - attachments.remove(Constants.FUTURE_GENERATED_KEY); + attachments.remove(ASYNC_KEY); + attachments.remove(FUTURE_GENERATED_KEY); return attachments; } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/DeprecatedFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/DeprecatedFilterTest.java index 5795ee5245d..eab8d32beb5 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/DeprecatedFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/DeprecatedFilterTest.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.rpc.filter; -import org.apache.dubbo.common.Constants; + import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.LogUtil; import org.apache.dubbo.rpc.Filter; @@ -28,6 +28,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.apache.dubbo.common.constants.RpcConstants.DEPRECATED_KEY; + /** * DeprecatedFilterTest.java */ @@ -37,7 +39,7 @@ public class DeprecatedFilterTest { @Test public void testDeprecatedFilter() { - URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1&echo." + Constants.DEPRECATED_KEY + "=true"); + URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1&echo." + DEPRECATED_KEY + "=true"); LogUtil.start(); deprecatedFilter.invoke(new MyInvoker(url), new MockInvocation()); assertEquals(1, diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.java index bd680e7502e..ef3cd8fb1be 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.filter; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.*; import org.apache.dubbo.rpc.service.GenericService; @@ -33,6 +32,9 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; +import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_NATIVE_JAVA; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; public class GenericFilterTest { GenericFilter genericFilter = new GenericFilter(); @@ -46,7 +48,7 @@ public void testInvokeWithDefault() throws Exception { person.put("name", "dubbo"); person.put("age", 10); - RpcInvocation invocation = new RpcInvocation(Constants.$INVOKE, genericInvoke.getParameterTypes(), + RpcInvocation invocation = new RpcInvocation($INVOKE, genericInvoke.getParameterTypes(), new Object[]{"getPerson", new String[]{Person.class.getCanonicalName()}, new Object[]{person}}); URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + @@ -72,9 +74,9 @@ public void testInvokeWithJavaException() throws Exception { person.put("name", "dubbo"); person.put("age", 10); - RpcInvocation invocation = new RpcInvocation(Constants.$INVOKE, genericInvoke.getParameterTypes(), + RpcInvocation invocation = new RpcInvocation($INVOKE, genericInvoke.getParameterTypes(), new Object[]{"getPerson", new String[]{Person.class.getCanonicalName()}, new Object[]{person}}); - invocation.setAttachment(Constants.GENERIC_KEY, Constants.GENERIC_SERIALIZATION_NATIVE_JAVA); + invocation.setAttachment(GENERIC_KEY, GENERIC_SERIALIZATION_NATIVE_JAVA); URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + "accesslog=true&group=dubbo&version=1.1"); @@ -120,7 +122,7 @@ public void testInvokeWithMethodArgumentSizeIsNot3() { person.put("name", "dubbo"); person.put("age", 10); - RpcInvocation invocation = new RpcInvocation(Constants.$INVOKE, genericInvoke.getParameterTypes() + RpcInvocation invocation = new RpcInvocation($INVOKE, genericInvoke.getParameterTypes() , new Object[]{"getPerson", new String[]{Person.class.getCanonicalName()}}); URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java index 43930ef6605..c1afcdd3e87 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.filter; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -39,6 +38,9 @@ import static org.mockito.Mockito.any; import static org.mockito.Mockito.when; +import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; + public class GenericImplFilterTest { private GenericImplFilter genericImplFilter = new GenericImplFilter(); @@ -97,7 +99,7 @@ public void testInvokeWithException() throws Exception { person.put("name", "dubbo"); person.put("age", 10); - RpcInvocation invocation = new RpcInvocation(Constants.$INVOKE, genericInvoke.getParameterTypes(), + RpcInvocation invocation = new RpcInvocation($INVOKE, genericInvoke.getParameterTypes(), new Object[]{"getPerson", new String[]{Person.class.getCanonicalName()}, new Object[]{person}}); URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + @@ -107,7 +109,7 @@ public void testInvokeWithException() throws Exception { when(invoker.getUrl()).thenReturn(url); genericImplFilter.invoke(invoker, invocation); - Assertions.assertEquals("true", invocation.getAttachment(Constants.GENERIC_KEY)); + Assertions.assertEquals("true", invocation.getAttachment(GENERIC_KEY)); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TokenFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TokenFilterTest.java index fea5c300e07..5c0b778ff89 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TokenFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TokenFilterTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.filter; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -34,6 +33,8 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; +import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; + public class TokenFilterTest { private TokenFilter tokenFilter = new TokenFilter(); @@ -48,7 +49,7 @@ public void testInvokeWithToken() throws Exception { when(invoker.invoke(any(Invocation.class))).thenReturn(new RpcResult("result")); Map attachments = new HashMap(); - attachments.put(Constants.TOKEN_KEY, token); + attachments.put(TOKEN_KEY, token); Invocation invocation = Mockito.mock(Invocation.class); when(invocation.getAttachments()).thenReturn(attachments); @@ -67,7 +68,7 @@ public void testInvokeWithWrongToken() throws Exception { when(invoker.invoke(any(Invocation.class))).thenReturn(new RpcResult("result")); Map attachments = new HashMap(); - attachments.put(Constants.TOKEN_KEY, "wrongToken"); + attachments.put(TOKEN_KEY, "wrongToken"); Invocation invocation = Mockito.mock(Invocation.class); when(invocation.getAttachments()).thenReturn(attachments); diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiterTest.java index cd1e9be3d23..57543fefe6e 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiterTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.filter.tps; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.support.MockInvocation; @@ -25,6 +24,8 @@ import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.TPS_LIMIT_RATE_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.TPS_LIMIT_INTERVAL_KEY; public class DefaultTPSLimiterTest { @@ -35,8 +36,8 @@ public void testIsAllowable() throws Exception { Invocation invocation = new MockInvocation(); URL url = URL.valueOf("test://test"); url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService"); - url = url.addParameter(Constants.TPS_LIMIT_RATE_KEY, 2); - url = url.addParameter(Constants.TPS_LIMIT_INTERVAL_KEY, 1000); + url = url.addParameter(TPS_LIMIT_RATE_KEY, 2); + url = url.addParameter(TPS_LIMIT_INTERVAL_KEY, 1000); for (int i = 0; i < 3; i++) { Assertions.assertTrue(defaultTPSLimiter.isAllowable(url, invocation)); } @@ -47,8 +48,8 @@ public void testIsNotAllowable() throws Exception { Invocation invocation = new MockInvocation(); URL url = URL.valueOf("test://test"); url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService"); - url = url.addParameter(Constants.TPS_LIMIT_RATE_KEY, 2); - url = url.addParameter(Constants.TPS_LIMIT_INTERVAL_KEY, 1000); + url = url.addParameter(TPS_LIMIT_RATE_KEY, 2); + url = url.addParameter(TPS_LIMIT_INTERVAL_KEY, 1000); for (int i = 0; i < 4; i++) { if (i == 3) { Assertions.assertFalse(defaultTPSLimiter.isAllowable(url, invocation)); @@ -64,12 +65,12 @@ public void testConfigChange() throws Exception { Invocation invocation = new MockInvocation(); URL url = URL.valueOf("test://test"); url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService"); - url = url.addParameter(Constants.TPS_LIMIT_RATE_KEY, 2); - url = url.addParameter(Constants.TPS_LIMIT_INTERVAL_KEY, 1000); + url = url.addParameter(TPS_LIMIT_RATE_KEY, 2); + url = url.addParameter(TPS_LIMIT_INTERVAL_KEY, 1000); for (int i = 0; i < 3; i++) { Assertions.assertTrue(defaultTPSLimiter.isAllowable(url, invocation)); } - url = url.addParameter(Constants.TPS_LIMIT_RATE_KEY, 2000); + url = url.addParameter(TPS_LIMIT_RATE_KEY, 2000); for (int i = 0; i < 3; i++) { Assertions.assertTrue(defaultTPSLimiter.isAllowable(url, invocation)); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/TpsLimitFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/TpsLimitFilterTest.java index 44662241721..16eda85dc7b 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/TpsLimitFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/TpsLimitFilterTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.filter.tps; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -29,6 +28,7 @@ import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.TPS_LIMIT_RATE_KEY; import static org.junit.jupiter.api.Assertions.assertTrue; public class TpsLimitFilterTest { @@ -39,7 +39,7 @@ public class TpsLimitFilterTest { public void testWithoutCount() throws Exception { URL url = URL.valueOf("test://test"); url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService"); - url = url.addParameter(Constants.TPS_LIMIT_RATE_KEY, 5); + url = url.addParameter(TPS_LIMIT_RATE_KEY, 5); Invoker invoker = new MyInvoker(url); Invocation invocation = new MockInvocation(); filter.invoke(invoker, invocation); @@ -50,7 +50,7 @@ public void testFail() throws Exception { Assertions.assertThrows(RpcException.class, () -> { URL url = URL.valueOf("test://test"); url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService"); - url = url.addParameter(Constants.TPS_LIMIT_RATE_KEY, 5); + url = url.addParameter(TPS_LIMIT_RATE_KEY, 5); Invoker invoker = new MyInvoker(url); Invocation invocation = new MockInvocation(); for (int i = 0; i < 10; i++) { diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java index b017ed6ea8a..6df479cf06a 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -27,6 +26,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; /** * MockInvocation.java @@ -50,8 +51,8 @@ public Map getAttachments() { attachments.put(PATH_KEY, "dubbo"); attachments.put(GROUP_KEY, "dubbo"); attachments.put(VERSION_KEY, "1.0.0"); - attachments.put(Constants.DUBBO_VERSION_KEY, "1.0.0"); - attachments.put(Constants.TOKEN_KEY, "sfag"); + attachments.put(DUBBO_VERSION_KEY, "1.0.0"); + attachments.put(TOKEN_KEY, "sfag"); attachments.put(TIMEOUT_KEY, "1000"); return attachments; } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/RpcUtilsTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/RpcUtilsTest.java index b3f502eecfc..1209ebd710d 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/RpcUtilsTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/RpcUtilsTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -36,6 +35,8 @@ import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; +import static org.apache.dubbo.common.constants.RpcConstants.AUTO_ATTACH_INVOCATIONID_KEY; + public class RpcUtilsTest { /** @@ -87,7 +88,7 @@ public void testAttachInvocationIdIfAsync_nullAttachments() { */ @Test public void testAttachInvocationIdIfAsync_forceNotAttache() { - URL url = URL.valueOf("dubbo://localhost/?test.async=true&" + Constants.AUTO_ATTACH_INVOCATIONID_KEY + "=false"); + URL url = URL.valueOf("dubbo://localhost/?test.async=true&" + AUTO_ATTACH_INVOCATIONID_KEY + "=false"); Invocation inv = new RpcInvocation("test", new Class[]{}, new String[]{}); RpcUtils.attachInvocationIdIfAsync(url, inv); assertNull(RpcUtils.getInvocationId(inv)); @@ -99,7 +100,7 @@ public void testAttachInvocationIdIfAsync_forceNotAttache() { */ @Test public void testAttachInvocationIdIfAsync_forceAttache() { - URL url = URL.valueOf("dubbo://localhost/?" + Constants.AUTO_ATTACH_INVOCATIONID_KEY + "=true"); + URL url = URL.valueOf("dubbo://localhost/?" + AUTO_ATTACH_INVOCATIONID_KEY + "=true"); Invocation inv = new RpcInvocation("test", new Class[]{}, new String[]{}); RpcUtils.attachInvocationIdIfAsync(url, inv); assertNotNull(RpcUtils.getInvocationId(inv)); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java index dadd4a43eae..0800c66783b 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.dubbo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.bytecode.Wrapper; import org.apache.dubbo.common.extension.ExtensionLoader; @@ -41,6 +40,13 @@ import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_SERVICE_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_INSTANCES_LIMIT_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_CALLBACK_INSTANCES; +import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_SERVICE_PROXY_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.IS_CALLBACK_SERVICE; +import static org.apache.dubbo.common.constants.RpcConstants.CHANNEL_CALLBACK_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.IS_SERVER_KEY; /** * callback service helper @@ -87,9 +93,9 @@ private static String exportOrUnexportCallbackService(Channel channel, URL url, Map params = new HashMap<>(3); // no need to new client again - params.put(Constants.IS_SERVER_KEY, Boolean.FALSE.toString()); + params.put(IS_SERVER_KEY, Boolean.FALSE.toString()); // mark it's a callback, for troubleshooting - params.put(Constants.IS_CALLBACK_SERVICE, Boolean.TRUE.toString()); + params.put(IS_CALLBACK_SERVICE, Boolean.TRUE.toString()); String group = (url == null ? null : url.getParameter(GROUP_KEY)); if (group != null && group.length() > 0) { params.put(GROUP_KEY, group); @@ -156,11 +162,11 @@ private static Object referOrDestroyCallbackService(Channel channel, URL url, Cl //convert error fail fast . //ignore concurrent problem. - Set> callbackInvokers = (Set>) channel.getAttribute(Constants.CHANNEL_CALLBACK_KEY); + Set> callbackInvokers = (Set>) channel.getAttribute(CHANNEL_CALLBACK_KEY); if (callbackInvokers == null) { callbackInvokers = new ConcurrentHashSet>(1); callbackInvokers.add(invoker); - channel.setAttribute(Constants.CHANNEL_CALLBACK_KEY, callbackInvokers); + channel.setAttribute(CHANNEL_CALLBACK_KEY, callbackInvokers); } logger.info("method " + inv.getMethodName() + " include a callback service :" + invoker.getUrl() + ", a proxy :" + invoker + " has been created."); } @@ -169,7 +175,7 @@ private static Object referOrDestroyCallbackService(Channel channel, URL url, Cl if (proxy != null) { Invoker invoker = (Invoker) channel.getAttribute(invokerCacheKey); try { - Set> callbackInvokers = (Set>) channel.getAttribute(Constants.CHANNEL_CALLBACK_KEY); + Set> callbackInvokers = (Set>) channel.getAttribute(CHANNEL_CALLBACK_KEY); if (callbackInvokers != null) { callbackInvokers.remove(invoker); } @@ -187,11 +193,11 @@ private static Object referOrDestroyCallbackService(Channel channel, URL url, Cl } private static String getClientSideCallbackServiceCacheKey(int instid) { - return Constants.CALLBACK_SERVICE_KEY + "." + instid; + return CALLBACK_SERVICE_KEY + "." + instid; } private static String getServerSideCallbackServiceCacheKey(Channel channel, String interfaceClass, int instid) { - return Constants.CALLBACK_SERVICE_PROXY_KEY + "." + System.identityHashCode(channel) + "." + interfaceClass + "." + instid; + return CALLBACK_SERVICE_PROXY_KEY + "." + System.identityHashCode(channel) + "." + interfaceClass + "." + instid; } private static String getServerSideCallbackInvokerCacheKey(Channel channel, String interfaceClass, int instid) { @@ -199,16 +205,16 @@ private static String getServerSideCallbackInvokerCacheKey(Channel channel, Stri } private static String getClientSideCountKey(String interfaceClass) { - return Constants.CALLBACK_SERVICE_KEY + "." + interfaceClass + ".COUNT"; + return CALLBACK_SERVICE_KEY + "." + interfaceClass + ".COUNT"; } private static String getServerSideCountKey(Channel channel, String interfaceClass) { - return Constants.CALLBACK_SERVICE_PROXY_KEY + "." + System.identityHashCode(channel) + "." + interfaceClass + ".COUNT"; + return CALLBACK_SERVICE_PROXY_KEY + "." + System.identityHashCode(channel) + "." + interfaceClass + ".COUNT"; } private static boolean isInstancesOverLimit(Channel channel, URL url, String interfaceClass, int instid, boolean isServer) { Integer count = (Integer) channel.getAttribute(isServer ? getServerSideCountKey(channel, interfaceClass) : getClientSideCountKey(interfaceClass)); - int limit = url.getParameter(Constants.CALLBACK_INSTANCES_LIMIT_KEY, Constants.DEFAULT_CALLBACK_INSTANCES); + int limit = url.getParameter(CALLBACK_INSTANCES_LIMIT_KEY, DEFAULT_CALLBACK_INSTANCES); if (count != null && count >= limit) { //client side error throw new IllegalStateException("interface " + interfaceClass + " `s callback instances num exceed providers limit :" + limit diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java index 02fc3d9a14c..5879cc2d12b 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.dubbo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.remoting.Channel; @@ -39,6 +38,9 @@ import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_SERVICE_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.ASYNC_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; /** * Wrap the existing invoker on the channel. @@ -50,7 +52,7 @@ class ChannelWrappedInvoker extends AbstractInvoker { private final ExchangeClient currentClient; ChannelWrappedInvoker(Class serviceType, Channel channel, URL url, String serviceKey) { - super(serviceType, url, new String[]{GROUP_KEY, Constants.TOKEN_KEY, TIMEOUT_KEY}); + super(serviceType, url, new String[]{GROUP_KEY, TOKEN_KEY, TIMEOUT_KEY}); this.channel = channel; this.serviceKey = serviceKey; this.currentClient = new HeaderExchangeClient(new ChannelWrapper(this.channel), false); @@ -61,10 +63,10 @@ protected Result doInvoke(Invocation invocation) throws Throwable { RpcInvocation inv = (RpcInvocation) invocation; // use interface's name as service path to export if it's not found on client side inv.setAttachment(PATH_KEY, getInterface().getName()); - inv.setAttachment(Constants.CALLBACK_SERVICE_KEY, serviceKey); + inv.setAttachment(CALLBACK_SERVICE_KEY, serviceKey); try { - if (getUrl().getMethodParameter(invocation.getMethodName(), Constants.ASYNC_KEY, false)) { // may have concurrency issue + if (getUrl().getMethodParameter(invocation.getMethodName(), ASYNC_KEY, false)) { // may have concurrency issue currentClient.send(inv, getUrl().getMethodParameter(invocation.getMethodName(), RemotingConstants.SENT_KEY, false)); return new RpcResult(); } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java index 9f3a367c8b5..7aa5198e597 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.rpc.protocol.dubbo; -import org.apache.dubbo.common.Constants; + import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.Cleanable; @@ -40,6 +40,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.CallbackServiceCodec.decodeInvocationArgument; +import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; public class DecodeableRpcInvocation extends RpcInvocation implements Codec, Decodeable { @@ -94,7 +95,7 @@ public Object decode(Channel channel, InputStream input) throws IOException { String dubboVersion = in.readUTF(); request.setVersion(dubboVersion); - setAttachment(Constants.DUBBO_VERSION_KEY, dubboVersion); + setAttachment(DUBBO_VERSION_KEY, dubboVersion); setAttachment(PATH_KEY, in.readUTF()); setAttachment(VERSION_KEY, in.readUTF()); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java index 1685f06fbc5..48e8bb227f3 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.dubbo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.io.Bytes; import org.apache.dubbo.common.io.UnsafeByteArrayInputStream; @@ -42,6 +41,9 @@ import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.CallbackServiceCodec.encodeInvocationArgument; +import static org.apache.dubbo.common.constants.RpcConstants.DECODE_IN_IO_THREAD_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_DECODE_IN_IO_THREAD; +import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; /** * Dubbo codec. @@ -85,9 +87,7 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro data = decodeEventData(channel, in); } else { DecodeableRpcResult result; - if (channel.getUrl().getParameter( - Constants.DECODE_IN_IO_THREAD_KEY, - Constants.DEFAULT_DECODE_IN_IO_THREAD)) { + if (channel.getUrl().getParameter(DECODE_IN_IO_THREAD_KEY, DEFAULT_DECODE_IN_IO_THREAD)) { result = new DecodeableRpcResult(channel, res, is, (Invocation) getRequestData(id), proto); result.decode(); @@ -128,9 +128,7 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro data = decodeEventData(channel, in); } else { DecodeableRpcInvocation inv; - if (channel.getUrl().getParameter( - Constants.DECODE_IN_IO_THREAD_KEY, - Constants.DEFAULT_DECODE_IN_IO_THREAD)) { + if (channel.getUrl().getParameter(DECODE_IN_IO_THREAD_KEY, DEFAULT_DECODE_IN_IO_THREAD)) { inv = new DecodeableRpcInvocation(channel, req, is, proto); inv.decode(); } else { @@ -212,7 +210,7 @@ protected void encodeResponseData(Channel channel, ObjectOutput out, Object data if (attach) { // returns current version of Response to consumer side. - result.getAttachments().put(Constants.DUBBO_VERSION_KEY, Version.getProtocolVersion()); + result.getAttachments().put(DUBBO_VERSION_KEY, Version.getProtocolVersion()); out.writeObject(result.getAttachments()); } } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCountCodec.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCountCodec.java index 4093eb266d6..fab4dd82b9c 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCountCodec.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCountCodec.java @@ -17,7 +17,6 @@ package org.apache.dubbo.rpc.protocol.dubbo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Codec2; import org.apache.dubbo.remoting.buffer.ChannelBuffer; @@ -29,6 +28,9 @@ import java.io.IOException; +import static org.apache.dubbo.common.constants.RpcConstants.INPUT_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.OUTPUT_KEY; + public final class DubboCountCodec implements Codec2 { private DubboCodec codec = new DubboCodec(); @@ -68,15 +70,13 @@ private void logMessageLength(Object result, int bytes) { } if (result instanceof Request) { try { - ((RpcInvocation) ((Request) result).getData()).setAttachment( - Constants.INPUT_KEY, String.valueOf(bytes)); + ((RpcInvocation) ((Request) result).getData()).setAttachment(INPUT_KEY, String.valueOf(bytes)); } catch (Throwable e) { /* ignore */ } } else if (result instanceof Response) { try { - ((RpcResult) ((Response) result).getResult()).setAttachment( - Constants.OUTPUT_KEY, String.valueOf(bytes)); + ((RpcResult) ((Response) result).getResult()).setAttachment(OUTPUT_KEY, String.valueOf(bytes)); } catch (Throwable e) { /* ignore */ } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java index 823c5610788..25c1c2c8c43 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.dubbo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.constants.RemotingConstants; @@ -46,6 +45,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; /** * DubboInvoker @@ -67,7 +67,7 @@ public DubboInvoker(Class serviceType, URL url, ExchangeClient[] clients) { } public DubboInvoker(Class serviceType, URL url, ExchangeClient[] clients, Set> invokers) { - super(serviceType, url, new String[]{INTERFACE_KEY, GROUP_KEY, Constants.TOKEN_KEY, TIMEOUT_KEY}); + super(serviceType, url, new String[]{INTERFACE_KEY, GROUP_KEY, TOKEN_KEY, TIMEOUT_KEY}); this.clients = clients; // get version. this.version = url.getParameter(VERSION_KEY, "0.0.0"); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java index 52c64c3aedd..84e5e148acd 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java @@ -65,6 +65,16 @@ import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.SHARE_CONNECTIONS_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_SHARE_CONNECTIONS; +import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_SERVICE_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.IS_CALLBACK_SERVICE; +import static org.apache.dubbo.common.constants.RpcConstants.OPTIMIZER_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.IS_SERVER_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.STUB_EVENT_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_STUB_EVENT; +import static org.apache.dubbo.common.constants.RpcConstants.STUB_EVENT_METHODS_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.CONNECTIONS_KEY; /** * dubbo protocol support. @@ -186,8 +196,8 @@ private Invocation createInvocation(Channel channel, URL url, String methodKey) invocation.setAttachment(GROUP_KEY, url.getParameter(GROUP_KEY)); invocation.setAttachment(INTERFACE_KEY, url.getParameter(INTERFACE_KEY)); invocation.setAttachment(VERSION_KEY, url.getParameter(VERSION_KEY)); - if (url.getParameter(Constants.STUB_EVENT_KEY, false)) { - invocation.setAttachment(Constants.STUB_EVENT_KEY, Boolean.TRUE.toString()); + if (url.getParameter(STUB_EVENT_KEY, false)) { + invocation.setAttachment(STUB_EVENT_KEY, Boolean.TRUE.toString()); } return invocation; @@ -234,7 +244,7 @@ Invoker getInvoker(Channel channel, Invocation inv) throws RemotingException String path = inv.getAttachments().get(PATH_KEY); // if it's callback service on client side - isStubServiceInvoke = Boolean.TRUE.toString().equals(inv.getAttachments().get(Constants.STUB_EVENT_KEY)); + isStubServiceInvoke = Boolean.TRUE.toString().equals(inv.getAttachments().get(STUB_EVENT_KEY)); if (isStubServiceInvoke) { port = channel.getRemoteAddress().getPort(); } @@ -242,7 +252,7 @@ Invoker getInvoker(Channel channel, Invocation inv) throws RemotingException //callback isCallBackServiceInvoke = isClientSide(channel) && !isStubServiceInvoke; if (isCallBackServiceInvoke) { - path += "." + inv.getAttachments().get(Constants.CALLBACK_SERVICE_KEY); + path += "." + inv.getAttachments().get(CALLBACK_SERVICE_KEY); inv.getAttachments().put(IS_CALLBACK_SERVICE_INVOKE, Boolean.TRUE.toString()); } @@ -276,10 +286,10 @@ public Exporter export(Invoker invoker) throws RpcException { exporterMap.put(key, exporter); //export an stub service for dispatching event - Boolean isStubSupportEvent = url.getParameter(Constants.STUB_EVENT_KEY, Constants.DEFAULT_STUB_EVENT); - Boolean isCallbackservice = url.getParameter(Constants.IS_CALLBACK_SERVICE, false); + Boolean isStubSupportEvent = url.getParameter(STUB_EVENT_KEY, DEFAULT_STUB_EVENT); + Boolean isCallbackservice = url.getParameter(IS_CALLBACK_SERVICE, false); if (isStubSupportEvent && !isCallbackservice) { - String stubServiceMethods = url.getParameter(Constants.STUB_EVENT_METHODS_KEY); + String stubServiceMethods = url.getParameter(STUB_EVENT_METHODS_KEY); if (stubServiceMethods == null || stubServiceMethods.length() == 0) { if (logger.isWarnEnabled()) { logger.warn(new IllegalStateException("consumer [" + url.getParameter(INTERFACE_KEY) + @@ -301,7 +311,7 @@ private void openServer(URL url) { // find server. String key = url.getAddress(); //client can export a service which's only for server to invoke - boolean isServer = url.getParameter(Constants.IS_SERVER_KEY, true); + boolean isServer = url.getParameter(IS_SERVER_KEY, true); if (isServer) { ExchangeServer server = serverMap.get(key); if (server == null) { @@ -351,7 +361,7 @@ private ExchangeServer createServer(URL url) { } private void optimizeSerialization(URL url) throws RpcException { - String className = url.getParameter(Constants.OPTIMIZER_KEY, ""); + String className = url.getParameter(OPTIMIZER_KEY, ""); if (StringUtils.isEmpty(className) || optimizers.contains(className)) { return; } @@ -403,7 +413,7 @@ private ExchangeClient[] getClients(URL url) { boolean useShareConnect = false; - int connections = url.getParameter(Constants.CONNECTIONS_KEY, 0); + int connections = url.getParameter(CONNECTIONS_KEY, 0); List shareClients = null; // if not configured, connection is shared, otherwise, one connection for one service if (connections == 0) { @@ -412,9 +422,9 @@ private ExchangeClient[] getClients(URL url) { /** * The xml configuration should have a higher priority than properties. */ - String shareConnectionsStr = url.getParameter(Constants.SHARE_CONNECTIONS_KEY, (String) null); - connections = Integer.parseInt(StringUtils.isBlank(shareConnectionsStr) ? ConfigUtils.getProperty(Constants.SHARE_CONNECTIONS_KEY, - Constants.DEFAULT_SHARE_CONNECTIONS) : shareConnectionsStr); + String shareConnectionsStr = url.getParameter(SHARE_CONNECTIONS_KEY, (String) null); + connections = Integer.parseInt(StringUtils.isBlank(shareConnectionsStr) ? ConfigUtils.getProperty(SHARE_CONNECTIONS_KEY, + DEFAULT_SHARE_CONNECTIONS) : shareConnectionsStr); shareClients = getSharedClient(url, connections); } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java index c0111a38b20..42db9617570 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.dubbo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.Parameters; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; @@ -35,6 +34,9 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; +import static org.apache.dubbo.common.constants.RpcConstants.LAZY_CONNECT_INITIAL_STATE_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_LAZY_CONNECT_INITIAL_STATE; + /** * dubbo protocol support class. */ @@ -62,7 +64,7 @@ public LazyConnectExchangeClient(URL url, ExchangeHandler requestHandler) { // lazy connect, need set send.reconnect = true, to avoid channel bad status. this.url = url.addParameter(RemotingConstants.SEND_RECONNECT_KEY, Boolean.TRUE.toString()); this.requestHandler = requestHandler; - this.initialState = url.getParameter(Constants.LAZY_CONNECT_INITIAL_STATE_KEY, Constants.DEFAULT_LAZY_CONNECT_INITIAL_STATE); + this.initialState = url.getParameter(LAZY_CONNECT_INITIAL_STATE_KEY, DEFAULT_LAZY_CONNECT_INITIAL_STATE); this.requestWithWarning = url.getParameter(REQUEST_WITH_WARNING_KEY, false); } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java index 5befa5f2ee7..519490b0efd 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.rpc.protocol.dubbo; -import org.apache.dubbo.common.Constants; + import org.apache.dubbo.common.Parameters; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; @@ -30,6 +30,8 @@ import java.net.InetSocketAddress; import java.util.concurrent.atomic.AtomicInteger; +import static org.apache.dubbo.common.constants.RpcConstants.LAZY_CONNECT_INITIAL_STATE_KEY; + /** * dubbo protocol support class. */ @@ -168,7 +170,7 @@ public void startClose() { private void replaceWithLazyClient() { // this is a defensive operation to avoid client is closed by accident, the initial state of the client is false URL lazyUrl = URLBuilder.from(url) - .addParameter(Constants.LAZY_CONNECT_INITIAL_STATE_KEY, Boolean.FALSE) + .addParameter(LAZY_CONNECT_INITIAL_STATE_KEY, Boolean.FALSE) .addParameter(RemotingConstants.RECONNECT_KEY, Boolean.FALSE) .addParameter(RemotingConstants.SEND_RECONNECT_KEY, Boolean.TRUE.toString()) .addParameter("warning", Boolean.TRUE.toString()) diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java index 24e72d607a2..a64dc2b66e7 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.dubbo.filter; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.Logger; @@ -34,6 +33,8 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE; + /** * EventFilter */ @@ -209,7 +210,7 @@ private ConsumerMethodModel.AsyncMethodInfo getAsyncMethodInfo(Invoker invoke } String methodName = invocation.getMethodName(); - if (methodName.equals(Constants.$INVOKE)) { + if (methodName.equals($INVOKE)) { methodName = (String) invocation.getArguments()[0]; } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ExplicitCallbackTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ExplicitCallbackTest.java index bcf80dfc36b..cf3635bff03 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ExplicitCallbackTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ExplicitCallbackTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.dubbo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.Exporter; @@ -36,6 +35,8 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; +import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_INSTANCES_LIMIT_KEY; + public class ExplicitCallbackTest { protected Exporter exporter = null; @@ -76,7 +77,7 @@ public void initOrResetUrl(int callbacks, int timeout) throws Exception { + "&unxxx2.0.callback=false" + "&timeout=" + timeout + "&retries=0" - + "&" + Constants.CALLBACK_INSTANCES_LIMIT_KEY + "=" + callbacks + + "&" + CALLBACK_INSTANCES_LIMIT_KEY + "=" + callbacks ); // uncomment is unblock invoking // serviceURL = serviceURL.addParameter("yyy."+Constants.ASYNC_KEY,String.valueOf(true)); @@ -203,7 +204,7 @@ public void TestCallbackProviderLimit() throws Exception { initOrResetUrl(1, 1000); // URL cannot be transferred automatically from the server side to the client side by using API, instead, // it needs manually specified. - serviceURL = serviceURL.addParameter(Constants.CALLBACK_INSTANCES_LIMIT_KEY, 1 + ""); + serviceURL = serviceURL.addParameter(CALLBACK_INSTANCES_LIMIT_KEY, 1 + ""); initOrResetService(); final AtomicInteger count = new AtomicInteger(0); demoProxy.xxx(new IDemoCallback() { diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java index b77e5e18b3c..50f592fcf64 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.dubbo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.DubboAppender; @@ -40,6 +39,9 @@ import java.util.List; import java.util.Objects; +import static org.apache.dubbo.common.constants.RpcConstants.SHARE_CONNECTIONS_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.CONNECTIONS_KEY; + public class ReferenceCountExchangeClientTest { @@ -208,8 +210,8 @@ private void init(int connections, int shareConnections) { Assertions.assertTrue(shareConnections >= 1); int port = NetUtils.getAvailablePort(); - URL demoUrl = URL.valueOf("dubbo://127.0.0.1:" + port + "/demo?" + Constants.CONNECTIONS_KEY + "=" + connections + "&" + Constants.SHARE_CONNECTIONS_KEY + "=" + shareConnections); - URL helloUrl = URL.valueOf("dubbo://127.0.0.1:" + port + "/hello?" + Constants.CONNECTIONS_KEY + "=" + connections + "&" + Constants.SHARE_CONNECTIONS_KEY + "=" + shareConnections); + URL demoUrl = URL.valueOf("dubbo://127.0.0.1:" + port + "/demo?" + CONNECTIONS_KEY + "=" + connections + "&" + SHARE_CONNECTIONS_KEY + "=" + shareConnections); + URL helloUrl = URL.valueOf("dubbo://127.0.0.1:" + port + "/hello?" + CONNECTIONS_KEY + "=" + connections + "&" + SHARE_CONNECTIONS_KEY + "=" + shareConnections); demoExporter = export(new DemoServiceImpl(), IDemoService.class, demoUrl); helloExporter = export(new HelloServiceImpl(), IHelloService.class, helloUrl); @@ -234,7 +236,7 @@ private void destoy() { } private ExchangeClient getClient(Invoker invoker) { - if (invoker.getUrl().getParameter(Constants.CONNECTIONS_KEY, 1) == 1) { + if (invoker.getUrl().getParameter(CONNECTIONS_KEY, 1) == 1) { return getInvokerClient(invoker); } else { ReferenceCountExchangeClient client = getReferenceClient(invoker); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/service/GenericServiceTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/service/GenericServiceTest.java index 6cbba5b13ff..daa93046763 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/service/GenericServiceTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/service/GenericServiceTest.java @@ -18,7 +18,6 @@ */ package org.apache.dubbo.rpc.service; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.beanutil.JavaBeanAccessor; import org.apache.dubbo.common.beanutil.JavaBeanDescriptor; import org.apache.dubbo.common.beanutil.JavaBeanSerializeUtil; @@ -43,6 +42,9 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicReference; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_NATIVE_JAVA; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_BEAN; + /** * GenericServiceTest */ @@ -151,7 +153,7 @@ public void testGenericSerializationJava() throws Exception { reference.setApplication(new ApplicationConfig("generic-consumer")); reference.setInterface(DemoService.class); reference.setUrl("dubbo://127.0.0.1:29581?scope=remote&timeout=3000"); - reference.setGeneric(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA); + reference.setGeneric(GENERIC_SERIALIZATION_NATIVE_JAVA); GenericService genericService = reference.get(); try { String name = "kimi"; @@ -220,7 +222,7 @@ public void testGenericInvokeWithBeanSerialization() throws Exception { reference.setApplication(new ApplicationConfig("bean-consumer")); reference.setInterface(DemoService.class); reference.setUrl("dubbo://127.0.0.1:29581?scope=remote&timeout=3000"); - reference.setGeneric(Constants.GENERIC_SERIALIZATION_BEAN); + reference.setGeneric(GENERIC_SERIALIZATION_BEAN); GenericService genericService = reference.get(); User user = new User(); user.setName("zhangsan"); diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocol.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocol.java index caa5b597eb3..94b86aeecd3 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocol.java +++ b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocol.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.hessian; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.remoting.http.HttpBinder; @@ -47,7 +46,12 @@ import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; - +import static org.apache.dubbo.common.constants.RpcConstants.HESSIAN2_REQUEST_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_HESSIAN2_REQUEST; +import static org.apache.dubbo.common.constants.RpcConstants.HESSIAN_OVERLOAD_METHOD_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_HESSIAN_OVERLOAD_METHOD; +import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_HTTP_CLIENT; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; /** * http rpc support. */ @@ -84,7 +88,7 @@ protected Runnable doExport(T impl, Class type, URL url) throws RpcExcept final HessianSkeleton skeleton = new HessianSkeleton(impl, type); skeletonMap.put(path, skeleton); - final String genericPath = path + "/" + Constants.GENERIC_KEY; + final String genericPath = path + "/" + GENERIC_KEY; skeletonMap.put(genericPath, new HessianSkeleton(impl, GenericService.class)); return new Runnable() { @@ -99,24 +103,24 @@ public void run() { @Override @SuppressWarnings("unchecked") protected T doRefer(Class serviceType, URL url) throws RpcException { - String generic = url.getParameter(Constants.GENERIC_KEY); + String generic = url.getParameter(GENERIC_KEY); boolean isGeneric = ProtocolUtils.isGeneric(generic) || serviceType.equals(GenericService.class); if (isGeneric) { - RpcContext.getContext().setAttachment(Constants.GENERIC_KEY, generic); - url = url.setPath(url.getPath() + "/" + Constants.GENERIC_KEY); + RpcContext.getContext().setAttachment(GENERIC_KEY, generic); + url = url.setPath(url.getPath() + "/" + GENERIC_KEY); } HessianProxyFactory hessianProxyFactory = new HessianProxyFactory(); - boolean isHessian2Request = url.getParameter(Constants.HESSIAN2_REQUEST_KEY, Constants.DEFAULT_HESSIAN2_REQUEST); + boolean isHessian2Request = url.getParameter(HESSIAN2_REQUEST_KEY, DEFAULT_HESSIAN2_REQUEST); hessianProxyFactory.setHessian2Request(isHessian2Request); - boolean isOverloadEnabled = url.getParameter(Constants.HESSIAN_OVERLOAD_METHOD_KEY, Constants.DEFAULT_HESSIAN_OVERLOAD_METHOD); + boolean isOverloadEnabled = url.getParameter(HESSIAN_OVERLOAD_METHOD_KEY, DEFAULT_HESSIAN_OVERLOAD_METHOD); hessianProxyFactory.setOverloadEnabled(isOverloadEnabled); - String client = url.getParameter(RemotingConstants.CLIENT_KEY, Constants.DEFAULT_HTTP_CLIENT); + String client = url.getParameter(RemotingConstants.CLIENT_KEY, DEFAULT_HTTP_CLIENT); if ("httpclient".equals(client)) { HessianConnectionFactory factory = new HttpClientConnectionFactory(); factory.setHessianProxyFactory(hessianProxyFactory); hessianProxyFactory.setConnectionFactory(factory); - } else if (client != null && client.length() > 0 && !Constants.DEFAULT_HTTP_CLIENT.equals(client)) { + } else if (client != null && client.length() > 0 && !DEFAULT_HTTP_CLIENT.equals(client)) { throw new IllegalStateException("Unsupported http protocol client=\"" + client + "\"!"); } else { HessianConnectionFactory factory = new DubboHessianURLConnectionFactory(); diff --git a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java b/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java index a3c91d0af47..342afeaca60 100644 --- a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java +++ b/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.http; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.StringUtils; @@ -51,6 +50,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; /** * HttpProtocol @@ -89,7 +90,7 @@ protected Runnable doExport(final T impl, Class type, URL url) throws Rpc final String path = url.getAbsolutePath(); skeletonMap.put(path, createExporter(impl, type)); - final String genericPath = path + "/" + Constants.GENERIC_KEY; + final String genericPath = path + "/" + GENERIC_KEY; skeletonMap.put(genericPath, createExporter(impl, GenericService.class)); return new Runnable() { @@ -116,7 +117,7 @@ private HttpInvokerServiceExporter createExporter(T impl, Class type) { @Override @SuppressWarnings("unchecked") protected T doRefer(final Class serviceType, final URL url) throws RpcException { - final String generic = url.getParameter(Constants.GENERIC_KEY); + final String generic = url.getParameter(GENERIC_KEY); final boolean isGeneric = ProtocolUtils.isGeneric(generic) || serviceType.equals(GenericService.class); final HttpInvokerProxyFactoryBean httpProxyFactoryBean = new HttpInvokerProxyFactoryBean(); @@ -138,14 +139,14 @@ public RemoteInvocation createRemoteInvocation(MethodInvocation methodInvocation versions, we need to check if the provider is v2.6.3 or higher before sending customized HttpRemoteInvocation. */ - if (Version.isRelease263OrHigher(url.getParameter(Constants.DUBBO_VERSION_KEY))) { + if (Version.isRelease263OrHigher(url.getParameter(DUBBO_VERSION_KEY))) { invocation = new com.alibaba.dubbo.rpc.protocol.http.HttpRemoteInvocation(methodInvocation); } else { invocation = new RemoteInvocation(methodInvocation); } } if (isGeneric) { - invocation.addAttribute(Constants.GENERIC_KEY, generic); + invocation.addAttribute(GENERIC_KEY, generic); } return invocation; } @@ -153,7 +154,7 @@ public RemoteInvocation createRemoteInvocation(MethodInvocation methodInvocation String key = url.toIdentityString(); if (isGeneric) { - key = key + "/" + Constants.GENERIC_KEY; + key = key + "/" + GENERIC_KEY; } httpProxyFactoryBean.setServiceUrl(key); diff --git a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpRemoteInvocation.java b/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpRemoteInvocation.java index b4617396c21..b60120546e6 100644 --- a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpRemoteInvocation.java +++ b/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpRemoteInvocation.java @@ -17,7 +17,6 @@ package org.apache.dubbo.rpc.protocol.http; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.RpcContext; @@ -28,6 +27,8 @@ import java.util.HashMap; import java.util.Map; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; + public class HttpRemoteInvocation extends RemoteInvocation { private static final long serialVersionUID = 1L; @@ -44,9 +45,9 @@ public Object invoke(Object targetObject) throws NoSuchMethodException, IllegalA RpcContext context = RpcContext.getContext(); context.setAttachments((Map) getAttribute(DUBBO_ATTACHMENTS_ATTR_NAME)); - String generic = (String) getAttribute(Constants.GENERIC_KEY); + String generic = (String) getAttribute(GENERIC_KEY); if (StringUtils.isNotEmpty(generic)) { - context.setAttachment(Constants.GENERIC_KEY, generic); + context.setAttachment(GENERIC_KEY, generic); } try { return super.invoke(targetObject); diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java b/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java index 1181e899d71..0e7bec8e169 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java @@ -30,12 +30,15 @@ import java.util.Map; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.LOCAL_PROTOCOL; + /** * InjvmProtocol */ public class InjvmProtocol extends AbstractProtocol implements Protocol { - public static final String NAME = Constants.LOCAL_PROTOCOL; + public static final String NAME = LOCAL_PROTOCOL; public static final int DEFAULT_PORT = 0; private static InjvmProtocol INSTANCE; @@ -70,7 +73,7 @@ static Exporter getExporter(Map> map, URL key) { if (result == null) { return null; } else if (ProtocolUtils.isGeneric( - result.getInvoker().getUrl().getParameter(Constants.GENERIC_KEY))) { + result.getInvoker().getUrl().getParameter(GENERIC_KEY))) { return null; } else { return result; @@ -95,14 +98,14 @@ public Invoker refer(Class serviceType, URL url) throws RpcException { public boolean isInjvmRefer(URL url) { String scope = url.getParameter(Constants.SCOPE_KEY); // Since injvm protocol is configured explicitly, we don't need to set any extra flag, use normal refer process. - if (Constants.SCOPE_LOCAL.equals(scope) || (url.getParameter(Constants.LOCAL_PROTOCOL, false))) { + if (Constants.SCOPE_LOCAL.equals(scope) || (url.getParameter(LOCAL_PROTOCOL, false))) { // if it's declared as local reference // 'scope=local' is equivalent to 'injvm=true', injvm will be deprecated in the future release return true; } else if (Constants.SCOPE_REMOTE.equals(scope)) { // it's declared as remote reference return false; - } else if (url.getParameter(Constants.GENERIC_KEY, false)) { + } else if (url.getParameter(GENERIC_KEY, false)) { // generic invocation is not local reference return false; } else if (getExporter(exporterMap, url) != null) { diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocolTest.java b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocolTest.java index cd19b8fcb06..c640ed0ac30 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocolTest.java @@ -39,6 +39,9 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.LOCAL_PROTOCOL; + /** * ProxiesTest */ @@ -95,13 +98,13 @@ public void testIsInjvmRefer() throws Exception { url = URL.valueOf("fake://127.0.0.1/TestService").addParameter(Constants.SCOPE_KEY, Constants.SCOPE_LOCAL); assertTrue(InjvmProtocol.getInjvmProtocol().isInjvmRefer(url)); - url = URL.valueOf("fake://127.0.0.1/TestService").addParameter(Constants.LOCAL_PROTOCOL,true); + url = URL.valueOf("fake://127.0.0.1/TestService").addParameter(LOCAL_PROTOCOL,true); assertTrue(InjvmProtocol.getInjvmProtocol().isInjvmRefer(url)); url = URL.valueOf("fake://127.0.0.1/TestService").addParameter(Constants.SCOPE_KEY, Constants.SCOPE_REMOTE); assertFalse(InjvmProtocol.getInjvmProtocol().isInjvmRefer(url)); - url = URL.valueOf("fake://127.0.0.1/TestService").addParameter(Constants.GENERIC_KEY, true); + url = URL.valueOf("fake://127.0.0.1/TestService").addParameter(GENERIC_KEY, true); assertFalse(InjvmProtocol.getInjvmProtocol().isInjvmRefer(url)); } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/BaseRestServer.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/BaseRestServer.java index f10abdd7976..41a67915d61 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/BaseRestServer.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/BaseRestServer.java @@ -16,13 +16,13 @@ */ package org.apache.dubbo.rpc.protocol.rest; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; import org.jboss.resteasy.spi.ResteasyDeployment; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; +import static org.apache.dubbo.common.constants.RpcConstants.EXTENSION_KEY; public abstract class BaseRestServer implements RestServer { @@ -35,7 +35,7 @@ public void start(URL url) { // TODO users can override this mapper, but we just rely on the current priority strategy of resteasy getDeployment().getProviderClasses().add(RpcExceptionMapper.class.getName()); - loadProviders(url.getParameter(Constants.EXTENSION_KEY, "")); + loadProviders(url.getParameter(EXTENSION_KEY, "")); doStart(url); } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/NettyServer.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/NettyServer.java index f17f8576fc0..370f26acc7c 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/NettyServer.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/NettyServer.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.NetUtils; @@ -31,6 +30,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS; import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.KEEP_ALIVE_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_KEEP_ALIVE; /** * Netty server can't support @Context injection of servlet objects since it's not a servlet container @@ -48,7 +49,7 @@ protected void doStart(URL url) { } server.setPort(url.getParameter(RemotingConstants.BIND_PORT_KEY, url.getPort())); Map channelOption = new HashMap(); - channelOption.put(ChannelOption.SO_KEEPALIVE, url.getParameter(Constants.KEEP_ALIVE_KEY, Constants.DEFAULT_KEEP_ALIVE)); + channelOption.put(ChannelOption.SO_KEEPALIVE, url.getParameter(KEEP_ALIVE_KEY, DEFAULT_KEEP_ALIVE)); server.setChildChannelOptions(channelOption); server.setExecutorThreadCount(url.getParameter(THREADS_KEY, DEFAULT_THREADS)); server.setIoWorkerCount(url.getParameter(IO_THREADS_KEY, RemotingConstants.DEFAULT_IO_THREADS)); diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java index 977bea2daa6..af72a465665 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.StringUtils; @@ -56,6 +55,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.CONNECTIONS_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.EXTENSION_KEY; public class RestProtocol extends AbstractProxyProtocol { @@ -139,8 +140,8 @@ protected T doRefer(Class serviceType, URL url) throws RpcException { // TODO more configs to add PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); // 20 is the default maxTotal of current PoolingClientConnectionManager - connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, HTTPCLIENTCONNECTIONMANAGER_MAXTOTAL)); - connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, HTTPCLIENTCONNECTIONMANAGER_MAXPERROUTE)); + connectionManager.setMaxTotal(url.getParameter(CONNECTIONS_KEY, HTTPCLIENTCONNECTIONMANAGER_MAXTOTAL)); + connectionManager.setDefaultMaxPerRoute(url.getParameter(CONNECTIONS_KEY, HTTPCLIENTCONNECTIONMANAGER_MAXPERROUTE)); if (connectionMonitor == null) { connectionMonitor = new ConnectionMonitor(); @@ -180,7 +181,7 @@ protected T doRefer(Class serviceType, URL url) throws RpcException { clients.add(client); client.register(RpcContextFilter.class); - for (String clazz : COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) { + for (String clazz : COMMA_SPLIT_PATTERN.split(url.getParameter(EXTENSION_KEY, ""))) { if (!StringUtils.isEmpty(clazz)) { try { client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim())); diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/RestProtocolTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/RestProtocolTest.java index aa850301427..1b68c098e65 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/RestProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/RestProtocolTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; @@ -40,6 +39,8 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; +import static org.apache.dubbo.common.constants.RpcConstants.EXTENSION_KEY; + public class RestProtocolTest { private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest"); private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); @@ -175,7 +176,7 @@ public void testFilter() { ApplicationModel.initProviderModel(exportUrl.getServiceKey(), providerModel); URL nettyUrl = exportUrl.addParameter(RemotingConstants.SERVER_KEY, "netty") - .addParameter(Constants.EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.support.LoggingFilter"); + .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.support.LoggingFilter"); Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); @@ -195,7 +196,7 @@ public void testRpcContextFilter() { // use RpcContextFilter URL nettyUrl = exportUrl.addParameter(RemotingConstants.SERVER_KEY, "netty") - .addParameter(Constants.EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.RpcContextFilter"); + .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.RpcContextFilter"); Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); @@ -217,7 +218,7 @@ public void testRegFail() { ProviderModel providerModel = new ProviderModel(exportUrl.getServiceKey(), server, DemoService.class); ApplicationModel.initProviderModel(exportUrl.getServiceKey(), providerModel); - URL nettyUrl = exportUrl.addParameter(Constants.EXTENSION_KEY, "com.not.existing.Filter"); + URL nettyUrl = exportUrl.addParameter(EXTENSION_KEY, "com.not.existing.Filter"); protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); }); } diff --git a/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocol.java b/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocol.java index 13d8cae220a..9b7f16b722c 100644 --- a/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocol.java +++ b/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocol.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rmi; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.protocol.AbstractProxyProtocol; @@ -32,6 +31,8 @@ import java.rmi.RemoteException; import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; import static org.apache.dubbo.common.Version.isRelease263OrHigher; import static org.apache.dubbo.common.Version.isRelease270OrHigher; @@ -72,7 +73,7 @@ public void run() { @SuppressWarnings("unchecked") protected T doRefer(final Class serviceType, final URL url) throws RpcException { final RmiProxyFactoryBean rmiProxyFactoryBean = new RmiProxyFactoryBean(); - final String generic = url.getParameter(Constants.GENERIC_KEY); + final String generic = url.getParameter(GENERIC_KEY); final boolean isGeneric = ProtocolUtils.isGeneric(generic) || serviceType.equals(GenericService.class); /* RMI needs extra parameter since it uses customized remote invocation object @@ -87,22 +88,22 @@ protected T doRefer(final Class serviceType, final URL url) throws RpcExc rmiProxyFactoryBean.setRemoteInvocationFactory((methodInvocation) -> { RemoteInvocation invocation = new RmiRemoteInvocation(methodInvocation); if (invocation != null && isGeneric) { - invocation.addAttribute(Constants.GENERIC_KEY, generic); + invocation.addAttribute(GENERIC_KEY, generic); } return invocation; }); - } else if (isRelease263OrHigher(url.getParameter(Constants.DUBBO_VERSION_KEY))) { + } else if (isRelease263OrHigher(url.getParameter(DUBBO_VERSION_KEY))) { rmiProxyFactoryBean.setRemoteInvocationFactory((methodInvocation) -> { RemoteInvocation invocation = new com.alibaba.dubbo.rpc.protocol.rmi.RmiRemoteInvocation(methodInvocation); if (invocation != null && isGeneric) { - invocation.addAttribute(Constants.GENERIC_KEY, generic); + invocation.addAttribute(GENERIC_KEY, generic); } return invocation; }); } String serviceUrl = url.toIdentityString(); if (isGeneric) { - serviceUrl = serviceUrl + "/" + Constants.GENERIC_KEY; + serviceUrl = serviceUrl + "/" + GENERIC_KEY; } rmiProxyFactoryBean.setServiceUrl(serviceUrl); rmiProxyFactoryBean.setServiceInterface(serviceType); @@ -135,7 +136,7 @@ private RmiServiceExporter createExporter(T impl, Class type, URL url, bo final RmiServiceExporter rmiServiceExporter = new RmiServiceExporter(); rmiServiceExporter.setRegistryPort(url.getPort()); if (isGeneric) { - rmiServiceExporter.setServiceName(url.getPath() + "/" + Constants.GENERIC_KEY); + rmiServiceExporter.setServiceName(url.getPath() + "/" + GENERIC_KEY); } else { rmiServiceExporter.setServiceName(url.getPath()); } diff --git a/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiRemoteInvocation.java b/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiRemoteInvocation.java index 96b49e7e493..d03618ea2bc 100644 --- a/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiRemoteInvocation.java +++ b/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiRemoteInvocation.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rmi; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.RpcContext; @@ -27,6 +26,8 @@ import java.util.HashMap; import java.util.Map; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; + public class RmiRemoteInvocation extends RemoteInvocation { private static final long serialVersionUID = 1L; private static final String dubboAttachmentsAttrName = "dubbo.attachments"; @@ -50,9 +51,9 @@ public Object invoke(Object targetObject) throws NoSuchMethodException, IllegalA InvocationTargetException { RpcContext context = RpcContext.getContext(); context.setAttachments((Map) getAttribute(dubboAttachmentsAttrName)); - String generic = (String) getAttribute(Constants.GENERIC_KEY); + String generic = (String) getAttribute(GENERIC_KEY); if (StringUtils.isNotEmpty(generic)) { - context.setAttachment(Constants.GENERIC_KEY, generic); + context.setAttachment(GENERIC_KEY, generic); } try { return super.invoke(targetObject); diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java index 8b79c2ac6c7..a5306844b30 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.thrift; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.AtomicPositiveInteger; @@ -39,6 +38,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; + /** * @since 2.7.0, use https://github.com/dubbo/dubbo-rpc-native-thrift instead @@ -59,7 +60,7 @@ public ThriftInvoker(Class service, URL url, ExchangeClient[] clients) { } public ThriftInvoker(Class type, URL url, ExchangeClient[] clients, Set> invokers) { - super(type, url, new String[]{INTERFACE_KEY, GROUP_KEY, Constants.TOKEN_KEY, TIMEOUT_KEY}); + super(type, url, new String[]{INTERFACE_KEY, GROUP_KEY, TOKEN_KEY, TIMEOUT_KEY}); this.clients = clients; this.invokers = invokers; } diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java index d5fc0b3a4b7..9f56a736f0c 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.thrift; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.constants.RemotingConstants; @@ -45,6 +44,8 @@ import java.util.concurrent.ConcurrentMap; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.IS_SERVER_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.CONNECTIONS_KEY; /** * @since 2.7.0, use https://github.com/dubbo/dubbo-rpc-native-thrift instead @@ -124,7 +125,7 @@ public Exporter export(Invoker invoker) throws RpcException { // find server. String key = url.getAddress(); // client can expose a service for server to invoke only. - boolean isServer = url.getParameter(Constants.IS_SERVER_KEY, true); + boolean isServer = url.getParameter(IS_SERVER_KEY, true); if (isServer && !serverMap.containsKey(key)) { serverMap.put(key, getServer(url)); } @@ -173,7 +174,7 @@ public Invoker refer(Class type, URL url) throws RpcException { private ExchangeClient[] getClients(URL url) { - int connections = url.getParameter(Constants.CONNECTIONS_KEY, 1); + int connections = url.getParameter(CONNECTIONS_KEY, 1); ExchangeClient[] clients = new ExchangeClient[connections]; From 7de8abb515ffa77ec07a90255afe3d62a648b303 Mon Sep 17 00:00:00 2001 From: fibbery <568263091@qq.com> Date: Mon, 13 May 2019 23:03:21 +0800 Subject: [PATCH 048/115] Fix telnet not work in some scene(#4007) (#4026) --- .../apache/dubbo/common/utils/PojoUtils.java | 19 ++++- .../org/apache/dubbo/common/model/User.java | 77 +++++++++++++++++++ .../dubbo/common/utils/PojoUtilsTest.java | 6 ++ 3 files changed, 101 insertions(+), 1 deletion(-) create mode 100644 dubbo-common/src/test/java/org/apache/dubbo/common/model/User.java diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PojoUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PojoUtils.java index 37aa5ddaa68..3bab26134e3 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PojoUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PojoUtils.java @@ -30,6 +30,7 @@ import java.lang.reflect.Proxy; import java.lang.reflect.Type; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -542,7 +543,8 @@ private static Object newInstance(Class cls) { } } constructor.setAccessible(true); - return constructor.newInstance(new Object[constructor.getParameterTypes().length]); + Object[] parameters = Arrays.stream(constructor.getParameterTypes()).map(PojoUtils::getDefaultValue).toArray(); + return constructor.newInstance(parameters); } catch (InstantiationException e) { throw new RuntimeException(e.getMessage(), e); } catch (IllegalAccessException e) { @@ -553,6 +555,21 @@ private static Object newInstance(Class cls) { } } + /** + * return init value + * @param parameterType + * @return + */ + private static Object getDefaultValue(Class parameterType) { + if (parameterType.getName().equals("char")) { + return Character.MIN_VALUE; + } + if (parameterType.getName().equals("bool")) { + return false; + } + return parameterType.isPrimitive() ? 0 : null; + } + private static Method getSetterMethod(Class cls, String property, Class valueCls) { String name = "set" + property.substring(0, 1).toUpperCase() + property.substring(1); Method method = NAME_METHODS_CACHE.get(cls.getName() + "." + name + "(" + valueCls.getName() + ")"); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/model/User.java b/dubbo-common/src/test/java/org/apache/dubbo/common/model/User.java new file mode 100644 index 00000000000..33d20bbc6cc --- /dev/null +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/model/User.java @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.common.model; + +import java.util.Objects; + +/** + * @author: fibbery + * @date: 2019-05-13 18:41 + * @description: this class has no nullary constructor and some field is primitive + */ +public class User { + private int age; + + private String name; + + public User(int age, String name) { + this.age = age; + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return String.format("User name(%s) age(%d) ", name, age); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + User user = (User) o; + if (name == null) { + if (user.name != null) { + return false; + } + } else if (!name.equals(user.name)) { + return false; + } + return Objects.equals(age, user.age); + } + + @Override + public int hashCode() { + return Objects.hash(age, name); + } +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/PojoUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/PojoUtilsTest.java index ecc3f46ee38..dcaad275ea1 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/PojoUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/PojoUtilsTest.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.model.Person; import org.apache.dubbo.common.model.SerializablePerson; +import org.apache.dubbo.common.model.User; import org.apache.dubbo.common.model.person.BigPerson; import org.apache.dubbo.common.model.person.FullAddress; import org.apache.dubbo.common.model.person.PersonInfo; @@ -132,6 +133,11 @@ public void test_pojo() throws Exception { assertObject(new SerializablePerson()); } + @Test + public void test_has_no_nullary_constructor_pojo() { + assertObject(new User(1,"fibbery")); + } + @Test public void test_Map_List_pojo() throws Exception { Map> map = new HashMap>(); From 175eab1b83e90d0d95961d38d4713a7add82ad48 Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Mon, 13 May 2019 23:54:45 +0800 Subject: [PATCH 049/115] start to use ClusterConstants, MonitorConstants (#4045) --- .../dubbo/rpc/cluster/Configurator.java | 6 +- .../configurator/AbstractConfigurator.java | 9 +- .../configurator/parser/ConfigParser.java | 4 +- .../cluster/directory/AbstractDirectory.java | 3 +- .../loadbalance/AbstractLoadBalance.java | 13 ++- .../router/condition/ConditionRouter.java | 19 +-- .../router/file/FileRouterFactory.java | 16 ++- .../router/mock/MockInvokersSelector.java | 12 +- .../cluster/router/script/ScriptRouter.java | 18 ++- .../rpc/cluster/router/tag/TagRouter.java | 24 ++-- .../support/AbstractClusterInvoker.java | 16 ++- .../rpc/cluster/support/ClusterUtils.java | 8 +- .../support/FailbackClusterInvoker.java | 14 ++- .../support/FailoverClusterInvoker.java | 6 +- .../support/ForkingClusterInvoker.java | 5 +- .../support/wrapper/MockClusterInvoker.java | 8 +- .../apache/dubbo/rpc/cluster/StickyTest.java | 10 +- .../configurator/parser/ConfigParserTest.java | 16 +-- .../directory/StaticDirectoryTest.java | 5 +- .../loadbalance/LoadBalanceBaseTest.java | 39 ++++--- .../router/condition/ConditionRouterTest.java | 26 +++-- .../router/file/FileRouterEngineTest.java | 4 +- .../router/script/ScriptRouterTest.java | 7 +- .../support/AbstractClusterInvokerTest.java | 11 +- .../org/apache/dubbo/common/Constants.java | 108 ------------------ .../dubbo/config/AbstractInterfaceConfig.java | 14 ++- .../dubbo/config/AbstractMethodConfig.java | 8 +- .../dubbo/config/AbstractReferenceConfig.java | 7 +- .../apache/dubbo/config/MetricsConfig.java | 8 +- .../apache/dubbo/config/ReferenceConfig.java | 3 +- .../apache/dubbo/config/ServiceConfig.java | 9 +- .../dubbo/config/annotation/Reference.java | 11 +- .../dubbo/config/annotation/Service.java | 14 ++- .../config/AbstractReferenceConfigTest.java | 15 ++- .../config/spring/SimpleRegistryExporter.java | 3 +- .../dubbo/monitor/support/MonitorFilter.java | 9 +- .../monitor/support/MonitorFilterTest.java | 4 +- .../dubbo/monitor/dubbo/MetricsFilter.java | 36 +++--- .../monitor/dubbo/MetricsFilterTest.java | 36 +++--- .../integration/RegistryDirectory.java | 6 +- .../integration/RegistryProtocol.java | 4 +- .../registry/dubbo/DubboRegistryFactory.java | 3 +- .../registry/dubbo/RegistryDirectoryTest.java | 37 +++--- .../dubbo/SimpleRegistryExporter.java | 3 +- .../dubbo/rpc/filter/ContextFilter.java | 6 +- 45 files changed, 305 insertions(+), 338 deletions(-) diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Configurator.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Configurator.java index b86409d8d13..dd6b4ba8d83 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Configurator.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Configurator.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.CollectionUtils; @@ -28,6 +27,7 @@ import java.util.Map; import java.util.Optional; +import static org.apache.dubbo.common.constants.ClusterConstants.PRIORITY_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; @@ -110,8 +110,8 @@ default int compareTo(Configurator o) { int ipCompare = getUrl().getHost().compareTo(o.getUrl().getHost()); // host is the same, sort by priority if (ipCompare == 0) { - int i = getUrl().getParameter(Constants.PRIORITY_KEY, 0); - int j = o.getUrl().getParameter(Constants.PRIORITY_KEY, 0); + int i = getUrl().getParameter(PRIORITY_KEY, 0); + int j = o.getUrl().getParameter(PRIORITY_KEY, 0); return Integer.compare(i, j); } else { return ipCompare; diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java index 5fdefb83e3f..84275aef9a7 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.configurator; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.NetUtils; @@ -27,6 +26,8 @@ import java.util.Map; import java.util.Set; +import static org.apache.dubbo.common.constants.ClusterConstants.CONFIG_VERSION_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.OVERRIDE_PROVIDERS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; @@ -67,7 +68,7 @@ public URL configure(URL url) { /** * This if branch is created since 2.7.0. */ - String apiVersion = configuratorUrl.getParameter(Constants.CONFIG_VERSION_KEY); + String apiVersion = configuratorUrl.getParameter(CONFIG_VERSION_KEY); if (StringUtils.isNotEmpty(apiVersion)) { String currentSide = url.getParameter(SIDE_KEY); String configuratorSide = configuratorUrl.getParameter(SIDE_KEY); @@ -108,7 +109,7 @@ private URL configureDeprecated(URL url) { private URL configureIfMatch(String host, URL url) { if (ANYHOST_VALUE.equals(configuratorUrl.getHost()) || host.equals(configuratorUrl.getHost())) { // TODO, to support wildcards - String providers = configuratorUrl.getParameter(Constants.OVERRIDE_PROVIDERS_KEY); + String providers = configuratorUrl.getParameter(OVERRIDE_PROVIDERS_KEY); if (StringUtils.isEmpty(providers) || providers.contains(url.getAddress()) || providers.contains(ANYHOST_VALUE)) { String configApplication = configuratorUrl.getParameter(APPLICATION_KEY, configuratorUrl.getUsername()); @@ -124,7 +125,7 @@ private URL configureIfMatch(String host, URL url) { conditionKeys.add(VERSION_KEY); conditionKeys.add(APPLICATION_KEY); conditionKeys.add(SIDE_KEY); - conditionKeys.add(Constants.CONFIG_VERSION_KEY); + conditionKeys.add(CONFIG_VERSION_KEY); for (Map.Entry entry : configuratorUrl.getParameters().entrySet()) { String key = entry.getKey(); String value = entry.getValue(); diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParser.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParser.java index b16783303db..5b6f457b14f 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParser.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParser.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.configurator.parser; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; @@ -31,6 +30,7 @@ import java.util.List; import java.util.Map; +import static org.apache.dubbo.common.constants.ClusterConstants.OVERRIDE_PROVIDERS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.RegistryConstants.APP_DYNAMIC_CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_CONFIGURATORS_CATEGORY; @@ -148,7 +148,7 @@ private static String toParameterString(ConfigItem item) { if (CollectionUtils.isNotEmpty(item.getProviderAddresses())) { sb.append("&"); - sb.append(Constants.OVERRIDE_PROVIDERS_KEY); + sb.append(OVERRIDE_PROVIDERS_KEY); sb.append("="); sb.append(CollectionUtils.join(item.getProviderAddresses(), ",")); } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java index f9677b970ed..680cbfb6319 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java @@ -32,6 +32,7 @@ import java.util.List; import java.util.Map; +import static org.apache.dubbo.common.constants.MonitorConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; /** @@ -66,7 +67,7 @@ public AbstractDirectory(URL url, URL consumerUrl, RouterChain routerChain) { if (url.getProtocol().equals(REGISTRY_PROTOCOL)) { Map queryMap = StringUtils.parseQueryString(url.getParameterAndDecoded(Constants.REFER_KEY)); - this.url = url.addParameters(queryMap).removeParameter(Constants.MONITOR_KEY); + this.url = url.addParameters(queryMap).removeParameter(MONITOR_KEY); } else { this.url = url; } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java index 78151ed5af4..9ca40e37617 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.loadbalance; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.rpc.Invocation; @@ -25,6 +24,12 @@ import java.util.List; +import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_WARMUP; +import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_WEIGHT; +import static org.apache.dubbo.common.constants.ClusterConstants.REMOTE_TIMESTAMP_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.WARMUP_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.WEIGHT_KEY; + /** * AbstractLoadBalance */ @@ -66,12 +71,12 @@ public Invoker select(List> invokers, URL url, Invocation invo * @return weight */ protected int getWeight(Invoker invoker, Invocation invocation) { - int weight = invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.WEIGHT_KEY, Constants.DEFAULT_WEIGHT); + int weight = invoker.getUrl().getMethodParameter(invocation.getMethodName(), WEIGHT_KEY, DEFAULT_WEIGHT); if (weight > 0) { - long timestamp = invoker.getUrl().getParameter(Constants.REMOTE_TIMESTAMP_KEY, 0L); + long timestamp = invoker.getUrl().getParameter(REMOTE_TIMESTAMP_KEY, 0L); if (timestamp > 0L) { int uptime = (int) (System.currentTimeMillis() - timestamp); - int warmup = invoker.getUrl().getParameter(Constants.WARMUP_KEY, Constants.DEFAULT_WARMUP); + int warmup = invoker.getUrl().getParameter(WARMUP_KEY, DEFAULT_WARMUP); if (uptime > 0 && uptime < warmup) { weight = calculateWarmupWeight(uptime, warmup, weight); } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java index ab75f894d74..c8d625c7db5 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java @@ -39,10 +39,15 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.ADDRESS_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.FORCE_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.PRIORITY_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.RULE_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.RUNTIME_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY_PREFIX; import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY; /** * ConditionRouter @@ -66,10 +71,10 @@ public ConditionRouter(String rule, boolean force, boolean enabled) { public ConditionRouter(URL url) { this.url = url; - this.priority = url.getParameter(Constants.PRIORITY_KEY, 0); - this.force = url.getParameter(Constants.FORCE_KEY, false); + this.priority = url.getParameter(PRIORITY_KEY, 0); + this.force = url.getParameter(FORCE_KEY, false); this.enabled = url.getParameter(ENABLED_KEY, true); - init(url.getParameterAndDecoded(Constants.RULE_KEY)); + init(url.getParameterAndDecoded(RULE_KEY)); } public void init(String rule) { @@ -188,7 +193,7 @@ public List> route(List> invokers, URL url, Invocation if (!result.isEmpty()) { return result; } else if (force) { - logger.warn("The route result is empty and force execute. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey() + ", router: " + url.getParameterAndDecoded(Constants.RULE_KEY)); + logger.warn("The route result is empty and force execute. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey() + ", router: " + url.getParameterAndDecoded(RULE_KEY)); return result; } } catch (Throwable t) { @@ -201,7 +206,7 @@ public List> route(List> invokers, URL url, Invocation public boolean isRuntime() { // We always return true for previously defined Router, that is, old Router doesn't support cache anymore. // return true; - return this.url.getParameter(Constants.RUNTIME_KEY, false); + return this.url.getParameter(RUNTIME_KEY, false); } @Override @@ -226,7 +231,7 @@ private boolean matchCondition(Map condition, URL url, URL pa //get real invoked method name from invocation if (invocation != null && (METHOD_KEY.equals(key) || METHODS_KEY.equals(key))) { sampleValue = invocation.getMethodName(); - } else if (Constants.ADDRESS_KEY.equals(key)) { + } else if (ADDRESS_KEY.equals(key)) { sampleValue = url.getAddress(); } else if (Constants.HOST_KEY.equals(key)) { sampleValue = url.getHost(); diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterFactory.java index 1dd446cc187..7ad7fc7f897 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterFactory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterFactory.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.router.file; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.utils.IOUtils; @@ -28,6 +27,11 @@ import java.io.FileReader; import java.io.IOException; +import static org.apache.dubbo.common.constants.ClusterConstants.ROUTER_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.RULE_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.RUNTIME_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.TYPE_KEY; + public class FileRouterFactory implements RouterFactory { public static final String NAME = "file"; @@ -43,7 +47,7 @@ public Router getRouter(URL url) { try { // Transform File URL into Script Route URL, and Load // file:///d:/path/to/route.js?router=script ==> script:///d:/path/to/route.js?type=js&rule= - String protocol = url.getParameter(Constants.ROUTER_KEY, ScriptRouterFactory.NAME); // Replace original protocol (maybe 'file') with 'script' + String protocol = url.getParameter(ROUTER_KEY, ScriptRouterFactory.NAME); // Replace original protocol (maybe 'file') with 'script' String type = null; // Use file suffix to config script type, e.g., js, groovy ... String path = url.getPath(); if (path != null) { @@ -55,12 +59,12 @@ public Router getRouter(URL url) { String rule = IOUtils.read(new FileReader(new File(url.getAbsolutePath()))); // FIXME: this code looks useless - boolean runtime = url.getParameter(Constants.RUNTIME_KEY, false); + boolean runtime = url.getParameter(RUNTIME_KEY, false); URL script = URLBuilder.from(url) .setProtocol(protocol) - .addParameter(Constants.TYPE_KEY, type) - .addParameter(Constants.RUNTIME_KEY, runtime) - .addParameterAndEncoded(Constants.RULE_KEY, rule) + .addParameter(TYPE_KEY, type) + .addParameter(RUNTIME_KEY, runtime) + .addParameterAndEncoded(RULE_KEY, rule) .build(); return routerFactory.getRouter(script); diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelector.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelector.java index 78ada664229..76fa6ded425 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelector.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelector.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.router.mock; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.rpc.Invocation; @@ -27,6 +26,9 @@ import java.util.ArrayList; import java.util.List; +import static org.apache.dubbo.common.constants.ClusterConstants.INVOCATION_NEED_MOCK; +import static org.apache.dubbo.common.constants.ClusterConstants.MOCK_PROTOCOL; + /** * A specific Router designed to realize mock feature. * If a request is configured to use mock, then this router guarantees that only the invokers with protocol MOCK appear in final the invoker list, all other invokers will be excluded. @@ -50,7 +52,7 @@ public List> route(final List> invokers, if (invocation.getAttachments() == null) { return getNormalInvokers(invokers); } else { - String value = invocation.getAttachments().get(Constants.INVOCATION_NEED_MOCK); + String value = invocation.getAttachments().get(INVOCATION_NEED_MOCK); if (value == null) { return getNormalInvokers(invokers); } else if (Boolean.TRUE.toString().equalsIgnoreCase(value)) { @@ -66,7 +68,7 @@ private List> getMockedInvokers(final List> invokers) } List> sInvokers = new ArrayList>(1); for (Invoker invoker : invokers) { - if (invoker.getUrl().getProtocol().equals(Constants.MOCK_PROTOCOL)) { + if (invoker.getUrl().getProtocol().equals(MOCK_PROTOCOL)) { sInvokers.add(invoker); } } @@ -79,7 +81,7 @@ private List> getNormalInvokers(final List> invokers) } else { List> sInvokers = new ArrayList>(invokers.size()); for (Invoker invoker : invokers) { - if (!invoker.getUrl().getProtocol().equals(Constants.MOCK_PROTOCOL)) { + if (!invoker.getUrl().getProtocol().equals(MOCK_PROTOCOL)) { sInvokers.add(invoker); } } @@ -90,7 +92,7 @@ private List> getNormalInvokers(final List> invokers) private boolean hasMockProviders(final List> invokers) { boolean hasMockProvider = false; for (Invoker invoker : invokers) { - if (invoker.getUrl().getProtocol().equals(Constants.MOCK_PROTOCOL)) { + if (invoker.getUrl().getProtocol().equals(MOCK_PROTOCOL)) { hasMockProvider = true; break; } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouter.java index 0b47d2e7530..c73d9a9ec13 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouter.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.router.script; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -40,6 +39,13 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; +import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_SCRIPT_TYPE_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.FORCE_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.PRIORITY_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.RULE_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.RUNTIME_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.TYPE_KEY; + /** * ScriptRouter */ @@ -58,7 +64,7 @@ public class ScriptRouter extends AbstractRouter { public ScriptRouter(URL url) { this.url = url; - this.priority = url.getParameter(Constants.PRIORITY_KEY, SCRIPT_ROUTER_DEFAULT_PRIORITY); + this.priority = url.getParameter(PRIORITY_KEY, SCRIPT_ROUTER_DEFAULT_PRIORITY); engine = getEngine(url); rule = getRule(url); @@ -77,7 +83,7 @@ public ScriptRouter(URL url) { * get rule from url parameters. */ private String getRule(URL url) { - String vRule = url.getParameterAndDecoded(Constants.RULE_KEY); + String vRule = url.getParameterAndDecoded(RULE_KEY); if (StringUtils.isEmpty(vRule)) { throw new IllegalStateException("route rule can not be empty."); } @@ -88,7 +94,7 @@ private String getRule(URL url) { * create ScriptEngine instance by type from url parameters, then cache it */ private ScriptEngine getEngine(URL url) { - String type = url.getParameter(Constants.TYPE_KEY, Constants.DEFAULT_SCRIPT_TYPE_KEY); + String type = url.getParameter(TYPE_KEY, DEFAULT_SCRIPT_TYPE_KEY); return engines.computeIfAbsent(type, t -> { ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName(type); @@ -142,12 +148,12 @@ private Bindings createBindings(List> invokers, Invocation invoca @Override public boolean isRuntime() { - return this.url.getParameter(Constants.RUNTIME_KEY, false); + return this.url.getParameter(RUNTIME_KEY, false); } @Override public boolean isForce() { - return url.getParameter(Constants.FORCE_KEY, false); + return url.getParameter(FORCE_KEY, false); } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java index d4d80d3b075..67ab112330f 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.rpc.cluster.router.tag; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.ClusterConstants; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -40,8 +40,8 @@ import java.util.function.Predicate; import java.util.stream.Collectors; +import static org.apache.dubbo.common.constants.ClusterConstants.TAG_KEY; import static org.apache.dubbo.common.constants.RpcConstants.FORCE_USE_TAG; -import static org.apache.dubbo.common.Constants.TAG_KEY; /** * TagRouter, "application.tag-router" @@ -97,8 +97,8 @@ public List> route(List> invokers, URL url, Invocation } List> result = invokers; - String tag = StringUtils.isEmpty(invocation.getAttachment(TAG_KEY)) ? url.getParameter(TAG_KEY) : - invocation.getAttachment(TAG_KEY); + String tag = StringUtils.isEmpty(invocation.getAttachment(ClusterConstants.TAG_KEY)) ? url.getParameter(ClusterConstants.TAG_KEY) : + invocation.getAttachment(ClusterConstants.TAG_KEY); // if we are requesting for a Provider with a specific tag if (StringUtils.isNotEmpty(tag)) { @@ -113,7 +113,7 @@ public List> route(List> invokers, URL url, Invocation } else { // dynamic tag group doesn't have any item about the requested app OR it's null after filtered by // dynamic tag group but force=false. check static tag - result = filterInvoker(invokers, invoker -> tag.equals(invoker.getUrl().getParameter(TAG_KEY))); + result = filterInvoker(invokers, invoker -> tag.equals(invoker.getUrl().getParameter(ClusterConstants.TAG_KEY))); } // If there's no tagged providers that can match the current tagged request. force.tag is set by default // to false, which means it will invoke any providers without a tag unless it's explicitly disallowed. @@ -124,7 +124,7 @@ public List> route(List> invokers, URL url, Invocation else { List> tmp = filterInvoker(invokers, invoker -> addressNotMatches(invoker.getUrl(), tagRouterRuleCopy.getAddresses())); - return filterInvoker(tmp, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(TAG_KEY))); + return filterInvoker(tmp, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(ClusterConstants.TAG_KEY))); } } else { // List addresses = tagRouterRule.filter(providerApp); @@ -140,7 +140,7 @@ public List> route(List> invokers, URL url, Invocation // static tag group. } return filterInvoker(result, invoker -> { - String localTag = invoker.getUrl().getParameter(TAG_KEY); + String localTag = invoker.getUrl().getParameter(ClusterConstants.TAG_KEY); return StringUtils.isEmpty(localTag) || !tagRouterRuleCopy.getTagNames().contains(localTag); }); } @@ -163,16 +163,16 @@ public List> route(List> invokers, URL url, Invocation private List> filterUsingStaticTag(List> invokers, URL url, Invocation invocation) { List> result = invokers; // Dynamic param - String tag = StringUtils.isEmpty(invocation.getAttachment(TAG_KEY)) ? url.getParameter(TAG_KEY) : - invocation.getAttachment(TAG_KEY); + String tag = StringUtils.isEmpty(invocation.getAttachment(ClusterConstants.TAG_KEY)) ? url.getParameter(ClusterConstants.TAG_KEY) : + invocation.getAttachment(ClusterConstants.TAG_KEY); // Tag request if (!StringUtils.isEmpty(tag)) { - result = filterInvoker(invokers, invoker -> tag.equals(invoker.getUrl().getParameter(Constants.TAG_KEY))); + result = filterInvoker(invokers, invoker -> tag.equals(invoker.getUrl().getParameter(TAG_KEY))); if (CollectionUtils.isEmpty(result) && !isForceUseTag(invocation)) { - result = filterInvoker(invokers, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(Constants.TAG_KEY))); + result = filterInvoker(invokers, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(TAG_KEY))); } } else { - result = filterInvoker(invokers, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(Constants.TAG_KEY))); + result = filterInvoker(invokers, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(TAG_KEY))); } return result; } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvoker.java index 257f8af6b89..922f4dc97df 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvoker.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.extension.ExtensionLoader; @@ -40,6 +39,13 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; +import static org.apache.dubbo.common.constants.ClusterConstants.CLUSTER_AVAILABLE_CHECK_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.CLUSTER_STICKY_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_CLUSTER_AVAILABLE_CHECK; +import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_CLUSTER_STICKY; +import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_LOADBALANCE; +import static org.apache.dubbo.common.constants.ClusterConstants.LOADBALANCE_KEY; + /** * AbstractClusterInvoker */ @@ -66,7 +72,7 @@ public AbstractClusterInvoker(Directory directory, URL url) { this.directory = directory; //sticky: invoker.isAvailable() should always be checked before using when availablecheck is true. - this.availablecheck = url.getParameter(Constants.CLUSTER_AVAILABLE_CHECK_KEY, Constants.DEFAULT_CLUSTER_AVAILABLE_CHECK); + this.availablecheck = url.getParameter(CLUSTER_AVAILABLE_CHECK_KEY, DEFAULT_CLUSTER_AVAILABLE_CHECK); } @Override @@ -120,7 +126,7 @@ protected Invoker select(LoadBalance loadbalance, Invocation invocation, String methodName = invocation == null ? StringUtils.EMPTY : invocation.getMethodName(); boolean sticky = invokers.get(0).getUrl() - .getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY); + .getMethodParameter(methodName, CLUSTER_STICKY_KEY, DEFAULT_CLUSTER_STICKY); //ignore overloaded method if (stickyInvoker != null && !invokers.contains(stickyInvoker)) { @@ -288,9 +294,9 @@ protected List> list(Invocation invocation) throws RpcException { protected LoadBalance initLoadBalance(List> invokers, Invocation invocation) { if (CollectionUtils.isNotEmpty(invokers)) { return ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(invokers.get(0).getUrl() - .getMethodParameter(RpcUtils.getMethodName(invocation), Constants.LOADBALANCE_KEY, Constants.DEFAULT_LOADBALANCE)); + .getMethodParameter(RpcUtils.getMethodName(invocation), LOADBALANCE_KEY, DEFAULT_LOADBALANCE)); } else { - return ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(Constants.DEFAULT_LOADBALANCE); + return ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(DEFAULT_LOADBALANCE); } } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java index 13df67a39ce..50d64edc0b8 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.StringUtils; @@ -26,6 +25,7 @@ import java.util.Map; import java.util.Set; +import static org.apache.dubbo.common.constants.ClusterConstants.TAG_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ALIVE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY; @@ -40,10 +40,10 @@ import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.ASYNC_KEY; import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.REFERENCE_FILTER_KEY; import static org.apache.dubbo.common.constants.RpcConstants.INVOKER_LISTENER_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.ASYNC_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.REFERENCE_FILTER_KEY; /** * ClusterUtils @@ -119,7 +119,7 @@ public static URL mergeUrl(URL remoteUrl, Map localMap) { reserveRemoteValue(VERSION_KEY, map, remoteMap); reserveRemoteValue(METHODS_KEY, map, remoteMap); reserveRemoteValue(TIMESTAMP_KEY, map, remoteMap); - reserveRemoteValue(Constants.TAG_KEY, map, remoteMap); + reserveRemoteValue(TAG_KEY, map, remoteMap); // TODO, for compatibility consideration, we cannot simply change the value behind APPLICATION_KEY from Consumer to Provider. So just add an extra key here. // Reserve application name from provider. map.put(REMOTE_APPLICATION_KEY, remoteMap.get(APPLICATION_KEY)); diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvoker.java index dd68d7ef3dd..f4ad2ad25dd 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvoker.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.timer.HashedWheelTimer; @@ -36,6 +35,11 @@ import java.util.List; import java.util.concurrent.TimeUnit; +import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_FAILBACK_TIMES; +import static org.apache.dubbo.common.constants.ClusterConstants.RETRIES_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_FAILBACK_TASKS; +import static org.apache.dubbo.common.constants.ClusterConstants.FAIL_BACK_TASKS_KEY; + /** * When fails, record failure requests and schedule for retry on a regular interval. * Especially useful for services of notification. @@ -57,13 +61,13 @@ public class FailbackClusterInvoker extends AbstractClusterInvoker { public FailbackClusterInvoker(Directory directory) { super(directory); - int retriesConfig = getUrl().getParameter(Constants.RETRIES_KEY, Constants.DEFAULT_FAILBACK_TIMES); + int retriesConfig = getUrl().getParameter(RETRIES_KEY, DEFAULT_FAILBACK_TIMES); if (retriesConfig <= 0) { - retriesConfig = Constants.DEFAULT_FAILBACK_TIMES; + retriesConfig = DEFAULT_FAILBACK_TIMES; } - int failbackTasksConfig = getUrl().getParameter(Constants.FAIL_BACK_TASKS_KEY, Constants.DEFAULT_FAILBACK_TASKS); + int failbackTasksConfig = getUrl().getParameter(FAIL_BACK_TASKS_KEY, DEFAULT_FAILBACK_TASKS); if (failbackTasksConfig <= 0) { - failbackTasksConfig = Constants.DEFAULT_FAILBACK_TASKS; + failbackTasksConfig = DEFAULT_FAILBACK_TASKS; } retries = retriesConfig; failbackTasks = failbackTasksConfig; diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvoker.java index 0ae150f4be3..bb3fecdeb70 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvoker.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -35,6 +34,9 @@ import java.util.List; import java.util.Set; +import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_RETRIES; +import static org.apache.dubbo.common.constants.ClusterConstants.RETRIES_KEY; + /** * When invoke fails, log the initial error and retry other invokers (retry n times, which means at most n different invokers will be invoked) * Note that retry causes latency. @@ -56,7 +58,7 @@ public Result doInvoke(Invocation invocation, final List> invokers, L List> copyInvokers = invokers; checkInvokers(copyInvokers, invocation); String methodName = RpcUtils.getMethodName(invocation); - int len = getUrl().getMethodParameter(methodName, Constants.RETRIES_KEY, Constants.DEFAULT_RETRIES) + 1; + int len = getUrl().getMethodParameter(methodName, RETRIES_KEY, DEFAULT_RETRIES) + 1; if (len <= 0) { len = 1; } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvoker.java index 4f84196f96f..bb44b0bd0f9 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvoker.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.threadlocal.NamedInternalThreadFactory; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -35,6 +34,8 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_FORKS; +import static org.apache.dubbo.common.constants.ClusterConstants.FORKS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; @@ -62,7 +63,7 @@ public Result doInvoke(final Invocation invocation, List> invokers, L try { checkInvokers(invokers, invocation); final List> selected; - final int forks = getUrl().getParameter(Constants.FORKS_KEY, Constants.DEFAULT_FORKS); + final int forks = getUrl().getParameter(FORKS_KEY, DEFAULT_FORKS); final int timeout = getUrl().getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT); if (forks <= 0 || forks >= invokers.size()) { selected = invokers; diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java index b78d2c76ce7..d2db9192533 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.support.wrapper; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -31,10 +30,11 @@ import org.apache.dubbo.rpc.cluster.Directory; import org.apache.dubbo.rpc.support.MockInvoker; -import static org.apache.dubbo.common.constants.RpcConstants.MOCK_KEY; - import java.util.List; +import static org.apache.dubbo.common.constants.ClusterConstants.INVOCATION_NEED_MOCK; +import static org.apache.dubbo.common.constants.RpcConstants.MOCK_KEY; + public class MockClusterInvoker implements Invoker { private static final Logger logger = LoggerFactory.getLogger(MockClusterInvoker.class); @@ -147,7 +147,7 @@ private List> selectMockInvoker(Invocation invocation) { //TODO generic invoker? if (invocation instanceof RpcInvocation) { //Note the implicit contract (although the description is added to the interface declaration, but extensibility is a problem. The practice placed in the attachment needs to be improved) - ((RpcInvocation) invocation).setAttachment(Constants.INVOCATION_NEED_MOCK, Boolean.TRUE.toString()); + ((RpcInvocation) invocation).setAttachment(INVOCATION_NEED_MOCK, Boolean.TRUE.toString()); //directory will return a list of normal invokers if Constants.INVOCATION_NEED_MOCK is present in invocation, otherwise, a list of mock invokers will return. try { invokers = directory.list(invocation); diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/StickyTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/StickyTest.java index b10fa01c802..6b093b97d59 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/StickyTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/StickyTest.java @@ -17,7 +17,6 @@ package org.apache.dubbo.rpc.cluster; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.rpc.Invocation; @@ -35,6 +34,7 @@ import java.util.ArrayList; import java.util.List; +import static org.apache.dubbo.common.constants.ClusterConstants.CLUSTER_STICKY_KEY; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -52,7 +52,7 @@ public class StickyTest { private StickyClusterInvoker clusterinvoker = null; private URL url = URL.valueOf("test://test:11/test?" + "&loadbalance=roundrobin" - + "&" + Constants.CLUSTER_STICKY_KEY + "=true" + + "&" + CLUSTER_STICKY_KEY + "=true" ); private int runs = 1; @@ -110,9 +110,9 @@ public void testMethodsSticky() { public int testSticky(String methodName, boolean check) { if (methodName == null) { - url = url.addParameter(Constants.CLUSTER_STICKY_KEY, String.valueOf(check)); + url = url.addParameter(CLUSTER_STICKY_KEY, String.valueOf(check)); } else { - url = url.addParameter(methodName + "." + Constants.CLUSTER_STICKY_KEY, String.valueOf(check)); + url = url.addParameter(methodName + "." + CLUSTER_STICKY_KEY, String.valueOf(check)); } given(invoker1.invoke(invocation)).willReturn(result); @@ -161,4 +161,4 @@ public Invoker getSelectedInvoker() { return selectedInvoker; } } -} \ No newline at end of file +} diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParserTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParserTest.java index e066f1cedee..9f4eb1b69a0 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParserTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParserTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.configurator.parser; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.cluster.configurator.parser.model.ConfigItem; import org.apache.dubbo.rpc.cluster.configurator.parser.model.ConfiguratorConfig; @@ -31,6 +30,9 @@ import java.io.InputStream; import java.util.List; +import static org.apache.dubbo.common.constants.ClusterConstants.LOADBALANCE_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.OVERRIDE_PROVIDERS_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.WEIGHT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; @@ -70,7 +72,7 @@ public void parseConfiguratorsServiceNoAppTest() throws Exception { Assertions.assertEquals(2, urls.size()); URL url = urls.get(0); Assertions.assertEquals(url.getAddress(), "127.0.0.1:20880"); - Assertions.assertEquals(url.getParameter(Constants.WEIGHT_KEY, 0), 222); + Assertions.assertEquals(url.getParameter(WEIGHT_KEY, 0), 222); } } @@ -120,7 +122,7 @@ public void parseConfiguratorsAppMultiServicesTest() throws IOException { Assertions.assertEquals("127.0.0.1", url.getAddress()); Assertions.assertEquals("service1", url.getServiceInterface()); Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); - Assertions.assertEquals("random", url.getParameter(Constants.LOADBALANCE_KEY)); + Assertions.assertEquals("random", url.getParameter(LOADBALANCE_KEY)); Assertions.assertEquals(url.getParameter(APPLICATION_KEY), "demo-consumer"); } } @@ -136,7 +138,7 @@ public void parseConfiguratorsAppAnyServicesTest() throws IOException { Assertions.assertEquals("127.0.0.1", url.getAddress()); Assertions.assertEquals("*", url.getServiceInterface()); Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); - Assertions.assertEquals("random", url.getParameter(Constants.LOADBALANCE_KEY)); + Assertions.assertEquals("random", url.getParameter(LOADBALANCE_KEY)); Assertions.assertEquals(url.getParameter(APPLICATION_KEY), "demo-consumer"); } } @@ -151,7 +153,7 @@ public void parseConfiguratorsAppNoServiceTest() throws IOException { Assertions.assertEquals("127.0.0.1", url.getAddress()); Assertions.assertEquals("*", url.getServiceInterface()); Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); - Assertions.assertEquals("random", url.getParameter(Constants.LOADBALANCE_KEY)); + Assertions.assertEquals("random", url.getParameter(LOADBALANCE_KEY)); Assertions.assertEquals(url.getParameter(APPLICATION_KEY), "demo-consumer"); } } @@ -166,8 +168,8 @@ public void parseConsumerSpecificProvidersTest() throws IOException { Assertions.assertEquals("127.0.0.1", url.getAddress()); Assertions.assertEquals("*", url.getServiceInterface()); Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); - Assertions.assertEquals("random", url.getParameter(Constants.LOADBALANCE_KEY)); - Assertions.assertEquals("127.0.0.1:20880", url.getParameter(Constants.OVERRIDE_PROVIDERS_KEY)); + Assertions.assertEquals("random", url.getParameter(LOADBALANCE_KEY)); + Assertions.assertEquals("127.0.0.1:20880", url.getParameter(OVERRIDE_PROVIDERS_KEY)); Assertions.assertEquals(url.getParameter(APPLICATION_KEY), "demo-consumer"); } } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java index 706f1416b5b..03e611ec1eb 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.directory; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.Invoker; @@ -31,6 +30,8 @@ import java.util.ArrayList; import java.util.List; +import static org.apache.dubbo.common.constants.ClusterConstants.RULE_KEY; + /** * StaticDirectory Test */ @@ -38,7 +39,7 @@ public class StaticDirectoryTest { private URL SCRIPT_URL = URL.valueOf("condition://0.0.0.0/com.foo.BarService"); private URL getRouteUrl(String rule) { - return SCRIPT_URL.addParameterAndEncoded(Constants.RULE_KEY, rule); + return SCRIPT_URL.addParameterAndEncoded(RULE_KEY, rule); } @Test diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LoadBalanceBaseTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LoadBalanceBaseTest.java index ec43e3871b7..47419fdd8de 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LoadBalanceBaseTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LoadBalanceBaseTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.loadbalance; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.rpc.Invocation; @@ -24,12 +23,12 @@ import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.RpcStatus; import org.apache.dubbo.rpc.cluster.LoadBalance; + +import com.alibaba.fastjson.JSON; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; - -import com.alibaba.fastjson.JSON; import org.mockito.Mockito; import java.util.ArrayList; @@ -38,6 +37,8 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; +import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_WARMUP; +import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_WEIGHT; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -129,7 +130,7 @@ public Map getInvokeCounter(int runs, String loadbalanceNam } return counter; } - + protected AbstractLoadBalance getLoadBalance(String loadbalanceName) { return (AbstractLoadBalance) ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(loadbalanceName); } @@ -158,11 +159,11 @@ public void testLoadBalanceWarmup() { * @return */ private static int calculateDefaultWarmupWeight(int uptime) { - return AbstractLoadBalance.calculateWarmupWeight(uptime, Constants.DEFAULT_WARMUP, Constants.DEFAULT_WEIGHT); + return AbstractLoadBalance.calculateWarmupWeight(uptime, DEFAULT_WARMUP, DEFAULT_WEIGHT); } /*------------------------------------test invokers for weight---------------------------------------*/ - + protected static class InvokeResult { private AtomicLong count = new AtomicLong(); private int weight = 0; @@ -175,28 +176,28 @@ public InvokeResult(int weight) { public AtomicLong getCount() { return count; } - + public int getWeight() { return weight; } - + public int getTotalWeight() { return totalWeight; } - + public void setTotalWeight(int totalWeight) { this.totalWeight = totalWeight; } - + public int getExpected(int runCount) { return getWeight() * runCount / getTotalWeight(); } - + public float getDeltaPercentage(int runCount) { int expected = getExpected(runCount); return Math.abs((expected - getCount().get()) * 100.0f / expected); } - + @Override public String toString() { return JSON.toJSONString(this); @@ -227,15 +228,15 @@ public void before() throws Exception { given(weightInvoker1.isAvailable()).willReturn(true); given(weightInvoker1.getInterface()).willReturn(LoadBalanceBaseTest.class); given(weightInvoker1.getUrl()).willReturn(url1); - + given(weightInvoker2.isAvailable()).willReturn(true); given(weightInvoker2.getInterface()).willReturn(LoadBalanceBaseTest.class); given(weightInvoker2.getUrl()).willReturn(url2); - + given(weightInvoker3.isAvailable()).willReturn(true); given(weightInvoker3.getInterface()).willReturn(LoadBalanceBaseTest.class); given(weightInvoker3.getUrl()).willReturn(url3); - + given(weightInvokerTmp.isAvailable()).willReturn(true); given(weightInvokerTmp.getInterface()).willReturn(LoadBalanceBaseTest.class); given(weightInvokerTmp.getUrl()).willReturn(urlTmp); @@ -251,7 +252,7 @@ public void before() throws Exception { // weightTestRpcStatus3 active is 1 RpcStatus.beginCount(weightInvoker3.getUrl(), weightTestInvocation.getMethodName()); } - + protected Map getWeightedInvokeResult(int runs, String loadbalanceName) { Map counter = new ConcurrentHashMap(); AbstractLoadBalance lb = getLoadBalance(loadbalanceName); @@ -271,5 +272,5 @@ protected Map getWeightedInvokeResult(int runs, String lo } return counter; } - -} \ No newline at end of file + +} diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java index a10949d3016..eb3d28db75c 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java @@ -17,7 +17,6 @@ package org.apache.dubbo.rpc.cluster.router.condition; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.Invocation; @@ -34,6 +33,9 @@ import java.util.ArrayList; import java.util.List; +import static org.apache.dubbo.common.constants.ClusterConstants.FORCE_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.RULE_KEY; + public class ConditionRouterTest { private URL SCRIPT_URL = URL.valueOf("condition://0.0.0.0/com.foo.BarService"); @@ -47,7 +49,7 @@ public void setUp() throws Exception { } private URL getRouteUrl(String rule) { - return SCRIPT_URL.addParameterAndEncoded(Constants.RULE_KEY, rule); + return SCRIPT_URL.addParameterAndEncoded(RULE_KEY, rule); } @Test @@ -97,23 +99,23 @@ public void testRoute_matchFilter() { invokers.add(invoker3); Router router1 = new ConditionRouterFactory().getRouter(getRouteUrl( - "host = " + NetUtils.getLocalHost() + " => " + " host = 10.20.3.3").addParameter(Constants.FORCE_KEY, + "host = " + NetUtils.getLocalHost() + " => " + " host = 10.20.3.3").addParameter(FORCE_KEY, String.valueOf(true))); Router router2 = new ConditionRouterFactory().getRouter(getRouteUrl( "host = " + NetUtils.getLocalHost() + " => " + " host = 10.20.3.* & host != 10.20.3.3").addParameter( - Constants.FORCE_KEY, String.valueOf(true))); + FORCE_KEY, String.valueOf(true))); Router router3 = new ConditionRouterFactory().getRouter(getRouteUrl( "host = " + NetUtils.getLocalHost() + " => " + " host = 10.20.3.3 & host != 10.20.3.3").addParameter( - Constants.FORCE_KEY, String.valueOf(true))); + FORCE_KEY, String.valueOf(true))); Router router4 = new ConditionRouterFactory().getRouter(getRouteUrl( "host = " + NetUtils.getLocalHost() + " => " + " host = 10.20.3.2,10.20.3.3,10.20.3.4").addParameter( - Constants.FORCE_KEY, String.valueOf(true))); + FORCE_KEY, String.valueOf(true))); Router router5 = new ConditionRouterFactory().getRouter(getRouteUrl( - "host = " + NetUtils.getLocalHost() + " => " + " host != 10.20.3.3").addParameter(Constants.FORCE_KEY, + "host = " + NetUtils.getLocalHost() + " => " + " host != 10.20.3.3").addParameter(FORCE_KEY, String.valueOf(true))); Router router6 = new ConditionRouterFactory().getRouter(getRouteUrl( "host = " + NetUtils.getLocalHost() + " => " + " serialization = fastjson").addParameter( - Constants.FORCE_KEY, String.valueOf(true))); + FORCE_KEY, String.valueOf(true))); List> filteredInvokers1 = router1.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation()); List> filteredInvokers2 = router2.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation()); @@ -166,14 +168,14 @@ public void testRoute_methodRoute() { Router router4 = new ConditionRouterFactory().getRouter(getRouteUrl( "host = " + NetUtils.getLocalHost() + " & methods = getFoo => " + " host = 10.20.3.3").addParameter( - Constants.FORCE_KEY, String.valueOf(true))); + FORCE_KEY, String.valueOf(true))); List> filteredInvokers1 = router4.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), invocation); Assertions.assertEquals(1, filteredInvokers1.size()); Router router5 = new ConditionRouterFactory().getRouter(getRouteUrl( "host = " + NetUtils.getLocalHost() + " & methods = unvalidmethod => " + " host = 10.20.3.3") - .addParameter(Constants.FORCE_KEY, String.valueOf(true))); + .addParameter(FORCE_KEY, String.valueOf(true))); List> filteredInvokers2 = router5.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), invocation); Assertions.assertEquals(3, filteredInvokers2.size()); @@ -293,7 +295,7 @@ public void testRoute_NoForce() { @Test public void testRoute_Force() { - Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + NetUtils.getLocalHost() + " => " + " host = 1.2.3.4").addParameter(Constants.FORCE_KEY, String.valueOf(true))); + Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + NetUtils.getLocalHost() + " => " + " host = 1.2.3.4").addParameter(FORCE_KEY, String.valueOf(true))); List> invokers = new ArrayList>(); Invoker invoker1 = new MockInvoker(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService")); Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService")); @@ -305,4 +307,4 @@ public void testRoute_Force() { Assertions.assertEquals(0, filteredInvokers.size()); } -} \ No newline at end of file +} diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java index c4cb85daf8b..ef7c37b2edc 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.router.file; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.rpc.Invocation; @@ -41,6 +40,7 @@ import java.util.Arrays; import java.util.List; +import static org.apache.dubbo.common.constants.ClusterConstants.RUNTIME_KEY; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -133,7 +133,7 @@ public void testRouteByMethodName() { private URL initUrl(String filename) { filename = getClass().getClassLoader().getResource(getClass().getPackage().getName().replace('.', '/') + "/" + filename).toString(); URL url = URL.valueOf(filename); - url = url.addParameter(Constants.RUNTIME_KEY, true); + url = url.addParameter(RUNTIME_KEY, true); return url; } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouterTest.java index 45e4e7fb9e4..29b29d1a7d3 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouterTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouterTest.java @@ -17,7 +17,6 @@ package org.apache.dubbo.rpc.cluster.router.script; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; @@ -32,6 +31,8 @@ import java.util.ArrayList; import java.util.List; +import static org.apache.dubbo.common.constants.ClusterConstants.RULE_KEY; + public class ScriptRouterTest { private URL SCRIPT_URL = URL.valueOf("script://javascript?type=javascript"); @@ -45,7 +46,7 @@ public void setUp() throws Exception { } private URL getRouteUrl(String rule) { - return SCRIPT_URL.addParameterAndEncoded(Constants.RULE_KEY, rule); + return SCRIPT_URL.addParameterAndEncoded(RULE_KEY, rule); } @Test @@ -128,4 +129,4 @@ public void testRoute_throwException() { List> routeResult = router.route(invokers, invokers.get(0).getUrl(), new RpcInvocation()); Assertions.assertEquals(3, routeResult.size()); } -} \ No newline at end of file +} diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java index 130cdb5dd81..6dcda9fe2fd 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java @@ -37,8 +37,8 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -48,6 +48,9 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; +import static org.apache.dubbo.common.constants.ClusterConstants.CLUSTER_AVAILABLE_CHECK_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.INVOCATION_NEED_MOCK; +import static org.apache.dubbo.common.constants.MonitorConstants.MONITOR_KEY; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -129,7 +132,7 @@ protected Result doInvoke(Invocation invocation, List invokers, LoadBalance load } }; - cluster_nocheck = new AbstractClusterInvoker(dic, url.addParameterIfAbsent(Constants.CLUSTER_AVAILABLE_CHECK_KEY, Boolean.FALSE.toString())) { + cluster_nocheck = new AbstractClusterInvoker(dic, url.addParameterIfAbsent(CLUSTER_AVAILABLE_CHECK_KEY, Boolean.FALSE.toString())) { @Override protected Result doInvoke(Invocation invocation, List invokers, LoadBalance loadbalance) throws RpcException { @@ -223,7 +226,7 @@ public void testSelect_multiInvokers() throws Exception { public void testCloseAvailablecheck() { LoadBalance lb = mock(LoadBalance.class); Map queryMap = StringUtils.parseQueryString(url.getParameterAndDecoded(Constants.REFER_KEY)); - URL tmpUrl = url.addParameters(queryMap).removeParameter(Constants.MONITOR_KEY); + URL tmpUrl = url.addParameters(queryMap).removeParameter(MONITOR_KEY); given(lb.select(invokers, tmpUrl, invocation)).willReturn(invoker1); initlistsize5(); @@ -523,7 +526,7 @@ public void testMockedInvokerSelect() { RpcInvocation mockedInvocation = new RpcInvocation(); mockedInvocation.setMethodName("sayHello"); - mockedInvocation.setAttachment(Constants.INVOCATION_NEED_MOCK, "true"); + mockedInvocation.setAttachment(INVOCATION_NEED_MOCK, "true"); List> mockedInvokers = dic.list(mockedInvocation); Assertions.assertEquals(1, mockedInvokers.size()); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java index 1efe9421dae..2c405c399af 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java @@ -180,114 +180,6 @@ public class Constants { public static final String ACCEPT_FOREIGN_IP = "qos.accept.foreign.ip"; // END dubbo-congfig-api - // BEGIN dubbo-cluster - /** - * key for router type, for e.g., "script"/"file", corresponding to ScriptRouterFactory.NAME, FileRouterFactory.NAME - */ - public static final String ROUTER_KEY = "router"; - - public static final String LOADBALANCE_KEY = "loadbalance"; - - public static final String DEFAULT_LOADBALANCE = "random"; - - public static final String FAIL_BACK_TASKS_KEY = "failbacktasks"; - - public static final int DEFAULT_FAILBACK_TASKS = 100; - - public static final String RETRIES_KEY = "retries"; - - public static final int DEFAULT_RETRIES = 2; - - public static final int DEFAULT_FAILBACK_TIMES = 3; - - public static final String FORKS_KEY = "forks"; - - public static final int DEFAULT_FORKS = 2; - - public static final String WEIGHT_KEY = "weight"; - - public static final int DEFAULT_WEIGHT = 100; - - public static final String MOCK_PROTOCOL = "mock"; - - public static final String FORCE_KEY = "force"; - - /** - * To decide whether to exclude unavailable invoker from the cluster - */ - public static final String CLUSTER_AVAILABLE_CHECK_KEY = "cluster.availablecheck"; - - /** - * The default value of cluster.availablecheck - * - * @see #CLUSTER_AVAILABLE_CHECK_KEY - */ - public static final boolean DEFAULT_CLUSTER_AVAILABLE_CHECK = true; - - /** - * To decide whether to enable sticky strategy for cluster - */ - public static final String CLUSTER_STICKY_KEY = "sticky"; - - /** - * The default value of sticky - * - * @see #CLUSTER_STICKY_KEY - */ - public static final boolean DEFAULT_CLUSTER_STICKY = false; - - public static final String ADDRESS_KEY = "address"; - - /** - * When this attribute appears in invocation's attachment, mock invoker will be used - */ - public static final String INVOCATION_NEED_MOCK = "invocation.need.mock"; - - /** - * when ROUTER_KEY's value is set to ROUTER_TYPE_CLEAR, RegistryDirectory will clean all current routers - */ - public static final String ROUTER_TYPE_CLEAR = "clean"; - - public static final String DEFAULT_SCRIPT_TYPE_KEY = "javascript"; - - public static final String PRIORITY_KEY = "priority"; - - public static final String RULE_KEY = "rule"; - - public static final String TYPE_KEY = "type"; - - public static final String RUNTIME_KEY = "runtime"; - - public static final String TAG_KEY = "dubbo.tag"; - - public static final String REMOTE_TIMESTAMP_KEY = "remote.timestamp"; - - public static final String WARMUP_KEY = "warmup"; - - public static final int DEFAULT_WARMUP = 10 * 60 * 1000; - - public static final String CONFIG_VERSION_KEY = "configVersion"; - - public static final String OVERRIDE_PROVIDERS_KEY = "providerAddresses"; - // END dubbo-cluster - - - // BEGIN dubbo-monitor-api - public static final String MONITOR_KEY = "monitor"; - public static final String LOGSTAT_PROTOCOL = "logstat"; - public static final String COUNT_PROTOCOL = "count"; - public static final String DUBBO_PROVIDER = "dubbo.provider"; - public static final String DUBBO_CONSUMER = "dubbo.consumer"; - public static final String DUBBO_PROVIDER_METHOD = "dubbo.provider.method"; - public static final String DUBBO_CONSUMER_METHOD = "dubbo.consumer.method"; - public static final String SERVICE = "service"; - public static final String METHOD = "method"; - public static final String DUBBO_GROUP = "dubbo"; - public static final String METRICS_KEY = "metrics"; - public static final String METRICS_PORT = "metrics.port"; - public static final String METRICS_PROTOCOL = "metrics.protocol"; - // END dubbo-monitor-api - // BEGIN dubbo-metadata-report-api public static final String METADATA_REPORT_KEY = "metadata"; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java index 42063bd1e69..6f8454afef7 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java @@ -54,6 +54,7 @@ import java.util.Set; import static org.apache.dubbo.common.config.ConfigurationUtils.parseProperties; +import static org.apache.dubbo.common.constants.ClusterConstants.TAG_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; @@ -64,17 +65,18 @@ import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; +import static org.apache.dubbo.common.constants.MonitorConstants.LOGSTAT_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.SUBSCRIBE_KEY; import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.INVOKER_LISTENER_KEY; import static org.apache.dubbo.common.constants.RpcConstants.LOCAL_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.RETURN_PREFIX; -import static org.apache.dubbo.common.constants.RpcConstants.THROW_PREFIX; import static org.apache.dubbo.common.constants.RpcConstants.PROXY_KEY; import static org.apache.dubbo.common.constants.RpcConstants.REFERENCE_FILTER_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.INVOKER_LISTENER_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.RETURN_PREFIX; +import static org.apache.dubbo.common.constants.RpcConstants.THROW_PREFIX; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; /** @@ -378,8 +380,8 @@ protected URL loadMonitor(URL registryURL) { } if (ConfigUtils.isNotEmpty(address)) { if (!map.containsKey(PROTOCOL_KEY)) { - if (getExtensionLoader(MonitorFactory.class).hasExtension(Constants.LOGSTAT_PROTOCOL)) { - map.put(PROTOCOL_KEY, Constants.LOGSTAT_PROTOCOL); + if (getExtensionLoader(MonitorFactory.class).hasExtension(LOGSTAT_PROTOCOL)) { + map.put(PROTOCOL_KEY, LOGSTAT_PROTOCOL); } else { map.put(PROTOCOL_KEY, Constants.DUBBO_PROTOCOL); } @@ -864,7 +866,7 @@ public void setMetrics(MetricsConfig metrics) { this.metrics = metrics; } - @Parameter(key = Constants.TAG_KEY, useKeyAsProperty = false) + @Parameter(key = TAG_KEY, useKeyAsProperty = false) public String getTag() { return tag; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractMethodConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractMethodConfig.java index a36d8568de2..d6d0086c5dd 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractMethodConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractMethodConfig.java @@ -16,17 +16,17 @@ */ package org.apache.dubbo.config; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.config.support.Parameter; import org.apache.dubbo.rpc.cluster.LoadBalance; import java.util.Map; +import static org.apache.dubbo.common.constants.ClusterConstants.LOADBALANCE_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.FAIL_PREFIX; +import static org.apache.dubbo.common.constants.RpcConstants.FORCE_PREFIX; import static org.apache.dubbo.common.constants.RpcConstants.MOCK_KEY; import static org.apache.dubbo.common.constants.RpcConstants.RETURN_PREFIX; import static org.apache.dubbo.common.constants.RpcConstants.THROW_PREFIX; -import static org.apache.dubbo.common.constants.RpcConstants.FAIL_PREFIX; -import static org.apache.dubbo.common.constants.RpcConstants.FORCE_PREFIX; /** * AbstractMethodConfig @@ -132,7 +132,7 @@ public String getLoadbalance() { } public void setLoadbalance(String loadbalance) { - checkExtension(LoadBalance.class, Constants.LOADBALANCE_KEY, loadbalance); + checkExtension(LoadBalance.class, LOADBALANCE_KEY, loadbalance); this.loadbalance = loadbalance; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java index 2062a0094e2..3ff25fe21ef 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java @@ -22,11 +22,12 @@ import org.apache.dubbo.rpc.InvokerListener; import org.apache.dubbo.rpc.support.ProtocolUtils; +import static org.apache.dubbo.common.constants.ClusterConstants.CLUSTER_STICKY_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.STUB_EVENT_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.REFERENCE_FILTER_KEY; import static org.apache.dubbo.common.constants.RpcConstants.INVOKER_LISTENER_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.REFERENCE_FILTER_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.STUB_EVENT_KEY; /** * AbstractConsumerConfig @@ -195,7 +196,7 @@ public void setReconnect(String reconnect) { this.reconnect = reconnect; } - @Parameter(key = Constants.CLUSTER_STICKY_KEY) + @Parameter(key = CLUSTER_STICKY_KEY) public Boolean getSticky() { return sticky; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MetricsConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MetricsConfig.java index 907d88e0664..15d44aa7fde 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MetricsConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MetricsConfig.java @@ -17,9 +17,11 @@ package org.apache.dubbo.config; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.config.support.Parameter; +import static org.apache.dubbo.common.constants.MonitorConstants.METRICS_PORT; +import static org.apache.dubbo.common.constants.MonitorConstants.METRICS_PROTOCOL; + public class MetricsConfig extends AbstractConfig { private static final long serialVersionUID = -9089919311611546383L; @@ -30,7 +32,7 @@ public class MetricsConfig extends AbstractConfig { public MetricsConfig() { } - @Parameter(key = Constants.METRICS_PORT) + @Parameter(key = METRICS_PORT) public String getPort() { return port; } @@ -39,7 +41,7 @@ public void setPort(String port) { this.port = port; } - @Parameter(key = Constants.METRICS_PROTOCOL) + @Parameter(key = METRICS_PROTOCOL) public String getProtocol() { return protocol; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java index 7ab502cc99b..2a0080124f6 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java @@ -66,6 +66,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SEMICOLON_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; +import static org.apache.dubbo.common.constants.MonitorConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; import static org.apache.dubbo.common.constants.RpcConstants.LOCAL_PROTOCOL; @@ -376,7 +377,7 @@ private T createProxy(Map map) { for (URL u : us) { URL monitorUrl = loadMonitor(u); if (monitorUrl != null) { - map.put(Constants.MONITOR_KEY, URL.encode(monitorUrl.toFullString())); + map.put(MONITOR_KEY, URL.encode(monitorUrl.toFullString())); } urls.add(u.addParameterAndEncoded(Constants.REFER_KEY, StringUtils.toQueryString(map))); } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index 54a3a403d35..415b7e966e3 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -72,11 +72,12 @@ import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.PROXY_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; +import static org.apache.dubbo.common.constants.MonitorConstants.MONITOR_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; import static org.apache.dubbo.common.constants.RpcConstants.LOCAL_PROTOCOL; -import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.PROXY_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; import static org.apache.dubbo.common.utils.NetUtils.getAvailablePort; import static org.apache.dubbo.common.utils.NetUtils.getLocalHost; import static org.apache.dubbo.common.utils.NetUtils.isInvalidLocalHost; @@ -578,7 +579,7 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r url = url.addParameterIfAbsent(DYNAMIC_KEY, registryURL.getParameter(DYNAMIC_KEY)); URL monitorUrl = loadMonitor(registryURL); if (monitorUrl != null) { - url = url.addParameterAndEncoded(Constants.MONITOR_KEY, monitorUrl.toFullString()); + url = url.addParameterAndEncoded(MONITOR_KEY, monitorUrl.toFullString()); } if (logger.isInfoEnabled()) { logger.info("Register dubbo service " + interfaceClass.getName() + " url " + url + " to registry " + registryURL); diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java index a849d153ea2..9ad68c1d73c 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java @@ -16,8 +16,9 @@ */ package org.apache.dubbo.config.annotation; -import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.ClusterConstants; import org.apache.dubbo.common.constants.RemotingConstants; +import org.apache.dubbo.common.constants.RpcConstants; import org.apache.dubbo.rpc.ExporterListener; import org.apache.dubbo.rpc.Filter; @@ -27,8 +28,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import org.apache.dubbo.common.constants.RpcConstants; - /** * Reference * @@ -111,7 +110,7 @@ /** * Whether to stick to the same node in the cluster, the default value is false * - * @see Constants#DEFAULT_CLUSTER_STICKY + * @see ClusterConstants#DEFAULT_CLUSTER_STICKY */ boolean sticky() default false; @@ -165,14 +164,14 @@ /** * Service invocation retry times * - * @see Constants#DEFAULT_RETRIES + * @see ClusterConstants#DEFAULT_RETRIES */ int retries() default 2; /** * Load balance strategy, legal values include: random, roundrobin, leastactive * - * @see Constants#DEFAULT_LOADBALANCE + * @see ClusterConstants#DEFAULT_LOADBALANCE */ String loadbalance() default ""; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Service.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Service.java index dfb14e77001..560547102b5 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Service.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Service.java @@ -16,7 +16,8 @@ */ package org.apache.dubbo.config.annotation; -import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.ClusterConstants; +import org.apache.dubbo.common.constants.RpcConstants; import org.apache.dubbo.rpc.ExporterListener; import org.apache.dubbo.rpc.Filter; @@ -27,7 +28,8 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import org.apache.dubbo.common.constants.RpcConstants; +import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_LOADBALANCE; +import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_RETRIES; /** * Service annotation @@ -171,16 +173,16 @@ /** * Service invocation retry times * - * @see Constants#DEFAULT_RETRIES + * @see ClusterConstants#DEFAULT_RETRIES */ - int retries() default Constants.DEFAULT_RETRIES; + int retries() default DEFAULT_RETRIES; /** * Load balance strategy, legal values include: random, roundrobin, leastactive * - * @see Constants#DEFAULT_LOADBALANCE + * @see ClusterConstants#DEFAULT_LOADBALANCE */ - String loadbalance() default Constants.DEFAULT_LOADBALANCE; + String loadbalance() default DEFAULT_LOADBALANCE; /** * Whether to enable async invocation, default value is false diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java index 6ba9ed7997f..63683895160 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java @@ -17,23 +17,22 @@ package org.apache.dubbo.config; -import org.apache.dubbo.common.Constants; - import org.apache.dubbo.common.constants.RemotingConstants; + import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; +import static org.apache.dubbo.common.constants.ClusterConstants.CLUSTER_STICKY_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.INVOKER_LISTENER_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.REFERENCE_FILTER_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.STUB_EVENT_KEY; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.hasValue; import static org.hamcrest.Matchers.is; -import static org.hamcrest.MatcherAssert.assertThat; - -import static org.apache.dubbo.common.constants.RpcConstants.STUB_EVENT_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.REFERENCE_FILTER_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.INVOKER_LISTENER_KEY; public class AbstractReferenceConfigTest { @@ -140,7 +139,7 @@ public void testSticky() throws Exception { Map parameters = new HashMap(); AbstractInterfaceConfig.appendParameters(parameters, referenceConfig); assertThat(referenceConfig.getSticky(), is(true)); - assertThat(parameters, hasKey(Constants.CLUSTER_STICKY_KEY)); + assertThat(parameters, hasKey(CLUSTER_STICKY_KEY)); } @Test diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java index d239f45227c..fca996e0f2a 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java @@ -28,6 +28,7 @@ import java.io.IOException; import java.net.ServerSocket; +import static org.apache.dubbo.common.constants.ClusterConstants.CLUSTER_STICKY_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_INSTANCES_LIMIT_KEY; @@ -58,7 +59,7 @@ public static Exporter export(int port, RegistryService registr new URLBuilder(Constants.DUBBO_PROTOCOL, NetUtils.getLocalHost(), port, RegistryService.class.getName()) .setPath(RegistryService.class.getName()) .addParameter(INTERFACE_KEY, RegistryService.class.getName()) - .addParameter(Constants.CLUSTER_STICKY_KEY, "true") + .addParameter(CLUSTER_STICKY_KEY, "true") .addParameter(CALLBACK_INSTANCES_LIMIT_KEY, "1000") .addParameter("ondisconnect", "disconnect") .addParameter("subscribe.1.callback", "true") diff --git a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java index ff7ee989f67..772676822fd 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java +++ b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.monitor.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.Logger; @@ -45,6 +44,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.MonitorConstants.COUNT_PROTOCOL; +import static org.apache.dubbo.common.constants.MonitorConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RpcConstants.INPUT_KEY; import static org.apache.dubbo.common.constants.RpcConstants.OUTPUT_KEY; /** @@ -79,7 +80,7 @@ public void setMonitorFactory(MonitorFactory monitorFactory) { */ @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { - if (invoker.getUrl().hasParameter(Constants.MONITOR_KEY)) { + if (invoker.getUrl().hasParameter(MONITOR_KEY)) { RpcContext context = RpcContext.getContext(); // provider must fetch context before invoke() gets called String remoteHost = context.getRemoteHost(); long start = System.currentTimeMillis(); // record start timestamp @@ -111,7 +112,7 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept */ private void collect(Invoker invoker, Invocation invocation, Result result, String remoteHost, long start, boolean error) { try { - URL monitorUrl = invoker.getUrl().getUrlParameter(Constants.MONITOR_KEY); + URL monitorUrl = invoker.getUrl().getUrlParameter(MONITOR_KEY); Monitor monitor = monitorFactory.getMonitor(monitorUrl); if (monitor == null) { return; @@ -165,7 +166,7 @@ private URL createStatisticsUrl(Invoker invoker, Invocation invocation, Resul output = result.getAttachment(OUTPUT_KEY); } - return new URL(Constants.COUNT_PROTOCOL, + return new URL(COUNT_PROTOCOL, NetUtils.getLocalHost(), localPort, service + PATH_SEPARATOR + method, MonitorService.APPLICATION, application, diff --git a/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java b/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java index 171d087bcec..b9db97ee9c7 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java +++ b/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.monitor.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.monitor.Monitor; @@ -41,6 +40,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; +import static org.apache.dubbo.common.constants.MonitorConstants.MONITOR_KEY; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -64,7 +64,7 @@ public Class getInterface() { public URL getUrl() { try { - return URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880?" + APPLICATION_KEY + "=abc&" + SIDE_KEY + "=" + CONSUMER_SIDE + "&" + Constants.MONITOR_KEY + "=" + URLEncoder.encode("dubbo://" + NetUtils.getLocalHost() + ":7070", "UTF-8")); + return URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880?" + APPLICATION_KEY + "=abc&" + SIDE_KEY + "=" + CONSUMER_SIDE + "&" + MONITOR_KEY + "=" + URLEncoder.encode("dubbo://" + NetUtils.getLocalHost() + ":7070", "UTF-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e.getMessage(), e); } diff --git a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java index 78d87e183c7..fe1df3abbb2 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java +++ b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.monitor.dubbo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; @@ -58,6 +57,15 @@ import java.util.concurrent.atomic.AtomicBoolean; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_PROTOCOL; +import static org.apache.dubbo.common.constants.MonitorConstants.DUBBO_CONSUMER; +import static org.apache.dubbo.common.constants.MonitorConstants.DUBBO_CONSUMER_METHOD; +import static org.apache.dubbo.common.constants.MonitorConstants.DUBBO_GROUP; +import static org.apache.dubbo.common.constants.MonitorConstants.DUBBO_PROVIDER; +import static org.apache.dubbo.common.constants.MonitorConstants.DUBBO_PROVIDER_METHOD; +import static org.apache.dubbo.common.constants.MonitorConstants.METHOD; +import static org.apache.dubbo.common.constants.MonitorConstants.METRICS_PORT; +import static org.apache.dubbo.common.constants.MonitorConstants.METRICS_PROTOCOL; +import static org.apache.dubbo.common.constants.MonitorConstants.SERVICE; public class MetricsFilter implements Filter { @@ -69,13 +77,13 @@ public class MetricsFilter implements Filter { @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { if (exported.compareAndSet(false, true)) { - this.protocolName = invoker.getUrl().getParameter(Constants.METRICS_PROTOCOL) == null ? - DEFAULT_PROTOCOL : invoker.getUrl().getParameter(Constants.METRICS_PROTOCOL); + this.protocolName = invoker.getUrl().getParameter(METRICS_PROTOCOL) == null ? + DEFAULT_PROTOCOL : invoker.getUrl().getParameter(METRICS_PROTOCOL); Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(protocolName); - this.port = invoker.getUrl().getParameter(Constants.METRICS_PORT) == null ? - protocol.getDefaultPort() : Integer.valueOf(invoker.getUrl().getParameter(Constants.METRICS_PORT)); + this.port = invoker.getUrl().getParameter(METRICS_PORT) == null ? + protocol.getDefaultPort() : Integer.valueOf(invoker.getUrl().getParameter(METRICS_PORT)); Invoker metricsInvoker = initMetricsInvoker(); @@ -142,23 +150,23 @@ private void reportMetrics(Invoker invoker, Invocation invocation, long durat MetricName global; MetricName method; if (isProvider) { - global = new MetricName(Constants.DUBBO_PROVIDER, MetricLevel.MAJOR); - method = new MetricName(Constants.DUBBO_PROVIDER_METHOD, new HashMap(4) { + global = new MetricName(DUBBO_PROVIDER, MetricLevel.MAJOR); + method = new MetricName(DUBBO_PROVIDER_METHOD, new HashMap(4) { { - put(Constants.SERVICE, serviceName); - put(Constants.METHOD, methodName); + put(SERVICE, serviceName); + put(METHOD, methodName); } }, MetricLevel.NORMAL); } else { - global = new MetricName(Constants.DUBBO_CONSUMER, MetricLevel.MAJOR); - method = new MetricName(Constants.DUBBO_CONSUMER_METHOD, new HashMap(4) { + global = new MetricName(DUBBO_CONSUMER, MetricLevel.MAJOR); + method = new MetricName(DUBBO_CONSUMER_METHOD, new HashMap(4) { { - put(Constants.SERVICE, serviceName); - put(Constants.METHOD, methodName); + put(SERVICE, serviceName); + put(METHOD, methodName); } }, MetricLevel.NORMAL); } - setCompassQuantity(Constants.DUBBO_GROUP, result, duration, global, method); + setCompassQuantity(DUBBO_GROUP, result, duration, global, method); } private void setCompassQuantity(String groupName, String result, long duration, MetricName... metricNames) { diff --git a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/MetricsFilterTest.java b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/MetricsFilterTest.java index 23bb1341cdd..5bffeac73f4 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/MetricsFilterTest.java +++ b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/MetricsFilterTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.monitor.dubbo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.monitor.MetricsService; @@ -50,6 +49,13 @@ import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.MonitorConstants.DUBBO_CONSUMER; +import static org.apache.dubbo.common.constants.MonitorConstants.DUBBO_CONSUMER_METHOD; +import static org.apache.dubbo.common.constants.MonitorConstants.DUBBO_GROUP; +import static org.apache.dubbo.common.constants.MonitorConstants.DUBBO_PROVIDER; +import static org.apache.dubbo.common.constants.MonitorConstants.DUBBO_PROVIDER_METHOD; +import static org.apache.dubbo.common.constants.MonitorConstants.METHOD; +import static org.apache.dubbo.common.constants.MonitorConstants.SERVICE; public class MetricsFilterTest { @@ -112,11 +118,11 @@ public void testConsumerSuccess() throws Exception { for (int i = 0; i < 100; i++) { metricsFilter.invoke(serviceInvoker, invocation); } - FastCompass dubboClient = metricManager.getFastCompass(Constants.DUBBO_GROUP, new MetricName(Constants.DUBBO_CONSUMER, MetricLevel.MAJOR)); - FastCompass dubboMethod = metricManager.getFastCompass(Constants.DUBBO_GROUP, new MetricName(Constants.DUBBO_CONSUMER_METHOD, new HashMap(4) { + FastCompass dubboClient = metricManager.getFastCompass(DUBBO_GROUP, new MetricName(DUBBO_CONSUMER, MetricLevel.MAJOR)); + FastCompass dubboMethod = metricManager.getFastCompass(DUBBO_GROUP, new MetricName(DUBBO_CONSUMER_METHOD, new HashMap(4) { { - put(Constants.SERVICE, "org.apache.dubbo.monitor.dubbo.service.DemoService"); - put(Constants.METHOD, "void sayName(Integer)"); + put(SERVICE, "org.apache.dubbo.monitor.dubbo.service.DemoService"); + put(METHOD, "void sayName(Integer)"); } }, MetricLevel.NORMAL)); long timestamp = System.currentTimeMillis() / 5000 * 5000; @@ -142,11 +148,11 @@ public void testConsumerTimeout() { //ignore } } - FastCompass dubboClient = metricManager.getFastCompass(Constants.DUBBO_GROUP, new MetricName(Constants.DUBBO_CONSUMER, MetricLevel.MAJOR)); - FastCompass dubboMethod = metricManager.getFastCompass(Constants.DUBBO_GROUP, new MetricName(Constants.DUBBO_CONSUMER_METHOD, new HashMap(4) { + FastCompass dubboClient = metricManager.getFastCompass(DUBBO_GROUP, new MetricName(DUBBO_CONSUMER, MetricLevel.MAJOR)); + FastCompass dubboMethod = metricManager.getFastCompass(DUBBO_GROUP, new MetricName(DUBBO_CONSUMER_METHOD, new HashMap(4) { { - put(Constants.SERVICE, "org.apache.dubbo.monitor.dubbo.service.DemoService"); - put(Constants.METHOD, "void timeoutException()"); + put(SERVICE, "org.apache.dubbo.monitor.dubbo.service.DemoService"); + put(METHOD, "void timeoutException()"); } }, MetricLevel.NORMAL)); long timestamp = System.currentTimeMillis() / 5000 * 5000; @@ -167,11 +173,11 @@ public void testProviderSuccess() throws Exception { for (int i = 0; i < 100; i++) { metricsFilter.invoke(serviceInvoker, invocation); } - FastCompass dubboClient = metricManager.getFastCompass(Constants.DUBBO_GROUP, new MetricName(Constants.DUBBO_PROVIDER, MetricLevel.MAJOR)); - FastCompass dubboMethod = metricManager.getFastCompass(Constants.DUBBO_GROUP, new MetricName(Constants.DUBBO_PROVIDER_METHOD, new HashMap(4) { + FastCompass dubboClient = metricManager.getFastCompass(DUBBO_GROUP, new MetricName(DUBBO_PROVIDER, MetricLevel.MAJOR)); + FastCompass dubboMethod = metricManager.getFastCompass(DUBBO_GROUP, new MetricName(DUBBO_PROVIDER_METHOD, new HashMap(4) { { - put(Constants.SERVICE, "org.apache.dubbo.monitor.dubbo.service.DemoService"); - put(Constants.METHOD, "void sayName()"); + put(SERVICE, "org.apache.dubbo.monitor.dubbo.service.DemoService"); + put(METHOD, "void sayName()"); } }, MetricLevel.NORMAL)); long timestamp = System.currentTimeMillis() / 5000 * 5000; @@ -200,7 +206,7 @@ public void testInvokeMetricsService() { Protocol protocol = new DubboProtocol(); URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":20880/" + MetricsService.class.getName()); Invoker invoker = protocol.refer(MetricsService.class, url); - invocation = new RpcInvocation("getMetricsByGroup", new Class[]{String.class}, new Object[]{Constants.DUBBO_GROUP}); + invocation = new RpcInvocation("getMetricsByGroup", new Class[]{String.class}, new Object[]{DUBBO_GROUP}); try { Thread.sleep(5000); } catch (Exception e) { @@ -252,7 +258,7 @@ public void testInvokeMetricsMethodService() { Protocol protocol = new DubboProtocol(); URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":20880/" + MetricsService.class.getName()); Invoker invoker = protocol.refer(MetricsService.class, url); - Invocation invocation = new RpcInvocation("getMetricsByGroup", new Class[]{String.class}, new Object[]{Constants.DUBBO_GROUP}); + Invocation invocation = new RpcInvocation("getMetricsByGroup", new Class[]{String.class}, new Object[]{DUBBO_GROUP}); try { Thread.sleep(15000); } catch (Exception e) { diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java index 5b968974d0d..624d58b9588 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java @@ -59,6 +59,7 @@ import java.util.Set; import java.util.stream.Collectors; +import static org.apache.dubbo.common.constants.ClusterConstants.ROUTER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DISABLED_KEY; @@ -66,6 +67,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; +import static org.apache.dubbo.common.constants.MonitorConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.APP_DYNAMIC_CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.COMPATIBLE_CONFIG_KEY; @@ -150,7 +152,7 @@ private URL turnRegistryUrlToConsumerUrl(URL url) { .setPath(url.getServiceInterface()) .clearParameters() .addParameters(queryMap) - .removeParameter(Constants.MONITOR_KEY) + .removeParameter(MONITOR_KEY) .build(); } @@ -343,7 +345,7 @@ private Optional> toRouters(List urls) { if (EMPTY_PROTOCOL.equals(url.getProtocol())) { continue; } - String routerType = url.getParameter(Constants.ROUTER_KEY); + String routerType = url.getParameter(ROUTER_KEY); if (routerType != null && routerType.length() > 0) { url = url.setProtocol(routerType); } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java index a94e72f11b4..4a155c07adf 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java @@ -54,8 +54,6 @@ import static java.util.concurrent.Executors.newSingleThreadExecutor; import static org.apache.dubbo.common.Constants.ACCEPT_FOREIGN_IP; import static org.apache.dubbo.common.Constants.EXPORT_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.INTERFACES; -import static org.apache.dubbo.common.Constants.MONITOR_KEY; import static org.apache.dubbo.common.Constants.QOS_ENABLE; import static org.apache.dubbo.common.Constants.QOS_PORT; import static org.apache.dubbo.common.Constants.REFER_KEY; @@ -77,6 +75,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.CLUSTER_KEY; +import static org.apache.dubbo.common.constants.MonitorConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_SUFFIX; @@ -101,6 +100,7 @@ import static org.apache.dubbo.common.constants.RpcConstants.CONNECTIONS_KEY; import static org.apache.dubbo.common.constants.RpcConstants.DEPRECATED_KEY; import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.INTERFACES; import static org.apache.dubbo.common.constants.RpcConstants.MOCK_KEY; import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; import static org.apache.dubbo.common.utils.UrlUtils.classifyUrls; diff --git a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java index ca5eb761b37..99aff9e1b69 100644 --- a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java +++ b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java @@ -38,6 +38,7 @@ import java.util.HashSet; import java.util.List; +import static org.apache.dubbo.common.constants.ClusterConstants.CLUSTER_STICKY_KEY; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; @@ -60,7 +61,7 @@ private static URL getRegistryURL(URL url) { .setPath(RegistryService.class.getName()) .removeParameter(Constants.EXPORT_KEY).removeParameter(Constants.REFER_KEY) .addParameter(INTERFACE_KEY, RegistryService.class.getName()) - .addParameter(Constants.CLUSTER_STICKY_KEY, "true") + .addParameter(CLUSTER_STICKY_KEY, "true") .addParameter(Constants.LAZY_CONNECT_KEY, "true") .addParameter(RemotingConstants.RECONNECT_KEY, "false") .addParameterIfAbsent(TIMEOUT_KEY, "10000") diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java index 3aa1d7dcc00..78ea9837eb9 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java @@ -50,20 +50,26 @@ import java.util.Map; import java.util.concurrent.CountDownLatch; +import static org.apache.dubbo.common.constants.ClusterConstants.INVOCATION_NEED_MOCK; +import static org.apache.dubbo.common.constants.ClusterConstants.LOADBALANCE_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.MOCK_PROTOCOL; +import static org.apache.dubbo.common.constants.ClusterConstants.ROUTER_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.RULE_KEY; +import static org.apache.dubbo.common.constants.ClusterConstants.TYPE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.DISABLED_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.MOCK_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.ROUTE_PROTOCOL; +import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE; +import static org.apache.dubbo.common.constants.RpcConstants.MOCK_KEY; import static org.junit.jupiter.api.Assertions.fail; @SuppressWarnings({"rawtypes", "unchecked"}) @@ -324,10 +330,7 @@ private void test_Notified3invokers(RegistryDirectory registryDirectory) { public void testParametersMerge() { RegistryDirectory registryDirectory = getRegistryDirectory(); URL regurl = noMeaningUrl.addParameter("test", "reg").addParameterAndEncoded(Constants.REFER_KEY, - "key=query&" - + Constants.LOADBALANCE_KEY - + "=" - + LeastActiveLoadBalance.NAME); + "key=query&" + LOADBALANCE_KEY + "=" + LeastActiveLoadBalance.NAME); RegistryDirectory registryDirectory2 = new RegistryDirectory( RegistryDirectoryTest.class, regurl); @@ -390,7 +393,7 @@ public void testParametersMerge() { } { serviceUrls.clear(); - serviceUrls.add(SERVICEURL.addParameter(Constants.LOADBALANCE_KEY, RoundRobinLoadBalance.NAME)); + serviceUrls.add(SERVICEURL.addParameter(LOADBALANCE_KEY, RoundRobinLoadBalance.NAME)); registryDirectory2.notify(serviceUrls); invocation = new RpcInvocation(); @@ -399,7 +402,7 @@ public void testParametersMerge() { Invoker invoker = (Invoker) invokers.get(0); URL url = invoker.getUrl(); - Assertions.assertEquals(LeastActiveLoadBalance.NAME, url.getMethodParameter("get", Constants.LOADBALANCE_KEY)); + Assertions.assertEquals(LeastActiveLoadBalance.NAME, url.getMethodParameter("get", LOADBALANCE_KEY)); } //test geturl { @@ -560,11 +563,9 @@ public void testNotifyRouterUrls() { List serviceUrls = new ArrayList(); // without ROUTER_KEY, the first router should not be created. - serviceUrls.add(routerurl.addParameter(CATEGORY_KEY, ROUTERS_CATEGORY).addParameter(Constants.TYPE_KEY, "javascript").addParameter(Constants.ROUTER_KEY, - "notsupported").addParameter(Constants.RULE_KEY, - "function test1(){}")); - serviceUrls.add(routerurl2.addParameter(CATEGORY_KEY, ROUTERS_CATEGORY).addParameter(Constants.TYPE_KEY, "javascript").addParameter(Constants.ROUTER_KEY, - ScriptRouterFactory.NAME).addParameter(Constants.RULE_KEY, + serviceUrls.add(routerurl.addParameter(CATEGORY_KEY, ROUTERS_CATEGORY).addParameter(TYPE_KEY, "javascript").addParameter(ROUTER_KEY, "notsupported").addParameter(RULE_KEY, "function test1(){}")); + serviceUrls.add(routerurl2.addParameter(CATEGORY_KEY, ROUTERS_CATEGORY).addParameter(TYPE_KEY, "javascript").addParameter(ROUTER_KEY, + ScriptRouterFactory.NAME).addParameter(RULE_KEY, "function test1(){}")); // FIXME @@ -941,9 +942,9 @@ public void testNofity_disabled_specifiedProvider() { public void testNotifyRouterUrls_Clean() { if (isScriptUnsupported) return; RegistryDirectory registryDirectory = getRegistryDirectory(); - URL routerurl = URL.valueOf(ROUTE_PROTOCOL + "://127.0.0.1:9096/").addParameter(Constants.ROUTER_KEY, - "javascript").addParameter(Constants.RULE_KEY, - "function test1(){}").addParameter(Constants.ROUTER_KEY, + URL routerurl = URL.valueOf(ROUTE_PROTOCOL + "://127.0.0.1:9096/").addParameter(ROUTER_KEY, + "javascript").addParameter(RULE_KEY, + "function test1(){}").addParameter(ROUTER_KEY, "script"); // FIX // BAD @@ -972,7 +973,7 @@ public void testNotify_MockProviderOnly() { List serviceUrls = new ArrayList(); serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1")); serviceUrls.add(SERVICEURL2.addParameter("methods", "getXXX1,getXXX2")); - serviceUrls.add(SERVICEURL.setProtocol(Constants.MOCK_PROTOCOL)); + serviceUrls.add(SERVICEURL.setProtocol(MOCK_PROTOCOL)); registryDirectory.notify(serviceUrls); Assertions.assertEquals(true, registryDirectory.isAvailable()); @@ -982,7 +983,7 @@ public void testNotify_MockProviderOnly() { Assertions.assertEquals(2, invokers.size()); RpcInvocation mockinvocation = new RpcInvocation(); - mockinvocation.setAttachment(Constants.INVOCATION_NEED_MOCK, "true"); + mockinvocation.setAttachment(INVOCATION_NEED_MOCK, "true"); invokers = registryDirectory.list(mockinvocation); Assertions.assertEquals(1, invokers.size()); } diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java index f9d9ea0a0a4..c4b02e1adb9 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java @@ -28,6 +28,7 @@ import java.io.IOException; import java.net.ServerSocket; +import static org.apache.dubbo.common.constants.ClusterConstants.CLUSTER_STICKY_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_INSTANCES_LIMIT_KEY; @@ -59,7 +60,7 @@ public static Exporter export(int port, RegistryService registr new URLBuilder(Constants.DUBBO_PROTOCOL, NetUtils.getLocalHost(), port, RegistryService.class.getName()) .setPath(RegistryService.class.getName()) .addParameter(INTERFACE_KEY, RegistryService.class.getName()) - .addParameter(Constants.CLUSTER_STICKY_KEY, "true") + .addParameter(CLUSTER_STICKY_KEY, "true") .addParameter(CALLBACK_INSTANCES_LIMIT_KEY, "1000") .addParameter("ondisconnect", "disconnect") .addParameter("subscribe.1.callback", "true") diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java index 802e6d01796..99596bf025b 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.filter; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; @@ -29,6 +28,7 @@ import java.util.HashMap; import java.util.Map; +import static org.apache.dubbo.common.constants.ClusterConstants.TAG_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; @@ -36,9 +36,9 @@ import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.ASYNC_KEY; import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.RpcConstants.FORCE_USE_TAG; -import static org.apache.dubbo.common.constants.RpcConstants.ASYNC_KEY; import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; @@ -65,7 +65,7 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept attachments.remove(TIMEOUT_KEY); // Remove async property to avoid being passed to the following invoke chain. attachments.remove(ASYNC_KEY); - attachments.remove(Constants.TAG_KEY); + attachments.remove(TAG_KEY); attachments.remove(FORCE_USE_TAG); } RpcContext.getContext() From d77a009a859e62b6a9a68266059b61376549528e Mon Sep 17 00:00:00 2001 From: myPrecious Date: Tue, 14 May 2019 11:00:39 +0800 Subject: [PATCH 050/115] [Dubbo-3846] Support nacos metadata (#4025) --- dubbo-all/pom.xml | 8 ++ dubbo-bom/pom.xml | 5 + .../dubbo-metadata-report-nacos/pom.xml | 41 ++++++ .../store/nacos/NacosMetadataReport.java | 125 ++++++++++++++++++ .../nacos/NacosMetadataReportFactory.java | 32 +++++ ...dubbo.metadata.store.MetadataReportFactory | 1 + .../store/nacos/NacosMetadata4TstService.java | 28 ++++ .../store/nacos/NacosMetadataReportTest.java | 115 ++++++++++++++++ dubbo-metadata-report/pom.xml | 1 + 9 files changed, 356 insertions(+) create mode 100644 dubbo-metadata-report/dubbo-metadata-report-nacos/pom.xml create mode 100644 dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java create mode 100644 dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java create mode 100644 dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory create mode 100644 dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadata4TstService.java create mode 100644 dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java diff --git a/dubbo-all/pom.xml b/dubbo-all/pom.xml index 6dc00fbcda7..5164d860cd2 100644 --- a/dubbo-all/pom.xml +++ b/dubbo-all/pom.xml @@ -485,6 +485,13 @@ compile true + + org.apache.dubbo + dubbo-metadata-report-nacos + ${project.version} + compile + true + @@ -613,6 +620,7 @@ org.apache.dubbo:dubbo-metadata-report-zookeeper org.apache.dubbo:dubbo-metadata-report-consul org.apache.dubbo:dubbo-metadata-report-etcd + org.apache.dubbo:dubbo-metadata-report-nacos org.apache.dubbo:dubbo-serialization-native-hession org.apache.dubbo:dubbo-rpc-native-thrift diff --git a/dubbo-bom/pom.xml b/dubbo-bom/pom.xml index 2b1e5feb2f6..e6f6eb8c011 100644 --- a/dubbo-bom/pom.xml +++ b/dubbo-bom/pom.xml @@ -382,6 +382,11 @@ dubbo-metadata-report-etcd ${project.version} + + org.apache.dubbo + dubbo-metadata-report-nacos + ${project.version} + org.apache.dubbo dubbo-configcenter-api diff --git a/dubbo-metadata-report/dubbo-metadata-report-nacos/pom.xml b/dubbo-metadata-report/dubbo-metadata-report-nacos/pom.xml new file mode 100644 index 00000000000..d324d5c49c1 --- /dev/null +++ b/dubbo-metadata-report/dubbo-metadata-report-nacos/pom.xml @@ -0,0 +1,41 @@ + + + + + + dubbo-metadata-report + org.apache.dubbo + ${revision} + + 4.0.0 + + dubbo-metadata-report-nacos + + + + org.apache.dubbo + dubbo-metadata-report-api + ${project.parent.version} + + + com.alibaba.nacos + nacos-client + + + + diff --git a/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java b/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java new file mode 100644 index 00000000000..03bdeb8f958 --- /dev/null +++ b/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java @@ -0,0 +1,125 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.metadata.store.nacos; + +import com.alibaba.nacos.api.NacosFactory; +import com.alibaba.nacos.api.config.ConfigService; +import com.alibaba.nacos.api.exception.NacosException; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.common.utils.StringUtils; +import org.apache.dubbo.metadata.identifier.MetadataIdentifier; +import org.apache.dubbo.metadata.support.AbstractMetadataReport; +import org.apache.dubbo.rpc.RpcException; + +import java.util.Properties; + +import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; +import static com.alibaba.nacos.api.PropertyKeyConst.SECRET_KEY; +import static com.alibaba.nacos.api.PropertyKeyConst.ACCESS_KEY; +import static com.alibaba.nacos.api.PropertyKeyConst.ENDPOINT; +import static com.alibaba.nacos.api.PropertyKeyConst.NAMESPACE; +import static com.alibaba.nacos.api.PropertyKeyConst.CLUSTER_NAME; +import static com.alibaba.nacos.client.naming.utils.UtilAndComs.NACOS_NAMING_LOG_NAME; +import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; + +/** + * metadata report impl for nacos + */ +public class NacosMetadataReport extends AbstractMetadataReport { + private static final Logger logger = LoggerFactory.getLogger(NacosMetadataReport.class); + private ConfigService configService; + + public NacosMetadataReport(URL url) { + super(url); + this.configService = buildConfigService(url); + } + + public ConfigService buildConfigService(URL url) { + Properties nacosProperties = buildNacosProperties(url); + try { + configService = NacosFactory.createConfigService(nacosProperties); + } catch (NacosException e) { + if (logger.isErrorEnabled()) { + logger.error(e.getErrMsg(), e); + } + throw new IllegalStateException(e); + } + return configService; + } + + private Properties buildNacosProperties(URL url) { + Properties properties = new Properties(); + setServerAddr(url, properties); + setProperties(url, properties); + return properties; + } + + private void setServerAddr(URL url, Properties properties) { + StringBuilder serverAddrBuilder = + new StringBuilder(url.getHost()) // Host + .append(":") + .append(url.getPort()); // Port + // Append backup parameter as other servers + String backup = url.getParameter(BACKUP_KEY); + if (backup != null) { + serverAddrBuilder.append(",").append(backup); + } + String serverAddr = serverAddrBuilder.toString(); + properties.put(SERVER_ADDR, serverAddr); + } + + private void setProperties(URL url, Properties properties) { + putPropertyIfAbsent(url, properties, NAMESPACE); + putPropertyIfAbsent(url, properties, NACOS_NAMING_LOG_NAME); + putPropertyIfAbsent(url, properties, ENDPOINT); + putPropertyIfAbsent(url, properties, ACCESS_KEY); + putPropertyIfAbsent(url, properties, SECRET_KEY); + putPropertyIfAbsent(url, properties, CLUSTER_NAME); + } + + private void putPropertyIfAbsent(URL url, Properties properties, String propertyName) { + String propertyValue = url.getParameter(propertyName); + if (StringUtils.isNotEmpty(propertyValue)) { + properties.setProperty(propertyName, propertyValue); + } + } + + @Override + protected void doStoreProviderMetadata(MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions) { + this.storeMetadata(providerMetadataIdentifier, serviceDefinitions); + } + + @Override + protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, String value) { + this.storeMetadata(consumerMetadataIdentifier, value); + } + + private void storeMetadata(MetadataIdentifier identifier, String value) { + try { + boolean publishResult = configService.publishConfig(identifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY), identifier.getGroup(), value); + if (!publishResult) { + throw new RuntimeException("publish nacos metadata failed"); + } + } catch (Throwable t) { + logger.error("Failed to put " + identifier + " to nacos " + value + ", cause: " + t.getMessage(), t); + throw new RpcException("Failed to put " + identifier + " to nacos " + value + ", cause: " + t.getMessage(), t); + } + } +} diff --git a/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java b/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java new file mode 100644 index 00000000000..b882042281c --- /dev/null +++ b/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java @@ -0,0 +1,32 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.metadata.store.nacos; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.metadata.store.MetadataReport; +import org.apache.dubbo.metadata.support.AbstractMetadataReportFactory; + +/** + * metadata report factory impl for nacos + */ +public class NacosMetadataReportFactory extends AbstractMetadataReportFactory { + @Override + protected MetadataReport createMetadataReport(URL url) { + return new NacosMetadataReport(url); + } +} diff --git a/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory b/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory new file mode 100644 index 00000000000..de3b50a4b41 --- /dev/null +++ b/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory @@ -0,0 +1 @@ +nacos=org.apache.dubbo.metadata.store.nacos.NacosMetadataReportFactory diff --git a/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadata4TstService.java b/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadata4TstService.java new file mode 100644 index 00000000000..e84efc529ca --- /dev/null +++ b/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadata4TstService.java @@ -0,0 +1,28 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.metadata.store.nacos; + +/** + * Test interface for Nacos metadata report + */ +public interface NacosMetadata4TstService { + + int getCounter(); + + void printResult(String var); +} diff --git a/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java b/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java new file mode 100644 index 00000000000..c90809c3d51 --- /dev/null +++ b/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java @@ -0,0 +1,115 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.metadata.store.nacos; + +import com.alibaba.nacos.api.config.ConfigService; +import com.google.gson.Gson; +import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.utils.NetUtils; +import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder; +import org.apache.dubbo.metadata.definition.model.FullServiceDefinition; +import org.apache.dubbo.metadata.identifier.MetadataIdentifier; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Disabled; + +import java.util.HashMap; +import java.util.Map; + +import static org.apache.dubbo.common.constants.RegistryConstants.SESSION_TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; +import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; + +@Disabled +public class NacosMetadataReportTest { + private static final String TEST_SERVICE = "org.apache.dubbo.metadata.store.nacos.NacosMetadata4TstService"; + private NacosMetadataReport nacosMetadataReport; + private NacosMetadataReportFactory nacosMetadataReportFactory; + private ConfigService configService; + + @BeforeEach + public void setUp() { + // timeout in 15 seconds. + URL url = URL.valueOf("nacos://127.0.0.1:8848") + .addParameter(SESSION_TIMEOUT_KEY, 15000); + nacosMetadataReportFactory = new NacosMetadataReportFactory(); + this.nacosMetadataReport = (NacosMetadataReport) nacosMetadataReportFactory.createMetadataReport(url); + this.configService = nacosMetadataReport.buildConfigService(url); + } + + @AfterEach + public void tearDown() throws Exception { + } + + @Test + public void testStoreProvider() throws Exception { + String version = "1.0.0"; + String group = null; + String application = "nacos-metdata-report-test"; + MetadataIdentifier providerIdentifier = + storeProvider(nacosMetadataReport, TEST_SERVICE, version, group, application); + String serverContent = configService.getConfig(providerIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY), group, 5000L); + Assertions.assertNotNull(serverContent); + + Gson gson = new Gson(); + FullServiceDefinition fullServiceDefinition = gson.fromJson(serverContent, FullServiceDefinition.class); + Assertions.assertEquals(fullServiceDefinition.getParameters().get("paramTest"), "nacosTest"); + } + + @Test + public void testStoreConsumer() throws Exception { + String version = "1.0.0"; + String group = null; + String application = "nacos-metadata-report-consumer-test"; + MetadataIdentifier consumerIdentifier = storeConsumer(nacosMetadataReport, TEST_SERVICE, version, group, application); + + String serverContent = configService.getConfig(consumerIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY), group, 5000L); + Assertions.assertNotNull(serverContent); + Assertions.assertEquals(serverContent, "{\"paramConsumerTest\":\"nacosConsumer\"}"); + } + + private MetadataIdentifier storeProvider(NacosMetadataReport nacosMetadataReport, String interfaceName, String version, + String group, String application) + throws ClassNotFoundException, InterruptedException { + URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + + "?paramTest=nacosTest&version=" + version + "&application=" + + application + (group == null ? "" : "&group=" + group)); + + MetadataIdentifier providerMetadataIdentifier = + new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE, application); + Class interfaceClass = Class.forName(interfaceName); + FullServiceDefinition fullServiceDefinition = + ServiceDefinitionBuilder.buildFullDefinition(interfaceClass, url.getParameters()); + + nacosMetadataReport.storeProviderMetadata(providerMetadataIdentifier, fullServiceDefinition); + Thread.sleep(1000); + return providerMetadataIdentifier; + } + + private MetadataIdentifier storeConsumer(NacosMetadataReport nacosMetadataReport, String interfaceName, + String version, String group, String application) throws InterruptedException { + MetadataIdentifier consumerIdentifier = new MetadataIdentifier(interfaceName, version, group, CONSUMER_SIDE, application); + Map tmp = new HashMap<>(); + tmp.put("paramConsumerTest", "nacosConsumer"); + nacosMetadataReport.storeConsumerMetadata(consumerIdentifier, tmp); + Thread.sleep(1000); + return consumerIdentifier; + } +} diff --git a/dubbo-metadata-report/pom.xml b/dubbo-metadata-report/pom.xml index 3cb254afb96..5e0fb1a4287 100644 --- a/dubbo-metadata-report/pom.xml +++ b/dubbo-metadata-report/pom.xml @@ -31,6 +31,7 @@ dubbo-metadata-definition dubbo-metadata-report-consul dubbo-metadata-report-etcd + dubbo-metadata-report-nacos From 6ca5a10c43196dbb87211022f274ce5590685fe9 Mon Sep 17 00:00:00 2001 From: Daniela Marques de Morais Date: Tue, 14 May 2019 00:11:05 -0300 Subject: [PATCH 051/115] [Dubbo-3764]Merge dubbo rpc xmlrpc (#3764) (#3775) * Create constants for 'hash.names' and 'hash.arguments' (#3744) * Merge dubbo-rpc-xmlrpc (#3764) * Removing .gitignore * Rename package name * Add Apache License * Rename groupID name and url * Update dubbo-rpc-xmlrpc version and add as a dependency in dubbo-all * Replace package for "org.apache.dubbo.xml" and rename "com.alibaba.*" to "org.apache.dubbo" * Fix the name of artifactID * Remove unused files and add dubbo-rpc-xml as a module in dubbo-rpc * Remove authors and delete files that are duplicate in the main repo have one * Fix the name of package and remove unnecessary space * Remove unnecessary space * Remove authors * Fix imports and remove authors from pom * Update groupID and the name of package * Remove unused tags * Add dubbo-rpc-xml as a dependency on dubbo-bom * Fix package names * Call JettyHttpBinder from remoting module to avoid duplicated files * Fix unit tests and upgrade to JUnit 5 * Call JettyHttpBinder from remoting module to avoid duplicated files * Add external dependencies on dubbo-dependencies-bom --- dubbo-all/pom.xml | 8 + dubbo-bom/pom.xml | 5 + dubbo-dependencies-bom/pom.xml | 7 + dubbo-rpc/dubbo-rpc-xml/README.md | 88 ++++++++ dubbo-rpc/dubbo-rpc-xml/pom.xml | 66 ++++++ .../rpc/protocol/xmlrpc/XmlRpcProtocol.java | 188 ++++++++++++++++++ .../xmlrpc/XmlRpcProxyFactoryBean.java | 137 +++++++++++++ .../org.apache.dubbo.remoting.http.HttpBinder | 1 + .../internal/org.apache.dubbo.rpc.Protocol | 1 + .../protocol/xmlrpc/XmlRpcProtocolTest.java | 86 ++++++++ .../rpc/protocol/xmlrpc/XmlRpcService.java | 25 +++ .../protocol/xmlrpc/XmlRpcServiceImpl.java | 51 +++++ dubbo-rpc/pom.xml | 1 + 13 files changed, 664 insertions(+) create mode 100644 dubbo-rpc/dubbo-rpc-xml/README.md create mode 100644 dubbo-rpc/dubbo-rpc-xml/pom.xml create mode 100644 dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java create mode 100644 dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProxyFactoryBean.java create mode 100644 dubbo-rpc/dubbo-rpc-xml/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.http.HttpBinder create mode 100644 dubbo-rpc/dubbo-rpc-xml/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol create mode 100644 dubbo-rpc/dubbo-rpc-xml/src/test/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocolTest.java create mode 100644 dubbo-rpc/dubbo-rpc-xml/src/test/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcService.java create mode 100644 dubbo-rpc/dubbo-rpc-xml/src/test/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcServiceImpl.java diff --git a/dubbo-all/pom.xml b/dubbo-all/pom.xml index 5164d860cd2..be5a2e3fd77 100644 --- a/dubbo-all/pom.xml +++ b/dubbo-all/pom.xml @@ -212,6 +212,13 @@ compile true + + org.apache.dubbo + dubbo-rpc-xml + ${project.version} + compile + true + org.apache.dubbo dubbo-registry-api @@ -576,6 +583,7 @@ org.apache.dubbo:dubbo-rpc-memcached org.apache.dubbo:dubbo-rpc-redis org.apache.dubbo:dubbo-rpc-rest + org.apache.dubbo:dubbo-rpc-xml org.apache.dubbo:dubbo-filter-validation org.apache.dubbo:dubbo-filter-cache org.apache.dubbo:dubbo-cluster diff --git a/dubbo-bom/pom.xml b/dubbo-bom/pom.xml index e6f6eb8c011..15908715496 100644 --- a/dubbo-bom/pom.xml +++ b/dubbo-bom/pom.xml @@ -222,6 +222,11 @@ dubbo-rpc-rest ${project.version} + + org.apache.dubbo + dubbo-rpc-xml + ${project.version} + org.apache.dubbo dubbo-registry-api diff --git a/dubbo-dependencies-bom/pom.xml b/dubbo-dependencies-bom/pom.xml index 6fc9a88ebc0..ef42a6e4517 100644 --- a/dubbo-dependencies-bom/pom.xml +++ b/dubbo-dependencies-bom/pom.xml @@ -150,6 +150,7 @@ 5.2.0 2.8.5 1.2.0 + 6.1.26 2.0 1.1.0 2.7.2-SNAPSHOT @@ -297,6 +298,12 @@ jetty-servlet ${jetty_version} + + org.mortbay.jetty + jetty + ${mortbay_jetty_version} + true + javax.validation validation-api diff --git a/dubbo-rpc/dubbo-rpc-xml/README.md b/dubbo-rpc/dubbo-rpc-xml/README.md new file mode 100644 index 00000000000..17c022c5fac --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-xml/README.md @@ -0,0 +1,88 @@ + +dubbo-rpc-xmlrpc +===================== +A RPC Extension for XML-RPC(http://ws.apache.org/xmlrpc) + +## Maven dependency: +```xml + + org.apache.dubbo + dubbo-rpc + 2.7.2-SNAPSHOT + + +``` + +## Configure: +Define xmlrpc protocol: +```xml + +``` + +Set default protocol: +```xml + +``` + +Set service protocol: +```xml + +``` + +Multi port: +```xml + + +``` +Multi protocol: +```xml + + +``` + +```xml + +``` + + +Jetty Server: (default) +```xml + + +Or Jetty9: + + +``` +Maven: +```xml + + org.mortbay.jetty + jetty + 6.1.26 + +``` + +Servlet Bridge Server: (recommend) +```xml + + +``` + +web.xml: +```xml + + dubbo + com.alibaba.dubbo.remoting.http.servlet.DispatcherServlet + 1 + + + dubbo + /* + +``` +Cors support: +```xml + + + +``` diff --git a/dubbo-rpc/dubbo-rpc-xml/pom.xml b/dubbo-rpc/dubbo-rpc-xml/pom.xml new file mode 100644 index 00000000000..8caed152b82 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-xml/pom.xml @@ -0,0 +1,66 @@ + + + 4.0.0 + + + org.apache.dubbo + dubbo-rpc + ${revision} + + + dubbo-rpc-xml + jar + ${project.artifactId} + The xml rpc module of dubbo project + + 3.1.3 + 1.8 + 1.8 + UTF-8 + UTF-8 + false + + https://github.com/apache/incubator-dubbo + + + + org.apache.xmlrpc + xmlrpc-server + ${xmlrpc_version} + + + + org.apache.xmlrpc + xmlrpc-client + ${xmlrpc_version} + + + + org.apache.dubbo + dubbo-remoting-http + ${project.parent.version} + + + + org.apache.dubbo + dubbo-compatible + ${project.parent.version} + + + + diff --git a/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java b/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java new file mode 100644 index 00000000000..c62bd8c85b8 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java @@ -0,0 +1,188 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.xml.rpc.protocol.xmlrpc; + +import java.io.IOException; +import java.net.SocketTimeoutException; +import java.util.ArrayList; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.remoting.http.HttpBinder; +import org.apache.dubbo.remoting.http.HttpHandler; +import org.apache.dubbo.remoting.http.HttpServer; +import org.apache.dubbo.rpc.RpcContext; +import org.apache.dubbo.rpc.RpcException; +import org.apache.dubbo.rpc.protocol.AbstractProxyProtocol; +import org.apache.xmlrpc.XmlRpcException; +import org.apache.xmlrpc.XmlRpcRequest; +import org.apache.xmlrpc.server.PropertyHandlerMapping; +import org.apache.xmlrpc.server.RequestProcessorFactoryFactory; +import org.apache.xmlrpc.server.XmlRpcServerConfigImpl; +import org.apache.xmlrpc.webserver.XmlRpcServletServer; +import org.springframework.remoting.RemoteAccessException; + +public class XmlRpcProtocol extends AbstractProxyProtocol { + + public static final String ACCESS_CONTROL_ALLOW_ORIGIN_HEADER = "Access-Control-Allow-Origin"; + public static final String ACCESS_CONTROL_ALLOW_METHODS_HEADER = "Access-Control-Allow-Methods"; + public static final String ACCESS_CONTROL_ALLOW_HEADERS_HEADER = "Access-Control-Allow-Headers"; + + private final Map serverMap = new ConcurrentHashMap<>(); + + private final Map skeletonMap = new ConcurrentHashMap<>(); + + private HttpBinder httpBinder; + + public XmlRpcProtocol() { + super(XmlRpcException.class); + } + + public void setHttpBinder(HttpBinder httpBinder) { + this.httpBinder = httpBinder; + } + + public int getDefaultPort() { + return 80; + } + + private class InternalHandler implements HttpHandler { + + private boolean cors; + + public InternalHandler(boolean cors) { + this.cors = cors; + } + + public void handle(HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { + String uri = request.getRequestURI(); + XmlRpcServletServer xmlrpc = skeletonMap.get(uri); + if (cors) { + response.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*"); + response.setHeader(ACCESS_CONTROL_ALLOW_METHODS_HEADER, "POST"); + response.setHeader(ACCESS_CONTROL_ALLOW_HEADERS_HEADER, "*"); + } + if (request.getMethod().equalsIgnoreCase("OPTIONS")) { + response.setStatus(200); + } else if (request.getMethod().equalsIgnoreCase("POST")) { + + RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort()); + try { + xmlrpc.execute (request,response); + } catch (Throwable e) { + throw new ServletException(e); + } + } else { + response.setStatus(500); + } + } + + } + + protected Runnable doExport(T impl, Class type, URL url) throws RpcException { + final URL http_url = url.setProtocol("http"); + String addr = http_url.getIp() + ":" + http_url.getPort(); + HttpServer server = serverMap.get(addr); + if (server == null) { + server = httpBinder.bind(http_url, new InternalHandler(http_url.getParameter("cors", false))); + serverMap.put(addr, server); + } + final String path = http_url.getAbsolutePath(); + + XmlRpcServletServer xmlRpcServer = new XmlRpcServletServer(); + + PropertyHandlerMapping propertyHandlerMapping = new PropertyHandlerMapping(); + try { + + propertyHandlerMapping.setRequestProcessorFactoryFactory(new RequestProcessorFactoryFactory(){ + public RequestProcessorFactory getRequestProcessorFactory(Class pClass) throws XmlRpcException{ + return new RequestProcessorFactory(){ + public Object getRequestProcessor(XmlRpcRequest pRequest) throws XmlRpcException{ + return impl; + } + }; + } + }); + + propertyHandlerMapping.addHandler(XmlRpcProxyFactoryBean.replace(type.getName()),type); + + } catch (Exception e) { + throw new RpcException(e); + } + xmlRpcServer.setHandlerMapping(propertyHandlerMapping); + + XmlRpcServerConfigImpl xmlRpcServerConfig = (XmlRpcServerConfigImpl) xmlRpcServer.getConfig(); + xmlRpcServerConfig.setEnabledForExceptions(true); + xmlRpcServerConfig.setContentLengthOptional(false); + + skeletonMap.put(path, xmlRpcServer); + return new Runnable() { + public void run() { + skeletonMap.remove(path); + } + }; + } + + @SuppressWarnings("unchecked") + protected T doRefer(final Class serviceType, URL url) throws RpcException { + XmlRpcProxyFactoryBean xmlRpcProxyFactoryBean = new XmlRpcProxyFactoryBean(); + xmlRpcProxyFactoryBean.setServiceUrl(url.setProtocol("http").toIdentityString()); + xmlRpcProxyFactoryBean.setServiceInterface(serviceType); + xmlRpcProxyFactoryBean.afterPropertiesSet(); + return (T) xmlRpcProxyFactoryBean.getObject(); + } + + protected int getErrorCode(Throwable e) { + if (e instanceof RemoteAccessException) { + e = e.getCause(); + } + if (e != null) { + Class cls = e.getClass(); + if (SocketTimeoutException.class.equals(cls)) { + return RpcException.TIMEOUT_EXCEPTION; + } else if (IOException.class.isAssignableFrom(cls)) { + return RpcException.NETWORK_EXCEPTION; + } else if (ClassNotFoundException.class.isAssignableFrom(cls)) { + return RpcException.SERIALIZATION_EXCEPTION; + } + } + return super.getErrorCode(e); + } + + public void destroy() { + super.destroy(); + for (String key : new ArrayList<>(serverMap.keySet())) { + HttpServer server = serverMap.remove(key); + if (server != null) { + try { + if (logger.isInfoEnabled()) { + logger.info("Close xml server " + server.getUrl()); + } + server.close(); + } catch (Throwable t) { + logger.warn(t.getMessage(), t); + } + } + } + } +} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProxyFactoryBean.java b/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProxyFactoryBean.java new file mode 100644 index 00000000000..c720b22f507 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProxyFactoryBean.java @@ -0,0 +1,137 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.xml.rpc.protocol.xmlrpc; + +import org.apache.dubbo.rpc.RpcException; + +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; +import org.apache.xmlrpc.client.XmlRpcClient; +import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.remoting.support.UrlBasedRemoteAccessor; + +import java.lang.reflect.Method; +import java.lang.reflect.Type; +import java.net.MalformedURLException; +import java.net.URL; + +public class XmlRpcProxyFactoryBean extends UrlBasedRemoteAccessor + implements MethodInterceptor, + InitializingBean, + FactoryBean, + ApplicationContextAware { + + private Object proxyObject = null; + private XmlRpcClient xmlRpcClient = null; +// private Map extraHttpHeaders = new HashMap(); + + + private ApplicationContext applicationContext; + + /** + * {@inheritDoc} + */ + @Override + @SuppressWarnings("unchecked") + public void afterPropertiesSet() { + super.afterPropertiesSet(); + + // create proxy + proxyObject = ProxyFactory.getProxy(getServiceInterface(), this); + + // create XmlRpcHttpClient + try { + xmlRpcClient = new XmlRpcClient(); + + XmlRpcClientConfigImpl xmlRpcClientConfig = new XmlRpcClientConfigImpl(); + xmlRpcClientConfig.setServerURL(new URL(getServiceUrl())); + xmlRpcClient.setConfig(xmlRpcClientConfig); + + } catch (MalformedURLException mue) { + throw new RpcException(mue); + } + } + + /** + * {@inheritDoc} + */ + public Object invoke(MethodInvocation invocation) + throws Throwable { + + // handle toString() + Method method = invocation.getMethod(); + if (method.getDeclaringClass() == Object.class && method.getName().equals("toString")) { + return proxyObject.getClass().getName() + "@" + System.identityHashCode(proxyObject); + } + + // get return type + Type retType = (invocation.getMethod().getGenericReturnType() != null) + ? invocation.getMethod().getGenericReturnType() + : invocation.getMethod().getReturnType(); + + return xmlRpcClient.execute(replace(method.getDeclaringClass().getName())+"." + +invocation.getMethod().getName(),invocation.getArguments()); + +// // get arguments +// Object arguments = ReflectionUtil.parseArguments( +// invocation.getMethod(), invocation.getArguments(), useNamedParams); +// +// // invoke it +// return jsonRpcHttpClient.invoke( +// invocation.getMethod().getName(), +// arguments, +// retType, extraHttpHeaders); + } + + /** + * {@inheritDoc} + */ + public Object getObject() { + return proxyObject; + } + + /** + * {@inheritDoc} + */ + public Class getObjectType() { + return getServiceInterface(); + } + + /** + * {@inheritDoc} + */ + public boolean isSingleton() { + return true; + } + + /** + * {@inheritDoc} + */ + public void setApplicationContext(ApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } + + public static final String replace(String name) { + return name.replaceAll("\\.","_"); + } + +} diff --git a/dubbo-rpc/dubbo-rpc-xml/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.http.HttpBinder b/dubbo-rpc/dubbo-rpc-xml/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.http.HttpBinder new file mode 100644 index 00000000000..e9453f2021e --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-xml/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.http.HttpBinder @@ -0,0 +1 @@ +jetty9=org.apache.dubbo.remoting.http.jetty.JettyHttpBinder \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-xml/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol b/dubbo-rpc/dubbo-rpc-xml/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol new file mode 100644 index 00000000000..d2f1ce82cb5 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-xml/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol @@ -0,0 +1 @@ +xmlrpc=org.apache.dubbo.xml.rpc.protocol.xmlrpc.XmlRpcProtocol \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-xml/src/test/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocolTest.java b/dubbo-rpc/dubbo-rpc-xml/src/test/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocolTest.java new file mode 100644 index 00000000000..55b101c73cd --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-xml/src/test/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocolTest.java @@ -0,0 +1,86 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.xml.rpc.protocol.xmlrpc; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.extension.ExtensionLoader; +import org.apache.dubbo.rpc.Exporter; +import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.Protocol; +import org.apache.dubbo.rpc.ProxyFactory; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + + +public class XmlRpcProtocolTest { + + @Test + public void testXmlRpcProtocol() { + XmlRpcServiceImpl server = new XmlRpcServiceImpl(); + Assertions.assertFalse(server.isCalled()); + ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); + URL url = URL.valueOf("xmlrpc://127.0.0.1:5342/" + XmlRpcService.class.getName() + "?version=1.0.0"); + Exporter exporter = protocol.export(proxyFactory.getInvoker(server, XmlRpcService.class, url)); + Invoker invoker = protocol.refer(XmlRpcService.class, url); + XmlRpcService client = proxyFactory.getProxy(invoker); + String result = client.sayHello("haha"); + Assertions.assertTrue(server.isCalled()); + Assertions.assertEquals("Hello, haha", result); + invoker.destroy(); + exporter.unexport(); + } + + @Test + public void testXmlRpcProtocolForServerJetty9() { + XmlRpcServiceImpl server = new XmlRpcServiceImpl(); + Assertions.assertFalse(server.isCalled()); + ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); + URL url = URL.valueOf("xmlrpc://127.0.0.1:5342/" + XmlRpcService.class.getName() + "?version=1.0.0&server=jetty9"); + Exporter exporter = protocol.export(proxyFactory.getInvoker(server, XmlRpcService.class, url)); + Invoker invoker = protocol.refer(XmlRpcService.class, url); + XmlRpcService client = proxyFactory.getProxy(invoker); + String result = client.sayHello("haha"); + Assertions.assertTrue(server.isCalled()); + Assertions.assertEquals("Hello, haha", result); + invoker.destroy(); + exporter.unexport(); + } + + @Test + @Disabled + public void testCustomException() { + XmlRpcServiceImpl server = new XmlRpcServiceImpl(); + ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); + URL url = URL.valueOf("xmlrpc://127.0.0.1:5342/" + + XmlRpcService.class.getName() + "?version=1.0.0&server=jetty9"); + Exporter exporter = protocol.export(proxyFactory.getInvoker(server, XmlRpcService.class, url)); + Invoker invoker = protocol.refer(XmlRpcService.class, url); + XmlRpcService client = proxyFactory.getProxy(invoker); + try { + client.customException(); + Assertions.fail(); + } catch (XmlRpcServiceImpl.MyException expected) { + } + invoker.destroy(); + exporter.unexport(); + } + +} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-xml/src/test/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcService.java b/dubbo-rpc/dubbo-rpc-xml/src/test/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcService.java new file mode 100644 index 00000000000..3355ba6f412 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-xml/src/test/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcService.java @@ -0,0 +1,25 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.xml.rpc.protocol.xmlrpc; + +public interface XmlRpcService { + String sayHello(String name); + + void timeOut(int millis); + + String customException(); +} diff --git a/dubbo-rpc/dubbo-rpc-xml/src/test/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcServiceImpl.java b/dubbo-rpc/dubbo-rpc-xml/src/test/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcServiceImpl.java new file mode 100644 index 00000000000..0a6111d86af --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-xml/src/test/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcServiceImpl.java @@ -0,0 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.xml.rpc.protocol.xmlrpc; + +public class XmlRpcServiceImpl implements XmlRpcService { + private boolean called; + + public String sayHello(String name) { + called = true; + return "Hello, " + name; + } + + public boolean isCalled() { + return called; + } + + public void timeOut(int millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + public String customException() { + throw new MyException("custom exception"); + } + + static class MyException extends RuntimeException{ + + private static final long serialVersionUID = -3051041116483629056L; + + public MyException(String message) { + super(message); + } + } +} diff --git a/dubbo-rpc/pom.xml b/dubbo-rpc/pom.xml index ed95d9fca01..44b064f6978 100644 --- a/dubbo-rpc/pom.xml +++ b/dubbo-rpc/pom.xml @@ -42,5 +42,6 @@ dubbo-rpc-memcached dubbo-rpc-redis dubbo-rpc-rest + dubbo-rpc-xml From d24d61401b4d504ba1267e26e26dc575b0080e2b Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Tue, 14 May 2019 11:11:48 +0800 Subject: [PATCH 052/115] move MetadataReportConstants back into metata-report-api module (#4049) --- .../org/apache/dubbo/common/Constants.java | 18 ------------------ .../integration/MetadataReportService.java | 8 ++++---- .../support/AbstractMetadataReport.java | 16 +++++++++++----- .../dubbo/metadata/support/Constants.java | 4 ++-- .../store/redis/RedisMetadataReportTest.java | 2 +- 5 files changed, 18 insertions(+), 30 deletions(-) rename dubbo-common/src/main/java/org/apache/dubbo/common/constants/MetadataReportConstants.java => dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/Constants.java (93%) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java index 2c405c399af..acec182d039 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java @@ -180,24 +180,6 @@ public class Constants { public static final String ACCEPT_FOREIGN_IP = "qos.accept.foreign.ip"; // END dubbo-congfig-api - // BEGIN dubbo-metadata-report-api - public static final String METADATA_REPORT_KEY = "metadata"; - - public static final String RETRY_TIMES_KEY = "retry.times"; - - public static final Integer DEFAULT_METADATA_REPORT_RETRY_TIMES = 100; - - public static final String RETRY_PERIOD_KEY = "retry.period"; - - public static final Integer DEFAULT_METADATA_REPORT_RETRY_PERIOD = 3000; - - public static final String SYNC_REPORT_KEY = "sync.report"; - - public static final String CYCLE_REPORT_KEY = "cycle.report"; - - public static final Boolean DEFAULT_METADATA_REPORT_CYCLE_REPORT = true; - // END dubbo-metadata-report-api - // BEGIN dubbo-filter-cache public static final String CACHE_KEY = "cache"; // END dubbo-filter-cache diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/MetadataReportService.java b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/MetadataReportService.java index 9bcc541935a..e8789925eb1 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/MetadataReportService.java +++ b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/MetadataReportService.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.integration; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.constants.RemotingConstants; @@ -42,6 +41,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.metadata.support.Constants.METADATA_REPORT_KEY; /** * @since 2.7.0 @@ -58,11 +58,11 @@ public class MetadataReportService { URL metadataReportUrl; MetadataReportService(URL metadataReportURL) { - if (Constants.METADATA_REPORT_KEY.equals(metadataReportURL.getProtocol())) { - String protocol = metadataReportURL.getParameter(Constants.METADATA_REPORT_KEY, DEFAULT_DIRECTORY); + if (METADATA_REPORT_KEY.equals(metadataReportURL.getProtocol())) { + String protocol = metadataReportURL.getParameter(METADATA_REPORT_KEY, DEFAULT_DIRECTORY); metadataReportURL = URLBuilder.from(metadataReportURL) .setProtocol(protocol) - .removeParameter(Constants.METADATA_REPORT_KEY) + .removeParameter(METADATA_REPORT_KEY) .build(); } this.metadataReportUrl = metadataReportURL; diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java index 67f06e7bbd0..12085084cbd 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java +++ b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -56,6 +55,13 @@ import static org.apache.dubbo.common.constants.CommonConstants.FILE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; +import static org.apache.dubbo.metadata.support.Constants.CYCLE_REPORT_KEY; +import static org.apache.dubbo.metadata.support.Constants.DEFAULT_METADATA_REPORT_CYCLE_REPORT; +import static org.apache.dubbo.metadata.support.Constants.DEFAULT_METADATA_REPORT_RETRY_PERIOD; +import static org.apache.dubbo.metadata.support.Constants.DEFAULT_METADATA_REPORT_RETRY_TIMES; +import static org.apache.dubbo.metadata.support.Constants.RETRY_PERIOD_KEY; +import static org.apache.dubbo.metadata.support.Constants.RETRY_TIMES_KEY; +import static org.apache.dubbo.metadata.support.Constants.SYNC_REPORT_KEY; /** * @@ -102,11 +108,11 @@ public AbstractMetadataReport(URL reportServerURL) { } this.file = file; loadProperties(); - syncReport = reportServerURL.getParameter(Constants.SYNC_REPORT_KEY, false); - metadataReportRetry = new MetadataReportRetry(reportServerURL.getParameter(Constants.RETRY_TIMES_KEY, Constants.DEFAULT_METADATA_REPORT_RETRY_TIMES), - reportServerURL.getParameter(Constants.RETRY_PERIOD_KEY, Constants.DEFAULT_METADATA_REPORT_RETRY_PERIOD)); + syncReport = reportServerURL.getParameter(SYNC_REPORT_KEY, false); + metadataReportRetry = new MetadataReportRetry(reportServerURL.getParameter(RETRY_TIMES_KEY, DEFAULT_METADATA_REPORT_RETRY_TIMES), + reportServerURL.getParameter(RETRY_PERIOD_KEY, DEFAULT_METADATA_REPORT_RETRY_PERIOD)); // cycle report the data switch - if (reportServerURL.getParameter(Constants.CYCLE_REPORT_KEY, Constants.DEFAULT_METADATA_REPORT_CYCLE_REPORT)) { + if (reportServerURL.getParameter(CYCLE_REPORT_KEY, DEFAULT_METADATA_REPORT_CYCLE_REPORT)) { ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("DubboMetadataReportTimer", true)); scheduler.scheduleAtFixedRate(this::publishAll, calculateStartTime(), ONE_DAY_IN_MIll, TimeUnit.MILLISECONDS); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/MetadataReportConstants.java b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/Constants.java similarity index 93% rename from dubbo-common/src/main/java/org/apache/dubbo/common/constants/MetadataReportConstants.java rename to dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/Constants.java index ee1119d4e6e..3d74b2bbad9 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/MetadataReportConstants.java +++ b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/Constants.java @@ -15,9 +15,9 @@ * limitations under the License. */ -package org.apache.dubbo.common.constants; +package org.apache.dubbo.metadata.support; -public interface MetadataReportConstants { +public interface Constants { String METADATA_REPORT_KEY = "metadata"; String RETRY_TIMES_KEY = "retry.times"; diff --git a/dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java b/dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java index 5ec061130d0..63a2a39514a 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java +++ b/dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java @@ -38,9 +38,9 @@ import java.util.HashMap; import java.util.Map; -import static org.apache.dubbo.common.Constants.SYNC_REPORT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; +import static org.apache.dubbo.metadata.support.Constants.SYNC_REPORT_KEY; /** * 2018/10/9 From 0b380e32807e51ad9f6b61f27556915a184f9681 Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Tue, 14 May 2019 16:12:30 +0800 Subject: [PATCH 053/115] [DUBBO-3137]: step3, remove constants completely. (#4053) * [DUBBO-3137]: step3, start to use ConfigConstants, FilterConstants, and remove Constants.java completely. * remove Constants imports --- .../cluster/directory/AbstractDirectory.java | 4 +- .../router/condition/ConditionRouter.java | 4 +- .../support/AbstractClusterInvokerTest.java | 4 +- .../rpc/cluster/support/ClusterUtilsTest.java | 4 +- .../wrapper/MockClusterInvokerTest.java | 1 - .../org/apache/dubbo/common/Constants.java | 211 ------------------ .../java/org/apache/dubbo/common/URL.java | 20 +- .../common/config/ConfigurationUtils.java | 7 +- .../common/constants/ConfigConstants.java | 2 - .../apache/dubbo/common/utils/NetUtils.java | 6 +- .../apache/dubbo/common/utils/UrlUtils.java | 22 +- .../common/config/ConfigurationUtilsTest.java | 14 +- .../com/alibaba/dubbo/common/Constants.java | 12 +- .../dubbo/config/ApplicationConfigTest.java | 9 +- .../apache/dubbo/config/MethodConfigTest.java | 24 +- .../dubbo/config/RegistryConfigTest.java | 9 +- .../dubbo/config/AbstractInterfaceConfig.java | 43 ++-- .../dubbo/config/AbstractReferenceConfig.java | 4 +- .../dubbo/config/ApplicationConfig.java | 45 ++-- .../dubbo/config/ConfigCenterConfig.java | 28 ++- .../org/apache/dubbo/config/MethodConfig.java | 20 +- .../org/apache/dubbo/config/ModuleConfig.java | 11 +- .../apache/dubbo/config/ProtocolConfig.java | 19 +- .../apache/dubbo/config/ProviderConfig.java | 10 +- .../apache/dubbo/config/ReferenceConfig.java | 19 +- .../apache/dubbo/config/RegistryConfig.java | 18 +- .../apache/dubbo/config/ServiceConfig.java | 40 ++-- .../config/builders/ApplicationBuilder.java | 13 +- .../config/AbstractInterfaceConfigTest.java | 22 +- .../dubbo/config/ApplicationConfigTest.java | 10 +- .../apache/dubbo/config/MethodConfigTest.java | 19 +- .../dubbo/config/RegistryConfigTest.java | 10 +- .../dubbo/config/ServiceConfigTest.java | 23 +- .../config/url/InvokerSideConfigUrlTest.java | 45 ++-- .../config/spring/SimpleRegistryExporter.java | 4 +- .../apollo/ApolloDynamicConfiguration.java | 13 +- .../consul/ConsulDynamicConfiguration.java | 2 +- .../etcd/EtcdDynamicConfiguration.java | 19 +- .../nacos/NacosDynamicConfiguration.java | 4 +- .../ZookeeperDynamicConfiguration.java | 2 +- .../dubbo/cache/filter/CacheFilter.java | 10 +- .../apache/dubbo/validation/Validation.java | 5 +- .../validation/filter/ValidationFilter.java | 10 +- .../AbstractMetadataReportFactory.java | 6 +- .../MetadataReportServiceTest.java | 6 +- .../store/nacos/NacosMetadataReportTest.java | 12 +- .../monitor/dubbo/DubboMonitorFactory.java | 4 +- .../dubbo/monitor/dubbo/DubboMonitorTest.java | 11 +- .../dubbo/monitor/dubbo/StatisticsTest.java | 6 +- .../qos/protocol/QosProtocolWrapper.java | 6 +- .../qos/protocol/QosProtocolWrapperTest.java | 10 +- .../integration/RegistryDirectory.java | 7 +- .../integration/RegistryProtocol.java | 14 +- .../support/AbstractRegistryFactory.java | 5 +- .../registry/dubbo/DubboRegistryFactory.java | 22 +- .../registry/dubbo/RegistryDirectoryTest.java | 14 +- .../registry/dubbo/RegistryProtocolTest.java | 10 +- .../dubbo/SimpleRegistryExporter.java | 4 +- .../telnet/support/TelnetHandlerAdapter.java | 4 +- .../codec/DeprecatedTelnetCodec.java | 1 - .../grizzly/GrizzlyTransporterTest.java | 7 +- .../org/apache/dubbo/rpc/RpcConstants.java | 13 +- .../rpc/protocol/dubbo/DubboProtocol.java | 20 +- .../dubbo/DubboInvokerAvilableTest.java | 12 +- .../protocol/dubbo/DubboLazyConnectTest.java | 11 +- .../rpc/protocol/dubbo/FutureFilterTest.java | 6 +- .../protocol/dubbo/ImplicitCallBackTest.java | 1 - .../rpc/protocol/injvm/InjvmProtocol.java | 10 +- .../rpc/protocol/injvm/InjvmProtocolTest.java | 13 +- 69 files changed, 483 insertions(+), 573 deletions(-) delete mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java index 680cbfb6319..63369653f30 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.directory; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -32,6 +31,7 @@ import java.util.List; import java.util.Map; +import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; import static org.apache.dubbo.common.constants.MonitorConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; @@ -66,7 +66,7 @@ public AbstractDirectory(URL url, URL consumerUrl, RouterChain routerChain) { } if (url.getProtocol().equals(REGISTRY_PROTOCOL)) { - Map queryMap = StringUtils.parseQueryString(url.getParameterAndDecoded(Constants.REFER_KEY)); + Map queryMap = StringUtils.parseQueryString(url.getParameterAndDecoded(REFER_KEY)); this.url = url.addParameters(queryMap).removeParameter(MONITOR_KEY); } else { this.url = url; diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java index c8d625c7db5..f69b1854fda 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.router.condition; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -48,6 +47,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.HOST_KEY; /** * ConditionRouter @@ -233,7 +233,7 @@ private boolean matchCondition(Map condition, URL url, URL pa sampleValue = invocation.getMethodName(); } else if (ADDRESS_KEY.equals(key)) { sampleValue = url.getAddress(); - } else if (Constants.HOST_KEY.equals(key)) { + } else if (HOST_KEY.equals(key)) { sampleValue = url.getHost(); } else { sampleValue = sample.get(key); diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java index 6dcda9fe2fd..6f0b37b7c8f 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; @@ -50,6 +49,7 @@ import static org.apache.dubbo.common.constants.ClusterConstants.CLUSTER_AVAILABLE_CHECK_KEY; import static org.apache.dubbo.common.constants.ClusterConstants.INVOCATION_NEED_MOCK; +import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; import static org.apache.dubbo.common.constants.MonitorConstants.MONITOR_KEY; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -225,7 +225,7 @@ public void testSelect_multiInvokers() throws Exception { @Test public void testCloseAvailablecheck() { LoadBalance lb = mock(LoadBalance.class); - Map queryMap = StringUtils.parseQueryString(url.getParameterAndDecoded(Constants.REFER_KEY)); + Map queryMap = StringUtils.parseQueryString(url.getParameterAndDecoded(REFER_KEY)); URL tmpUrl = url.addParameters(queryMap).removeParameter(MONITOR_KEY); given(lb.select(invokers, tmpUrl, invocation)).willReturn(invoker1); initlistsize5(); diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ClusterUtilsTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ClusterUtilsTest.java index 8c093cd6ad7..5cdc25f30b9 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ClusterUtilsTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ClusterUtilsTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; @@ -33,6 +32,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; public class ClusterUtilsTest { @@ -62,7 +62,7 @@ public void testMergeUrl() throws Exception { .addParameter(DEFAULT_KEY_PREFIX + THREAD_NAME_KEY, "test") .build(); - URL consumerURL = new URLBuilder(Constants.DUBBO_PROTOCOL, "localhost", 55555) + URL consumerURL = new URLBuilder(DUBBO_PROTOCOL, "localhost", 55555) .addParameter(PID_KEY, "1234") .addParameter(THREADPOOL_KEY, "foo") .build(); diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java index ba9caa8f5d9..71245539680 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.support.wrapper; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.rpc.Invocation; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java deleted file mode 100644 index acec182d039..00000000000 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/Constants.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.dubbo.common; - - -import static org.apache.dubbo.common.constants.CommonConstants.DUBBO; - -/** - * Constants - */ -public class Constants { - - - - - // BEGIN dubbo-config-api - public static final String CLUSTER_KEY = "cluster"; - - public static final String STATUS_KEY = "status"; - - public static final String CONTEXTPATH_KEY = "contextpath"; - - public static final String LISTENER_KEY = "listener"; - - public static final String LAYER_KEY = "layer"; - - /** - * General - */ - /** - * Application name; - */ - public static final String NAME = "name"; - - /** - * Application owner name; - */ - public static final String OWNER = "owner"; - - /** - * Running application organization name. - */ - public static final String ORGANIZATION = "organization"; - - /** - * Application architecture name. - */ - public static final String ARCHITECTURE = "architecture"; - - /** - * Environment name - */ - public static final String ENVIRONMENT = "environment"; - - /** - * Test environment key. - */ - public static final String TEST_ENVIRONMENT = "test"; - - /** - * Development environment key. - */ - public static final String DEVELOPMENT_ENVIRONMENT = "develop"; - - /** - * Production environment key. - */ - public static final String PRODUCTION_ENVIRONMENT = "product"; - - public static final String CONFIG_CLUSTER_KEY = "config.cluster"; - public static final String CONFIG_NAMESPACE_KEY = "config.namespace"; - public static final String CONFIG_GROUP_KEY = "config.group"; - public static final String CONFIG_CHECK_KEY = "config.check"; - - public static final String CONFIG_CONFIGFILE_KEY = "config.config-file"; - public static final String CONFIG_ENABLE_KEY = "config.highest-priority"; - public static final String CONFIG_TIMEOUT_KEY = "config.timeout"; - public static final String CONFIG_APPNAME_KEY = "config.app-name"; - - public static final String USERNAME_KEY = "username"; - - public static final String PASSWORD_KEY = "password"; - - public static final String HOST_KEY = "host"; - - public static final String PORT_KEY = "port"; - - public static final String MULTICAST = "multicast"; - - public static final String REGISTER_IP_KEY = "register.ip"; - - public static final String DUBBO_IP_TO_REGISTRY = "DUBBO_IP_TO_REGISTRY"; - - public static final String DUBBO_PORT_TO_REGISTRY = "DUBBO_PORT_TO_REGISTRY"; - - public static final String DUBBO_IP_TO_BIND = "DUBBO_IP_TO_BIND"; - - public static final String DUBBO_PORT_TO_BIND = "DUBBO_PORT_TO_BIND"; - - public static final String SCOPE_KEY = "scope"; - - public static final String SCOPE_LOCAL = "local"; - - public static final String SCOPE_REMOTE = "remote"; - - public static final String SCOPE_NONE = "none"; - - public static final String ON_CONNECT_KEY = "onconnect"; - - public static final String ON_DISCONNECT_KEY = "ondisconnect"; - - public static final String ON_INVOKE_METHOD_KEY = "oninvoke.method"; - - public static final String ON_RETURN_METHOD_KEY = "onreturn.method"; - - public static final String ON_THROW_METHOD_KEY = "onthrow.method"; - - public static final String ON_INVOKE_INSTANCE_KEY = "oninvoke.instance"; - - public static final String ON_RETURN_INSTANCE_KEY = "onreturn.instance"; - - public static final String ON_THROW_INSTANCE_KEY = "onthrow.instance"; - - @Deprecated - public static final String SHUTDOWN_WAIT_SECONDS_KEY = "dubbo.service.shutdown.wait.seconds"; - - public static final String SHUTDOWN_WAIT_KEY = "dubbo.service.shutdown.wait"; - - /** - * The key name for export URL in register center - */ - public static final String EXPORT_KEY = "export"; - - /** - * The key name for reference URL in register center - */ - public static final String REFER_KEY = "refer"; - - /** - * To decide whether to make connection when the client is created - */ - public static final String LAZY_CONNECT_KEY = "lazy"; - - public static final String DUBBO_PROTOCOL = DUBBO; - - public static final String ZOOKEEPER_PROTOCOL = "zookeeper"; - - // FIXME: is this still useful? - public static final String SHUTDOWN_TIMEOUT_KEY = "shutdown.timeout"; - - public static final int DEFAULT_SHUTDOWN_TIMEOUT = 1000 * 60 * 15; - - public static final String PROTOCOLS_SUFFIX = "dubbo.protocols."; - - public static final String PROTOCOL_SUFFIX = "dubbo.protocol."; - - public static final String REGISTRIES_SUFFIX = "dubbo.registries."; - - public static final String TELNET = "telnet"; - - public static final String QOS_ENABLE = "qos.enable"; - - public static final String QOS_PORT = "qos.port"; - - public static final String ACCEPT_FOREIGN_IP = "qos.accept.foreign.ip"; - // END dubbo-congfig-api - - // BEGIN dubbo-filter-cache - public static final String CACHE_KEY = "cache"; - // END dubbo-filter-cache - - - // BEGIN dubbo-filter-validation - public static final String VALIDATION_KEY = "validation"; - // END dubbo-filter-validation - - public static final String DEFAULT_CLUSTER = "failover"; - - /** - * public static final int DEFAULT_REGISTRY_CONNECT_TIMEOUT = 5000; - */ - - public static final String DIRECTORY_KEY = "directory"; - - public static final String ASYNC_SUFFIX = "Async"; - - public static final String WAIT_KEY = "wait"; - - public static final String HESSIAN_VERSION_KEY = "hessian.version"; - - - public static final String CONFIG_PROTOCOL = "config"; - - - public static final String RELIABLE_PROTOCOL = "napoli"; -} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java b/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java index c71bc9055fc..b67b917b1de 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java @@ -40,6 +40,8 @@ import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; +import static org.apache.dubbo.common.constants.ConfigConstants.HOST_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.PORT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; @@ -50,6 +52,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.PASSWORD_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.USERNAME_KEY; /** * URL - Uniform Resource Locator (Immutable, ThreadSafe) @@ -1137,16 +1141,16 @@ public String getRawParameter(String key) { if (PROTOCOL_KEY.equals(key)) { return protocol; } - if (Constants.USERNAME_KEY.equals(key)) { + if (USERNAME_KEY.equals(key)) { return username; } - if (Constants.PASSWORD_KEY.equals(key)) { + if (PASSWORD_KEY.equals(key)) { return password; } - if (Constants.HOST_KEY.equals(key)) { + if (HOST_KEY.equals(key)) { return host; } - if (Constants.PORT_KEY.equals(key)) { + if (PORT_KEY.equals(key)) { return String.valueOf(port); } if (PATH_KEY.equals(key)) { @@ -1161,16 +1165,16 @@ public Map toMap() { map.put(PROTOCOL_KEY, protocol); } if (username != null) { - map.put(Constants.USERNAME_KEY, username); + map.put(USERNAME_KEY, username); } if (password != null) { - map.put(Constants.USERNAME_KEY, password); + map.put(USERNAME_KEY, password); } if (host != null) { - map.put(Constants.HOST_KEY, host); + map.put(HOST_KEY, host); } if (port > 0) { - map.put(Constants.PORT_KEY, String.valueOf(port)); + map.put(PORT_KEY, String.valueOf(port)); } if (path != null) { map.put(PATH_KEY, path); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java index a9425fafa63..29699acea5b 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.config; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; @@ -28,6 +27,8 @@ import java.util.Properties; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_SERVER_SHUTDOWN_TIMEOUT; +import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_SECONDS_KEY; /** * Utilities for manipulating configurations from different sources @@ -40,7 +41,7 @@ public class ConfigurationUtils { public static int getServerShutdownTimeout() { int timeout = DEFAULT_SERVER_SHUTDOWN_TIMEOUT; Configuration configuration = Environment.getInstance().getConfiguration(); - String value = StringUtils.trim(configuration.getString(Constants.SHUTDOWN_WAIT_KEY)); + String value = StringUtils.trim(configuration.getString(SHUTDOWN_WAIT_KEY)); if (value != null && value.length() > 0) { try { @@ -49,7 +50,7 @@ public static int getServerShutdownTimeout() { // ignore } } else { - value = StringUtils.trim(configuration.getString(Constants.SHUTDOWN_WAIT_SECONDS_KEY)); + value = StringUtils.trim(configuration.getString(SHUTDOWN_WAIT_SECONDS_KEY)); if (value != null && value.length() > 0) { try { timeout = Integer.parseInt(value) * 1000; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ConfigConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ConfigConstants.java index 5899641a625..7f6351e605f 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ConfigConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ConfigConstants.java @@ -21,7 +21,6 @@ * ConfigConstants */ public interface ConfigConstants { - // BEGIN dubbo-config-api String CLUSTER_KEY = "cluster"; String STATUS_KEY = "status"; @@ -171,5 +170,4 @@ public interface ConfigConstants { String QOS_PORT = "qos.port"; String ACCEPT_FOREIGN_IP = "qos.accept.foreign.ip"; - // END dubbo-congfig-api } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java index b5ca11e8c34..916fdcd185b 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.utils; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.logger.Logger; @@ -37,9 +36,10 @@ import java.util.concurrent.ThreadLocalRandom; import java.util.regex.Pattern; -import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_VALUE; +import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_IP_TO_BIND; /** * IP and Port Helper for RPC @@ -208,7 +208,7 @@ public static String filterLocalHost(String host) { } public static String getIpByConfig() { - String configIp = ConfigurationUtils.getProperty(Constants.DUBBO_IP_TO_BIND); + String configIp = ConfigurationUtils.getProperty(DUBBO_IP_TO_BIND); if (configIp != null) { return configIp; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java index cca3b29b897..6cac0e0630e 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.utils; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; @@ -39,6 +38,11 @@ import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.REMOVE_VALUE_PREFIX; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; +import static org.apache.dubbo.common.constants.ConfigConstants.HOST_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.PASSWORD_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.PORT_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.USERNAME_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; @@ -78,19 +82,19 @@ public static URL parseURL(String address, Map defaults) { } String defaultProtocol = defaults == null ? null : defaults.get(PROTOCOL_KEY); if (defaultProtocol == null || defaultProtocol.length() == 0) { - defaultProtocol = Constants.DUBBO_PROTOCOL; + defaultProtocol = DUBBO_PROTOCOL; } - String defaultUsername = defaults == null ? null : defaults.get(Constants.USERNAME_KEY); - String defaultPassword = defaults == null ? null : defaults.get(Constants.PASSWORD_KEY); - int defaultPort = StringUtils.parseInteger(defaults == null ? null : defaults.get(Constants.PORT_KEY)); + String defaultUsername = defaults == null ? null : defaults.get(USERNAME_KEY); + String defaultPassword = defaults == null ? null : defaults.get(PASSWORD_KEY); + int defaultPort = StringUtils.parseInteger(defaults == null ? null : defaults.get(PORT_KEY)); String defaultPath = defaults == null ? null : defaults.get(PATH_KEY); Map defaultParameters = defaults == null ? null : new HashMap(defaults); if (defaultParameters != null) { defaultParameters.remove(PROTOCOL_KEY); - defaultParameters.remove(Constants.USERNAME_KEY); - defaultParameters.remove(Constants.PASSWORD_KEY); - defaultParameters.remove(Constants.HOST_KEY); - defaultParameters.remove(Constants.PORT_KEY); + defaultParameters.remove(USERNAME_KEY); + defaultParameters.remove(PASSWORD_KEY); + defaultParameters.remove(HOST_KEY); + defaultParameters.remove(PORT_KEY); defaultParameters.remove(PATH_KEY); } URL u = URL.valueOf(url); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/config/ConfigurationUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/config/ConfigurationUtilsTest.java index a16a3748310..d741e6d88dc 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/config/ConfigurationUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/config/ConfigurationUtilsTest.java @@ -16,13 +16,13 @@ */ package org.apache.dubbo.common.config; -import org.apache.dubbo.common.Constants; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Map; +import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; + /** * */ @@ -30,16 +30,16 @@ public class ConfigurationUtilsTest { @Test public void testGetServerShutdownTimeout () { - System.setProperty(Constants.SHUTDOWN_WAIT_KEY, " 10000"); + System.setProperty(SHUTDOWN_WAIT_KEY, " 10000"); Assertions.assertEquals(10000, ConfigurationUtils.getServerShutdownTimeout()); - System.clearProperty(Constants.SHUTDOWN_WAIT_KEY); + System.clearProperty(SHUTDOWN_WAIT_KEY); } @Test public void testGetProperty () { - System.setProperty(Constants.SHUTDOWN_WAIT_KEY, " 10000"); - Assertions.assertEquals("10000", ConfigurationUtils.getProperty(Constants.SHUTDOWN_WAIT_KEY)); - System.clearProperty(Constants.SHUTDOWN_WAIT_KEY); + System.setProperty(SHUTDOWN_WAIT_KEY, " 10000"); + Assertions.assertEquals("10000", ConfigurationUtils.getProperty(SHUTDOWN_WAIT_KEY)); + System.clearProperty(SHUTDOWN_WAIT_KEY); } @Test diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java index 10a28831a23..b862f9e7e78 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java @@ -17,6 +17,16 @@ package com.alibaba.dubbo.common; +import org.apache.dubbo.common.constants.ClusterConstants; +import org.apache.dubbo.common.constants.CommonConstants; +import org.apache.dubbo.common.constants.ConfigConstants; +import org.apache.dubbo.common.constants.FilterConstants; +import org.apache.dubbo.common.constants.MonitorConstants; +import org.apache.dubbo.common.constants.RegistryConstants; +import org.apache.dubbo.common.constants.RemotingConstants; +import org.apache.dubbo.common.constants.RpcConstants; + @Deprecated -public class Constants extends org.apache.dubbo.common.Constants { +public class Constants implements ClusterConstants, CommonConstants, ConfigConstants, FilterConstants, + MonitorConstants, RegistryConstants, RemotingConstants, RpcConstants { } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java index c7998b2145f..40fb9370f21 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java @@ -17,7 +17,6 @@ package org.apache.dubbo.config; -import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.config.ApplicationConfig; import com.alibaba.dubbo.config.MonitorConfig; import com.alibaba.dubbo.config.RegistryConfig; @@ -30,6 +29,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DUMP_DIRECTORY; +import static org.apache.dubbo.common.constants.ConfigConstants.ACCEPT_FOREIGN_IP; +import static org.apache.dubbo.common.constants.ConfigConstants.QOS_ENABLE; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; @@ -152,7 +153,7 @@ public void testQosEnable() throws Exception { assertThat(application.getQosEnable(), is(true)); Map parameters = new HashMap(); ApplicationConfig.appendParameters(parameters, application); - assertThat(parameters, hasEntry(Constants.QOS_ENABLE, "true")); + assertThat(parameters, hasEntry(QOS_ENABLE, "true")); } @Test @@ -169,7 +170,7 @@ public void testQosAcceptForeignIp() throws Exception { assertThat(application.getQosAcceptForeignIp(), is(true)); Map parameters = new HashMap(); ApplicationConfig.appendParameters(parameters, application); - assertThat(parameters, hasEntry(Constants.ACCEPT_FOREIGN_IP, "true")); + assertThat(parameters, hasEntry(ACCEPT_FOREIGN_IP, "true")); } @Test @@ -180,6 +181,6 @@ public void testParameters() throws Exception { parameters.put("k1", "v1"); ApplicationConfig.appendParameters(parameters, application); assertThat(parameters, hasEntry("k1", "v1")); - assertThat(parameters, hasEntry(Constants.ACCEPT_FOREIGN_IP, "true")); + assertThat(parameters, hasEntry(ACCEPT_FOREIGN_IP, "true")); } } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/MethodConfigTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/MethodConfigTest.java index 075c5548085..1681dd4d9dd 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/MethodConfigTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/MethodConfigTest.java @@ -20,10 +20,8 @@ import org.apache.dubbo.rpc.model.ConsumerMethodModel; import org.apache.dubbo.service.Person; -import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.config.ArgumentConfig; import com.alibaba.dubbo.config.MethodConfig; - import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; @@ -31,13 +29,19 @@ import java.util.HashMap; import java.util.Map; +import static org.apache.dubbo.common.constants.ConfigConstants.ON_INVOKE_INSTANCE_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.ON_INVOKE_METHOD_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.ON_RETURN_INSTANCE_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.ON_RETURN_METHOD_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.ON_THROW_INSTANCE_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.ON_THROW_METHOD_KEY; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertTrue; public class MethodConfigTest { @@ -120,7 +124,7 @@ public void testOnreturn() throws Exception { assertThat(method.getOnreturn(), equalTo((Object) "on-return-object")); Map attribute = new HashMap(); MethodConfig.appendAttributes(attribute, method); - assertThat(attribute, hasEntry((Object) Constants.ON_RETURN_INSTANCE_KEY, (Object) "on-return-object")); + assertThat(attribute, hasEntry((Object) ON_RETURN_INSTANCE_KEY, (Object) "on-return-object")); Map parameters = new HashMap(); MethodConfig.appendParameters(parameters, method); assertThat(parameters.size(), is(0)); @@ -133,7 +137,7 @@ public void testOnreturnMethod() throws Exception { assertThat(method.getOnreturnMethod(), equalTo("on-return-method")); Map attribute = new HashMap(); MethodConfig.appendAttributes(attribute, method); - assertThat(attribute, hasEntry((Object) Constants.ON_RETURN_METHOD_KEY, (Object) "on-return-method")); + assertThat(attribute, hasEntry((Object) ON_RETURN_METHOD_KEY, (Object) "on-return-method")); Map parameters = new HashMap(); MethodConfig.appendParameters(parameters, method); assertThat(parameters.size(), is(0)); @@ -146,7 +150,7 @@ public void testOnthrow() throws Exception { assertThat(method.getOnthrow(), equalTo((Object) "on-throw-object")); Map attribute = new HashMap(); MethodConfig.appendAttributes(attribute, method); - assertThat(attribute, hasEntry((Object) Constants.ON_THROW_INSTANCE_KEY, (Object) "on-throw-object")); + assertThat(attribute, hasEntry((Object) ON_THROW_INSTANCE_KEY, (Object) "on-throw-object")); Map parameters = new HashMap(); MethodConfig.appendParameters(parameters, method); assertThat(parameters.size(), is(0)); @@ -159,7 +163,7 @@ public void testOnthrowMethod() throws Exception { assertThat(method.getOnthrowMethod(), equalTo("on-throw-method")); Map attribute = new HashMap(); MethodConfig.appendAttributes(attribute, method); - assertThat(attribute, hasEntry((Object) Constants.ON_THROW_METHOD_KEY, (Object) "on-throw-method")); + assertThat(attribute, hasEntry((Object) ON_THROW_METHOD_KEY, (Object) "on-throw-method")); Map parameters = new HashMap(); MethodConfig.appendParameters(parameters, method); assertThat(parameters.size(), is(0)); @@ -172,7 +176,7 @@ public void testOninvoke() throws Exception { assertThat(method.getOninvoke(), equalTo((Object) "on-invoke-object")); Map attribute = new HashMap(); MethodConfig.appendAttributes(attribute, method); - assertThat(attribute, hasEntry((Object) Constants.ON_INVOKE_INSTANCE_KEY, (Object) "on-invoke-object")); + assertThat(attribute, hasEntry((Object) ON_INVOKE_INSTANCE_KEY, (Object) "on-invoke-object")); Map parameters = new HashMap(); MethodConfig.appendParameters(parameters, method); assertThat(parameters.size(), is(0)); @@ -185,7 +189,7 @@ public void testOninvokeMethod() throws Exception { assertThat(method.getOninvokeMethod(), equalTo("on-invoke-method")); Map attribute = new HashMap(); MethodConfig.appendAttributes(attribute, method); - assertThat(attribute, hasEntry((Object) Constants.ON_INVOKE_METHOD_KEY, (Object) "on-invoke-method")); + assertThat(attribute, hasEntry((Object) ON_INVOKE_METHOD_KEY, (Object) "on-invoke-method")); Map parameters = new HashMap(); MethodConfig.appendParameters(parameters, method); assertThat(parameters.size(), is(0)); @@ -197,4 +201,4 @@ public void testReturn() throws Exception { method.setReturn(true); assertThat(method.isReturn(), is(true)); } -} \ No newline at end of file +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java index 3b66191b17b..746eee97c92 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java @@ -17,21 +17,20 @@ package org.apache.dubbo.config; -import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.config.RegistryConfig; - import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.HashMap; import java.util.Map; +import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.not; -import static org.hamcrest.MatcherAssert.assertThat; public class RegistryConfigTest { @Test @@ -70,7 +69,7 @@ public void testWait() throws Exception { RegistryConfig registry = new RegistryConfig(); registry.setWait(10); assertThat(registry.getWait(), is(10)); - assertThat(System.getProperty(Constants.SHUTDOWN_WAIT_KEY), equalTo("10")); + assertThat(System.getProperty(SHUTDOWN_WAIT_KEY), equalTo("10")); } @Test @@ -173,4 +172,4 @@ public void testDefault() throws Exception { registry.setDefault(true); assertThat(registry.isDefault(), is(true)); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java index 6f8454afef7..cd04ac85d22 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.Version; @@ -65,6 +64,16 @@ import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.CLUSTER_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_IP_TO_REGISTRY; +import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; +import static org.apache.dubbo.common.constants.ConfigConstants.LAYER_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.LISTENER_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.REGISTER_IP_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.REGISTRIES_SUFFIX; +import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_SECONDS_KEY; import static org.apache.dubbo.common.constants.MonitorConstants.LOGSTAT_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY; @@ -211,13 +220,13 @@ protected void checkApplication() { ApplicationModel.setApplication(application.getName()); // backward compatibility - String wait = ConfigUtils.getProperty(Constants.SHUTDOWN_WAIT_KEY); + String wait = ConfigUtils.getProperty(SHUTDOWN_WAIT_KEY); if (wait != null && wait.trim().length() > 0) { - System.setProperty(Constants.SHUTDOWN_WAIT_KEY, wait.trim()); + System.setProperty(SHUTDOWN_WAIT_KEY, wait.trim()); } else { - wait = ConfigUtils.getProperty(Constants.SHUTDOWN_WAIT_SECONDS_KEY); + wait = ConfigUtils.getProperty(SHUTDOWN_WAIT_SECONDS_KEY); if (wait != null && wait.trim().length() > 0) { - System.setProperty(Constants.SHUTDOWN_WAIT_SECONDS_KEY, wait.trim()); + System.setProperty(SHUTDOWN_WAIT_SECONDS_KEY, wait.trim()); } } } @@ -330,7 +339,7 @@ protected List loadRegistries(boolean provider) { map.put(PATH_KEY, RegistryService.class.getName()); appendRuntimeParameters(map); if (!map.containsKey(PROTOCOL_KEY)) { - map.put(PROTOCOL_KEY, Constants.DUBBO_PROTOCOL); + map.put(PROTOCOL_KEY, DUBBO_PROTOCOL); } List urls = UrlUtils.parseURLs(address, map); @@ -363,14 +372,14 @@ protected URL loadMonitor(URL registryURL) { map.put(INTERFACE_KEY, MonitorService.class.getName()); appendRuntimeParameters(map); //set ip - String hostToRegistry = ConfigUtils.getSystemProperty(Constants.DUBBO_IP_TO_REGISTRY); + String hostToRegistry = ConfigUtils.getSystemProperty(DUBBO_IP_TO_REGISTRY); if (StringUtils.isEmpty(hostToRegistry)) { hostToRegistry = NetUtils.getLocalHost(); } else if (NetUtils.isInvalidLocalHost(hostToRegistry)) { throw new IllegalArgumentException("Specified invalid registry ip from property:" + - Constants.DUBBO_IP_TO_REGISTRY + ", value:" + hostToRegistry); + DUBBO_IP_TO_REGISTRY + ", value:" + hostToRegistry); } - map.put(Constants.REGISTER_IP_KEY, hostToRegistry); + map.put(REGISTER_IP_KEY, hostToRegistry); appendParameters(map, monitor); appendParameters(map, application); String address = monitor.getAddress(); @@ -383,15 +392,15 @@ protected URL loadMonitor(URL registryURL) { if (getExtensionLoader(MonitorFactory.class).hasExtension(LOGSTAT_PROTOCOL)) { map.put(PROTOCOL_KEY, LOGSTAT_PROTOCOL); } else { - map.put(PROTOCOL_KEY, Constants.DUBBO_PROTOCOL); + map.put(PROTOCOL_KEY, DUBBO_PROTOCOL); } } return UrlUtils.parseURL(address, map); } else if (REGISTRY_PROTOCOL.equals(monitor.getProtocol()) && registryURL != null) { return URLBuilder.from(registryURL) - .setProtocol(Constants.DUBBO_PROTOCOL) + .setProtocol(DUBBO_PROTOCOL) .addParameter(PROTOCOL_KEY, REGISTRY_PROTOCOL) - .addParameterAndEncoded(Constants.REFER_KEY, StringUtils.toQueryString(map)) + .addParameterAndEncoded(REFER_KEY, StringUtils.toQueryString(map)) .build(); } return null; @@ -538,9 +547,9 @@ private void convertRegistryIdsToRegistries() { if (StringUtils.isEmpty(registryIds) && CollectionUtils.isEmpty(registries)) { Set configedRegistries = new HashSet<>(); configedRegistries.addAll(getSubProperties(Environment.getInstance().getExternalConfigurationMap(), - Constants.REGISTRIES_SUFFIX)); + REGISTRIES_SUFFIX)); configedRegistries.addAll(getSubProperties(Environment.getInstance().getAppExternalConfigurationMap(), - Constants.REGISTRIES_SUFFIX)); + REGISTRIES_SUFFIX)); registryIds = String.join(COMMA_SEPARATOR, configedRegistries); } @@ -674,7 +683,7 @@ public String getCluster() { } public void setCluster(String cluster) { - checkExtension(Cluster.class, Constants.CLUSTER_KEY, cluster); + checkExtension(Cluster.class, CLUSTER_KEY, cluster); this.cluster = cluster; } @@ -711,7 +720,7 @@ public String getListener() { } public void setListener(String listener) { - checkMultiExtension(InvokerListener.class, Constants.LISTENER_KEY, listener); + checkMultiExtension(InvokerListener.class, LISTENER_KEY, listener); this.listener = listener; } @@ -720,7 +729,7 @@ public String getLayer() { } public void setLayer(String layer) { - checkNameHasSymbol(Constants.LAYER_KEY, layer); + checkNameHasSymbol(LAYER_KEY, layer); this.layer = layer; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java index 3ff25fe21ef..80409f23d05 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.config.support.Parameter; import org.apache.dubbo.rpc.InvokerListener; @@ -25,6 +24,7 @@ import static org.apache.dubbo.common.constants.ClusterConstants.CLUSTER_STICKY_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.LAZY_CONNECT_KEY; import static org.apache.dubbo.common.constants.RpcConstants.INVOKER_LISTENER_KEY; import static org.apache.dubbo.common.constants.RpcConstants.REFERENCE_FILTER_KEY; import static org.apache.dubbo.common.constants.RpcConstants.STUB_EVENT_KEY; @@ -157,7 +157,7 @@ public void setListener(String listener) { super.setListener(listener); } - @Parameter(key = Constants.LAZY_CONNECT_KEY) + @Parameter(key = LAZY_CONNECT_KEY) public Boolean getLazy() { return lazy; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java index 1aa364a0b74..5c13c0bd9c7 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.compiler.support.AdaptiveCompiler; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; @@ -29,6 +28,18 @@ import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DUMP_DIRECTORY; +import static org.apache.dubbo.common.constants.ConfigConstants.ACCEPT_FOREIGN_IP; +import static org.apache.dubbo.common.constants.ConfigConstants.ARCHITECTURE; +import static org.apache.dubbo.common.constants.ConfigConstants.DEVELOPMENT_ENVIRONMENT; +import static org.apache.dubbo.common.constants.ConfigConstants.ENVIRONMENT; +import static org.apache.dubbo.common.constants.ConfigConstants.NAME; +import static org.apache.dubbo.common.constants.ConfigConstants.ORGANIZATION; +import static org.apache.dubbo.common.constants.ConfigConstants.OWNER; +import static org.apache.dubbo.common.constants.ConfigConstants.PRODUCTION_ENVIRONMENT; +import static org.apache.dubbo.common.constants.ConfigConstants.QOS_ENABLE; +import static org.apache.dubbo.common.constants.ConfigConstants.QOS_PORT; +import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.TEST_ENVIRONMENT; /** @@ -139,7 +150,7 @@ public String getName() { } public void setName(String name) { - checkName(Constants.NAME, name); + checkName(NAME, name); this.name = name; if (StringUtils.isEmpty(id)) { id = name; @@ -160,7 +171,7 @@ public String getOwner() { } public void setOwner(String owner) { - checkMultiName(Constants.OWNER, owner); + checkMultiName(OWNER, owner); this.owner = owner; } @@ -169,7 +180,7 @@ public String getOrganization() { } public void setOrganization(String organization) { - checkName(Constants.ORGANIZATION, organization); + checkName(ORGANIZATION, organization); this.organization = organization; } @@ -178,7 +189,7 @@ public String getArchitecture() { } public void setArchitecture(String architecture) { - checkName(Constants.ARCHITECTURE, architecture); + checkName(ARCHITECTURE, architecture); this.architecture = architecture; } @@ -187,18 +198,18 @@ public String getEnvironment() { } public void setEnvironment(String environment) { - checkName(Constants.ENVIRONMENT, environment); + checkName(ENVIRONMENT, environment); if (environment != null) { - if (!(Constants.DEVELOPMENT_ENVIRONMENT.equals(environment) - || Constants.TEST_ENVIRONMENT.equals(environment) - || Constants.PRODUCTION_ENVIRONMENT.equals(environment))) { + if (!(DEVELOPMENT_ENVIRONMENT.equals(environment) + || TEST_ENVIRONMENT.equals(environment) + || PRODUCTION_ENVIRONMENT.equals(environment))) { throw new IllegalStateException(String.format("Unsupported environment: %s, only support %s/%s/%s, default is %s.", environment, - Constants.DEVELOPMENT_ENVIRONMENT, - Constants.TEST_ENVIRONMENT, - Constants.PRODUCTION_ENVIRONMENT, - Constants.PRODUCTION_ENVIRONMENT)); + DEVELOPMENT_ENVIRONMENT, + TEST_ENVIRONMENT, + PRODUCTION_ENVIRONMENT, + PRODUCTION_ENVIRONMENT)); } } this.environment = environment; @@ -279,7 +290,7 @@ public void setDumpDirectory(String dumpDirectory) { this.dumpDirectory = dumpDirectory; } - @Parameter(key = Constants.QOS_ENABLE) + @Parameter(key = QOS_ENABLE) public Boolean getQosEnable() { return qosEnable; } @@ -288,7 +299,7 @@ public void setQosEnable(Boolean qosEnable) { this.qosEnable = qosEnable; } - @Parameter(key = Constants.QOS_PORT) + @Parameter(key = QOS_PORT) public Integer getQosPort() { return qosPort; } @@ -297,7 +308,7 @@ public void setQosPort(Integer qosPort) { this.qosPort = qosPort; } - @Parameter(key = Constants.ACCEPT_FOREIGN_IP) + @Parameter(key = ACCEPT_FOREIGN_IP) public Boolean getQosAcceptForeignIp() { return qosAcceptForeignIp; } @@ -320,7 +331,7 @@ public String getShutwait() { } public void setShutwait(String shutwait) { - System.setProperty(Constants.SHUTDOWN_WAIT_KEY, shutwait); + System.setProperty(SHUTDOWN_WAIT_KEY, shutwait); this.shutwait = shutwait; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java index 6870b1aaa55..5334f0492c5 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.Environment; import org.apache.dubbo.common.utils.StringUtils; @@ -29,6 +28,15 @@ import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_APPNAME_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_CHECK_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_CLUSTER_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_CONFIGFILE_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_ENABLE_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_GROUP_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_NAMESPACE_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.ZOOKEEPER_PROTOCOL; /** * ConfigCenterConfig @@ -65,7 +73,7 @@ public URL toUrl() { map.put(PATH_KEY, ConfigCenterConfig.class.getSimpleName()); // use 'zookeeper' as the default configcenter. if (StringUtils.isEmpty(map.get(PROTOCOL_KEY))) { - map.put(PROTOCOL_KEY, Constants.ZOOKEEPER_PROTOCOL); + map.put(PROTOCOL_KEY, ZOOKEEPER_PROTOCOL); } return UrlUtils.parseURL(address, map); } @@ -99,7 +107,7 @@ public void setAddress(String address) { this.address = address; } - @Parameter(key = Constants.CONFIG_CLUSTER_KEY, useKeyAsProperty = false) + @Parameter(key = CONFIG_CLUSTER_KEY, useKeyAsProperty = false) public String getCluster() { return cluster; } @@ -108,7 +116,7 @@ public void setCluster(String cluster) { this.cluster = cluster; } - @Parameter(key = Constants.CONFIG_NAMESPACE_KEY, useKeyAsProperty = false) + @Parameter(key = CONFIG_NAMESPACE_KEY, useKeyAsProperty = false) public String getNamespace() { return namespace; } @@ -117,7 +125,7 @@ public void setNamespace(String namespace) { this.namespace = namespace; } - @Parameter(key = Constants.CONFIG_GROUP_KEY, useKeyAsProperty = false) + @Parameter(key = CONFIG_GROUP_KEY, useKeyAsProperty = false) public String getGroup() { return group; } @@ -126,7 +134,7 @@ public void setGroup(String group) { this.group = group; } - @Parameter(key = Constants.CONFIG_CHECK_KEY, useKeyAsProperty = false) + @Parameter(key = CONFIG_CHECK_KEY, useKeyAsProperty = false) public Boolean isCheck() { return check; } @@ -135,7 +143,7 @@ public void setCheck(Boolean check) { this.check = check; } - @Parameter(key = Constants.CONFIG_ENABLE_KEY, useKeyAsProperty = false) + @Parameter(key = CONFIG_ENABLE_KEY, useKeyAsProperty = false) public Boolean isHighestPriority() { return highestPriority; } @@ -160,7 +168,7 @@ public void setPassword(String password) { this.password = password; } - @Parameter(key = Constants.CONFIG_TIMEOUT_KEY, useKeyAsProperty = false) + @Parameter(key = CONFIG_TIMEOUT_KEY, useKeyAsProperty = false) public Long getTimeout() { return timeout; } @@ -169,7 +177,7 @@ public void setTimeout(Long timeout) { this.timeout = timeout; } - @Parameter(key = Constants.CONFIG_CONFIGFILE_KEY, useKeyAsProperty = false) + @Parameter(key = CONFIG_CONFIGFILE_KEY, useKeyAsProperty = false) public String getConfigFile() { return configFile; } @@ -187,7 +195,7 @@ public void setAppConfigFile(String appConfigFile) { this.appConfigFile = appConfigFile; } - @Parameter(key = Constants.CONFIG_APPNAME_KEY, useKeyAsProperty = false) + @Parameter(key = CONFIG_APPNAME_KEY, useKeyAsProperty = false) public String getAppName() { return appName; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MethodConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MethodConfig.java index 0bc989fb3c8..c9dfdaa6d79 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MethodConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MethodConfig.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.annotation.Method; @@ -26,6 +25,13 @@ import java.util.Collections; import java.util.List; +import static org.apache.dubbo.common.constants.ConfigConstants.ON_INVOKE_INSTANCE_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.ON_INVOKE_METHOD_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.ON_RETURN_INSTANCE_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.ON_RETURN_METHOD_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.ON_THROW_INSTANCE_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.ON_THROW_METHOD_KEY; + /** * The method configuration * @@ -231,7 +237,7 @@ public void setSticky(Boolean sticky) { this.sticky = sticky; } - @Parameter(key = Constants.ON_RETURN_INSTANCE_KEY, excluded = true, attribute = true) + @Parameter(key = ON_RETURN_INSTANCE_KEY, excluded = true, attribute = true) public Object getOnreturn() { return onreturn; } @@ -240,7 +246,7 @@ public void setOnreturn(Object onreturn) { this.onreturn = onreturn; } - @Parameter(key = Constants.ON_RETURN_METHOD_KEY, excluded = true, attribute = true) + @Parameter(key = ON_RETURN_METHOD_KEY, excluded = true, attribute = true) public String getOnreturnMethod() { return onreturnMethod; } @@ -249,7 +255,7 @@ public void setOnreturnMethod(String onreturnMethod) { this.onreturnMethod = onreturnMethod; } - @Parameter(key = Constants.ON_THROW_INSTANCE_KEY, excluded = true, attribute = true) + @Parameter(key = ON_THROW_INSTANCE_KEY, excluded = true, attribute = true) public Object getOnthrow() { return onthrow; } @@ -258,7 +264,7 @@ public void setOnthrow(Object onthrow) { this.onthrow = onthrow; } - @Parameter(key = Constants.ON_THROW_METHOD_KEY, excluded = true, attribute = true) + @Parameter(key = ON_THROW_METHOD_KEY, excluded = true, attribute = true) public String getOnthrowMethod() { return onthrowMethod; } @@ -267,7 +273,7 @@ public void setOnthrowMethod(String onthrowMethod) { this.onthrowMethod = onthrowMethod; } - @Parameter(key = Constants.ON_INVOKE_INSTANCE_KEY, excluded = true, attribute = true) + @Parameter(key = ON_INVOKE_INSTANCE_KEY, excluded = true, attribute = true) public Object getOninvoke() { return oninvoke; } @@ -276,7 +282,7 @@ public void setOninvoke(Object oninvoke) { this.oninvoke = oninvoke; } - @Parameter(key = Constants.ON_INVOKE_METHOD_KEY, excluded = true, attribute = true) + @Parameter(key = ON_INVOKE_METHOD_KEY, excluded = true, attribute = true) public String getOninvokeMethod() { return oninvokeMethod; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ModuleConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ModuleConfig.java index b47c35c479f..23b5743f6f7 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ModuleConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ModuleConfig.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.support.Parameter; @@ -24,6 +23,10 @@ import java.util.ArrayList; import java.util.List; +import static org.apache.dubbo.common.constants.ConfigConstants.NAME; +import static org.apache.dubbo.common.constants.ConfigConstants.ORGANIZATION; +import static org.apache.dubbo.common.constants.ConfigConstants.OWNER; + /** * The module info * @@ -81,7 +84,7 @@ public String getName() { } public void setName(String name) { - checkName(Constants.NAME, name); + checkName(NAME, name); this.name = name; if (StringUtils.isEmpty(id)) { id = name; @@ -102,7 +105,7 @@ public String getOwner() { } public void setOwner(String owner) { - checkName(Constants.OWNER, owner); + checkName(OWNER, owner); this.owner = owner; } @@ -111,7 +114,7 @@ public String getOrganization() { } public void setOrganization(String organization) { - checkName(Constants.ORGANIZATION, organization); + checkName(ORGANIZATION, organization); this.organization = organization; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java index a32344125d8..a4cd9c150f3 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.serialize.Serialization; @@ -34,6 +33,10 @@ import java.util.Map; import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; +import static org.apache.dubbo.common.constants.ConfigConstants.HOST_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.PROTOCOLS_SUFFIX; +import static org.apache.dubbo.common.constants.ConfigConstants.TELNET; import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; /** @@ -233,7 +236,7 @@ public String getHost() { } public void setHost(String host) { - checkName(Constants.HOST_KEY, host); + checkName(HOST_KEY, host); this.host = host; } @@ -321,7 +324,7 @@ public String getCodec() { } public void setCodec(String codec) { - if (Constants.DUBBO_PROTOCOL.equals(name)) { + if (DUBBO_PROTOCOL.equals(name)) { checkMultiExtension(Codec.class, RemotingConstants.CODEC_KEY, codec); } this.codec = codec; @@ -332,7 +335,7 @@ public String getSerialization() { } public void setSerialization(String serialization) { - if (Constants.DUBBO_PROTOCOL.equals(name)) { + if (DUBBO_PROTOCOL.equals(name)) { checkMultiExtension(Serialization.class, RemotingConstants.SERIALIZATION_KEY, serialization); } this.serialization = serialization; @@ -375,7 +378,7 @@ public String getServer() { } public void setServer(String server) { - if (Constants.DUBBO_PROTOCOL.equals(name)) { + if (DUBBO_PROTOCOL.equals(name)) { checkMultiExtension(Transporter.class, RemotingConstants.SERVER_KEY, server); } this.server = server; @@ -386,7 +389,7 @@ public String getClient() { } public void setClient(String client) { - if (Constants.DUBBO_PROTOCOL.equals(name)) { + if (DUBBO_PROTOCOL.equals(name)) { checkMultiExtension(Transporter.class, RemotingConstants.CLIENT_KEY, client); } this.client = client; @@ -405,7 +408,7 @@ public String getTelnet() { } public void setTelnet(String telnet) { - checkMultiExtension(TelnetHandler.class, Constants.TELNET, telnet); + checkMultiExtension(TelnetHandler.class, TELNET, telnet); this.telnet = telnet; } @@ -544,7 +547,7 @@ public void refresh() { } super.refresh(); if (StringUtils.isNotEmpty(this.getId())) { - this.setPrefix(Constants.PROTOCOLS_SUFFIX); + this.setPrefix(PROTOCOLS_SUFFIX); super.refresh(); } } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProviderConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProviderConfig.java index 33a88e68642..63d0bc894f6 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProviderConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProviderConfig.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.status.StatusChecker; import org.apache.dubbo.common.threadpool.ThreadPool; @@ -30,6 +29,9 @@ import java.util.Arrays; import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.CONTEXTPATH_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.STATUS_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.TELNET; /** * The service provider default configuration @@ -210,7 +212,7 @@ public String getContextpath() { } public void setContextpath(String contextpath) { - checkPathName(Constants.CONTEXTPATH_KEY, contextpath); + checkPathName(CONTEXTPATH_KEY, contextpath); this.contextpath = contextpath; } @@ -308,7 +310,7 @@ public String getTelnet() { } public void setTelnet(String telnet) { - checkMultiExtension(TelnetHandler.class, Constants.TELNET, telnet); + checkMultiExtension(TelnetHandler.class, TELNET, telnet); this.telnet = telnet; } @@ -326,7 +328,7 @@ public String getStatus() { } public void setStatus(String status) { - checkMultiExtension(StatusChecker.class, Constants.STATUS_KEY, status); + checkMultiExtension(StatusChecker.class, STATUS_KEY, status); this.status = status; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java index 2a0080124f6..9fd9e2916fd 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.bytecode.Wrapper; @@ -66,6 +65,10 @@ import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SEMICOLON_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.CLUSTER_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_IP_TO_REGISTRY; +import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.REGISTER_IP_KEY; import static org.apache.dubbo.common.constants.MonitorConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; @@ -316,13 +319,13 @@ private void init() { } } - String hostToRegistry = ConfigUtils.getSystemProperty(Constants.DUBBO_IP_TO_REGISTRY); + String hostToRegistry = ConfigUtils.getSystemProperty(DUBBO_IP_TO_REGISTRY); if (StringUtils.isEmpty(hostToRegistry)) { hostToRegistry = NetUtils.getLocalHost(); } else if (isInvalidLocalHost(hostToRegistry)) { - throw new IllegalArgumentException("Specified invalid registry ip from property:" + Constants.DUBBO_IP_TO_REGISTRY + ", value:" + hostToRegistry); + throw new IllegalArgumentException("Specified invalid registry ip from property:" + DUBBO_IP_TO_REGISTRY + ", value:" + hostToRegistry); } - map.put(Constants.REGISTER_IP_KEY, hostToRegistry); + map.put(REGISTER_IP_KEY, hostToRegistry); ref = createProxy(map); @@ -362,7 +365,7 @@ private T createProxy(Map map) { url = url.setPath(interfaceName); } if (REGISTRY_PROTOCOL.equals(url.getProtocol())) { - urls.add(url.addParameterAndEncoded(Constants.REFER_KEY, StringUtils.toQueryString(map))); + urls.add(url.addParameterAndEncoded(REFER_KEY, StringUtils.toQueryString(map))); } else { urls.add(ClusterUtils.mergeUrl(url, map)); } @@ -379,7 +382,7 @@ private T createProxy(Map map) { if (monitorUrl != null) { map.put(MONITOR_KEY, URL.encode(monitorUrl.toFullString())); } - urls.add(u.addParameterAndEncoded(Constants.REFER_KEY, StringUtils.toQueryString(map))); + urls.add(u.addParameterAndEncoded(REFER_KEY, StringUtils.toQueryString(map))); } } if (urls.isEmpty()) { @@ -401,7 +404,7 @@ private T createProxy(Map map) { } if (registryURL != null) { // registry url is available // use RegistryAwareCluster only when register's CLUSTER is available - URL u = registryURL.addParameter(Constants.CLUSTER_KEY, RegistryAwareCluster.NAME); + URL u = registryURL.addParameter(CLUSTER_KEY, RegistryAwareCluster.NAME); // The invoker wrap relation would be: RegistryAwareClusterInvoker(StaticDirectory) -> FailoverClusterInvoker(RegistryDirectory, will execute route) -> Invoker invoker = CLUSTER.join(new StaticDirectory(u, invokers)); } else { // not a registry url, must be direct invoke. @@ -424,7 +427,7 @@ private T createProxy(Map map) { */ MetadataReportService metadataReportService = null; if ((metadataReportService = getMetadataReportService()) != null) { - URL consumerURL = new URL(CONSUMER_PROTOCOL, map.remove(Constants.REGISTER_IP_KEY), 0, map.get(INTERFACE_KEY), map); + URL consumerURL = new URL(CONSUMER_PROTOCOL, map.remove(REGISTER_IP_KEY), 0, map.get(INTERFACE_KEY), map); metadataReportService.publishConsumer(consumerURL); } // create service proxy diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java index dfbf749b16e..f0d7158a915 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.support.Parameter; @@ -25,6 +24,11 @@ import static org.apache.dubbo.common.constants.CommonConstants.FILE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.PASSWORD_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.REGISTRIES_SUFFIX; +import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.USERNAME_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.ZOOKEEPER_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.EXTRA_KEYS_KEY; /** @@ -195,7 +199,7 @@ public String getUsername() { } public void setUsername(String username) { - checkName(Constants.USERNAME_KEY, username); + checkName(USERNAME_KEY, username); this.username = username; } @@ -204,7 +208,7 @@ public String getPassword() { } public void setPassword(String password) { - checkLength(Constants.PASSWORD_KEY, password); + checkLength(PASSWORD_KEY, password); this.password = password; } @@ -227,7 +231,7 @@ public Integer getWait() { public void setWait(Integer wait) { this.wait = wait; if (wait != null && wait > 0) { - System.setProperty(Constants.SHUTDOWN_WAIT_KEY, String.valueOf(wait)); + System.setProperty(SHUTDOWN_WAIT_KEY, String.valueOf(wait)); } } @@ -408,15 +412,15 @@ public boolean isZookeeperProtocol() { if (!isValid()) { return false; } - return Constants.ZOOKEEPER_PROTOCOL.equals(getProtocol()) - || getAddress().startsWith(Constants.ZOOKEEPER_PROTOCOL); + return ZOOKEEPER_PROTOCOL.equals(getProtocol()) + || getAddress().startsWith(ZOOKEEPER_PROTOCOL); } @Override public void refresh() { super.refresh(); if (StringUtils.isNotEmpty(this.getId())) { - this.setPrefix(Constants.REGISTRIES_SUFFIX); + this.setPrefix(REGISTRIES_SUFFIX); super.refresh(); } } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index 415b7e966e3..3ca193e88f8 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.Version; @@ -72,6 +71,17 @@ import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_IP_TO_BIND; +import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_IP_TO_REGISTRY; +import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PORT_TO_BIND; +import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PORT_TO_REGISTRY; +import static org.apache.dubbo.common.constants.ConfigConstants.EXPORT_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.MULTICAST; +import static org.apache.dubbo.common.constants.ConfigConstants.PROTOCOLS_SUFFIX; +import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_LOCAL; +import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_NONE; +import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_REMOTE; import static org.apache.dubbo.common.constants.MonitorConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; @@ -557,16 +567,16 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r .getExtension(url.getProtocol()).getConfigurator(url).configure(url); } - String scope = url.getParameter(Constants.SCOPE_KEY); + String scope = url.getParameter(SCOPE_KEY); // don't export when none is configured - if (!Constants.SCOPE_NONE.equalsIgnoreCase(scope)) { + if (!SCOPE_NONE.equalsIgnoreCase(scope)) { // export to local if the config is not remote (export to remote only when config is remote) - if (!Constants.SCOPE_REMOTE.equalsIgnoreCase(scope)) { + if (!SCOPE_REMOTE.equalsIgnoreCase(scope)) { exportLocal(url); } // export to remote if the config is not local (export to local only when config is local) - if (!Constants.SCOPE_LOCAL.equalsIgnoreCase(scope)) { + if (!SCOPE_LOCAL.equalsIgnoreCase(scope)) { if (!isOnlyInJvm() && logger.isInfoEnabled()) { logger.info("Export dubbo service " + interfaceClass.getName() + " to url " + url); } @@ -591,7 +601,7 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r registryURL = registryURL.addParameter(PROXY_KEY, proxy); } - Invoker invoker = proxyFactory.getInvoker(ref, (Class) interfaceClass, registryURL.addParameterAndEncoded(Constants.EXPORT_KEY, url.toFullString())); + Invoker invoker = proxyFactory.getInvoker(ref, (Class) interfaceClass, registryURL.addParameterAndEncoded(EXPORT_KEY, url.toFullString())); DelegateProviderMetaDataInvoker wrapperInvoker = new DelegateProviderMetaDataInvoker(invoker, this); Exporter exporter = protocol.export(wrapperInvoker); @@ -658,9 +668,9 @@ protected Class getServiceClass(T ref) { private String findConfigedHosts(ProtocolConfig protocolConfig, List registryURLs, Map map) { boolean anyhost = false; - String hostToBind = getValueFromConfig(protocolConfig, Constants.DUBBO_IP_TO_BIND); + String hostToBind = getValueFromConfig(protocolConfig, DUBBO_IP_TO_BIND); if (hostToBind != null && hostToBind.length() > 0 && isInvalidLocalHost(hostToBind)) { - throw new IllegalArgumentException("Specified invalid bind ip from property:" + Constants.DUBBO_IP_TO_BIND + ", value:" + hostToBind); + throw new IllegalArgumentException("Specified invalid bind ip from property:" + DUBBO_IP_TO_BIND + ", value:" + hostToBind); } // if bind ip is not found in environment, keep looking up @@ -679,7 +689,7 @@ private String findConfigedHosts(ProtocolConfig protocolConfig, List regist if (isInvalidLocalHost(hostToBind)) { if (CollectionUtils.isNotEmpty(registryURLs)) { for (URL registryURL : registryURLs) { - if (Constants.MULTICAST.equalsIgnoreCase(registryURL.getParameter("registry"))) { + if (MULTICAST.equalsIgnoreCase(registryURL.getParameter("registry"))) { // skip multicast registry since we cannot connect to it via Socket continue; } @@ -703,9 +713,9 @@ private String findConfigedHosts(ProtocolConfig protocolConfig, List regist map.put(RemotingConstants.BIND_IP_KEY, hostToBind); // registry ip is not used for bind ip by default - String hostToRegistry = getValueFromConfig(protocolConfig, Constants.DUBBO_IP_TO_REGISTRY); + String hostToRegistry = getValueFromConfig(protocolConfig, DUBBO_IP_TO_REGISTRY); if (hostToRegistry != null && hostToRegistry.length() > 0 && isInvalidLocalHost(hostToRegistry)) { - throw new IllegalArgumentException("Specified invalid registry ip from property:" + Constants.DUBBO_IP_TO_REGISTRY + ", value:" + hostToRegistry); + throw new IllegalArgumentException("Specified invalid registry ip from property:" + DUBBO_IP_TO_REGISTRY + ", value:" + hostToRegistry); } else if (StringUtils.isEmpty(hostToRegistry)) { // bind ip is used as registry ip by default hostToRegistry = hostToBind; @@ -729,7 +739,7 @@ private Integer findConfigedPorts(ProtocolConfig protocolConfig, String name, Ma Integer portToBind = null; // parse bind port from environment - String port = getValueFromConfig(protocolConfig, Constants.DUBBO_PORT_TO_BIND); + String port = getValueFromConfig(protocolConfig, DUBBO_PORT_TO_BIND); portToBind = parsePort(port); // if there's no bind port found from environment, keep looking up. @@ -755,7 +765,7 @@ private Integer findConfigedPorts(ProtocolConfig protocolConfig, String name, Ma map.put(RemotingConstants.BIND_PORT_KEY, String.valueOf(portToBind)); // registry port, not used as bind port by default - String portToRegistryStr = getValueFromConfig(protocolConfig, Constants.DUBBO_PORT_TO_REGISTRY); + String portToRegistryStr = getValueFromConfig(protocolConfig, DUBBO_PORT_TO_REGISTRY); Integer portToRegistry = parsePort(portToRegistryStr); if (portToRegistry == null) { portToRegistry = portToBind; @@ -858,9 +868,9 @@ private void convertProtocolIdsToProtocols() { if (StringUtils.isEmpty(protocolIds) && CollectionUtils.isEmpty(protocols)) { List configedProtocols = new ArrayList<>(); configedProtocols.addAll(getSubProperties(Environment.getInstance() - .getExternalConfigurationMap(), Constants.PROTOCOLS_SUFFIX)); + .getExternalConfigurationMap(), PROTOCOLS_SUFFIX)); configedProtocols.addAll(getSubProperties(Environment.getInstance() - .getAppExternalConfigurationMap(), Constants.PROTOCOLS_SUFFIX)); + .getAppExternalConfigurationMap(), PROTOCOLS_SUFFIX)); protocolIds = String.join(",", configedProtocols); } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ApplicationBuilder.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ApplicationBuilder.java index 8fc16bad71f..45992a4f516 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ApplicationBuilder.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ApplicationBuilder.java @@ -16,16 +16,17 @@ */ package org.apache.dubbo.config.builders; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.MonitorConfig; import org.apache.dubbo.config.RegistryConfig; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.apache.dubbo.common.constants.ConfigConstants.PRODUCTION_ENVIRONMENT; + /** * This is a builder for build {@link ApplicationConfig}. * @since 2.7 @@ -36,7 +37,7 @@ public class ApplicationBuilder extends AbstractBuilder registries; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractInterfaceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractInterfaceConfigTest.java index 004d78006f0..355c39e5161 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractInterfaceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractInterfaceConfigTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.ConfigUtils; @@ -47,6 +46,9 @@ import java.util.List; import java.util.Properties; +import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_SECONDS_KEY; + public class AbstractInterfaceConfigTest { private static File dubboProperties; @@ -90,29 +92,29 @@ public void testCheckRegistry2() { public void checkApplication1() { try { ConfigUtils.setProperties(null); - System.clearProperty(Constants.SHUTDOWN_WAIT_KEY); - System.clearProperty(Constants.SHUTDOWN_WAIT_SECONDS_KEY); + System.clearProperty(SHUTDOWN_WAIT_KEY); + System.clearProperty(SHUTDOWN_WAIT_SECONDS_KEY); - writeDubboProperties(Constants.SHUTDOWN_WAIT_KEY, "100"); + writeDubboProperties(SHUTDOWN_WAIT_KEY, "100"); System.setProperty("dubbo.application.name", "demo"); InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.checkApplication(); ApplicationConfig appConfig = interfaceConfig.getApplication(); Assertions.assertEquals("demo", appConfig.getName()); - Assertions.assertEquals("100", System.getProperty(Constants.SHUTDOWN_WAIT_KEY)); + Assertions.assertEquals("100", System.getProperty(SHUTDOWN_WAIT_KEY)); - System.clearProperty(Constants.SHUTDOWN_WAIT_KEY); + System.clearProperty(SHUTDOWN_WAIT_KEY); ConfigUtils.setProperties(null); - writeDubboProperties(Constants.SHUTDOWN_WAIT_SECONDS_KEY, "1000"); + writeDubboProperties(SHUTDOWN_WAIT_SECONDS_KEY, "1000"); System.setProperty("dubbo.application.name", "demo"); interfaceConfig = new InterfaceConfig(); interfaceConfig.checkApplication(); - Assertions.assertEquals("1000", System.getProperty(Constants.SHUTDOWN_WAIT_SECONDS_KEY)); + Assertions.assertEquals("1000", System.getProperty(SHUTDOWN_WAIT_SECONDS_KEY)); } finally { ConfigUtils.setProperties(null); System.clearProperty("dubbo.application.name"); - System.clearProperty(Constants.SHUTDOWN_WAIT_KEY); - System.clearProperty(Constants.SHUTDOWN_WAIT_SECONDS_KEY); + System.clearProperty(SHUTDOWN_WAIT_KEY); + System.clearProperty(SHUTDOWN_WAIT_SECONDS_KEY); } } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java index be140fce8be..64f09ae2661 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java @@ -17,8 +17,6 @@ package org.apache.dubbo.config; -import org.apache.dubbo.common.Constants; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -28,6 +26,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DUMP_DIRECTORY; +import static org.apache.dubbo.common.constants.ConfigConstants.ACCEPT_FOREIGN_IP; +import static org.apache.dubbo.common.constants.ConfigConstants.QOS_ENABLE; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; @@ -150,7 +150,7 @@ public void testQosEnable() throws Exception { assertThat(application.getQosEnable(), is(true)); Map parameters = new HashMap(); ApplicationConfig.appendParameters(parameters, application); - assertThat(parameters, hasEntry(Constants.QOS_ENABLE, "true")); + assertThat(parameters, hasEntry(QOS_ENABLE, "true")); } @Test @@ -167,7 +167,7 @@ public void testQosAcceptForeignIp() throws Exception { assertThat(application.getQosAcceptForeignIp(), is(true)); Map parameters = new HashMap(); ApplicationConfig.appendParameters(parameters, application); - assertThat(parameters, hasEntry(Constants.ACCEPT_FOREIGN_IP, "true")); + assertThat(parameters, hasEntry(ACCEPT_FOREIGN_IP, "true")); } @Test @@ -178,6 +178,6 @@ public void testParameters() throws Exception { parameters.put("k1", "v1"); ApplicationConfig.appendParameters(parameters, application); assertThat(parameters, hasEntry("k1", "v1")); - assertThat(parameters, hasEntry(Constants.ACCEPT_FOREIGN_IP, "true")); + assertThat(parameters, hasEntry(ACCEPT_FOREIGN_IP, "true")); } } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MethodConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MethodConfigTest.java index 1d976d7e4ee..e50caa1e3a5 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MethodConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MethodConfigTest.java @@ -17,7 +17,7 @@ package org.apache.dubbo.config; -import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.ConfigConstants; import org.apache.dubbo.config.annotation.Argument; import org.apache.dubbo.config.annotation.Method; import org.apache.dubbo.config.annotation.Reference; @@ -30,6 +30,11 @@ import java.util.List; import java.util.Map; +import static org.apache.dubbo.common.constants.ConfigConstants.ON_INVOKE_INSTANCE_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.ON_RETURN_INSTANCE_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.ON_RETURN_METHOD_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.ON_THROW_INSTANCE_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.ON_THROW_METHOD_KEY; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; @@ -155,7 +160,7 @@ public void testOnreturn() throws Exception { assertThat(method.getOnreturn(), equalTo((Object) "on-return-object")); Map attribute = new HashMap(); MethodConfig.appendAttributes(attribute, method); - assertThat(attribute, hasEntry((Object) Constants.ON_RETURN_INSTANCE_KEY, (Object) "on-return-object")); + assertThat(attribute, hasEntry((Object) ON_RETURN_INSTANCE_KEY, (Object) "on-return-object")); Map parameters = new HashMap(); MethodConfig.appendParameters(parameters, method); assertThat(parameters.size(), is(0)); @@ -168,7 +173,7 @@ public void testOnreturnMethod() throws Exception { assertThat(method.getOnreturnMethod(), equalTo("on-return-method")); Map attribute = new HashMap(); MethodConfig.appendAttributes(attribute, method); - assertThat(attribute, hasEntry((Object) Constants.ON_RETURN_METHOD_KEY, (Object) "on-return-method")); + assertThat(attribute, hasEntry((Object) ON_RETURN_METHOD_KEY, (Object) "on-return-method")); Map parameters = new HashMap(); MethodConfig.appendParameters(parameters, method); assertThat(parameters.size(), is(0)); @@ -181,7 +186,7 @@ public void testOnthrow() throws Exception { assertThat(method.getOnthrow(), equalTo((Object) "on-throw-object")); Map attribute = new HashMap(); MethodConfig.appendAttributes(attribute, method); - assertThat(attribute, hasEntry((Object) Constants.ON_THROW_INSTANCE_KEY, (Object) "on-throw-object")); + assertThat(attribute, hasEntry((Object) ON_THROW_INSTANCE_KEY, (Object) "on-throw-object")); Map parameters = new HashMap(); MethodConfig.appendParameters(parameters, method); assertThat(parameters.size(), is(0)); @@ -194,7 +199,7 @@ public void testOnthrowMethod() throws Exception { assertThat(method.getOnthrowMethod(), equalTo("on-throw-method")); Map attribute = new HashMap(); MethodConfig.appendAttributes(attribute, method); - assertThat(attribute, hasEntry((Object) Constants.ON_THROW_METHOD_KEY, (Object) "on-throw-method")); + assertThat(attribute, hasEntry((Object) ON_THROW_METHOD_KEY, (Object) "on-throw-method")); Map parameters = new HashMap(); MethodConfig.appendParameters(parameters, method); assertThat(parameters.size(), is(0)); @@ -207,7 +212,7 @@ public void testOninvoke() throws Exception { assertThat(method.getOninvoke(), equalTo((Object) "on-invoke-object")); Map attribute = new HashMap(); MethodConfig.appendAttributes(attribute, method); - assertThat(attribute, hasEntry((Object) Constants.ON_INVOKE_INSTANCE_KEY, (Object) "on-invoke-object")); + assertThat(attribute, hasEntry((Object) ON_INVOKE_INSTANCE_KEY, (Object) "on-invoke-object")); Map parameters = new HashMap(); MethodConfig.appendParameters(parameters, method); assertThat(parameters.size(), is(0)); @@ -220,7 +225,7 @@ public void testOninvokeMethod() throws Exception { assertThat(method.getOninvokeMethod(), equalTo("on-invoke-method")); Map attribute = new HashMap(); MethodConfig.appendAttributes(attribute, method); - assertThat(attribute, hasEntry((Object) Constants.ON_INVOKE_METHOD_KEY, (Object) "on-invoke-method")); + assertThat(attribute, hasEntry((Object) ConfigConstants.ON_INVOKE_METHOD_KEY, (Object) "on-invoke-method")); Map parameters = new HashMap(); MethodConfig.appendParameters(parameters, method); assertThat(parameters.size(), is(0)); diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java index bb52242bf10..70567fac1ec 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java @@ -17,20 +17,20 @@ package org.apache.dubbo.config; -import org.apache.dubbo.common.Constants; - import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.HashMap; import java.util.Map; +import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.not; -import static org.hamcrest.MatcherAssert.assertThat; public class RegistryConfigTest { @Test @@ -70,9 +70,9 @@ public void testWait() throws Exception { RegistryConfig registry = new RegistryConfig(); registry.setWait(10); assertThat(registry.getWait(), is(10)); - assertThat(System.getProperty(Constants.SHUTDOWN_WAIT_KEY), equalTo("10")); + assertThat(System.getProperty(SHUTDOWN_WAIT_KEY), equalTo("10")); } finally { - System.clearProperty(Constants.SHUTDOWN_TIMEOUT_KEY); + System.clearProperty(SHUTDOWN_TIMEOUT_KEY); } } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java index 0a472677ee9..09724cdcda3 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java @@ -17,9 +17,7 @@ package org.apache.dubbo.config; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.config.api.DemoService; import org.apache.dubbo.config.api.Greeting; import org.apache.dubbo.config.context.ConfigManager; @@ -43,16 +41,21 @@ import java.util.Collections; import java.util.concurrent.TimeUnit; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_BEAN; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_DEFAULT; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_NATIVE_JAVA; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.EXPORT_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; +import static org.apache.dubbo.common.constants.RemotingConstants.BIND_IP_KEY; +import static org.apache.dubbo.common.constants.RemotingConstants.BIND_PORT_KEY; import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_BEAN; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_DEFAULT; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_NATIVE_JAVA; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; @@ -140,9 +143,9 @@ public void testExport() throws Exception { assertThat(url.getPath(), equalTo(DemoService.class.getName())); assertThat(url.getParameters(), hasEntry(ANYHOST_KEY, "true")); assertThat(url.getParameters(), hasEntry(APPLICATION_KEY, "app")); - assertThat(url.getParameters(), hasKey(RemotingConstants.BIND_IP_KEY)); - assertThat(url.getParameters(), hasKey(RemotingConstants.BIND_PORT_KEY)); - assertThat(url.getParameters(), hasEntry(Constants.EXPORT_KEY, "true")); + assertThat(url.getParameters(), hasKey(BIND_IP_KEY)); + assertThat(url.getParameters(), hasKey(BIND_PORT_KEY)); + assertThat(url.getParameters(), hasEntry(EXPORT_KEY, "true")); assertThat(url.getParameters(), hasEntry("echo.0.callback", "false")); assertThat(url.getParameters(), hasEntry(GENERIC_KEY, "false")); assertThat(url.getParameters(), hasEntry(INTERFACE_KEY, DemoService.class.getName())); @@ -173,14 +176,14 @@ public void testDelayExport() throws Exception { @Test @Disabled("cannot pass in travis") public void testUnexport() throws Exception { - System.setProperty(Constants.SHUTDOWN_WAIT_KEY, "0"); + System.setProperty(SHUTDOWN_WAIT_KEY, "0"); try { service.export(); service.unexport(); Thread.sleep(1000); Mockito.verify(exporter, Mockito.atLeastOnce()).unexport(); } finally { - System.clearProperty(Constants.SHUTDOWN_TIMEOUT_KEY); + System.clearProperty(SHUTDOWN_TIMEOUT_KEY); } } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/InvokerSideConfigUrlTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/InvokerSideConfigUrlTest.java index 1155ec4a1f8..3d8c1e645ec 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/InvokerSideConfigUrlTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/InvokerSideConfigUrlTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config.url; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.config.ConsumerConfig; @@ -35,13 +34,15 @@ import java.util.Arrays; +import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_REMOTE; + public class InvokerSideConfigUrlTest extends UrlTestBase { private static final Logger log = LoggerFactory.getLogger(InvokerSideConfigUrlTest.class); // ====================================================== // invoker related data preparing - // ====================================================== + // ====================================================== private RegistryConfig regConfForConsumer; private RegistryConfig regConfForReference; private MethodConfig methodConfForReference; @@ -57,10 +58,10 @@ public class InvokerSideConfigUrlTest extends UrlTestBase { }; private Object regConfForConsumerTable[][] = { -// {"timeout", "registry.timeout", "int", 5000, 9000, "", "", "", "", ""}, -// {"file", "registry.file", "string", "", "regConfForServiceTable.log", "", "", "", "", ""}, -// {"wait", "registry.wait", "int", 0, 9000, "", "", "", "", ""}, -// {"transport", "registry.transporter", "string", "netty", "mina", "", "", "", "", ""}, +// {"timeout", "registry.timeout", "int", 5000, 9000, "", "", "", "", ""}, +// {"file", "registry.file", "string", "", "regConfForServiceTable.log", "", "", "", "", ""}, +// {"wait", "registry.wait", "int", 0, 9000, "", "", "", "", ""}, +// {"transport", "registry.transporter", "string", "netty", "mina", "", "", "", "", ""}, {"subscribe", "subscribe", "boolean", true, false, "", "", "", "", ""}, {"dynamic", "dynamic", "boolean", true, false, "", "", "", "", ""}, }; @@ -83,21 +84,21 @@ public class InvokerSideConfigUrlTest extends UrlTestBase { }; private Object refConfTable[][] = { -// {"version", "version", "string", "0.0.0", "1.2.3", "", "", "", "", ""}, -// {"group", "group", "string", "", "HaominTest", "", "", "", "", ""}, +// {"version", "version", "string", "0.0.0", "1.2.3", "", "", "", "", ""}, +// {"group", "group", "string", "", "HaominTest", "", "", "", "", ""}, -// {"delay", "delay", "int", 0, 5, "", "", "", "", ""}, // not boolean +// {"delay", "delay", "int", 0, 5, "", "", "", "", ""}, // not boolean {"timeout", "timeout", "int", 5000, 3000, "", "", "", "", ""}, {"retries", "retries", "int", 2, 5, "", "", "", "", ""}, {"connections", "connections", "boolean", 100, 20, "", "", "", "", ""}, {"loadbalance", "loadbalance", "string", "random", "roundrobin", "leastactive", "", "", ""}, {"async", "async", "boolean", false, true, "", "", "", "", ""}, //excluded = true -// {"generic", "generic", "boolean", false, true, "", "", "", "", ""}, +// {"generic", "generic", "boolean", false, true, "", "", "", "", ""}, {"check", "check", "boolean", false, true, "", "", "", "", ""}, - //{"local", "local", "string", "false", "HelloServiceLocal", "true", "", "", "", ""}, - //{"local", "local", "string", "false", "true", "", "", "", "", ""}, - //{"mock", "mock", "string", "false", "dubbo.test.HelloServiceMock", "true", "", "", "", ""}, + //{"local", "local", "string", "false", "HelloServiceLocal", "true", "", "", "", ""}, + //{"local", "local", "string", "false", "true", "", "", "", "", ""}, + //{"mock", "mock", "string", "false", "dubbo.test.HelloServiceMock", "true", "", "", "", ""}, {"mock", "mock", "string", "false", "false", "", "", "", "", ""}, {"proxy", "proxy", "boolean", "javassist", "jdk", "", "", "", "", ""}, {"client", "client", "string", "netty", "mina", "", "", "", "", ""}, @@ -106,25 +107,25 @@ public class InvokerSideConfigUrlTest extends UrlTestBase { {"actives", "actives", "int", 0, 30, "", "", "", "", ""}, {"cluster", "cluster", "string", "failover", "failfast", "failsafe", "failback", "forking", "", ""}, //excluded = true -// {"filter", "service.filter", "string", "default", "-generic", "", "", "", "", ""}, +// {"filter", "service.filter", "string", "default", "-generic", "", "", "", "", ""}, //excluded = true -// {"listener", "exporter.listener", "string", "default", "-deprecated", "", "", "", "", ""}, - //{"", "", "", "", "", "", "", "", "", ""}, +// {"listener", "exporter.listener", "string", "default", "-deprecated", "", "", "", "", ""}, + //{"", "", "", "", "", "", "", "", "", ""}, }; private Object consumerConfTable[][] = {{"timeout", "timeout", "int", 5000, 8000, "", "", "", "", ""}, {"retries", "retries", "int", 2, 5, "", "", "", "", ""}, {"loadbalance", "loadbalance", "string", "random", "leastactive", "", "", "", "", ""}, {"async", "async", "boolean", false, true, "", "", "", "", ""}, {"connections", "connections", "int", 100, 5, "", "", "", "", ""}, -// {"generic", "generic", "boolean", false, false, "", "", "", "", ""}, +// {"generic", "generic", "boolean", false, false, "", "", "", "", ""}, {"check", "check", "boolean", true, false, "", "", "", "", ""}, {"proxy", "proxy", "string", "javassist", "jdk", "javassist", "", "", "", ""}, {"owner", "owner", "string", "", "haomin", "", "", "", "", ""}, {"actives", "actives", "int", 0, 5, "", "", "", "", ""}, {"cluster", "cluster", "string", "failover", "forking", "", "", "", "", ""}, {"filter", "", "string", "", "", "", "", "", "", ""}, {"listener", "", "string", "", "", "", "", "", "", ""}, -// {"", "", "", "", "", "", "", "", "", ""}, +// {"", "", "", "", "", "", "", "", "", ""}, }; // ====================================================== // test Start - // ====================================================== + // ====================================================== @BeforeAll public static void start() { @@ -164,7 +165,7 @@ public void regConfForConsumerUrlTest() { // ====================================================== // private helper - // ====================================================== + // ====================================================== private void initRefConf() { regConfForConsumer = new RegistryConfig(); regConfForReference = new RegistryConfig(); @@ -188,7 +189,7 @@ private void initRefConf() { refConf.setMethods(Arrays.asList(new MethodConfig[]{methodConfForReference})); - refConf.setScope(Constants.SCOPE_REMOTE); + refConf.setScope(SCOPE_REMOTE); } private void verifyInvokerUrlGeneration(T config, Object[][] dataTable) { @@ -214,4 +215,4 @@ private void verifyInvokerUrlGeneration(T config, Object[][] dataTable) { private String getSubscribedUrlString() { return MockRegistry.getSubscribedUrl().toString(); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java index fca996e0f2a..4f7ea52c455 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config.spring; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; @@ -30,6 +29,7 @@ import static org.apache.dubbo.common.constants.ClusterConstants.CLUSTER_STICKY_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_INSTANCES_LIMIT_KEY; /** @@ -56,7 +56,7 @@ public static Exporter export(int port) { public static Exporter export(int port, RegistryService registryService) { return protocol.export(proxyFactory.getInvoker(registryService, RegistryService.class, - new URLBuilder(Constants.DUBBO_PROTOCOL, NetUtils.getLocalHost(), port, RegistryService.class.getName()) + new URLBuilder(DUBBO_PROTOCOL, NetUtils.getLocalHost(), port, RegistryService.class.getName()) .setPath(RegistryService.class.getName()) .addParameter(INTERFACE_KEY, RegistryService.class.getName()) .addParameter(CLUSTER_STICKY_KEY, "true") diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java index 4df84265d12..b89477be751 100644 --- a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.configcenter.support.apollo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -43,6 +42,10 @@ import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; +import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_CHECK_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_CLUSTER_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_GROUP_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_NAMESPACE_KEY; /** * Apollo implementation, https://github.com/ctripcorp/apollo @@ -63,7 +66,7 @@ public class ApolloDynamicConfiguration implements DynamicConfiguration { // Instead of using Dubbo's configuration, I would suggest use the original configuration method Apollo provides. String configEnv = url.getParameter(APOLLO_ENV_KEY); String configAddr = getAddressWithProtocolPrefix(url); - String configCluster = url.getParameter(Constants.CONFIG_CLUSTER_KEY); + String configCluster = url.getParameter(CONFIG_CLUSTER_KEY); if (configEnv != null) { System.setProperty(APOLLO_ENV_KEY, configEnv); } @@ -74,9 +77,9 @@ public class ApolloDynamicConfiguration implements DynamicConfiguration { System.setProperty(APOLLO_CLUSTER_KEY, configCluster); } - dubboConfig = ConfigService.getConfig(url.getParameter(Constants.CONFIG_NAMESPACE_KEY, DEFAULT_GROUP)); + dubboConfig = ConfigService.getConfig(url.getParameter(CONFIG_NAMESPACE_KEY, DEFAULT_GROUP)); // Decide to fail or to continue when failed to connect to remote server. - boolean check = url.getParameter(Constants.CONFIG_CHECK_KEY, true); + boolean check = url.getParameter(CONFIG_CHECK_KEY, true); if (dubboConfig.getSourceType() != ConfigSourceType.REMOTE) { if (check) { throw new IllegalStateException("Failed to connect to config center, the config center is Apollo, " + @@ -133,7 +136,7 @@ public void removeListener(String key, String group, ConfigurationListener liste */ @Override public String getConfig(String key, String group, long timeout) throws IllegalStateException { - if (StringUtils.isNotEmpty(group) && !url.getParameter(Constants.CONFIG_GROUP_KEY, DEFAULT_GROUP).equals(group)) { + if (StringUtils.isNotEmpty(group) && !url.getParameter(CONFIG_GROUP_KEY, DEFAULT_GROUP).equals(group)) { Config config = ConfigService.getAppConfig(); return config.getProperty(key, null); } diff --git a/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfiguration.java index d03e0f1c560..6727ed42c2a 100644 --- a/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfiguration.java @@ -39,8 +39,8 @@ import java.util.concurrent.ExecutorService; import static java.util.concurrent.Executors.newCachedThreadPool; -import static org.apache.dubbo.common.Constants.CONFIG_NAMESPACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; +import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_NAMESPACE_KEY; import static org.apache.dubbo.configcenter.ConfigChangeType.ADDED; /** diff --git a/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfiguration.java index 66799b9015f..78f5242c3ed 100644 --- a/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfiguration.java @@ -17,6 +17,15 @@ package org.apache.dubbo.configcenter.support.etcd; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.utils.StringUtils; +import org.apache.dubbo.configcenter.ConfigChangeEvent; +import org.apache.dubbo.configcenter.ConfigChangeType; +import org.apache.dubbo.configcenter.ConfigurationListener; +import org.apache.dubbo.configcenter.DynamicConfiguration; +import org.apache.dubbo.remoting.etcd.StateListener; +import org.apache.dubbo.remoting.etcd.jetcd.JEtcdClient; + import com.google.protobuf.ByteString; import io.etcd.jetcd.api.Event; import io.etcd.jetcd.api.WatchCancelRequest; @@ -26,21 +35,13 @@ import io.etcd.jetcd.api.WatchResponse; import io.grpc.ManagedChannel; import io.grpc.stub.StreamObserver; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.configcenter.ConfigChangeEvent; -import org.apache.dubbo.configcenter.ConfigChangeType; -import org.apache.dubbo.configcenter.ConfigurationListener; -import org.apache.dubbo.configcenter.DynamicConfiguration; -import org.apache.dubbo.remoting.etcd.StateListener; -import org.apache.dubbo.remoting.etcd.jetcd.JEtcdClient; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.apache.dubbo.common.Constants.CONFIG_NAMESPACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; +import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_NAMESPACE_KEY; /** * The etcd implementation of {@link DynamicConfiguration} diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java index 3baf27c7cc0..afdc97f7ac3 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java @@ -46,10 +46,10 @@ import static com.alibaba.nacos.api.PropertyKeyConst.SECRET_KEY; import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; import static com.alibaba.nacos.client.naming.utils.UtilAndComs.NACOS_NAMING_LOG_NAME; -import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; -import static org.apache.dubbo.common.Constants.CONFIG_NAMESPACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_CHAR_SEPERATOR; import static org.apache.dubbo.common.constants.CommonConstants.PROPERTIES_CHAR_SEPERATOR; +import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_NAMESPACE_KEY; +import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; /** * The nacos implementation of {@link DynamicConfiguration} diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java index dac49ccb0e6..2ee64263563 100644 --- a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java @@ -31,7 +31,7 @@ import java.util.concurrent.Executor; import java.util.concurrent.Executors; -import static org.apache.dubbo.common.Constants.CONFIG_NAMESPACE_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_NAMESPACE_KEY; /** * diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java index 89463d8e2b4..24fa51cd531 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java @@ -18,8 +18,6 @@ import org.apache.dubbo.cache.Cache; import org.apache.dubbo.cache.CacheFactory; -import org.apache.dubbo.common.Constants; -import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.StringUtils; @@ -32,6 +30,10 @@ import java.io.Serializable; +import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; +import static org.apache.dubbo.common.constants.FilterConstants.CACHE_KEY; + /** * CacheFilter is a core component of dubbo.Enabling cache key of service,method,consumer or provider dubbo will cache method return value. * Along with cache key we need to configure cache type. Dubbo default implemented cache types are @@ -61,7 +63,7 @@ * @see org.apache.dubbo.cache.support.expiring.ExpiringCacheFactory * @see org.apache.dubbo.cache.support.expiring.ExpiringCache */ -@Activate(group = {CommonConstants.CONSUMER, CommonConstants.PROVIDER}, value = Constants.CACHE_KEY) +@Activate(group = {CONSUMER, PROVIDER}, value = CACHE_KEY) public class CacheFilter implements Filter { private CacheFactory cacheFactory; @@ -89,7 +91,7 @@ public void setCacheFactory(CacheFactory cacheFactory) { */ @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { - if (cacheFactory != null && ConfigUtils.isNotEmpty(invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.CACHE_KEY))) { + if (cacheFactory != null && ConfigUtils.isNotEmpty(invoker.getUrl().getMethodParameter(invocation.getMethodName(), CACHE_KEY))) { Cache cache = cacheFactory.getCache(invoker.getUrl(), invocation); if (cache != null) { String key = StringUtils.toArgumentString(invocation.getArguments()); diff --git a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validation.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validation.java index d6775f0e270..281346c2ec6 100644 --- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validation.java +++ b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validation.java @@ -16,11 +16,12 @@ */ package org.apache.dubbo.validation; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.SPI; +import static org.apache.dubbo.common.constants.FilterConstants.VALIDATION_KEY; + /** * Instance of Validation interface provide instance of {@link Validator} based on the value of validation attribute. */ @@ -32,7 +33,7 @@ public interface Validation { * @param url Invocation url * @return Instance of {@link Validator} */ - @Adaptive(Constants.VALIDATION_KEY) + @Adaptive(VALIDATION_KEY) Validator getValidator(URL url); } diff --git a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java index 0aa0e361f0d..5d2551dd149 100644 --- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java +++ b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java @@ -16,8 +16,6 @@ */ package org.apache.dubbo.validation.filter; -import org.apache.dubbo.common.Constants; -import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.rpc.Filter; @@ -29,6 +27,10 @@ import org.apache.dubbo.validation.Validation; import org.apache.dubbo.validation.Validator; +import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; +import static org.apache.dubbo.common.constants.FilterConstants.VALIDATION_KEY; + /** * ValidationFilter invoke the validation by finding the right {@link Validator} instance based on the * configured validation attribute value of invoker url before the actual method invocation. @@ -56,7 +58,7 @@ * @see Filter * @see org.apache.dubbo.validation.support.AbstractValidation */ -@Activate(group = {CommonConstants.CONSUMER, CommonConstants.PROVIDER}, value = Constants.VALIDATION_KEY, order = 10000) +@Activate(group = {CONSUMER, PROVIDER}, value = VALIDATION_KEY, order = 10000) public class ValidationFilter implements Filter { private Validation validation; @@ -79,7 +81,7 @@ public void setValidation(Validation validation) { @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { if (validation != null && !invocation.getMethodName().startsWith("$") - && ConfigUtils.isNotEmpty(invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.VALIDATION_KEY))) { + && ConfigUtils.isNotEmpty(invoker.getUrl().getMethodParameter(invocation.getMethodName(), VALIDATION_KEY))) { try { Validator validator = validation.getValidator(invoker.getUrl()); if (validator != null) { diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactory.java b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactory.java index f3ce5d68c92..7ca49fcda93 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactory.java +++ b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactory.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.metadata.store.MetadataReport; import org.apache.dubbo.metadata.store.MetadataReportFactory; @@ -25,6 +24,9 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; +import static org.apache.dubbo.common.constants.ConfigConstants.EXPORT_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; + /** */ public abstract class AbstractMetadataReportFactory implements MetadataReportFactory { @@ -38,7 +40,7 @@ public abstract class AbstractMetadataReportFactory implements MetadataReportFac @Override public MetadataReport getMetadataReport(URL url) { url = url.setPath(MetadataReport.class.getName()) - .removeParameters(Constants.EXPORT_KEY, Constants.REFER_KEY); + .removeParameters(EXPORT_KEY, REFER_KEY); String key = url.toServiceString(); // Lock the registry access process to ensure a single instance of the registry LOCK.lock(); diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/MetadataReportServiceTest.java b/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/MetadataReportServiceTest.java index b0e24b53b00..d6ec49112f5 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/MetadataReportServiceTest.java +++ b/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/MetadataReportServiceTest.java @@ -16,18 +16,16 @@ */ package org.apache.dubbo.metadata.integration; -import com.google.gson.Gson; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.metadata.definition.model.FullServiceDefinition; import org.apache.dubbo.metadata.store.test.JTestMetadataReport4Test; + +import com.google.gson.Gson; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.Collections; -import java.util.HashMap; import java.util.Map; import java.util.function.Supplier; diff --git a/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java b/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java index c90809c3d51..6e46bd7417f 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java +++ b/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java @@ -16,26 +16,26 @@ */ package org.apache.dubbo.metadata.store.nacos; -import com.alibaba.nacos.api.config.ConfigService; -import com.google.gson.Gson; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder; import org.apache.dubbo.metadata.definition.model.FullServiceDefinition; import org.apache.dubbo.metadata.identifier.MetadataIdentifier; + +import com.alibaba.nacos.api.config.ConfigService; +import com.google.gson.Gson; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; -import static org.apache.dubbo.common.constants.RegistryConstants.SESSION_TIMEOUT_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; +import static org.apache.dubbo.common.constants.RegistryConstants.SESSION_TIMEOUT_KEY; @Disabled public class NacosMetadataReportTest { diff --git a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java index 2d2a8af0373..6764e739327 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java +++ b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java @@ -26,10 +26,10 @@ import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; +import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; import static org.apache.dubbo.common.constants.RemotingConstants.CHECK_KEY; -import static org.apache.dubbo.common.Constants.DUBBO_PROTOCOL; import static org.apache.dubbo.common.constants.RpcConstants.REFERENCE_FILTER_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; /** * DefaultMonitorFactory diff --git a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/DubboMonitorTest.java b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/DubboMonitorTest.java index 67c7a5a4eb6..71354e159ce 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/DubboMonitorTest.java +++ b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/DubboMonitorTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.monitor.dubbo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.extension.ExtensionLoader; @@ -30,6 +29,7 @@ import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; + import org.hamcrest.CustomMatcher; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -38,11 +38,12 @@ import java.util.Arrays; import java.util.List; +import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.Matchers.not; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.not; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.atLeastOnce; @@ -93,7 +94,7 @@ public List lookup(URL query) { @Test public void testCount() throws Exception { DubboMonitor monitor = new DubboMonitor(monitorInvoker, monitorService); - URL statistics = new URLBuilder(Constants.DUBBO_PROTOCOL, "10.20.153.10", 0) + URL statistics = new URLBuilder(DUBBO_PROTOCOL, "10.20.153.10", 0) .addParameter(MonitorService.APPLICATION, "morgan") .addParameter(MonitorService.INTERFACE, "MemberService") .addParameter(MonitorService.METHOD, "findPerson") @@ -129,7 +130,7 @@ public void testCount() throws Exception { @Test public void testMonitorFactory() throws Exception { MockMonitorService monitorService = new MockMonitorService(); - URL statistics = new URLBuilder(Constants.DUBBO_PROTOCOL, "10.20.153.10", 0) + URL statistics = new URLBuilder(DUBBO_PROTOCOL, "10.20.153.10", 0) .addParameter(MonitorService.APPLICATION, "morgan") .addParameter(MonitorService.INTERFACE, "MemberService") .addParameter(MonitorService.METHOD, "findPerson") @@ -191,7 +192,7 @@ public void testAvailable() { @Test public void testSum() { - URL statistics = new URLBuilder(Constants.DUBBO_PROTOCOL, "10.20.153.11", 0) + URL statistics = new URLBuilder(DUBBO_PROTOCOL, "10.20.153.11", 0) .addParameter(MonitorService.APPLICATION, "morgan") .addParameter(MonitorService.INTERFACE, "MemberService") .addParameter(MonitorService.METHOD, "findPerson") diff --git a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/StatisticsTest.java b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/StatisticsTest.java index e2bdc897718..fb91790e064 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/StatisticsTest.java +++ b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/StatisticsTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.monitor.dubbo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.monitor.MonitorService; @@ -24,6 +23,7 @@ import org.hamcrest.MatcherAssert; import org.junit.jupiter.api.Test; +import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; @@ -32,7 +32,7 @@ public class StatisticsTest { @Test public void testEquals() { - URL statistics = new URLBuilder(Constants.DUBBO_PROTOCOL, "10.20.153.10", 0) + URL statistics = new URLBuilder(DUBBO_PROTOCOL, "10.20.153.10", 0) .addParameter(MonitorService.APPLICATION, "morgan") .addParameter(MonitorService.INTERFACE, "MemberService") .addParameter(MonitorService.METHOD, "findPerson") @@ -74,7 +74,7 @@ public void testToString() { statistics.setService("MemberService"); assertThat(statistics.toString(), is("dubbo://10.20.153.10")); - Statistics statisticsWithDetailInfo = new Statistics(new URLBuilder(Constants.DUBBO_PROTOCOL, "10.20.153.10", 0) + Statistics statisticsWithDetailInfo = new Statistics(new URLBuilder(DUBBO_PROTOCOL, "10.20.153.10", 0) .addParameter(MonitorService.APPLICATION, "morgan") .addParameter(MonitorService.INTERFACE, "MemberService") .addParameter(MonitorService.METHOD, "findPerson") diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/protocol/QosProtocolWrapper.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/protocol/QosProtocolWrapper.java index 03f265e2c65..361c5ee92b2 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/protocol/QosProtocolWrapper.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/protocol/QosProtocolWrapper.java @@ -28,9 +28,9 @@ import java.util.concurrent.atomic.AtomicBoolean; -import static org.apache.dubbo.common.Constants.ACCEPT_FOREIGN_IP; -import static org.apache.dubbo.common.Constants.QOS_ENABLE; -import static org.apache.dubbo.common.Constants.QOS_PORT; +import static org.apache.dubbo.common.constants.ConfigConstants.ACCEPT_FOREIGN_IP; +import static org.apache.dubbo.common.constants.ConfigConstants.QOS_ENABLE; +import static org.apache.dubbo.common.constants.ConfigConstants.QOS_PORT; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/protocol/QosProtocolWrapperTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/protocol/QosProtocolWrapperTest.java index a958d7cbdc1..ad310f6d156 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/protocol/QosProtocolWrapperTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/protocol/QosProtocolWrapperTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.qos.protocol; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.qos.command.BaseCommand; import org.apache.dubbo.qos.server.Server; @@ -28,6 +27,9 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import static org.apache.dubbo.common.constants.ConfigConstants.ACCEPT_FOREIGN_IP; +import static org.apache.dubbo.common.constants.ConfigConstants.QOS_ENABLE; +import static org.apache.dubbo.common.constants.ConfigConstants.QOS_PORT; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @@ -44,9 +46,9 @@ public class QosProtocolWrapperTest { @BeforeEach public void setUp() throws Exception { - when(url.getParameter(Constants.QOS_ENABLE, true)).thenReturn(true); - when(url.getParameter(Constants.QOS_PORT, 22222)).thenReturn(12345); - when(url.getParameter(Constants.ACCEPT_FOREIGN_IP, true)).thenReturn(false); + when(url.getParameter(QOS_ENABLE, true)).thenReturn(true); + when(url.getParameter(QOS_PORT, 22222)).thenReturn(12345); + when(url.getParameter(ACCEPT_FOREIGN_IP, true)).thenReturn(false); when(invoker.getUrl()).thenReturn(url); when(url.getProtocol()).thenReturn(REGISTRY_PROTOCOL); } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java index 624d58b9588..327b5c029de 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.registry.integration; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.Version; @@ -67,6 +66,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; +import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; import static org.apache.dubbo.common.constants.MonitorConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.APP_DYNAMIC_CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; @@ -136,7 +137,7 @@ public RegistryDirectory(Class serviceType, URL url) { } this.serviceType = serviceType; this.serviceKey = url.getServiceKey(); - this.queryMap = StringUtils.parseQueryString(url.getParameterAndDecoded(Constants.REFER_KEY)); + this.queryMap = StringUtils.parseQueryString(url.getParameterAndDecoded(REFER_KEY)); this.overrideDirectoryUrl = this.directoryUrl = turnRegistryUrlToConsumerUrl(url); String group = directoryUrl.getParameter(GROUP_KEY, ""); this.multiGroup = group != null && (ANY_VALUE.equals(group) || group.contains(",")); @@ -452,7 +453,7 @@ private URL mergeUrl(URL providerUrl) { this.overrideDirectoryUrl = this.overrideDirectoryUrl.addParametersIfAbsent(providerUrl.getParameters()); // Merge the provider side parameters if ((providerUrl.getPath() == null || providerUrl.getPath() - .length() == 0) && Constants.DUBBO_PROTOCOL.equals(providerUrl.getProtocol())) { // Compatible version 1.0 + .length() == 0) && DUBBO_PROTOCOL.equals(providerUrl.getProtocol())) { // Compatible version 1.0 //fix by tony.chenl DUBBO-44 String path = directoryUrl.getParameter(INTERFACE_KEY); if (path != null) { diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java index 4a155c07adf..69173d9121c 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java @@ -52,13 +52,6 @@ import java.util.concurrent.ExecutorService; import static java.util.concurrent.Executors.newSingleThreadExecutor; -import static org.apache.dubbo.common.Constants.ACCEPT_FOREIGN_IP; -import static org.apache.dubbo.common.Constants.EXPORT_KEY; -import static org.apache.dubbo.common.Constants.QOS_ENABLE; -import static org.apache.dubbo.common.Constants.QOS_PORT; -import static org.apache.dubbo.common.Constants.REFER_KEY; -import static org.apache.dubbo.common.Constants.REGISTER_IP_KEY; -import static org.apache.dubbo.common.Constants.VALIDATION_KEY; import static org.apache.dubbo.common.constants.ClusterConstants.LOADBALANCE_KEY; import static org.apache.dubbo.common.constants.ClusterConstants.WARMUP_KEY; import static org.apache.dubbo.common.constants.ClusterConstants.WEIGHT_KEY; @@ -74,7 +67,14 @@ import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.ACCEPT_FOREIGN_IP; import static org.apache.dubbo.common.constants.ConfigConstants.CLUSTER_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.EXPORT_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.QOS_ENABLE; +import static org.apache.dubbo.common.constants.ConfigConstants.QOS_PORT; +import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.REGISTER_IP_KEY; +import static org.apache.dubbo.common.constants.FilterConstants.VALIDATION_KEY; import static org.apache.dubbo.common.constants.MonitorConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.java index 1819a09640e..3837f2c0ff0 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.registry.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.logger.Logger; @@ -32,6 +31,8 @@ import java.util.concurrent.locks.ReentrantLock; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.EXPORT_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; /** * AbstractRegistryFactory. (SPI, Singleton, ThreadSafe) @@ -88,7 +89,7 @@ public Registry getRegistry(URL url) { url = URLBuilder.from(url) .setPath(RegistryService.class.getName()) .addParameter(INTERFACE_KEY, RegistryService.class.getName()) - .removeParameters(Constants.EXPORT_KEY, Constants.REFER_KEY) + .removeParameters(EXPORT_KEY, REFER_KEY) .build(); String key = url.toServiceStringWithoutResolving(); // Lock the registry access process to ensure a single instance of the registry diff --git a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java index 99aff9e1b69..5a3f6ab5655 100644 --- a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java +++ b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java @@ -16,11 +16,9 @@ */ package org.apache.dubbo.registry.dubbo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.bytecode.Wrapper; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.registry.Registry; @@ -43,7 +41,13 @@ import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.EXPORT_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.LAZY_CONNECT_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; +import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; +import static org.apache.dubbo.common.constants.RemotingConstants.CONNECT_TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.RemotingConstants.RECONNECT_KEY; import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_INSTANCES_LIMIT_KEY; /** @@ -59,14 +63,14 @@ public class DubboRegistryFactory extends AbstractRegistryFactory { private static URL getRegistryURL(URL url) { return URLBuilder.from(url) .setPath(RegistryService.class.getName()) - .removeParameter(Constants.EXPORT_KEY).removeParameter(Constants.REFER_KEY) + .removeParameter(EXPORT_KEY).removeParameter(REFER_KEY) .addParameter(INTERFACE_KEY, RegistryService.class.getName()) .addParameter(CLUSTER_STICKY_KEY, "true") - .addParameter(Constants.LAZY_CONNECT_KEY, "true") - .addParameter(RemotingConstants.RECONNECT_KEY, "false") + .addParameter(LAZY_CONNECT_KEY, "true") + .addParameter(RECONNECT_KEY, "false") .addParameterIfAbsent(TIMEOUT_KEY, "10000") .addParameterIfAbsent(CALLBACK_INSTANCES_LIMIT_KEY, "10000") - .addParameterIfAbsent(RemotingConstants.CONNECT_TIMEOUT_KEY, "10000") + .addParameterIfAbsent(CONNECT_TIMEOUT_KEY, "10000") .addParameter(METHODS_KEY, StringUtils.join(new HashSet<>(Arrays.asList(Wrapper.getWrapper(RegistryService.class).getDeclaredMethodNames())), ",")) //.addParameter(Constants.STUB_KEY, RegistryServiceStub.class.getName()) //.addParameter(Constants.STUB_EVENT_KEY, Boolean.TRUE.toString()) //for event dispatch @@ -92,15 +96,15 @@ public void setCluster(Cluster cluster) { public Registry createRegistry(URL url) { url = getRegistryURL(url); List urls = new ArrayList<>(); - urls.add(url.removeParameter(RemotingConstants.BACKUP_KEY)); - String backup = url.getParameter(RemotingConstants.BACKUP_KEY); + urls.add(url.removeParameter(BACKUP_KEY)); + String backup = url.getParameter(BACKUP_KEY); if (backup != null && backup.length() > 0) { String[] addresses = COMMA_SPLIT_PATTERN.split(backup); for (String address : addresses) { urls.add(url.setAddress(address)); } } - RegistryDirectory directory = new RegistryDirectory<>(RegistryService.class, url.addParameter(INTERFACE_KEY, RegistryService.class.getName()).addParameterAndEncoded(Constants.REFER_KEY, url.toParameterString())); + RegistryDirectory directory = new RegistryDirectory<>(RegistryService.class, url.addParameter(INTERFACE_KEY, RegistryService.class.getName()).addParameterAndEncoded(REFER_KEY, url.toParameterString())); Invoker registryInvoker = cluster.join(directory); RegistryService registryService = proxyFactory.getProxy(registryInvoker); DubboRegistry registry = new DubboRegistry(registryInvoker, registryService); diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java index 78ea9837eb9..77616c4912a 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.registry.dubbo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; @@ -62,6 +61,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.DISABLED_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; @@ -136,7 +136,7 @@ public void test_Constructor_WithErrorParam() { @Test public void test_Constructor_CheckStatus() throws Exception { - URL url = URL.valueOf("notsupported://10.20.30.40/" + service + "?a=b").addParameterAndEncoded(Constants.REFER_KEY, + URL url = URL.valueOf("notsupported://10.20.30.40/" + service + "?a=b").addParameterAndEncoded(REFER_KEY, "foo=bar"); RegistryDirectory reg = getRegistryDirectory(url); Field field = reg.getClass().getDeclaredField("queryMap"); @@ -329,7 +329,7 @@ private void test_Notified3invokers(RegistryDirectory registryDirectory) { @Test public void testParametersMerge() { RegistryDirectory registryDirectory = getRegistryDirectory(); - URL regurl = noMeaningUrl.addParameter("test", "reg").addParameterAndEncoded(Constants.REFER_KEY, + URL regurl = noMeaningUrl.addParameter("test", "reg").addParameterAndEncoded(REFER_KEY, "key=query&" + LOADBALANCE_KEY + "=" + LeastActiveLoadBalance.NAME); RegistryDirectory registryDirectory2 = new RegistryDirectory( RegistryDirectoryTest.class, @@ -1012,7 +1012,7 @@ public void test_Notified_acceptProtocol0() { @Test public void test_Notified_acceptProtocol1() { URL errorPathUrl = URL.valueOf("notsupport:/xxx"); - errorPathUrl = errorPathUrl.addParameterAndEncoded(Constants.REFER_KEY, "interface=" + service + "&protocol=dubbo"); + errorPathUrl = errorPathUrl.addParameterAndEncoded(REFER_KEY, "interface=" + service + "&protocol=dubbo"); RegistryDirectory registryDirectory = getRegistryDirectory(errorPathUrl); List serviceUrls = new ArrayList(); URL dubbo1URL = URL.valueOf("dubbo://127.0.0.1:9098?lazy=true&methods=getXXX"); @@ -1031,7 +1031,7 @@ public void test_Notified_acceptProtocol1() { @Test public void test_Notified_acceptProtocol2() { URL errorPathUrl = URL.valueOf("notsupport:/xxx"); - errorPathUrl = errorPathUrl.addParameterAndEncoded(Constants.REFER_KEY, "interface=" + service + "&protocol=dubbo,injvm"); + errorPathUrl = errorPathUrl.addParameterAndEncoded(REFER_KEY, "interface=" + service + "&protocol=dubbo,injvm"); RegistryDirectory registryDirectory = getRegistryDirectory(errorPathUrl); List serviceUrls = new ArrayList(); URL dubbo1URL = URL.valueOf("dubbo://127.0.0.1:9098?lazy=true&methods=getXXX"); @@ -1048,7 +1048,7 @@ public void test_Notified_acceptProtocol2() { @Test public void test_Notified_withGroupFilter() { - URL directoryUrl = noMeaningUrl.addParameterAndEncoded(Constants.REFER_KEY, "interface" + service + "&group=group1,group2"); + URL directoryUrl = noMeaningUrl.addParameterAndEncoded(REFER_KEY, "interface" + service + "&group=group1,group2"); RegistryDirectory directory = this.getRegistryDirectory(directoryUrl); URL provider1 = URL.valueOf("dubbo://10.134.108.1:20880/" + service + "?methods=getXXX&group=group1&mock=false&application=mockApplication"); URL provider2 = URL.valueOf("dubbo://10.134.108.1:20880/" + service + "?methods=getXXX&group=group2&mock=false&application=mockApplication"); @@ -1066,7 +1066,7 @@ public void test_Notified_withGroupFilter() { Assertions.assertTrue(invokers.get(0) instanceof MockClusterInvoker); Assertions.assertTrue(invokers.get(1) instanceof MockClusterInvoker); - directoryUrl = noMeaningUrl.addParameterAndEncoded(Constants.REFER_KEY, "interface" + service + "&group=group1"); + directoryUrl = noMeaningUrl.addParameterAndEncoded(REFER_KEY, "interface" + service + "&group=group1"); directory = this.getRegistryDirectory(directoryUrl); directory.notify(providers); diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java index 40d5cb4ea02..2e5dfd23659 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.registry.dubbo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.extension.ExtensionLoader; @@ -42,6 +41,7 @@ import java.util.ArrayList; import java.util.List; +import static org.apache.dubbo.common.constants.ConfigConstants.EXPORT_KEY; import static org.apache.dubbo.registry.integration.RegistryProtocol.DEFAULT_REGISTER_PROVIDER_KEYS; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -87,7 +87,7 @@ public void testExport() { Protocol dubboProtocol = DubboProtocol.getDubboProtocol(); registryProtocol.setProtocol(dubboProtocol); - URL newRegistryUrl = registryUrl.addParameter(Constants.EXPORT_KEY, serviceUrl); + URL newRegistryUrl = registryUrl.addParameter(EXPORT_KEY, serviceUrl); DubboInvoker invoker = new DubboInvoker(DemoService.class, newRegistryUrl, new ExchangeClient[]{new MockedClient("10.20.20.20", 2222, true)}); Exporter exporter = registryProtocol.export(invoker); @@ -101,7 +101,7 @@ public void testExport() { @Test public void testNotifyOverride() throws Exception { - URL newRegistryUrl = registryUrl.addParameter(Constants.EXPORT_KEY, serviceUrl); + URL newRegistryUrl = registryUrl.addParameter(EXPORT_KEY, serviceUrl); Invoker invoker = new MockInvoker(RegistryProtocolTest.class, newRegistryUrl); Exporter exporter = protocol.export(invoker); RegistryProtocol rprotocol = RegistryProtocol.getRegistryProtocol(); @@ -131,7 +131,7 @@ public void testNotifyOverride() throws Exception { */ @Test public void testNotifyOverride_notmatch() throws Exception { - URL newRegistryUrl = registryUrl.addParameter(Constants.EXPORT_KEY, serviceUrl); + URL newRegistryUrl = registryUrl.addParameter(EXPORT_KEY, serviceUrl); Invoker invoker = new MockInvoker(RegistryProtocolTest.class, newRegistryUrl); Exporter exporter = protocol.export(invoker); RegistryProtocol rprotocol = RegistryProtocol.getRegistryProtocol(); @@ -150,7 +150,7 @@ public void testNotifyOverride_notmatch() throws Exception { */ @Test public void testDestoryRegistry() { - URL newRegistryUrl = registryUrl.addParameter(Constants.EXPORT_KEY, serviceUrl); + URL newRegistryUrl = registryUrl.addParameter(EXPORT_KEY, serviceUrl); Invoker invoker = new MockInvoker(RegistryProtocolTest.class, newRegistryUrl); Exporter exporter = protocol.export(invoker); destroyRegistryProtocol(); diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java index c4b02e1adb9..d07c815df9e 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.registry.dubbo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; @@ -30,6 +29,7 @@ import static org.apache.dubbo.common.constants.ClusterConstants.CLUSTER_STICKY_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_INSTANCES_LIMIT_KEY; /** @@ -57,7 +57,7 @@ public static Exporter export(int port) { public static Exporter export(int port, RegistryService registryService) { return protocol.export(proxyFactory.getInvoker(registryService, RegistryService.class, - new URLBuilder(Constants.DUBBO_PROTOCOL, NetUtils.getLocalHost(), port, RegistryService.class.getName()) + new URLBuilder(DUBBO_PROTOCOL, NetUtils.getLocalHost(), port, RegistryService.class.getName()) .setPath(RegistryService.class.getName()) .addParameter(INTERFACE_KEY, RegistryService.class.getName()) .addParameter(CLUSTER_STICKY_KEY, "true") diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java index 1dec8162b31..a89c43f0a31 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.telnet.support; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; @@ -27,6 +26,7 @@ import org.apache.dubbo.remoting.transport.ChannelHandlerAdapter; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; +import static org.apache.dubbo.common.constants.ConfigConstants.TELNET; public class TelnetHandlerAdapter extends ChannelHandlerAdapter implements TelnetHandler { @@ -84,7 +84,7 @@ public String telnet(Channel channel, String message) throws RemotingException { } private boolean commandEnabled(URL url, String command) { - String supportCommands = url.getParameter(Constants.TELNET); + String supportCommands = url.getParameter(TELNET); if (StringUtils.isEmpty(supportCommands)) { return true; } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java index 7342b9c233f..419f01e1b3a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.transport.codec; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; diff --git a/dubbo-remoting/dubbo-remoting-grizzly/src/main/test/org/apache/dubbo/remoting/transport/grizzly/GrizzlyTransporterTest.java b/dubbo-remoting/dubbo-remoting-grizzly/src/main/test/org/apache/dubbo/remoting/transport/grizzly/GrizzlyTransporterTest.java index 3fb0dde3e42..971a8b35c4a 100644 --- a/dubbo-remoting/dubbo-remoting-grizzly/src/main/test/org/apache/dubbo/remoting/transport/grizzly/GrizzlyTransporterTest.java +++ b/dubbo-remoting/dubbo-remoting-grizzly/src/main/test/org/apache/dubbo/remoting/transport/grizzly/GrizzlyTransporterTest.java @@ -16,13 +16,14 @@ */ package org.apache.dubbo.remoting.transport.grizzly; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Server; import org.apache.dubbo.remoting.transport.ChannelHandlerAdapter; + import org.junit.jupiter.api.Test; +import static org.apache.dubbo.common.constants.RemotingConstants.BIND_PORT_KEY; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -31,10 +32,10 @@ public class GrizzlyTransporterTest { public void shouldAbleToBindGrizzly() throws Exception { int port = NetUtils.getAvailablePort(); URL url = new URL("http", "localhost", port, - new String[]{Constants.BIND_PORT_KEY, String.valueOf(port)}); + new String[]{BIND_PORT_KEY, String.valueOf(port)}); Server server = new GrizzlyTransporter().bind(url, new ChannelHandlerAdapter()); assertThat(server.isBound(), is(true)); } -} \ No newline at end of file +} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcConstants.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcConstants.java index ce2925a6c42..7d592b1c762 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcConstants.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcConstants.java @@ -16,7 +16,13 @@ */ package org.apache.dubbo.rpc; -import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.constants.ClusterConstants; +import org.apache.dubbo.common.constants.CommonConstants; +import org.apache.dubbo.common.constants.ConfigConstants; +import org.apache.dubbo.common.constants.FilterConstants; +import org.apache.dubbo.common.constants.MonitorConstants; +import org.apache.dubbo.common.constants.RegistryConstants; +import org.apache.dubbo.common.constants.RemotingConstants; /** * RpcConstants @@ -24,9 +30,10 @@ * @deprecated Replace to org.apache.dubbo.common.Constants */ @Deprecated -public final class RpcConstants extends Constants { +public final class RpcConstants implements ClusterConstants, CommonConstants, ConfigConstants, FilterConstants, + MonitorConstants, RegistryConstants, RemotingConstants, org.apache.dubbo.common.constants.RpcConstants { private RpcConstants() { } -} \ No newline at end of file +} diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java index 84e5e148acd..2d993bea27b 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.dubbo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.config.ConfigurationUtils; @@ -65,16 +64,19 @@ import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.SHARE_CONNECTIONS_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_SHARE_CONNECTIONS; +import static org.apache.dubbo.common.constants.ConfigConstants.LAZY_CONNECT_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.ON_CONNECT_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.ON_DISCONNECT_KEY; import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_SERVICE_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.CONNECTIONS_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_SHARE_CONNECTIONS; +import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_STUB_EVENT; import static org.apache.dubbo.common.constants.RpcConstants.IS_CALLBACK_SERVICE; -import static org.apache.dubbo.common.constants.RpcConstants.OPTIMIZER_KEY; import static org.apache.dubbo.common.constants.RpcConstants.IS_SERVER_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.OPTIMIZER_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.SHARE_CONNECTIONS_KEY; import static org.apache.dubbo.common.constants.RpcConstants.STUB_EVENT_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_STUB_EVENT; import static org.apache.dubbo.common.constants.RpcConstants.STUB_EVENT_METHODS_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.CONNECTIONS_KEY; /** * dubbo protocol support. @@ -163,7 +165,7 @@ public void received(Channel channel, Object message) throws RemotingException { @Override public void connected(Channel channel) throws RemotingException { - invoke(channel, Constants.ON_CONNECT_KEY); + invoke(channel, ON_CONNECT_KEY); } @Override @@ -171,7 +173,7 @@ public void disconnected(Channel channel) throws RemotingException { if (logger.isDebugEnabled()) { logger.debug("disconnected from " + channel.getRemoteAddress() + ",url:" + channel.getUrl()); } - invoke(channel, Constants.ON_DISCONNECT_KEY); + invoke(channel, ON_DISCONNECT_KEY); } private void invoke(Channel channel, String methodKey) { @@ -586,7 +588,7 @@ private ExchangeClient initClient(URL url) { ExchangeClient client; try { // connection should be lazy - if (url.getParameter(Constants.LAZY_CONNECT_KEY, false)) { + if (url.getParameter(LAZY_CONNECT_KEY, false)) { client = new LazyConnectExchangeClient(url, requestHandler); } else { diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java index b63a3584652..4f00cad3d29 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java @@ -17,9 +17,7 @@ package org.apache.dubbo.rpc.protocol.dubbo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; @@ -27,15 +25,17 @@ import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.protocol.dubbo.support.ProtocolUtils; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.lang.reflect.Field; +import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; import static org.junit.jupiter.api.Assertions.fail; /** @@ -97,10 +97,10 @@ public void test_normal_channel_close_wait_gracefully() throws Exception { long start = System.currentTimeMillis(); try{ - System.setProperty(Constants.SHUTDOWN_WAIT_KEY, "2000"); + System.setProperty(SHUTDOWN_WAIT_KEY, "2000"); protocol.destroy(); }finally { - System.getProperties().remove(Constants.SHUTDOWN_WAIT_KEY); + System.getProperties().remove(SHUTDOWN_WAIT_KEY); } long waitTime = System.currentTimeMillis() - start; @@ -164,4 +164,4 @@ public String get() { return "ok"; } } -} \ No newline at end of file +} diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboLazyConnectTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboLazyConnectTest.java index d4a98bab90d..b539a7fa9ef 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboLazyConnectTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboLazyConnectTest.java @@ -17,7 +17,6 @@ package org.apache.dubbo.rpc.protocol.dubbo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.RpcException; @@ -29,6 +28,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.apache.dubbo.common.constants.ConfigConstants.LAZY_CONNECT_KEY; + /** * dubbo protocol lazy connect test */ @@ -57,14 +58,14 @@ public void testSticky1() { @Test public void testSticky2() { - URL url = URL.valueOf("dubbo://127.0.0.1:9090/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?" + Constants.LAZY_CONNECT_KEY + "=true"); + URL url = URL.valueOf("dubbo://127.0.0.1:9090/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?" + LAZY_CONNECT_KEY + "=true"); ProtocolUtils.refer(IDemoService.class, url); } @Test public void testSticky3() { Assertions.assertThrows(RpcException.class, () -> { - URL url = URL.valueOf("dubbo://127.0.0.1:9090/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?" + Constants.LAZY_CONNECT_KEY + "=true"); + URL url = URL.valueOf("dubbo://127.0.0.1:9090/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?" + LAZY_CONNECT_KEY + "=true"); IDemoService service = (IDemoService) ProtocolUtils.refer(IDemoService.class, url); service.get(); }); @@ -73,7 +74,7 @@ public void testSticky3() { @Test public void testSticky4() { int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?" + Constants.LAZY_CONNECT_KEY + "=true&timeout=20000"); + URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?" + LAZY_CONNECT_KEY + "=true&timeout=20000"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); @@ -86,4 +87,4 @@ public String get() { return "ok"; } } -} \ No newline at end of file +} diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/FutureFilterTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/FutureFilterTest.java index 7e9818d07f1..39dc86187aa 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/FutureFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/FutureFilterTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.dubbo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invoker; @@ -31,6 +30,7 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import static org.apache.dubbo.common.constants.ConfigConstants.ON_THROW_METHOD_KEY; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -77,10 +77,10 @@ public void testSyncCallbackHasException() throws RpcException, Throwable { RpcResult result = new RpcResult(); result.setException(new RuntimeException()); given(invoker.invoke(invocation)).willReturn(result); - URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1&" + Constants.ON_THROW_METHOD_KEY + "=echo"); + URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1&" + ON_THROW_METHOD_KEY + "=echo"); given(invoker.getUrl()).willReturn(url); eventFilter.invoke(invoker, invocation).recreate(); }); } -} \ No newline at end of file +} diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ImplicitCallBackTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ImplicitCallBackTest.java index 2baa67ccae6..fd5979b7469 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ImplicitCallBackTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ImplicitCallBackTest.java @@ -17,7 +17,6 @@ package org.apache.dubbo.rpc.protocol.dubbo; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.Exporter; diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java b/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java index 0e7bec8e169..45c7134b9c0 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.injvm; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.CollectionUtils; @@ -30,6 +29,9 @@ import java.util.Map; +import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_LOCAL; +import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_REMOTE; import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; import static org.apache.dubbo.common.constants.RpcConstants.LOCAL_PROTOCOL; @@ -96,13 +98,13 @@ public Invoker refer(Class serviceType, URL url) throws RpcException { } public boolean isInjvmRefer(URL url) { - String scope = url.getParameter(Constants.SCOPE_KEY); + String scope = url.getParameter(SCOPE_KEY); // Since injvm protocol is configured explicitly, we don't need to set any extra flag, use normal refer process. - if (Constants.SCOPE_LOCAL.equals(scope) || (url.getParameter(LOCAL_PROTOCOL, false))) { + if (SCOPE_LOCAL.equals(scope) || (url.getParameter(LOCAL_PROTOCOL, false))) { // if it's declared as local reference // 'scope=local' is equivalent to 'injvm=true', injvm will be deprecated in the future release return true; - } else if (Constants.SCOPE_REMOTE.equals(scope)) { + } else if (SCOPE_REMOTE.equals(scope)) { // it's declared as remote reference return false; } else if (url.getParameter(GENERIC_KEY, false)) { diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocolTest.java b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocolTest.java index c640ed0ac30..6c3b72d53ca 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocolTest.java @@ -17,7 +17,6 @@ package org.apache.dubbo.rpc.protocol.injvm; -import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.rpc.Exporter; @@ -35,13 +34,15 @@ import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_LOCAL; +import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_REMOTE; +import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.LOCAL_PROTOCOL; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.LOCAL_PROTOCOL; - /** * ProxiesTest */ @@ -95,13 +96,13 @@ public void testIsInjvmRefer() throws Exception { .addParameter(VERSION_KEY, "*"); assertTrue(InjvmProtocol.getInjvmProtocol().isInjvmRefer(url)); - url = URL.valueOf("fake://127.0.0.1/TestService").addParameter(Constants.SCOPE_KEY, Constants.SCOPE_LOCAL); + url = URL.valueOf("fake://127.0.0.1/TestService").addParameter(SCOPE_KEY, SCOPE_LOCAL); assertTrue(InjvmProtocol.getInjvmProtocol().isInjvmRefer(url)); url = URL.valueOf("fake://127.0.0.1/TestService").addParameter(LOCAL_PROTOCOL,true); assertTrue(InjvmProtocol.getInjvmProtocol().isInjvmRefer(url)); - url = URL.valueOf("fake://127.0.0.1/TestService").addParameter(Constants.SCOPE_KEY, Constants.SCOPE_REMOTE); + url = URL.valueOf("fake://127.0.0.1/TestService").addParameter(SCOPE_KEY, SCOPE_REMOTE); assertFalse(InjvmProtocol.getInjvmProtocol().isInjvmRefer(url)); url = URL.valueOf("fake://127.0.0.1/TestService").addParameter(GENERIC_KEY, true); From 789775b3ae35d673028dd99e5251e92334ff14c3 Mon Sep 17 00:00:00 2001 From: wavesZh <30332053+wavesZh@users.noreply.github.com> Date: Wed, 15 May 2019 11:05:48 +0800 Subject: [PATCH 054/115] Change CopyOnWriteArrayList to regular list in DubboProtocol (#4056) --- .../org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java index 2d993bea27b..4782bbd2907 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java @@ -58,7 +58,6 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.CopyOnWriteArrayList; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; @@ -544,7 +543,7 @@ private void batchClientRefIncr(List referenceCoun * @return */ private List buildReferenceCountExchangeClientList(URL url, int connectNum) { - List clients = new CopyOnWriteArrayList<>(); + List clients = new ArrayList<>(); for (int i = 0; i < connectNum; i++) { clients.add(buildReferenceCountExchangeClient(url)); From ae669ead2ea075360742d70c9b3b026904a3eb90 Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Wed, 15 May 2019 12:30:51 +0800 Subject: [PATCH 055/115] =?UTF-8?q?Dubbo=202.7.0=E7=9A=84provider=E6=97=A0?= =?UTF-8?q?=E6=B3=95=E6=8C=87=E5=AE=9A=E5=AE=A2=E6=88=B7=E7=AB=AF=E9=BB=98?= =?UTF-8?q?=E8=AE=A4async=20(#4058)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #3650 --- .../dubbo/rpc/cluster/support/ClusterUtils.java | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java index 50d64edc0b8..a3418adb845 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java @@ -21,9 +21,7 @@ import org.apache.dubbo.common.utils.StringUtils; import java.util.HashMap; -import java.util.HashSet; import java.util.Map; -import java.util.Set; import static org.apache.dubbo.common.constants.ClusterConstants.TAG_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ALIVE_KEY; @@ -40,7 +38,6 @@ import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.ASYNC_KEY; import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.RpcConstants.INVOKER_LISTENER_KEY; import static org.apache.dubbo.common.constants.RpcConstants.REFERENCE_FILTER_KEY; @@ -81,20 +78,6 @@ public static URL mergeUrl(URL remoteUrl, Map localMap) { map.remove(RemotingConstants.TRANSPORTER_KEY); map.remove(DEFAULT_KEY_PREFIX + RemotingConstants.TRANSPORTER_KEY); - - map.remove(ASYNC_KEY); - map.remove(DEFAULT_KEY_PREFIX + ASYNC_KEY); - - // remove method async entry. - Set methodAsyncKey = new HashSet<>(); - for (String key : map.keySet()) { - if (key != null && key.endsWith("." + ASYNC_KEY)) { - methodAsyncKey.add(key); - } - } - for (String needRemove : methodAsyncKey) { - map.remove(needRemove); - } } if (localMap != null && localMap.size() > 0) { From 4f9d8960665ae1e8cfae1f398c6017d6def5593f Mon Sep 17 00:00:00 2001 From: huazhongming Date: Wed, 15 May 2019 12:42:51 +0800 Subject: [PATCH 056/115] constants step4 remoting (#4057) --- .../common/constants/RemotingConstants.java | 56 --------------- .../org/apache/dubbo/remoting/Constants.java | 68 +++++++++++++++++++ .../support/header/HeaderExchangeClient.java | 11 +-- .../support/header/HeaderExchangeServer.java | 12 ++-- .../remoting/telnet/codec/TelnetCodec.java | 10 +-- .../remoting/transport/AbstractServer.java | 16 +++-- .../ConnectionOrderedChannelHandler.java | 8 ++- .../dubbo/remoting/PerformanceServerTest.java | 4 +- .../support/header/HeartBeatTaskTest.java | 6 +- .../codec/DeprecatedTelnetCodec.java | 5 +- .../grizzly/GrizzlyCodecAdapter.java | 10 ++- dubbo-remoting/dubbo-remoting-http/pom.xml | 5 ++ .../http/tomcat/TomcatHttpServer.java | 4 +- .../transport/mina/MinaCodecAdapter.java | 10 ++- .../transport/netty/NettyCodecAdapter.java | 10 ++- 15 files changed, 141 insertions(+), 94 deletions(-) create mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Constants.java diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RemotingConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RemotingConstants.java index 4e50feea1c9..c2532aa8779 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RemotingConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RemotingConstants.java @@ -30,17 +30,6 @@ public interface RemotingConstants { */ int DEFAULT_PAYLOAD = 8 * 1024 * 1024; - String BUFFER_KEY = "buffer"; - - /** - * default buffer size is 8k. - */ - int DEFAULT_BUFFER_SIZE = 8 * 1024; - - int MAX_BUFFER_SIZE = 16 * 1024; - - int MIN_BUFFER_SIZE = 1 * 1024; - String CONNECT_TIMEOUT_KEY = "connect.timeout"; int DEFAULT_CONNECT_TIMEOUT = 3000; @@ -49,22 +38,12 @@ public interface RemotingConstants { int DEFAULT_HEARTBEAT = 60 * 1000; - String IDLE_TIMEOUT_KEY = "idle.timeout"; - - int DEFAULT_IDLE_TIMEOUT = 600 * 1000; - - String ACCEPTS_KEY = "accepts"; - - int DEFAULT_ACCEPTS = 0; - String SERIALIZATION_KEY = "serialization"; String DEFAULT_REMOTING_SERIALIZATION = "hessian2"; String CODEC_KEY = "codec"; - String DEFAULT_REMOTING_CODEC = "dubbo"; - String SERVER_KEY = "server"; String DEFAULT_REMOTING_SERVER = "netty"; @@ -91,22 +70,8 @@ public interface RemotingConstants { String SENT_KEY = "sent"; - boolean DEFAULT_SENT = false; - String DISPATCHER_KEY = "dispatcher"; - String CHANNEL_HANDLER_KEY = "channel.handler"; - - String DEFAULT_CHANNEL_HANDLER = "default"; - - String SERVICE_DESCIPTOR_KEY = "serviceDescriptor"; - - String CONNECT_QUEUE_CAPACITY = "connect.queue.capacity"; - - String CONNECT_QUEUE_WARNING_SIZE = "connect.queue.warning.size"; - - int DEFAULT_CONNECT_QUEUE_WARNING_SIZE = 1000; - String CHANNEL_ATTRIBUTE_READONLY_KEY = "channel.readonly"; String CHANNEL_READONLYEVENT_SENT_KEY = "channel.readonly.sent"; @@ -115,29 +80,8 @@ public interface RemotingConstants { String EXECUTOR_SERVICE_COMPONENT_KEY = ExecutorService.class.getName(); - String CHARSET_KEY = "charset"; - - String DEFAULT_CHARSET = "UTF-8"; - String BACKUP_KEY = "backup"; - /** - * Every heartbeat duration / HEATBEAT_CHECK_TICK, check if a heartbeat should be sent. Every heartbeat timeout - * duration / HEATBEAT_CHECK_TICK, check if a connection should be closed on server side, and if reconnect on - * client side - */ - int HEARTBEAT_CHECK_TICK = 3; - - /** - * the least heartbeat during is 1000 ms. - */ - long LEAST_HEARTBEAT_DURATION = 1000; - - /** - * ticks per wheel. - */ - int TICKS_PER_WHEEL = 128; - String HEARTBEAT_TIMEOUT_KEY = "heartbeat.timeout"; String RECONNECT_KEY = "reconnect"; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Constants.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Constants.java new file mode 100644 index 00000000000..a057da14e81 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Constants.java @@ -0,0 +1,68 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.remoting; + + +public interface Constants { + + String BUFFER_KEY = "buffer"; + + /** + * default buffer size is 8k. + */ + int DEFAULT_BUFFER_SIZE = 8 * 1024; + + int MAX_BUFFER_SIZE = 16 * 1024; + + int MIN_BUFFER_SIZE = 1 * 1024; + + String IDLE_TIMEOUT_KEY = "idle.timeout"; + + int DEFAULT_IDLE_TIMEOUT = 600 * 1000; + + String ACCEPTS_KEY = "accepts"; + + int DEFAULT_ACCEPTS = 0; + + String CONNECT_QUEUE_CAPACITY = "connect.queue.capacity"; + + String CONNECT_QUEUE_WARNING_SIZE = "connect.queue.warning.size"; + + int DEFAULT_CONNECT_QUEUE_WARNING_SIZE = 1000; + + String CHARSET_KEY = "charset"; + + String DEFAULT_CHARSET = "UTF-8"; + + /** + * Every heartbeat duration / HEATBEAT_CHECK_TICK, check if a heartbeat should be sent. Every heartbeat timeout + * duration / HEATBEAT_CHECK_TICK, check if a connection should be closed on server side, and if reconnect on + * client side + */ + int HEARTBEAT_CHECK_TICK = 3; + + /** + * the least heartbeat during is 1000 ms. + */ + long LEAST_HEARTBEAT_DURATION = 1000; + + /** + * ticks per wheel. + */ + int TICKS_PER_WHEEL = 128; +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java index 944daac3079..a57f82dec34 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java @@ -35,6 +35,9 @@ import static org.apache.dubbo.common.utils.UrlUtils.getHeartbeat; import static org.apache.dubbo.common.utils.UrlUtils.getIdleTimeout; +import static org.apache.dubbo.remoting.Constants.HEARTBEAT_CHECK_TICK; +import static org.apache.dubbo.remoting.Constants.LEAST_HEARTBEAT_DURATION; +import static org.apache.dubbo.remoting.Constants.TICKS_PER_WHEEL; /** * DefaultMessageClient @@ -45,7 +48,7 @@ public class HeaderExchangeClient implements ExchangeClient { private final ExchangeChannel channel; private static final HashedWheelTimer IDLE_CHECK_TIMER = new HashedWheelTimer( - new NamedThreadFactory("dubbo-client-idleCheck", true), 1, TimeUnit.SECONDS, RemotingConstants.TICKS_PER_WHEEL); + new NamedThreadFactory("dubbo-client-idleCheck", true), 1, TimeUnit.SECONDS, TICKS_PER_WHEEL); private HeartbeatTimerTask heartBeatTimerTask; private ReconnectTimerTask reconnectTimerTask; @@ -206,10 +209,10 @@ private void doClose() { * Each interval cannot be less than 1000ms. */ private long calculateLeastDuration(int time) { - if (time / RemotingConstants.HEARTBEAT_CHECK_TICK <= 0) { - return RemotingConstants.LEAST_HEARTBEAT_DURATION; + if (time / HEARTBEAT_CHECK_TICK <= 0) { + return LEAST_HEARTBEAT_DURATION; } else { - return time / RemotingConstants.HEARTBEAT_CHECK_TICK; + return time / HEARTBEAT_CHECK_TICK; } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java index be52d6d601e..0f1e71f7962 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java @@ -42,6 +42,10 @@ import static java.util.Collections.unmodifiableCollection; +import static org.apache.dubbo.remoting.Constants.HEARTBEAT_CHECK_TICK; +import static org.apache.dubbo.remoting.Constants.LEAST_HEARTBEAT_DURATION; +import static org.apache.dubbo.remoting.Constants.TICKS_PER_WHEEL; + /** * ExchangeServerImpl */ @@ -53,7 +57,7 @@ public class HeaderExchangeServer implements ExchangeServer { private AtomicBoolean closed = new AtomicBoolean(false); private static final HashedWheelTimer IDLE_CHECK_TIMER = new HashedWheelTimer(new NamedThreadFactory("dubbo-server-idleCheck", true), 1, - TimeUnit.SECONDS, RemotingConstants.TICKS_PER_WHEEL); + TimeUnit.SECONDS, TICKS_PER_WHEEL); private CloseTimerTask closeTimerTask; @@ -246,10 +250,10 @@ public void send(Object message, boolean sent) throws RemotingException { * Each interval cannot be less than 1000ms. */ private long calculateLeastDuration(int time) { - if (time / RemotingConstants.HEARTBEAT_CHECK_TICK <= 0) { - return RemotingConstants.LEAST_HEARTBEAT_DURATION; + if (time / HEARTBEAT_CHECK_TICK <= 0) { + return LEAST_HEARTBEAT_DURATION; } else { - return time / RemotingConstants.HEARTBEAT_CHECK_TICK; + return time / HEARTBEAT_CHECK_TICK; } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/codec/TelnetCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/codec/TelnetCodec.java index b34ee153692..3ac276bf19c 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/codec/TelnetCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/codec/TelnetCodec.java @@ -17,7 +17,6 @@ package org.apache.dubbo.remoting.telnet.codec; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; @@ -34,6 +33,9 @@ import java.util.LinkedList; import java.util.List; +import static org.apache.dubbo.remoting.Constants.CHARSET_KEY; +import static org.apache.dubbo.remoting.Constants.DEFAULT_CHARSET; + /** * TelnetCodec */ @@ -60,7 +62,7 @@ public class TelnetCodec extends TransportCodec { private static Charset getCharset(Channel channel) { if (channel != null) { - Object attribute = channel.getAttribute(RemotingConstants.CHARSET_KEY); + Object attribute = channel.getAttribute(CHARSET_KEY); if (attribute instanceof String) { try { return Charset.forName((String) attribute); @@ -72,7 +74,7 @@ private static Charset getCharset(Channel channel) { } URL url = channel.getUrl(); if (url != null) { - String parameter = url.getParameter(RemotingConstants.CHARSET_KEY); + String parameter = url.getParameter(CHARSET_KEY); if (StringUtils.isNotEmpty(parameter)) { try { return Charset.forName(parameter); @@ -83,7 +85,7 @@ private static Charset getCharset(Channel channel) { } } try { - return Charset.forName(RemotingConstants.DEFAULT_CHARSET); + return Charset.forName(DEFAULT_CHARSET); } catch (Throwable t) { logger.warn(t.getMessage(), t); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractServer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractServer.java index a252ca46d34..ea801a05c8a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractServer.java @@ -37,6 +37,10 @@ import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; +import static org.apache.dubbo.remoting.Constants.IDLE_TIMEOUT_KEY; +import static org.apache.dubbo.remoting.Constants.DEFAULT_IDLE_TIMEOUT; +import static org.apache.dubbo.remoting.Constants.ACCEPTS_KEY; +import static org.apache.dubbo.remoting.Constants.DEFAULT_ACCEPTS; /** * AbstractServer @@ -61,8 +65,8 @@ public AbstractServer(URL url, ChannelHandler handler) throws RemotingException bindIp = ANYHOST_VALUE; } bindAddress = new InetSocketAddress(bindIp, bindPort); - this.accepts = url.getParameter(RemotingConstants.ACCEPTS_KEY, RemotingConstants.DEFAULT_ACCEPTS); - this.idleTimeout = url.getParameter(RemotingConstants.IDLE_TIMEOUT_KEY, RemotingConstants.DEFAULT_IDLE_TIMEOUT); + this.accepts = url.getParameter(ACCEPTS_KEY, DEFAULT_ACCEPTS); + this.idleTimeout = url.getParameter(IDLE_TIMEOUT_KEY, DEFAULT_IDLE_TIMEOUT); try { doOpen(); if (logger.isInfoEnabled()) { @@ -87,8 +91,8 @@ public void reset(URL url) { return; } try { - if (url.hasParameter(RemotingConstants.ACCEPTS_KEY)) { - int a = url.getParameter(RemotingConstants.ACCEPTS_KEY, 0); + if (url.hasParameter(ACCEPTS_KEY)) { + int a = url.getParameter(ACCEPTS_KEY, 0); if (a > 0) { this.accepts = a; } @@ -97,8 +101,8 @@ public void reset(URL url) { logger.error(t.getMessage(), t); } try { - if (url.hasParameter(RemotingConstants.IDLE_TIMEOUT_KEY)) { - int t = url.getParameter(RemotingConstants.IDLE_TIMEOUT_KEY, 0); + if (url.hasParameter(IDLE_TIMEOUT_KEY)) { + int t = url.getParameter(IDLE_TIMEOUT_KEY, 0); if (t > 0) { this.idleTimeout = t; } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java index 91310ef0f86..33bc2791bbe 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java @@ -17,7 +17,6 @@ package org.apache.dubbo.remoting.transport.dispatcher.connection; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.remoting.Channel; @@ -38,6 +37,9 @@ import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREAD_NAME; +import static org.apache.dubbo.remoting.Constants.CONNECT_QUEUE_CAPACITY; +import static org.apache.dubbo.remoting.Constants.CONNECT_QUEUE_WARNING_SIZE; +import static org.apache.dubbo.remoting.Constants.DEFAULT_CONNECT_QUEUE_WARNING_SIZE; public class ConnectionOrderedChannelHandler extends WrappedChannelHandler { @@ -49,11 +51,11 @@ public ConnectionOrderedChannelHandler(ChannelHandler handler, URL url) { String threadName = url.getParameter(THREAD_NAME_KEY, DEFAULT_THREAD_NAME); connectionExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, - new LinkedBlockingQueue(url.getPositiveParameter(RemotingConstants.CONNECT_QUEUE_CAPACITY, Integer.MAX_VALUE)), + new LinkedBlockingQueue(url.getPositiveParameter(CONNECT_QUEUE_CAPACITY, Integer.MAX_VALUE)), new NamedThreadFactory(threadName, true), new AbortPolicyWithReport(threadName, url) ); // FIXME There's no place to release connectionExecutor! - queuewarninglimit = url.getParameter(RemotingConstants.CONNECT_QUEUE_WARNING_SIZE, RemotingConstants.DEFAULT_CONNECT_QUEUE_WARNING_SIZE); + queuewarninglimit = url.getParameter(CONNECT_QUEUE_WARNING_SIZE, DEFAULT_CONNECT_QUEUE_WARNING_SIZE); } @Override diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.java index 04c9c673426..8f3808a4ec0 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.java @@ -36,6 +36,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS; +import static org.apache.dubbo.remoting.Constants.BUFFER_KEY; +import static org.apache.dubbo.remoting.Constants.DEFAULT_BUFFER_SIZE; /** * PerformanceServer @@ -71,7 +73,7 @@ private static ExchangeServer statServer() throws Exception { final String threadpool = PerformanceUtils.getProperty(THREADPOOL_KEY, DEFAULT_THREADPOOL); final int threads = PerformanceUtils.getIntProperty(THREADS_KEY, DEFAULT_THREADS); final int iothreads = PerformanceUtils.getIntProperty(IO_THREADS_KEY, RemotingConstants.DEFAULT_IO_THREADS); - final int buffer = PerformanceUtils.getIntProperty(RemotingConstants.BUFFER_KEY, RemotingConstants.DEFAULT_BUFFER_SIZE); + final int buffer = PerformanceUtils.getIntProperty(BUFFER_KEY, DEFAULT_BUFFER_SIZE); final String channelHandler = PerformanceUtils.getProperty(RemotingConstants.DISPATCHER_KEY, ExecutionDispatcher.NAME); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.java index 23a0e3a4cc6..aaf8f7a0f6c 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.java @@ -18,7 +18,6 @@ package org.apache.dubbo.remoting.exchange.support.header; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.timer.HashedWheelTimer; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.exchange.Request; @@ -31,6 +30,7 @@ import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.remoting.Constants.HEARTBEAT_CHECK_TICK; public class HeartBeatTaskTest { @@ -44,7 +44,7 @@ public class HeartBeatTaskTest { @BeforeEach public void setup() throws Exception { long tickDuration = 1000; - heartbeatTimer = new HashedWheelTimer(tickDuration / RemotingConstants.HEARTBEAT_CHECK_TICK, TimeUnit.MILLISECONDS); + heartbeatTimer = new HashedWheelTimer(tickDuration / HEARTBEAT_CHECK_TICK, TimeUnit.MILLISECONDS); channel = new MockChannel() { @@ -55,7 +55,7 @@ public URL getUrl() { }; AbstractTimerTask.ChannelProvider cp = () -> Collections.singletonList(channel); - heartbeatTimerTask = new HeartbeatTimerTask(cp, tickDuration / RemotingConstants.HEARTBEAT_CHECK_TICK, (int) tickDuration); + heartbeatTimerTask = new HeartbeatTimerTask(cp, tickDuration / HEARTBEAT_CHECK_TICK, (int) tickDuration); } @Test diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java index 419f01e1b3a..2b37e89b5c5 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java @@ -39,6 +39,7 @@ import java.util.List; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; +import static org.apache.dubbo.remoting.Constants.CHARSET_KEY; public class DeprecatedTelnetCodec implements Codec { @@ -70,7 +71,7 @@ static void checkPayload(Channel channel, long size) throws IOException { private static Charset getCharset(Channel channel) { if (channel != null) { - Object attribute = channel.getAttribute(RemotingConstants.CHARSET_KEY); + Object attribute = channel.getAttribute(CHARSET_KEY); if (attribute instanceof String) { try { return Charset.forName((String) attribute); @@ -82,7 +83,7 @@ private static Charset getCharset(Channel channel) { } URL url = channel.getUrl(); if (url != null) { - String parameter = url.getParameter(RemotingConstants.CHARSET_KEY); + String parameter = url.getParameter(CHARSET_KEY); if (StringUtils.isNotEmpty(parameter)) { try { return Charset.forName(parameter); diff --git a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyCodecAdapter.java b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyCodecAdapter.java index a7162456795..39e6990c195 100644 --- a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyCodecAdapter.java +++ b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyCodecAdapter.java @@ -17,7 +17,6 @@ package org.apache.dubbo.remoting.transport.grizzly; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Codec2; @@ -33,6 +32,11 @@ import java.io.IOException; +import static org.apache.dubbo.remoting.Constants.BUFFER_KEY; +import static org.apache.dubbo.remoting.Constants.DEFAULT_BUFFER_SIZE; +import static org.apache.dubbo.remoting.Constants.MAX_BUFFER_SIZE; +import static org.apache.dubbo.remoting.Constants.MIN_BUFFER_SIZE; + /** * GrizzlyCodecAdapter */ @@ -52,8 +56,8 @@ public GrizzlyCodecAdapter(Codec2 codec, URL url, ChannelHandler handler) { this.codec = codec; this.url = url; this.handler = handler; - int b = url.getPositiveParameter(RemotingConstants.BUFFER_KEY, RemotingConstants.DEFAULT_BUFFER_SIZE); - this.bufferSize = b >= RemotingConstants.MIN_BUFFER_SIZE && b <= RemotingConstants.MAX_BUFFER_SIZE ? b : RemotingConstants.DEFAULT_BUFFER_SIZE; + int b = url.getPositiveParameter(BUFFER_KEY, DEFAULT_BUFFER_SIZE); + this.bufferSize = b >= MIN_BUFFER_SIZE && b <= MAX_BUFFER_SIZE ? b : DEFAULT_BUFFER_SIZE; } @Override diff --git a/dubbo-remoting/dubbo-remoting-http/pom.xml b/dubbo-remoting/dubbo-remoting-http/pom.xml index 9937a191294..19c8220e409 100644 --- a/dubbo-remoting/dubbo-remoting-http/pom.xml +++ b/dubbo-remoting/dubbo-remoting-http/pom.xml @@ -34,6 +34,11 @@ dubbo-common ${project.parent.version} + + org.apache.dubbo + dubbo-remoting-api + ${project.parent.version} + org.eclipse.jetty jetty-server diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java index e59f8f6bd95..df421300cfb 100755 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java @@ -17,7 +17,6 @@ package org.apache.dubbo.remoting.http.tomcat; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.http.HttpHandler; @@ -33,6 +32,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS; +import static org.apache.dubbo.remoting.Constants.ACCEPTS_KEY; public class TomcatHttpServer extends AbstractHttpServer { @@ -57,7 +57,7 @@ public TomcatHttpServer(URL url, final HttpHandler handler) { // "minSpareThreads", String.valueOf(url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS))); tomcat.getConnector().setProperty( - "maxConnections", String.valueOf(url.getParameter(RemotingConstants.ACCEPTS_KEY, -1))); + "maxConnections", String.valueOf(url.getParameter(ACCEPTS_KEY, -1))); tomcat.getConnector().setProperty("URIEncoding", "UTF-8"); tomcat.getConnector().setProperty("connectionTimeout", "60000"); diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaCodecAdapter.java b/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaCodecAdapter.java index 128f119c062..7ce92536664 100644 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaCodecAdapter.java +++ b/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaCodecAdapter.java @@ -17,7 +17,6 @@ package org.apache.dubbo.remoting.transport.mina; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Codec2; @@ -33,6 +32,11 @@ import org.apache.mina.filter.codec.ProtocolEncoder; import org.apache.mina.filter.codec.ProtocolEncoderOutput; +import static org.apache.dubbo.remoting.Constants.BUFFER_KEY; +import static org.apache.dubbo.remoting.Constants.DEFAULT_BUFFER_SIZE; +import static org.apache.dubbo.remoting.Constants.MAX_BUFFER_SIZE; +import static org.apache.dubbo.remoting.Constants.MIN_BUFFER_SIZE; + /** * MinaCodecAdapter. */ @@ -54,8 +58,8 @@ public MinaCodecAdapter(Codec2 codec, URL url, ChannelHandler handler) { this.codec = codec; this.url = url; this.handler = handler; - int b = url.getPositiveParameter(RemotingConstants.BUFFER_KEY, RemotingConstants.DEFAULT_BUFFER_SIZE); - this.bufferSize = b >= RemotingConstants.MIN_BUFFER_SIZE && b <= RemotingConstants.MAX_BUFFER_SIZE ? b : RemotingConstants.DEFAULT_BUFFER_SIZE; + int b = url.getPositiveParameter(BUFFER_KEY, DEFAULT_BUFFER_SIZE); + this.bufferSize = b >= MIN_BUFFER_SIZE && b <= MAX_BUFFER_SIZE ? b : DEFAULT_BUFFER_SIZE; } @Override diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyCodecAdapter.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyCodecAdapter.java index 5088001278c..94e6c17125b 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyCodecAdapter.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyCodecAdapter.java @@ -17,7 +17,6 @@ package org.apache.dubbo.remoting.transport.netty; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.remoting.Codec2; import org.apache.dubbo.remoting.buffer.DynamicChannelBuffer; @@ -35,6 +34,11 @@ import java.io.IOException; +import static org.apache.dubbo.remoting.Constants.BUFFER_KEY; +import static org.apache.dubbo.remoting.Constants.DEFAULT_BUFFER_SIZE; +import static org.apache.dubbo.remoting.Constants.MAX_BUFFER_SIZE; +import static org.apache.dubbo.remoting.Constants.MIN_BUFFER_SIZE; + /** * NettyCodecAdapter. */ @@ -56,8 +60,8 @@ public NettyCodecAdapter(Codec2 codec, URL url, org.apache.dubbo.remoting.Channe this.codec = codec; this.url = url; this.handler = handler; - int b = url.getPositiveParameter(RemotingConstants.BUFFER_KEY, RemotingConstants.DEFAULT_BUFFER_SIZE); - this.bufferSize = b >= RemotingConstants.MIN_BUFFER_SIZE && b <= RemotingConstants.MAX_BUFFER_SIZE ? b : RemotingConstants.DEFAULT_BUFFER_SIZE; + int b = url.getPositiveParameter(BUFFER_KEY, DEFAULT_BUFFER_SIZE); + this.bufferSize = b >= MIN_BUFFER_SIZE && b <= MAX_BUFFER_SIZE ? b : DEFAULT_BUFFER_SIZE; } public ChannelHandler getEncoder() { From cdce2b278364c6391a07e35bca8dd5750529a63e Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Wed, 15 May 2019 14:35:25 +0800 Subject: [PATCH 057/115] [DUBBO-3778]: Annotation mode cannot set service parameters in 2.7.0 (#4060) --- ...bleServiceAnnotationBeanPostProcessor.java | 27 ++++++++++++++++--- .../ServiceAnnotationBeanPostProcessor.java | 25 +++++++++++++++-- 2 files changed, 46 insertions(+), 6 deletions(-) diff --git a/dubbo-compatible/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/CompatibleServiceAnnotationBeanPostProcessor.java b/dubbo-compatible/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/CompatibleServiceAnnotationBeanPostProcessor.java index b71adfdbd77..3d0370c7cc2 100644 --- a/dubbo-compatible/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/CompatibleServiceAnnotationBeanPostProcessor.java +++ b/dubbo-compatible/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/CompatibleServiceAnnotationBeanPostProcessor.java @@ -18,11 +18,11 @@ import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.config.spring.ServiceBean; import org.apache.dubbo.config.spring.context.annotation.DubboClassPathBeanDefinitionScanner; import com.alibaba.dubbo.config.annotation.Service; - import org.springframework.beans.BeansException; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.BeanClassLoaderAware; @@ -54,8 +54,10 @@ import java.util.Arrays; import java.util.Collection; +import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; import java.util.Set; import static org.apache.dubbo.config.spring.util.ObjectUtils.of; @@ -389,7 +391,8 @@ private AbstractBeanDefinition buildServiceBeanDefinition(Service service, Class MutablePropertyValues propertyValues = beanDefinition.getPropertyValues(); - String[] ignoreAttributeNames = of("provider", "monitor", "application", "module", "registry", "protocol", "interface"); + String[] ignoreAttributeNames = of("provider", "monitor", "application", "module", "registry", "protocol", + "interface", "parameters"); propertyValues.addPropertyValues(new AnnotationPropertyValuesAdapter(service, environment, ignoreAttributeNames)); @@ -397,6 +400,8 @@ private AbstractBeanDefinition buildServiceBeanDefinition(Service service, Class addPropertyReference(builder, "ref", annotatedServiceBeanName); // Set interface builder.addPropertyValue("interface", interfaceClass.getName()); + // Convert parameters into map + builder.addPropertyValue("parameters", convertParameters(service.parameters())); /** * Add {@link org.apache.dubbo.config.ProviderConfig} Bean reference @@ -482,6 +487,21 @@ private void addPropertyReference(BeanDefinitionBuilder builder, String property builder.addPropertyReference(propertyName, resolvedBeanName); } + private Map convertParameters(String[] parameters) { + if (ArrayUtils.isEmpty(parameters)) { + return null; + } + + if (parameters.length % 2 != 0) { + throw new IllegalArgumentException("parameter attribute must be paired with key followed by value"); + } + + Map map = new HashMap<>(); + for (int i = 0; i < parameters.length; i += 2) { + map.put(parameters[i], parameters[i + 1]); + } + return map; + } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { @@ -502,5 +522,4 @@ public void setResourceLoader(ResourceLoader resourceLoader) { public void setBeanClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } - -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java index 8a07feed05e..305e3724132 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.config.annotation.Service; import org.apache.dubbo.config.spring.ServiceBean; import org.apache.dubbo.config.spring.context.annotation.DubboClassPathBeanDefinitionScanner; @@ -53,8 +54,10 @@ import java.util.Arrays; import java.util.Collection; +import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; import java.util.Set; import static org.apache.dubbo.config.spring.util.ObjectUtils.of; @@ -372,7 +375,7 @@ private AbstractBeanDefinition buildServiceBeanDefinition(Service service, Class MutablePropertyValues propertyValues = beanDefinition.getPropertyValues(); String[] ignoreAttributeNames = of("provider", "monitor", "application", "module", "registry", "protocol", - "interface", "interfaceName"); + "interface", "interfaceName", "parameters"); propertyValues.addPropertyValues(new AnnotationPropertyValuesAdapter(service, environment, ignoreAttributeNames)); @@ -380,6 +383,8 @@ private AbstractBeanDefinition buildServiceBeanDefinition(Service service, Class addPropertyReference(builder, "ref", annotatedServiceBeanName); // Set interface builder.addPropertyValue("interface", interfaceClass.getName()); + // Convert parameters into map + builder.addPropertyValue("parameters", convertParameters(service.parameters())); /** * Add {@link org.apache.dubbo.config.ProviderConfig} Bean reference @@ -466,6 +471,22 @@ private void addPropertyReference(BeanDefinitionBuilder builder, String property } + private Map convertParameters(String[] parameters) { + if (ArrayUtils.isEmpty(parameters)) { + return null; + } + + if (parameters.length % 2 != 0) { + throw new IllegalArgumentException("parameter attribute must be paired with key followed by value"); + } + + Map map = new HashMap<>(); + for (int i = 0; i < parameters.length; i += 2) { + map.put(parameters[i], parameters[i + 1]); + } + return map; + } + @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { @@ -486,4 +507,4 @@ public void setBeanClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } -} \ No newline at end of file +} From effc2ef9f2c061ddcee3782da811a6fc7331855d Mon Sep 17 00:00:00 2001 From: min Date: Wed, 15 May 2019 17:03:44 +0800 Subject: [PATCH 058/115] remove compatible key when merging (#4064) fixes #4059 --- .../dubbo/rpc/cluster/configurator/AbstractConfigurator.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java index 84275aef9a7..306a720149d 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java @@ -38,6 +38,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.COMPATIBLE_CONFIG_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; /** @@ -126,6 +127,7 @@ private URL configureIfMatch(String host, URL url) { conditionKeys.add(APPLICATION_KEY); conditionKeys.add(SIDE_KEY); conditionKeys.add(CONFIG_VERSION_KEY); + conditionKeys.add(COMPATIBLE_CONFIG_KEY); for (Map.Entry entry : configuratorUrl.getParameters().entrySet()) { String key = entry.getKey(); String value = entry.getValue(); From 310bf91b38a2e1cafe64733d5bdf88ca3c9e4877 Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Wed, 15 May 2019 18:19:12 +0800 Subject: [PATCH 059/115] [DUBBO-3137]: step4 - remove ClusterConstants (#4065) --- .../apache/dubbo/rpc/cluster/Configurator.java | 2 +- .../apache/dubbo/rpc/cluster/Constants.java | 14 ++++---------- .../configurator/AbstractConfigurator.java | 4 ++-- .../configurator/parser/ConfigParser.java | 2 +- .../loadbalance/AbstractLoadBalance.java | 10 +++++----- .../router/condition/ConditionRouter.java | 10 +++++----- .../cluster/router/file/FileRouterFactory.java | 8 ++++---- .../router/mock/MockInvokersSelector.java | 4 ++-- .../cluster/router/script/ScriptRouter.java | 12 ++++++------ .../rpc/cluster/router/tag/TagRouter.java | 18 +++++++++--------- .../support/AbstractClusterInvoker.java | 12 ++++++------ .../rpc/cluster/support/ClusterUtils.java | 2 +- .../support/FailbackClusterInvoker.java | 8 ++++---- .../support/FailoverClusterInvoker.java | 4 ++-- .../cluster/support/ForkingClusterInvoker.java | 4 ++-- .../support/wrapper/MockClusterInvoker.java | 2 +- .../apache/dubbo/rpc/cluster/StickyTest.java | 2 +- .../configurator/parser/ConfigParserTest.java | 6 +++--- .../cluster/directory/StaticDirectoryTest.java | 2 +- .../loadbalance/LoadBalanceBaseTest.java | 4 ++-- .../router/condition/ConditionRouterTest.java | 4 ++-- .../router/file/FileRouterEngineTest.java | 2 +- .../router/script/ScriptRouterTest.java | 2 +- .../support/AbstractClusterInvokerTest.java | 4 ++-- .../common/constants/RegistryConstants.java | 4 ++++ .../com/alibaba/dubbo/common/Constants.java | 5 ++--- .../dubbo/config/AbstractInterfaceConfig.java | 2 +- .../dubbo/config/AbstractMethodConfig.java | 2 +- .../dubbo/config/AbstractReferenceConfig.java | 2 +- .../dubbo/config/annotation/Reference.java | 8 ++++---- .../dubbo/config/annotation/Service.java | 10 +++++----- .../config/AbstractReferenceConfigTest.java | 2 +- .../config/spring/SimpleRegistryExporter.java | 2 +- .../integration/RegistryDirectory.java | 2 +- .../registry/integration/RegistryProtocol.java | 6 +++--- .../registry/dubbo/DubboRegistryFactory.java | 2 +- .../registry/dubbo/RegistryDirectoryTest.java | 12 ++++++------ .../registry/dubbo/SimpleRegistryExporter.java | 2 +- .../org/apache/dubbo/rpc/RpcConstants.java | 5 ++--- .../apache/dubbo/rpc/filter/ContextFilter.java | 2 +- 40 files changed, 103 insertions(+), 107 deletions(-) rename dubbo-common/src/main/java/org/apache/dubbo/common/constants/ClusterConstants.java => dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Constants.java (91%) diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Configurator.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Configurator.java index dd6b4ba8d83..24e568375dc 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Configurator.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Configurator.java @@ -27,7 +27,7 @@ import java.util.Map; import java.util.Optional; -import static org.apache.dubbo.common.constants.ClusterConstants.PRIORITY_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.PRIORITY_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ClusterConstants.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Constants.java similarity index 91% rename from dubbo-common/src/main/java/org/apache/dubbo/common/constants/ClusterConstants.java rename to dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Constants.java index 269fd75a340..8849c267145 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ClusterConstants.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Constants.java @@ -14,15 +14,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package org.apache.dubbo.rpc.cluster; -package org.apache.dubbo.common.constants; - -public interface ClusterConstants { - /** - * key for router type, for e.g., "script"/"file", corresponding to ScriptRouterFactory.NAME, FileRouterFactory.NAME - */ - String ROUTER_KEY = "router"; - +public interface Constants { String LOADBALANCE_KEY = "loadbalance"; String DEFAULT_LOADBALANCE = "random"; @@ -95,8 +89,6 @@ public interface ClusterConstants { String RUNTIME_KEY = "runtime"; - String TAG_KEY = "dubbo.tag"; - String REMOTE_TIMESTAMP_KEY = "remote.timestamp"; String WARMUP_KEY = "warmup"; @@ -106,4 +98,6 @@ public interface ClusterConstants { String CONFIG_VERSION_KEY = "configVersion"; String OVERRIDE_PROVIDERS_KEY = "providerAddresses"; + + String TAG_KEY = "dubbo.tag"; } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java index 306a720149d..cc8b7c0a38f 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java @@ -26,8 +26,8 @@ import java.util.Map; import java.util.Set; -import static org.apache.dubbo.common.constants.ClusterConstants.CONFIG_VERSION_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.OVERRIDE_PROVIDERS_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.CONFIG_VERSION_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.OVERRIDE_PROVIDERS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParser.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParser.java index 5b6f457b14f..349c9f68e8a 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParser.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParser.java @@ -30,7 +30,7 @@ import java.util.List; import java.util.Map; -import static org.apache.dubbo.common.constants.ClusterConstants.OVERRIDE_PROVIDERS_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.OVERRIDE_PROVIDERS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.RegistryConstants.APP_DYNAMIC_CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_CONFIGURATORS_CATEGORY; diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java index 9ca40e37617..ed6f3c4e985 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java @@ -24,11 +24,11 @@ import java.util.List; -import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_WARMUP; -import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_WEIGHT; -import static org.apache.dubbo.common.constants.ClusterConstants.REMOTE_TIMESTAMP_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.WARMUP_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.WEIGHT_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_WARMUP; +import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_WEIGHT; +import static org.apache.dubbo.rpc.cluster.Constants.REMOTE_TIMESTAMP_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.WARMUP_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.WEIGHT_KEY; /** * AbstractLoadBalance diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java index f69b1854fda..5fe82025460 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java @@ -38,11 +38,11 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import static org.apache.dubbo.common.constants.ClusterConstants.ADDRESS_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.FORCE_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.PRIORITY_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.RULE_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.RUNTIME_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.ADDRESS_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.FORCE_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.PRIORITY_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.RUNTIME_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY_PREFIX; import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterFactory.java index 7ad7fc7f897..13e929c6121 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterFactory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterFactory.java @@ -27,10 +27,10 @@ import java.io.FileReader; import java.io.IOException; -import static org.apache.dubbo.common.constants.ClusterConstants.ROUTER_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.RULE_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.RUNTIME_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.TYPE_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.ROUTER_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.RUNTIME_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.TYPE_KEY; public class FileRouterFactory implements RouterFactory { diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelector.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelector.java index 76fa6ded425..c20c5f3abd7 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelector.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelector.java @@ -26,8 +26,8 @@ import java.util.ArrayList; import java.util.List; -import static org.apache.dubbo.common.constants.ClusterConstants.INVOCATION_NEED_MOCK; -import static org.apache.dubbo.common.constants.ClusterConstants.MOCK_PROTOCOL; +import static org.apache.dubbo.rpc.cluster.Constants.INVOCATION_NEED_MOCK; +import static org.apache.dubbo.rpc.cluster.Constants.MOCK_PROTOCOL; /** * A specific Router designed to realize mock feature. diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouter.java index c73d9a9ec13..8d66a9e7b38 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouter.java @@ -39,12 +39,12 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; -import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_SCRIPT_TYPE_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.FORCE_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.PRIORITY_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.RULE_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.RUNTIME_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.TYPE_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_SCRIPT_TYPE_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.FORCE_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.PRIORITY_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.RUNTIME_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.TYPE_KEY; /** * ScriptRouter diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java index 67ab112330f..d4cf9dfd5b4 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java @@ -17,7 +17,6 @@ package org.apache.dubbo.rpc.cluster.router.tag; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.ClusterConstants; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -31,6 +30,7 @@ import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; +import org.apache.dubbo.rpc.cluster.Constants; import org.apache.dubbo.rpc.cluster.router.AbstractRouter; import org.apache.dubbo.rpc.cluster.router.tag.model.TagRouterRule; import org.apache.dubbo.rpc.cluster.router.tag.model.TagRuleParser; @@ -40,7 +40,7 @@ import java.util.function.Predicate; import java.util.stream.Collectors; -import static org.apache.dubbo.common.constants.ClusterConstants.TAG_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.TAG_KEY; import static org.apache.dubbo.common.constants.RpcConstants.FORCE_USE_TAG; /** @@ -97,8 +97,8 @@ public List> route(List> invokers, URL url, Invocation } List> result = invokers; - String tag = StringUtils.isEmpty(invocation.getAttachment(ClusterConstants.TAG_KEY)) ? url.getParameter(ClusterConstants.TAG_KEY) : - invocation.getAttachment(ClusterConstants.TAG_KEY); + String tag = StringUtils.isEmpty(invocation.getAttachment(Constants.TAG_KEY)) ? url.getParameter(Constants.TAG_KEY) : + invocation.getAttachment(Constants.TAG_KEY); // if we are requesting for a Provider with a specific tag if (StringUtils.isNotEmpty(tag)) { @@ -113,7 +113,7 @@ public List> route(List> invokers, URL url, Invocation } else { // dynamic tag group doesn't have any item about the requested app OR it's null after filtered by // dynamic tag group but force=false. check static tag - result = filterInvoker(invokers, invoker -> tag.equals(invoker.getUrl().getParameter(ClusterConstants.TAG_KEY))); + result = filterInvoker(invokers, invoker -> tag.equals(invoker.getUrl().getParameter(Constants.TAG_KEY))); } // If there's no tagged providers that can match the current tagged request. force.tag is set by default // to false, which means it will invoke any providers without a tag unless it's explicitly disallowed. @@ -124,7 +124,7 @@ public List> route(List> invokers, URL url, Invocation else { List> tmp = filterInvoker(invokers, invoker -> addressNotMatches(invoker.getUrl(), tagRouterRuleCopy.getAddresses())); - return filterInvoker(tmp, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(ClusterConstants.TAG_KEY))); + return filterInvoker(tmp, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(Constants.TAG_KEY))); } } else { // List addresses = tagRouterRule.filter(providerApp); @@ -140,7 +140,7 @@ public List> route(List> invokers, URL url, Invocation // static tag group. } return filterInvoker(result, invoker -> { - String localTag = invoker.getUrl().getParameter(ClusterConstants.TAG_KEY); + String localTag = invoker.getUrl().getParameter(Constants.TAG_KEY); return StringUtils.isEmpty(localTag) || !tagRouterRuleCopy.getTagNames().contains(localTag); }); } @@ -163,8 +163,8 @@ public List> route(List> invokers, URL url, Invocation private List> filterUsingStaticTag(List> invokers, URL url, Invocation invocation) { List> result = invokers; // Dynamic param - String tag = StringUtils.isEmpty(invocation.getAttachment(ClusterConstants.TAG_KEY)) ? url.getParameter(ClusterConstants.TAG_KEY) : - invocation.getAttachment(ClusterConstants.TAG_KEY); + String tag = StringUtils.isEmpty(invocation.getAttachment(Constants.TAG_KEY)) ? url.getParameter(Constants.TAG_KEY) : + invocation.getAttachment(Constants.TAG_KEY); // Tag request if (!StringUtils.isEmpty(tag)) { result = filterInvoker(invokers, invoker -> tag.equals(invoker.getUrl().getParameter(TAG_KEY))); diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvoker.java index 922f4dc97df..db2d401eba9 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvoker.java @@ -39,12 +39,12 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; -import static org.apache.dubbo.common.constants.ClusterConstants.CLUSTER_AVAILABLE_CHECK_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.CLUSTER_STICKY_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_CLUSTER_AVAILABLE_CHECK; -import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_CLUSTER_STICKY; -import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_LOADBALANCE; -import static org.apache.dubbo.common.constants.ClusterConstants.LOADBALANCE_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_AVAILABLE_CHECK_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_STICKY_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_CLUSTER_AVAILABLE_CHECK; +import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_CLUSTER_STICKY; +import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_LOADBALANCE; +import static org.apache.dubbo.rpc.cluster.Constants.LOADBALANCE_KEY; /** * AbstractClusterInvoker diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java index a3418adb845..93d2b6bcad9 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java @@ -23,7 +23,7 @@ import java.util.HashMap; import java.util.Map; -import static org.apache.dubbo.common.constants.ClusterConstants.TAG_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.TAG_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ALIVE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY; diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvoker.java index f4ad2ad25dd..a17c4abcbd2 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvoker.java @@ -35,10 +35,10 @@ import java.util.List; import java.util.concurrent.TimeUnit; -import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_FAILBACK_TIMES; -import static org.apache.dubbo.common.constants.ClusterConstants.RETRIES_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_FAILBACK_TASKS; -import static org.apache.dubbo.common.constants.ClusterConstants.FAIL_BACK_TASKS_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_FAILBACK_TIMES; +import static org.apache.dubbo.rpc.cluster.Constants.RETRIES_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_FAILBACK_TASKS; +import static org.apache.dubbo.rpc.cluster.Constants.FAIL_BACK_TASKS_KEY; /** * When fails, record failure requests and schedule for retry on a regular interval. diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvoker.java index bb3fecdeb70..77254470b5d 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvoker.java @@ -34,8 +34,8 @@ import java.util.List; import java.util.Set; -import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_RETRIES; -import static org.apache.dubbo.common.constants.ClusterConstants.RETRIES_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_RETRIES; +import static org.apache.dubbo.rpc.cluster.Constants.RETRIES_KEY; /** * When invoke fails, log the initial error and retry other invokers (retry n times, which means at most n different invokers will be invoked) diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvoker.java index bb44b0bd0f9..70a6eaa75ff 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvoker.java @@ -34,8 +34,8 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_FORKS; -import static org.apache.dubbo.common.constants.ClusterConstants.FORKS_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_FORKS; +import static org.apache.dubbo.rpc.cluster.Constants.FORKS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java index d2db9192533..c9e7ac6ed1c 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java @@ -32,7 +32,7 @@ import java.util.List; -import static org.apache.dubbo.common.constants.ClusterConstants.INVOCATION_NEED_MOCK; +import static org.apache.dubbo.rpc.cluster.Constants.INVOCATION_NEED_MOCK; import static org.apache.dubbo.common.constants.RpcConstants.MOCK_KEY; public class MockClusterInvoker implements Invoker { diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/StickyTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/StickyTest.java index 6b093b97d59..878e3742df6 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/StickyTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/StickyTest.java @@ -34,7 +34,7 @@ import java.util.ArrayList; import java.util.List; -import static org.apache.dubbo.common.constants.ClusterConstants.CLUSTER_STICKY_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_STICKY_KEY; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParserTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParserTest.java index 9f4eb1b69a0..364a813ddc1 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParserTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParserTest.java @@ -30,9 +30,9 @@ import java.io.InputStream; import java.util.List; -import static org.apache.dubbo.common.constants.ClusterConstants.LOADBALANCE_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.OVERRIDE_PROVIDERS_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.WEIGHT_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.LOADBALANCE_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.OVERRIDE_PROVIDERS_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.WEIGHT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java index 03e611ec1eb..7ce8f4ae941 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java @@ -30,7 +30,7 @@ import java.util.ArrayList; import java.util.List; -import static org.apache.dubbo.common.constants.ClusterConstants.RULE_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY; /** * StaticDirectory Test diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LoadBalanceBaseTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LoadBalanceBaseTest.java index 47419fdd8de..fef733ae7af 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LoadBalanceBaseTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LoadBalanceBaseTest.java @@ -37,8 +37,8 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; -import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_WARMUP; -import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_WEIGHT; +import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_WARMUP; +import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_WEIGHT; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java index eb3d28db75c..bf378f0c214 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java @@ -33,8 +33,8 @@ import java.util.ArrayList; import java.util.List; -import static org.apache.dubbo.common.constants.ClusterConstants.FORCE_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.RULE_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.FORCE_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY; public class ConditionRouterTest { diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java index ef7c37b2edc..635014863b1 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java @@ -40,7 +40,7 @@ import java.util.Arrays; import java.util.List; -import static org.apache.dubbo.common.constants.ClusterConstants.RUNTIME_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.RUNTIME_KEY; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouterTest.java index 29b29d1a7d3..f52347f0b85 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouterTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptRouterTest.java @@ -31,7 +31,7 @@ import java.util.ArrayList; import java.util.List; -import static org.apache.dubbo.common.constants.ClusterConstants.RULE_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY; public class ScriptRouterTest { diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java index 6f0b37b7c8f..de191d757ea 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java @@ -47,8 +47,8 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; -import static org.apache.dubbo.common.constants.ClusterConstants.CLUSTER_AVAILABLE_CHECK_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.INVOCATION_NEED_MOCK; +import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_AVAILABLE_CHECK_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.INVOCATION_NEED_MOCK; import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; import static org.apache.dubbo.common.constants.MonitorConstants.MONITOR_KEY; import static org.mockito.BDDMockito.given; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java index d8bf70139f7..d04856f81a1 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java @@ -129,4 +129,8 @@ public interface RegistryConstants { String SESSION_TIMEOUT_KEY = "session"; int DEFAULT_SESSION_TIMEOUT = 60 * 1000; + /** + * key for router type, for e.g., "script"/"file", corresponding to ScriptRouterFactory.NAME, FileRouterFactory.NAME + */ + String ROUTER_KEY = "router"; } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java index b862f9e7e78..f447d2967f5 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java @@ -17,7 +17,6 @@ package com.alibaba.dubbo.common; -import org.apache.dubbo.common.constants.ClusterConstants; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.constants.ConfigConstants; import org.apache.dubbo.common.constants.FilterConstants; @@ -27,6 +26,6 @@ import org.apache.dubbo.common.constants.RpcConstants; @Deprecated -public class Constants implements ClusterConstants, CommonConstants, ConfigConstants, FilterConstants, - MonitorConstants, RegistryConstants, RemotingConstants, RpcConstants { +public class Constants implements CommonConstants, ConfigConstants, FilterConstants, + MonitorConstants, RegistryConstants, RemotingConstants, RpcConstants, org.apache.dubbo.rpc.cluster.Constants { } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java index cd04ac85d22..d0bcb4ddd68 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java @@ -53,7 +53,7 @@ import java.util.Set; import static org.apache.dubbo.common.config.ConfigurationUtils.parseProperties; -import static org.apache.dubbo.common.constants.ClusterConstants.TAG_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.TAG_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractMethodConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractMethodConfig.java index d6d0086c5dd..42e4ca90ef2 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractMethodConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractMethodConfig.java @@ -21,7 +21,7 @@ import java.util.Map; -import static org.apache.dubbo.common.constants.ClusterConstants.LOADBALANCE_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.LOADBALANCE_KEY; import static org.apache.dubbo.common.constants.RpcConstants.FAIL_PREFIX; import static org.apache.dubbo.common.constants.RpcConstants.FORCE_PREFIX; import static org.apache.dubbo.common.constants.RpcConstants.MOCK_KEY; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java index 80409f23d05..7fe8dc4fae2 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java @@ -21,7 +21,7 @@ import org.apache.dubbo.rpc.InvokerListener; import org.apache.dubbo.rpc.support.ProtocolUtils; -import static org.apache.dubbo.common.constants.ClusterConstants.CLUSTER_STICKY_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_STICKY_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.LAZY_CONNECT_KEY; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java index 9ad68c1d73c..d6e93441fd0 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.config.annotation; -import org.apache.dubbo.common.constants.ClusterConstants; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.constants.RpcConstants; import org.apache.dubbo.rpc.ExporterListener; import org.apache.dubbo.rpc.Filter; +import org.apache.dubbo.rpc.cluster.Constants; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; @@ -110,7 +110,7 @@ /** * Whether to stick to the same node in the cluster, the default value is false * - * @see ClusterConstants#DEFAULT_CLUSTER_STICKY + * @see Constants#DEFAULT_CLUSTER_STICKY */ boolean sticky() default false; @@ -164,14 +164,14 @@ /** * Service invocation retry times * - * @see ClusterConstants#DEFAULT_RETRIES + * @see Constants#DEFAULT_RETRIES */ int retries() default 2; /** * Load balance strategy, legal values include: random, roundrobin, leastactive * - * @see ClusterConstants#DEFAULT_LOADBALANCE + * @see Constants#DEFAULT_LOADBALANCE */ String loadbalance() default ""; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Service.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Service.java index 560547102b5..f743386f139 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Service.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Service.java @@ -16,10 +16,10 @@ */ package org.apache.dubbo.config.annotation; -import org.apache.dubbo.common.constants.ClusterConstants; import org.apache.dubbo.common.constants.RpcConstants; import org.apache.dubbo.rpc.ExporterListener; import org.apache.dubbo.rpc.Filter; +import org.apache.dubbo.rpc.cluster.Constants; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; @@ -28,8 +28,8 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_LOADBALANCE; -import static org.apache.dubbo.common.constants.ClusterConstants.DEFAULT_RETRIES; +import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_LOADBALANCE; +import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_RETRIES; /** * Service annotation @@ -173,14 +173,14 @@ /** * Service invocation retry times * - * @see ClusterConstants#DEFAULT_RETRIES + * @see Constants#DEFAULT_RETRIES */ int retries() default DEFAULT_RETRIES; /** * Load balance strategy, legal values include: random, roundrobin, leastactive * - * @see ClusterConstants#DEFAULT_LOADBALANCE + * @see Constants#DEFAULT_LOADBALANCE */ String loadbalance() default DEFAULT_LOADBALANCE; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java index 63683895160..ab40eb1d53f 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java @@ -24,7 +24,7 @@ import java.util.HashMap; import java.util.Map; -import static org.apache.dubbo.common.constants.ClusterConstants.CLUSTER_STICKY_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_STICKY_KEY; import static org.apache.dubbo.common.constants.RpcConstants.INVOKER_LISTENER_KEY; import static org.apache.dubbo.common.constants.RpcConstants.REFERENCE_FILTER_KEY; import static org.apache.dubbo.common.constants.RpcConstants.STUB_EVENT_KEY; diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java index 4f7ea52c455..38f57abc330 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java @@ -27,7 +27,7 @@ import java.io.IOException; import java.net.ServerSocket; -import static org.apache.dubbo.common.constants.ClusterConstants.CLUSTER_STICKY_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_STICKY_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_INSTANCES_LIMIT_KEY; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java index 327b5c029de..20c8b09a4d3 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java @@ -58,7 +58,7 @@ import java.util.Set; import java.util.stream.Collectors; -import static org.apache.dubbo.common.constants.ClusterConstants.ROUTER_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.ROUTER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DISABLED_KEY; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java index 69173d9121c..780d4bc12e5 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java @@ -52,9 +52,9 @@ import java.util.concurrent.ExecutorService; import static java.util.concurrent.Executors.newSingleThreadExecutor; -import static org.apache.dubbo.common.constants.ClusterConstants.LOADBALANCE_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.WARMUP_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.WEIGHT_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.LOADBALANCE_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.WARMUP_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.WEIGHT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; diff --git a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java index 5a3f6ab5655..1728e146e3f 100644 --- a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java +++ b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java @@ -36,7 +36,7 @@ import java.util.HashSet; import java.util.List; -import static org.apache.dubbo.common.constants.ClusterConstants.CLUSTER_STICKY_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_STICKY_KEY; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java index 77616c4912a..b3cb0de7b86 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java @@ -49,12 +49,12 @@ import java.util.Map; import java.util.concurrent.CountDownLatch; -import static org.apache.dubbo.common.constants.ClusterConstants.INVOCATION_NEED_MOCK; -import static org.apache.dubbo.common.constants.ClusterConstants.LOADBALANCE_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.MOCK_PROTOCOL; -import static org.apache.dubbo.common.constants.ClusterConstants.ROUTER_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.RULE_KEY; -import static org.apache.dubbo.common.constants.ClusterConstants.TYPE_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.INVOCATION_NEED_MOCK; +import static org.apache.dubbo.rpc.cluster.Constants.LOADBALANCE_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.MOCK_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.ROUTER_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.TYPE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java index d07c815df9e..785cf528858 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java @@ -27,7 +27,7 @@ import java.io.IOException; import java.net.ServerSocket; -import static org.apache.dubbo.common.constants.ClusterConstants.CLUSTER_STICKY_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_STICKY_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_INSTANCES_LIMIT_KEY; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcConstants.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcConstants.java index 7d592b1c762..8a3b60dfe14 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcConstants.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcConstants.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc; -import org.apache.dubbo.common.constants.ClusterConstants; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.constants.ConfigConstants; import org.apache.dubbo.common.constants.FilterConstants; @@ -30,8 +29,8 @@ * @deprecated Replace to org.apache.dubbo.common.Constants */ @Deprecated -public final class RpcConstants implements ClusterConstants, CommonConstants, ConfigConstants, FilterConstants, - MonitorConstants, RegistryConstants, RemotingConstants, org.apache.dubbo.common.constants.RpcConstants { +public final class RpcConstants implements CommonConstants, ConfigConstants, FilterConstants, MonitorConstants, + RegistryConstants, RemotingConstants, org.apache.dubbo.common.constants.RpcConstants { private RpcConstants() { } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java index 99596bf025b..1d04b8a090c 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java @@ -28,7 +28,6 @@ import java.util.HashMap; import java.util.Map; -import static org.apache.dubbo.common.constants.ClusterConstants.TAG_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; @@ -50,6 +49,7 @@ */ @Activate(group = PROVIDER, order = -10000) public class ContextFilter implements Filter { + private static final String TAG_KEY = "dubbo.tag"; @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { From 85e595e29a7f6b8f4bcef2ca71fb89edb75de4c5 Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Thu, 16 May 2019 10:39:02 +0800 Subject: [PATCH 060/115] [DUBBO-3137]: step4 - remove MonitorConstants (#4069) * [DUBBO-3137]: step4 - remove MonitorConstants * remove unused import --- .../cluster/directory/AbstractDirectory.java | 2 +- .../support/AbstractClusterInvokerTest.java | 2 +- .../common/constants/CommonConstants.java | 2 ++ .../com/alibaba/dubbo/common/Constants.java | 5 ++--- .../dubbo/config/AbstractInterfaceConfig.java | 2 +- .../apache/dubbo/config/MetricsConfig.java | 4 ++-- .../apache/dubbo/config/ReferenceConfig.java | 2 +- .../apache/dubbo/config/ServiceConfig.java | 2 +- .../org/apache/dubbo/monitor/Constants.java | 22 ++++--------------- .../dubbo/monitor/support/MonitorFilter.java | 4 ++-- .../monitor/support/MonitorFilterTest.java | 2 +- .../dubbo/monitor/dubbo/MetricsFilter.java | 18 +++++++-------- .../monitor/dubbo/MetricsFilterTest.java | 14 ++++++------ .../integration/RegistryDirectory.java | 2 +- .../integration/RegistryProtocol.java | 2 +- .../org/apache/dubbo/rpc/RpcConstants.java | 3 +-- 16 files changed, 37 insertions(+), 51 deletions(-) rename dubbo-common/src/main/java/org/apache/dubbo/common/constants/MonitorConstants.java => dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/Constants.java (91%) diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java index 63369653f30..71089fc0eaf 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java @@ -32,7 +32,7 @@ import java.util.Map; import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; -import static org.apache.dubbo.common.constants.MonitorConstants.MONITOR_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; /** diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java index de191d757ea..ca47ba8ab9a 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java @@ -50,7 +50,7 @@ import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_AVAILABLE_CHECK_KEY; import static org.apache.dubbo.rpc.cluster.Constants.INVOCATION_NEED_MOCK; import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; -import static org.apache.dubbo.common.constants.MonitorConstants.MONITOR_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java index 3ce4f83ac0e..702b8412419 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java @@ -157,4 +157,6 @@ public interface CommonConstants { String RELEASE_KEY = "release"; int MAX_PROXY_COUNT = 65535; + + String MONITOR_KEY = "monitor"; } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java index f447d2967f5..1b0042bd7eb 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java @@ -20,12 +20,11 @@ import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.constants.ConfigConstants; import org.apache.dubbo.common.constants.FilterConstants; -import org.apache.dubbo.common.constants.MonitorConstants; import org.apache.dubbo.common.constants.RegistryConstants; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.constants.RpcConstants; @Deprecated -public class Constants implements CommonConstants, ConfigConstants, FilterConstants, - MonitorConstants, RegistryConstants, RemotingConstants, RpcConstants, org.apache.dubbo.rpc.cluster.Constants { +public class Constants implements CommonConstants, ConfigConstants, FilterConstants, RegistryConstants, + RemotingConstants, RpcConstants, org.apache.dubbo.rpc.cluster.Constants, org.apache.dubbo.monitor.Constants { } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java index d0bcb4ddd68..8a337dc3a30 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java @@ -74,7 +74,7 @@ import static org.apache.dubbo.common.constants.ConfigConstants.REGISTRIES_SUFFIX; import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_SECONDS_KEY; -import static org.apache.dubbo.common.constants.MonitorConstants.LOGSTAT_PROTOCOL; +import static org.apache.dubbo.monitor.Constants.LOGSTAT_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MetricsConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MetricsConfig.java index 15d44aa7fde..024480796be 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MetricsConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MetricsConfig.java @@ -19,8 +19,8 @@ import org.apache.dubbo.config.support.Parameter; -import static org.apache.dubbo.common.constants.MonitorConstants.METRICS_PORT; -import static org.apache.dubbo.common.constants.MonitorConstants.METRICS_PROTOCOL; +import static org.apache.dubbo.monitor.Constants.METRICS_PORT; +import static org.apache.dubbo.monitor.Constants.METRICS_PROTOCOL; public class MetricsConfig extends AbstractConfig { diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java index 9fd9e2916fd..0d3e7e93330 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java @@ -69,7 +69,7 @@ import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_IP_TO_REGISTRY; import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.REGISTER_IP_KEY; -import static org.apache.dubbo.common.constants.MonitorConstants.MONITOR_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; import static org.apache.dubbo.common.constants.RpcConstants.LOCAL_PROTOCOL; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index 3ca193e88f8..5d15e3ba753 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -82,7 +82,7 @@ import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_LOCAL; import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_NONE; import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_REMOTE; -import static org.apache.dubbo.common.constants.MonitorConstants.MONITOR_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; import static org.apache.dubbo.common.constants.RpcConstants.LOCAL_PROTOCOL; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/MonitorConstants.java b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/Constants.java similarity index 91% rename from dubbo-common/src/main/java/org/apache/dubbo/common/constants/MonitorConstants.java rename to dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/Constants.java index 94079bf5f95..dc4aea222d8 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/MonitorConstants.java +++ b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/Constants.java @@ -14,33 +14,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package org.apache.dubbo.monitor; -package org.apache.dubbo.common.constants; - -public interface MonitorConstants { - String MONITOR_KEY = "monitor"; - - String LOGSTAT_PROTOCOL = "logstat"; - - String COUNT_PROTOCOL = "count"; - +public interface Constants { String DUBBO_PROVIDER = "dubbo.provider"; - String DUBBO_CONSUMER = "dubbo.consumer"; - String DUBBO_PROVIDER_METHOD = "dubbo.provider.method"; - String DUBBO_CONSUMER_METHOD = "dubbo.consumer.method"; - String SERVICE = "service"; - String METHOD = "method"; - String DUBBO_GROUP = "dubbo"; - String METRICS_KEY = "metrics"; - String METRICS_PORT = "metrics.port"; - String METRICS_PROTOCOL = "metrics.protocol"; + String LOGSTAT_PROTOCOL = "logstat"; + String COUNT_PROTOCOL = "count"; } diff --git a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java index 772676822fd..ef498063dbd 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java +++ b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java @@ -44,8 +44,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.MonitorConstants.COUNT_PROTOCOL; -import static org.apache.dubbo.common.constants.MonitorConstants.MONITOR_KEY; +import static org.apache.dubbo.monitor.Constants.COUNT_PROTOCOL; +import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RpcConstants.INPUT_KEY; import static org.apache.dubbo.common.constants.RpcConstants.OUTPUT_KEY; /** diff --git a/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java b/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java index b9db97ee9c7..586ea60d10d 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java +++ b/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java @@ -40,7 +40,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; -import static org.apache.dubbo.common.constants.MonitorConstants.MONITOR_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; diff --git a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java index fe1df3abbb2..899cc645b20 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java +++ b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java @@ -57,15 +57,15 @@ import java.util.concurrent.atomic.AtomicBoolean; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_PROTOCOL; -import static org.apache.dubbo.common.constants.MonitorConstants.DUBBO_CONSUMER; -import static org.apache.dubbo.common.constants.MonitorConstants.DUBBO_CONSUMER_METHOD; -import static org.apache.dubbo.common.constants.MonitorConstants.DUBBO_GROUP; -import static org.apache.dubbo.common.constants.MonitorConstants.DUBBO_PROVIDER; -import static org.apache.dubbo.common.constants.MonitorConstants.DUBBO_PROVIDER_METHOD; -import static org.apache.dubbo.common.constants.MonitorConstants.METHOD; -import static org.apache.dubbo.common.constants.MonitorConstants.METRICS_PORT; -import static org.apache.dubbo.common.constants.MonitorConstants.METRICS_PROTOCOL; -import static org.apache.dubbo.common.constants.MonitorConstants.SERVICE; +import static org.apache.dubbo.monitor.Constants.DUBBO_CONSUMER; +import static org.apache.dubbo.monitor.Constants.DUBBO_CONSUMER_METHOD; +import static org.apache.dubbo.monitor.Constants.DUBBO_GROUP; +import static org.apache.dubbo.monitor.Constants.DUBBO_PROVIDER; +import static org.apache.dubbo.monitor.Constants.DUBBO_PROVIDER_METHOD; +import static org.apache.dubbo.monitor.Constants.METHOD; +import static org.apache.dubbo.monitor.Constants.METRICS_PORT; +import static org.apache.dubbo.monitor.Constants.METRICS_PROTOCOL; +import static org.apache.dubbo.monitor.Constants.SERVICE; public class MetricsFilter implements Filter { diff --git a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/MetricsFilterTest.java b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/MetricsFilterTest.java index 5bffeac73f4..47b607db7f9 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/MetricsFilterTest.java +++ b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/MetricsFilterTest.java @@ -49,13 +49,13 @@ import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; -import static org.apache.dubbo.common.constants.MonitorConstants.DUBBO_CONSUMER; -import static org.apache.dubbo.common.constants.MonitorConstants.DUBBO_CONSUMER_METHOD; -import static org.apache.dubbo.common.constants.MonitorConstants.DUBBO_GROUP; -import static org.apache.dubbo.common.constants.MonitorConstants.DUBBO_PROVIDER; -import static org.apache.dubbo.common.constants.MonitorConstants.DUBBO_PROVIDER_METHOD; -import static org.apache.dubbo.common.constants.MonitorConstants.METHOD; -import static org.apache.dubbo.common.constants.MonitorConstants.SERVICE; +import static org.apache.dubbo.monitor.Constants.DUBBO_CONSUMER; +import static org.apache.dubbo.monitor.Constants.DUBBO_CONSUMER_METHOD; +import static org.apache.dubbo.monitor.Constants.DUBBO_GROUP; +import static org.apache.dubbo.monitor.Constants.DUBBO_PROVIDER; +import static org.apache.dubbo.monitor.Constants.DUBBO_PROVIDER_METHOD; +import static org.apache.dubbo.monitor.Constants.METHOD; +import static org.apache.dubbo.monitor.Constants.SERVICE; public class MetricsFilterTest { diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java index 20c8b09a4d3..f65785fc33f 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java @@ -68,7 +68,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; -import static org.apache.dubbo.common.constants.MonitorConstants.MONITOR_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.APP_DYNAMIC_CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.COMPATIBLE_CONFIG_KEY; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java index 780d4bc12e5..ef407910ede 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java @@ -75,7 +75,7 @@ import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.REGISTER_IP_KEY; import static org.apache.dubbo.common.constants.FilterConstants.VALIDATION_KEY; -import static org.apache.dubbo.common.constants.MonitorConstants.MONITOR_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_SUFFIX; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcConstants.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcConstants.java index 8a3b60dfe14..57dacca0225 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcConstants.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcConstants.java @@ -19,7 +19,6 @@ import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.constants.ConfigConstants; import org.apache.dubbo.common.constants.FilterConstants; -import org.apache.dubbo.common.constants.MonitorConstants; import org.apache.dubbo.common.constants.RegistryConstants; import org.apache.dubbo.common.constants.RemotingConstants; @@ -29,7 +28,7 @@ * @deprecated Replace to org.apache.dubbo.common.Constants */ @Deprecated -public final class RpcConstants implements CommonConstants, ConfigConstants, FilterConstants, MonitorConstants, +public final class RpcConstants implements CommonConstants, ConfigConstants, FilterConstants, RegistryConstants, RemotingConstants, org.apache.dubbo.common.constants.RpcConstants { private RpcConstants() { From 1798fed5c2a33908b5997e7733095354c2d19ab4 Mon Sep 17 00:00:00 2001 From: huazhongming Date: Thu, 16 May 2019 14:14:21 +0800 Subject: [PATCH 061/115] constants step4 rpc (#4072) --- .../rpc/cluster/router/tag/TagRouter.java | 2 +- .../rpc/cluster/support/ClusterUtils.java | 4 +- .../support/MergeableClusterInvoker.java | 2 +- .../support/wrapper/MockClusterInvoker.java | 2 +- .../cluster/directory/MockDirInvocation.java | 2 +- .../support/MergeableClusterInvokerTest.java | 2 +- .../wrapper/MockClusterInvokerTest.java | 2 +- .../dubbo/common/constants/RpcConstants.java | 148 ------------------ .../apache/dubbo/filter/LegacyInvocation.java | 2 +- .../apache/dubbo/service/MockInvocation.java | 2 +- .../dubbo/config/AbstractInterfaceConfig.java | 12 +- .../dubbo/config/AbstractMethodConfig.java | 10 +- .../dubbo/config/AbstractReferenceConfig.java | 6 +- .../dubbo/config/AbstractServiceConfig.java | 6 +- .../apache/dubbo/config/ReferenceConfig.java | 2 +- .../apache/dubbo/config/ServiceConfig.java | 8 +- .../dubbo/config/annotation/Reference.java | 2 +- .../config/AbstractReferenceConfigTest.java | 6 +- .../config/AbstractServiceConfigTest.java | 4 +- .../dubbo/config/ReferenceConfigTest.java | 2 +- .../dubbo/config/ServiceConfigTest.java | 8 +- .../config/builders/ServiceBuilderTest.java | 6 +- .../dubbo/config/spring/ConfigTest.java | 4 +- .../monitor/dubbo/DubboMonitorFactory.java | 2 +- .../dubbo/DubboMonitorFactoryTest.java | 2 +- .../integration/RegistryProtocol.java | 8 +- .../registry/dubbo/RegistryDirectoryTest.java | 2 +- .../java/org/apache/dubbo/rpc/Constants.java | 105 +++++++++++++ .../org/apache/dubbo/rpc/ProxyFactory.java | 2 +- .../java/org/apache/dubbo/rpc/RpcContext.java | 4 +- .../org/apache/dubbo/rpc/RpcInvocation.java | 2 +- .../dubbo/rpc/filter/AccessLogFilter.java | 2 +- .../dubbo/rpc/filter/ActiveLimitFilter.java | 2 +- .../dubbo/rpc/filter/ContextFilter.java | 6 +- .../dubbo/rpc/filter/DeprecatedFilter.java | 2 +- .../apache/dubbo/rpc/filter/EchoFilter.java | 2 +- .../dubbo/rpc/filter/ExecuteLimitFilter.java | 2 +- .../dubbo/rpc/filter/GenericFilter.java | 8 +- .../dubbo/rpc/filter/GenericImplFilter.java | 2 +- .../apache/dubbo/rpc/filter/TokenFilter.java | 2 +- .../dubbo/rpc/filter/TpsLimitFilter.java | 2 +- .../rpc/filter/tps/DefaultTPSLimiter.java | 6 +- .../listener/DeprecatedInvokerListener.java | 2 +- .../dubbo/rpc/protocol/AbstractInvoker.java | 2 +- .../rpc/protocol/ProtocolFilterWrapper.java | 4 +- .../rpc/protocol/ProtocolListenerWrapper.java | 4 +- .../dubbo/rpc/proxy/AbstractProxyFactory.java | 2 +- .../rpc/proxy/InvokerInvocationHandler.java | 4 +- .../wrapper/StubProxyFactoryWrapper.java | 12 +- .../apache/dubbo/rpc/support/MockInvoker.java | 12 +- .../dubbo/rpc/support/ProtocolUtils.java | 8 +- .../apache/dubbo/rpc/support/RpcUtils.java | 12 +- .../rpc/filter/DeprecatedFilterTest.java | 2 +- .../dubbo/rpc/filter/GenericFilterTest.java | 4 +- .../rpc/filter/GenericImplFilterTest.java | 2 +- .../dubbo/rpc/filter/TokenFilterTest.java | 2 +- .../rpc/filter/tps/DefaultTPSLimiterTest.java | 4 +- .../rpc/filter/tps/TpsLimitFilterTest.java | 2 +- .../dubbo/rpc/support/MockInvocation.java | 2 +- .../dubbo/rpc/support/RpcUtilsTest.java | 2 +- .../protocol/dubbo/CallbackServiceCodec.java | 10 +- .../protocol/dubbo/ChannelWrappedInvoker.java | 6 +- .../dubbo/rpc/protocol/dubbo/Constants.java | 65 ++++++++ .../dubbo/rpc/protocol/dubbo/DubboCodec.java | 4 +- .../rpc/protocol/dubbo/DubboInvoker.java | 2 +- .../rpc/protocol/dubbo/DubboProtocol.java | 19 +-- .../dubbo/LazyConnectExchangeClient.java | 4 +- .../dubbo/ReferenceCountExchangeClient.java | 2 +- .../ReferenceCountExchangeClientTest.java | 2 +- .../dubbo/rpc/service/GenericServiceTest.java | 4 +- .../dubbo/rpc/protocol/hessian/Constants.java | 35 +++++ .../rpc/protocol/hessian/HessianProtocol.java | 13 +- .../dubbo/rpc/protocol/http/HttpProtocol.java | 2 +- .../protocol/http/HttpRemoteInvocation.java | 2 +- .../rpc/protocol/injvm/InjvmProtocol.java | 4 +- .../rpc/protocol/injvm/InjvmProtocolTest.java | 4 +- .../rpc/protocol/rest/BaseRestServer.java | 2 +- .../dubbo/rpc/protocol/rest/Constants.java | 29 ++++ .../dubbo/rpc/protocol/rest/NettyServer.java | 4 +- .../dubbo/rpc/protocol/rest/RestProtocol.java | 2 +- .../rpc/protocol/rest/RestProtocolTest.java | 2 +- .../dubbo/rpc/protocol/rmi/RmiProtocol.java | 2 +- .../rpc/protocol/rmi/RmiRemoteInvocation.java | 2 +- .../rpc/protocol/thrift/ThriftInvoker.java | 2 +- .../rpc/protocol/thrift/ThriftProtocol.java | 2 +- 85 files changed, 401 insertions(+), 313 deletions(-) create mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Constants.java create mode 100644 dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/Constants.java create mode 100644 dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/Constants.java create mode 100644 dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/Constants.java diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java index d4cf9dfd5b4..c6387fe3fc5 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java @@ -41,7 +41,7 @@ import java.util.stream.Collectors; import static org.apache.dubbo.rpc.cluster.Constants.TAG_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.FORCE_USE_TAG; +import static org.apache.dubbo.rpc.Constants.FORCE_USE_TAG; /** * TagRouter, "application.tag-router" diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java index 93d2b6bcad9..4ada4139c1a 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java @@ -39,8 +39,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.INVOKER_LISTENER_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.REFERENCE_FILTER_KEY; +import static org.apache.dubbo.rpc.Constants.INVOKER_LISTENER_KEY; +import static org.apache.dubbo.rpc.Constants.REFERENCE_FILTER_KEY; /** * ClusterUtils diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java index 334b6f2c849..d23459e909d 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java @@ -49,7 +49,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.MERGER_KEY; +import static org.apache.dubbo.rpc.Constants.MERGER_KEY; @SuppressWarnings("unchecked") public class MergeableClusterInvoker extends AbstractClusterInvoker { diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java index c9e7ac6ed1c..c85eed476bb 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java @@ -33,7 +33,7 @@ import java.util.List; import static org.apache.dubbo.rpc.cluster.Constants.INVOCATION_NEED_MOCK; -import static org.apache.dubbo.common.constants.RpcConstants.MOCK_KEY; +import static org.apache.dubbo.rpc.Constants.MOCK_KEY; public class MockClusterInvoker implements Invoker { diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java index fbe697995cd..ec3541eed1f 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java @@ -27,7 +27,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; +import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** * MockInvocation.java diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.java index e80380cbd65..07bae73e2f5 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.java @@ -38,7 +38,7 @@ import java.util.Map; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.MERGER_KEY; +import static org.apache.dubbo.rpc.Constants.MERGER_KEY; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java index 71245539680..9bc5686efd9 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java @@ -38,7 +38,7 @@ import java.util.Arrays; import java.util.List; -import static org.apache.dubbo.common.constants.RpcConstants.MOCK_KEY; +import static org.apache.dubbo.rpc.Constants.MOCK_KEY; public class MockClusterInvokerTest { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RpcConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RpcConstants.java index 9e7302ff0ad..75c70852666 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RpcConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RpcConstants.java @@ -21,44 +21,11 @@ * RpcConstants */ public interface RpcConstants { - // BEGIN dubbo-rpc-hessian - String HESSIAN2_REQUEST_KEY = "hessian2.request"; - - boolean DEFAULT_HESSIAN2_REQUEST = false; - - String HESSIAN_OVERLOAD_METHOD_KEY = "hessian.overload.method"; - - boolean DEFAULT_HESSIAN_OVERLOAD_METHOD = false; - - String DEFAULT_HTTP_CLIENT = "jdk"; - - String DEFAULT_HTTP_SERVER = "servlet"; - - String DEFAULT_HTTP_SERIALIZATION = "json"; - // END dubbo-rpc-hessian - - // BEGIN dubbo-rpc-dubbo - String SHARE_CONNECTIONS_KEY = "shareconnections"; - - /** - * By default, a consumer JVM instance and a provider JVM instance share a long TCP connection (except when connections are set), - * which can set the number of long TCP connections shared to avoid the bottleneck of sharing a single long TCP connection. - */ - String DEFAULT_SHARE_CONNECTIONS = "1"; String INPUT_KEY = "input"; String OUTPUT_KEY = "output"; - String DECODE_IN_IO_THREAD_KEY = "decode.in.io"; - - boolean DEFAULT_DECODE_IN_IO_THREAD = true; - - /** - * callback inst id - */ - String CALLBACK_SERVICE_KEY = "callback.service.instid"; - /** * The limit of callback service instances for one interface on every client */ @@ -71,125 +38,10 @@ public interface RpcConstants { */ int DEFAULT_CALLBACK_INSTANCES = 1; - String CALLBACK_SERVICE_PROXY_KEY = "callback.service.proxy"; - - String IS_CALLBACK_SERVICE = "is_callback_service"; - - /** - * Invokers in channel's callback - */ - String CHANNEL_CALLBACK_KEY = "channel.callback.invokers.key"; - - /** - * The initial state for lazy connection - */ - String LAZY_CONNECT_INITIAL_STATE_KEY = "connect.lazy.initial.state"; - - /** - * The default value of lazy connection's initial state: true - * - * @see #LAZY_CONNECT_INITIAL_STATE_KEY - */ - boolean DEFAULT_LAZY_CONNECT_INITIAL_STATE = true; - - String OPTIMIZER_KEY = "optimizer"; - // END dubbo-rpc-dubbo - - - // BEGIN dubbo-rpc-api String DUBBO_VERSION_KEY = "dubbo"; - String LOCAL_KEY = "local"; - - String STUB_KEY = "stub"; - - String MOCK_KEY = "mock"; - - String DEPRECATED_KEY = "deprecated"; - String $INVOKE = "$invoke"; - String $ECHO = "$echo"; - - String RETURN_PREFIX = "return "; - - String THROW_PREFIX = "throw"; - - String FAIL_PREFIX = "fail:"; - - String FORCE_PREFIX = "force:"; - - String MERGER_KEY = "merger"; - - String IS_SERVER_KEY = "isserver"; - - String FORCE_USE_TAG = "dubbo.force.tag"; - - String GENERIC_SERIALIZATION_NATIVE_JAVA = "nativejava"; - - String GENERIC_SERIALIZATION_DEFAULT = "true"; - - String GENERIC_SERIALIZATION_BEAN = "bean"; - - String GENERIC_SERIALIZATION_PROTOBUF = "protobuf-json"; - - String TPS_LIMIT_RATE_KEY = "tps"; - - String TPS_LIMIT_INTERVAL_KEY = "tps.interval"; - - long DEFAULT_TPS_LIMIT_INTERVAL = 60 * 1000; - - String AUTO_ATTACH_INVOCATIONID_KEY = "invocationid.autoattach"; - - String STUB_EVENT_KEY = "dubbo.stub.event"; - - boolean DEFAULT_STUB_EVENT = false; - - String STUB_EVENT_METHODS_KEY = "dubbo.stub.event.methods"; - - String PROXY_KEY = "proxy"; - - String EXECUTES_KEY = "executes"; - - String REFERENCE_FILTER_KEY = "reference.filter"; - - String INVOKER_LISTENER_KEY = "invoker.listener"; - - String SERVICE_FILTER_KEY = "service.filter"; - - String EXPORTER_LISTENER_KEY = "exporter.listener"; - - String ACCESS_LOG_KEY = "accesslog"; - - String ACTIVES_KEY = "actives"; - String CONNECTIONS_KEY = "connections"; - String ID_KEY = "id"; - - String ASYNC_KEY = "async"; - - String FUTURE_GENERATED_KEY = "future_generated"; - - String FUTURE_RETURNTYPE_KEY = "future_returntype"; - - String RETURN_KEY = "return"; - - String TOKEN_KEY = "token"; - - String INTERFACES = "interfaces"; - - String GENERIC_KEY = "generic"; - - String LOCAL_PROTOCOL = "injvm"; - // END dubbo-rpc-api - - - // BEGIN dubbo-rpc-rest - String KEEP_ALIVE_KEY = "keepalive"; - - boolean DEFAULT_KEEP_ALIVE = true; - - String EXTENSION_KEY = "extension"; - // END dubbo-rpc-rest } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvocation.java b/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvocation.java index 4f4f1314f69..509d316dc27 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvocation.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvocation.java @@ -28,7 +28,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; +import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** * MockInvocation.java diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java b/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java index db85951e312..761ce4b99e7 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java @@ -27,7 +27,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; +import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** * MockInvocation.java diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java index 8a337dc3a30..f94f148ec6e 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java @@ -80,12 +80,12 @@ import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.SUBSCRIBE_KEY; import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.INVOKER_LISTENER_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.LOCAL_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.PROXY_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.REFERENCE_FILTER_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.RETURN_PREFIX; -import static org.apache.dubbo.common.constants.RpcConstants.THROW_PREFIX; +import static org.apache.dubbo.rpc.Constants.INVOKER_LISTENER_KEY; +import static org.apache.dubbo.rpc.Constants.LOCAL_KEY; +import static org.apache.dubbo.rpc.Constants.PROXY_KEY; +import static org.apache.dubbo.rpc.Constants.REFERENCE_FILTER_KEY; +import static org.apache.dubbo.rpc.Constants.RETURN_PREFIX; +import static org.apache.dubbo.rpc.Constants.THROW_PREFIX; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; /** diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractMethodConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractMethodConfig.java index 42e4ca90ef2..0e82c52bd70 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractMethodConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractMethodConfig.java @@ -22,11 +22,11 @@ import java.util.Map; import static org.apache.dubbo.rpc.cluster.Constants.LOADBALANCE_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.FAIL_PREFIX; -import static org.apache.dubbo.common.constants.RpcConstants.FORCE_PREFIX; -import static org.apache.dubbo.common.constants.RpcConstants.MOCK_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.RETURN_PREFIX; -import static org.apache.dubbo.common.constants.RpcConstants.THROW_PREFIX; +import static org.apache.dubbo.rpc.Constants.FAIL_PREFIX; +import static org.apache.dubbo.rpc.Constants.FORCE_PREFIX; +import static org.apache.dubbo.rpc.Constants.MOCK_KEY; +import static org.apache.dubbo.rpc.Constants.RETURN_PREFIX; +import static org.apache.dubbo.rpc.Constants.THROW_PREFIX; /** * AbstractMethodConfig diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java index 7fe8dc4fae2..57ece98b472 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java @@ -25,9 +25,9 @@ import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.LAZY_CONNECT_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.INVOKER_LISTENER_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.REFERENCE_FILTER_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.STUB_EVENT_KEY; +import static org.apache.dubbo.rpc.Constants.INVOKER_LISTENER_KEY; +import static org.apache.dubbo.rpc.Constants.REFERENCE_FILTER_KEY; +import static org.apache.dubbo.rpc.Constants.STUB_EVENT_KEY; /** * AbstractConsumerConfig diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java index 7bf3ccd4d52..8aff2aa7a89 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java @@ -27,9 +27,9 @@ import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.SERVICE_FILTER_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.EXPORTER_LISTENER_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; +import static org.apache.dubbo.rpc.Constants.SERVICE_FILTER_KEY; +import static org.apache.dubbo.rpc.Constants.EXPORTER_LISTENER_KEY; +import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** * AbstractServiceConfig diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java index 0d3e7e93330..1a5fb07957d 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java @@ -72,7 +72,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; -import static org.apache.dubbo.common.constants.RpcConstants.LOCAL_PROTOCOL; +import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL; import static org.apache.dubbo.common.utils.NetUtils.isInvalidLocalHost; /** diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index 5d15e3ba753..266099ee1e1 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -84,10 +84,10 @@ import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_REMOTE; import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.LOCAL_PROTOCOL; -import static org.apache.dubbo.common.constants.RpcConstants.PROXY_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; +import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; +import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL; +import static org.apache.dubbo.rpc.Constants.PROXY_KEY; +import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; import static org.apache.dubbo.common.utils.NetUtils.getAvailablePort; import static org.apache.dubbo.common.utils.NetUtils.getLocalHost; import static org.apache.dubbo.common.utils.NetUtils.isInvalidLocalHost; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java index d6e93441fd0..eb17a000abb 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java @@ -95,7 +95,7 @@ /** * Export an stub service for event dispatch, default value is false. * - * @see RpcConstants#STUB_EVENT_METHODS_KEY + * @see org.apache.dubbo.rpc.Constants#STUB_EVENT_METHODS_KEY */ boolean stubevent() default false; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java index ab40eb1d53f..5cebcc12c40 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java @@ -25,9 +25,9 @@ import java.util.Map; import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_STICKY_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.INVOKER_LISTENER_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.REFERENCE_FILTER_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.STUB_EVENT_KEY; +import static org.apache.dubbo.rpc.Constants.INVOKER_LISTENER_KEY; +import static org.apache.dubbo.rpc.Constants.REFERENCE_FILTER_KEY; +import static org.apache.dubbo.rpc.Constants.STUB_EVENT_KEY; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasKey; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractServiceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractServiceConfigTest.java index 8f0e7171123..3f12e44e68e 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractServiceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractServiceConfigTest.java @@ -33,8 +33,8 @@ import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; -import static org.apache.dubbo.common.constants.RpcConstants.SERVICE_FILTER_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.EXPORTER_LISTENER_KEY; +import static org.apache.dubbo.rpc.Constants.SERVICE_FILTER_KEY; +import static org.apache.dubbo.rpc.Constants.EXPORTER_LISTENER_KEY; public class AbstractServiceConfigTest { @Test diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java index d5941a1b179..d1e02636dd7 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java @@ -28,7 +28,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.apache.dubbo.common.constants.RpcConstants.LOCAL_PROTOCOL; +import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL; public class ReferenceConfigTest { diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java index 09724cdcda3..cb8554cfc97 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java @@ -52,10 +52,10 @@ import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.common.constants.RemotingConstants.BIND_IP_KEY; import static org.apache.dubbo.common.constants.RemotingConstants.BIND_PORT_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_BEAN; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_DEFAULT; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_NATIVE_JAVA; +import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; +import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_BEAN; +import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_DEFAULT; +import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_NATIVE_JAVA; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/builders/ServiceBuilderTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/builders/ServiceBuilderTest.java index 0c93ca6d451..46d1e1f9e12 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/builders/ServiceBuilderTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/builders/ServiceBuilderTest.java @@ -25,9 +25,9 @@ import java.util.Collections; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_BEAN; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_DEFAULT; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_NATIVE_JAVA; +import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_BEAN; +import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_DEFAULT; +import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_NATIVE_JAVA; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ConfigTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ConfigTest.java index 518fedb0161..d44fb17bda3 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ConfigTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ConfigTest.java @@ -65,8 +65,8 @@ import static org.junit.Assert.fail; import static org.junit.matchers.JUnitMatchers.containsString; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_BEAN; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; +import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_BEAN; +import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; /** diff --git a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java index 6764e739327..ddcecc5ac20 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java +++ b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java @@ -29,7 +29,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; import static org.apache.dubbo.common.constants.RemotingConstants.CHECK_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.REFERENCE_FILTER_KEY; +import static org.apache.dubbo.rpc.Constants.REFERENCE_FILTER_KEY; /** * DefaultMonitorFactory diff --git a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactoryTest.java b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactoryTest.java index f96a3ae9281..27bbab5b48b 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactoryTest.java +++ b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactoryTest.java @@ -34,7 +34,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.MockitoAnnotations.initMocks; -import static org.apache.dubbo.common.constants.RpcConstants.REFERENCE_FILTER_KEY; +import static org.apache.dubbo.rpc.Constants.REFERENCE_FILTER_KEY; public class DubboMonitorFactoryTest { private DubboMonitorFactory dubboMonitorFactory; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java index ef407910ede..9c60abdac57 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java @@ -98,11 +98,11 @@ import static org.apache.dubbo.common.constants.RemotingConstants.EXCHANGER_KEY; import static org.apache.dubbo.common.constants.RemotingConstants.SERIALIZATION_KEY; import static org.apache.dubbo.common.constants.RpcConstants.CONNECTIONS_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.DEPRECATED_KEY; import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.INTERFACES; -import static org.apache.dubbo.common.constants.RpcConstants.MOCK_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; +import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY; +import static org.apache.dubbo.rpc.Constants.INTERFACES; +import static org.apache.dubbo.rpc.Constants.MOCK_KEY; +import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; import static org.apache.dubbo.common.utils.UrlUtils.classifyUrls; /** diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java index b3cb0de7b86..7ad418f7e39 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java @@ -69,7 +69,7 @@ import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.ROUTE_PROTOCOL; import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE; -import static org.apache.dubbo.common.constants.RpcConstants.MOCK_KEY; +import static org.apache.dubbo.rpc.Constants.MOCK_KEY; import static org.junit.jupiter.api.Assertions.fail; @SuppressWarnings({"rawtypes", "unchecked"}) diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Constants.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Constants.java new file mode 100644 index 00000000000..c87ccdbbe4b --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Constants.java @@ -0,0 +1,105 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.rpc; + +/** + * + */ +public interface Constants { + String LOCAL_KEY = "local"; + + String STUB_KEY = "stub"; + + String MOCK_KEY = "mock"; + + String DEPRECATED_KEY = "deprecated"; + + String $ECHO = "$echo"; + + String RETURN_PREFIX = "return "; + + String THROW_PREFIX = "throw"; + + String FAIL_PREFIX = "fail:"; + + String FORCE_PREFIX = "force:"; + + String MERGER_KEY = "merger"; + + String IS_SERVER_KEY = "isserver"; + + String FORCE_USE_TAG = "dubbo.force.tag"; + + String GENERIC_SERIALIZATION_NATIVE_JAVA = "nativejava"; + + String GENERIC_SERIALIZATION_DEFAULT = "true"; + + String GENERIC_SERIALIZATION_BEAN = "bean"; + + String GENERIC_SERIALIZATION_PROTOBUF = "protobuf-json"; + + String TPS_LIMIT_RATE_KEY = "tps"; + + String TPS_LIMIT_INTERVAL_KEY = "tps.interval"; + + long DEFAULT_TPS_LIMIT_INTERVAL = 60 * 1000; + + String AUTO_ATTACH_INVOCATIONID_KEY = "invocationid.autoattach"; + + String STUB_EVENT_KEY = "dubbo.stub.event"; + + boolean DEFAULT_STUB_EVENT = false; + + String STUB_EVENT_METHODS_KEY = "dubbo.stub.event.methods"; + + String PROXY_KEY = "proxy"; + + String EXECUTES_KEY = "executes"; + + String REFERENCE_FILTER_KEY = "reference.filter"; + + String INVOKER_LISTENER_KEY = "invoker.listener"; + + String SERVICE_FILTER_KEY = "service.filter"; + + String EXPORTER_LISTENER_KEY = "exporter.listener"; + + String ACCESS_LOG_KEY = "accesslog"; + + String ACTIVES_KEY = "actives"; + + String ID_KEY = "id"; + + String ASYNC_KEY = "async"; + + String FUTURE_GENERATED_KEY = "future_generated"; + + String FUTURE_RETURNTYPE_KEY = "future_returntype"; + + String RETURN_KEY = "return"; + + String TOKEN_KEY = "token"; + + String INTERFACES = "interfaces"; + + String GENERIC_KEY = "generic"; + + String LOCAL_PROTOCOL = "injvm"; + + +} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ProxyFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ProxyFactory.java index 1abe78a4126..c745a765de1 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ProxyFactory.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ProxyFactory.java @@ -20,7 +20,7 @@ import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.SPI; -import static org.apache.dubbo.common.constants.RpcConstants.PROXY_KEY; +import static org.apache.dubbo.rpc.Constants.PROXY_KEY; /** * ProxyFactory. (API/SPI, Singleton, ThreadSafe) diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java index 233a5844066..a468baa0719 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java @@ -38,8 +38,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.ASYNC_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.RETURN_KEY; +import static org.apache.dubbo.rpc.Constants.ASYNC_KEY; +import static org.apache.dubbo.rpc.Constants.RETURN_KEY; /** diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.java index 7c73c825346..a03e3dc15a2 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.java @@ -31,7 +31,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; +import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** * RPC Invocation. diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java index 0e3cfb08cfe..55633719eda 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java @@ -47,7 +47,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.ACCESS_LOG_KEY; +import static org.apache.dubbo.rpc.Constants.ACCESS_LOG_KEY; /** * Record access log for the service. diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java index f0e4f2022d9..0e1df8f1d02 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java @@ -27,7 +27,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.ACTIVES_KEY; +import static org.apache.dubbo.rpc.Constants.ACTIVES_KEY; /** * ActiveLimitFilter restrict the concurrent client invocation for a service or service's method from client side. diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java index 1d04b8a090c..8939c3ace2a 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java @@ -35,10 +35,10 @@ import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.ASYNC_KEY; +import static org.apache.dubbo.rpc.Constants.ASYNC_KEY; import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.FORCE_USE_TAG; -import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; +import static org.apache.dubbo.rpc.Constants.FORCE_USE_TAG; +import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java index b38babea7fa..59fe7c4e18b 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java @@ -29,7 +29,7 @@ import java.util.Set; -import static org.apache.dubbo.common.constants.RpcConstants.DEPRECATED_KEY; +import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY; /** * DeprecatedFilter logs error message if a invoked method has been marked as deprecated. To check whether a method diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/EchoFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/EchoFilter.java index 63d3c9fc4ab..b50e9ffe16c 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/EchoFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/EchoFilter.java @@ -25,7 +25,7 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcResult; -import static org.apache.dubbo.common.constants.RpcConstants.$ECHO; +import static org.apache.dubbo.rpc.Constants.$ECHO; /** * Dubbo provided default Echo echo service, which is available for all dubbo provider service interface. diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java index 1eff0635f6e..f14dddfab68 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java @@ -26,7 +26,7 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcStatus; -import static org.apache.dubbo.common.constants.RpcConstants.EXECUTES_KEY; +import static org.apache.dubbo.rpc.Constants.EXECUTES_KEY; /** diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java index 72f600a5c7d..07702dcb3e9 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java @@ -44,10 +44,10 @@ import java.lang.reflect.Method; import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_NATIVE_JAVA; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_BEAN; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_PROTOBUF; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; +import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_NATIVE_JAVA; +import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_BEAN; +import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_PROTOBUF; +import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; /** * GenericInvokerFilter. diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java index b4b0c6b9e5c..d422fb474e9 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java @@ -40,7 +40,7 @@ import java.lang.reflect.Method; import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; +import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; /** * GenericImplInvokerFilter diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TokenFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TokenFilter.java index 630a866b06d..164f42a89e4 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TokenFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TokenFilter.java @@ -28,7 +28,7 @@ import java.util.Map; -import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; +import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** * Perform check whether given provider token is matching with remote token or not. If it does not match diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TpsLimitFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TpsLimitFilter.java index b6378315615..4678e0109f7 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TpsLimitFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TpsLimitFilter.java @@ -27,7 +27,7 @@ import org.apache.dubbo.rpc.filter.tps.DefaultTPSLimiter; import org.apache.dubbo.rpc.filter.tps.TPSLimiter; -import static org.apache.dubbo.common.constants.RpcConstants.TPS_LIMIT_RATE_KEY; +import static org.apache.dubbo.rpc.Constants.TPS_LIMIT_RATE_KEY; /** * TpsLimitFilter limit the TPS (transaction per second) for all method of a service or a particular method. diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiter.java index 496597e5dc8..058378b18b2 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiter.java @@ -22,9 +22,9 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -import static org.apache.dubbo.common.constants.RpcConstants.TPS_LIMIT_RATE_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.TPS_LIMIT_INTERVAL_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_TPS_LIMIT_INTERVAL; +import static org.apache.dubbo.rpc.Constants.TPS_LIMIT_RATE_KEY; +import static org.apache.dubbo.rpc.Constants.TPS_LIMIT_INTERVAL_KEY; +import static org.apache.dubbo.rpc.Constants.DEFAULT_TPS_LIMIT_INTERVAL; /** * DefaultTPSLimiter is a default implementation for tps filter. It is an in memory based implementation for storing diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/DeprecatedInvokerListener.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/DeprecatedInvokerListener.java index ce324ebcd07..5e983708019 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/DeprecatedInvokerListener.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/DeprecatedInvokerListener.java @@ -22,7 +22,7 @@ import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; -import static org.apache.dubbo.common.constants.RpcConstants.DEPRECATED_KEY; +import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY; /** * DeprecatedProtocolFilter diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractInvoker.java index 5cb5c4dfe2d..e218fa25f09 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractInvoker.java @@ -38,7 +38,7 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; -import static org.apache.dubbo.common.constants.RpcConstants.ASYNC_KEY; +import static org.apache.dubbo.rpc.Constants.ASYNC_KEY; /** * AbstractInvoker. diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolFilterWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolFilterWrapper.java index 4bd945371a6..f0039dbb7ab 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolFilterWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolFilterWrapper.java @@ -32,8 +32,8 @@ import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; -import static org.apache.dubbo.common.constants.RpcConstants.REFERENCE_FILTER_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.SERVICE_FILTER_KEY; +import static org.apache.dubbo.rpc.Constants.REFERENCE_FILTER_KEY; +import static org.apache.dubbo.rpc.Constants.SERVICE_FILTER_KEY; /** * ListenerProtocol diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapper.java index 013ffef7e3d..e8d2a26d8df 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapper.java @@ -31,8 +31,8 @@ import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; -import static org.apache.dubbo.common.constants.RpcConstants.INVOKER_LISTENER_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.EXPORTER_LISTENER_KEY; +import static org.apache.dubbo.rpc.Constants.INVOKER_LISTENER_KEY; +import static org.apache.dubbo.rpc.Constants.EXPORTER_LISTENER_KEY; /** * ListenerProtocol diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.java index 2a792dbbb07..675b9d92990 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.java @@ -25,7 +25,7 @@ import com.alibaba.dubbo.rpc.service.EchoService; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; -import static org.apache.dubbo.common.constants.RpcConstants.INTERFACES; +import static org.apache.dubbo.rpc.Constants.INTERFACES; /** * AbstractProxyFactory diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvokerInvocationHandler.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvokerInvocationHandler.java index fc4e021c9b9..a76f081122c 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvokerInvocationHandler.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvokerInvocationHandler.java @@ -25,8 +25,8 @@ import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; -import static org.apache.dubbo.common.constants.RpcConstants.ASYNC_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.FUTURE_RETURNTYPE_KEY; +import static org.apache.dubbo.rpc.Constants.ASYNC_KEY; +import static org.apache.dubbo.rpc.Constants.FUTURE_RETURNTYPE_KEY; /** * InvokerHandler diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapper.java index 02addc67ddd..dd680359679 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapper.java @@ -35,12 +35,12 @@ import java.lang.reflect.Constructor; -import static org.apache.dubbo.common.constants.RpcConstants.LOCAL_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.STUB_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.IS_SERVER_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.STUB_EVENT_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_STUB_EVENT; -import static org.apache.dubbo.common.constants.RpcConstants.STUB_EVENT_METHODS_KEY; +import static org.apache.dubbo.rpc.Constants.LOCAL_KEY; +import static org.apache.dubbo.rpc.Constants.STUB_KEY; +import static org.apache.dubbo.rpc.Constants.IS_SERVER_KEY; +import static org.apache.dubbo.rpc.Constants.STUB_EVENT_KEY; +import static org.apache.dubbo.rpc.Constants.DEFAULT_STUB_EVENT; +import static org.apache.dubbo.rpc.Constants.STUB_EVENT_METHODS_KEY; /** * StubProxyFactoryWrapper diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java index f2f6afb10d9..32fc5ae6324 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java @@ -39,12 +39,12 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import static org.apache.dubbo.common.constants.RpcConstants.MOCK_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.RETURN_PREFIX; -import static org.apache.dubbo.common.constants.RpcConstants.THROW_PREFIX; -import static org.apache.dubbo.common.constants.RpcConstants.FAIL_PREFIX; -import static org.apache.dubbo.common.constants.RpcConstants.FORCE_PREFIX; -import static org.apache.dubbo.common.constants.RpcConstants.RETURN_KEY; +import static org.apache.dubbo.rpc.Constants.MOCK_KEY; +import static org.apache.dubbo.rpc.Constants.RETURN_PREFIX; +import static org.apache.dubbo.rpc.Constants.THROW_PREFIX; +import static org.apache.dubbo.rpc.Constants.FAIL_PREFIX; +import static org.apache.dubbo.rpc.Constants.FORCE_PREFIX; +import static org.apache.dubbo.rpc.Constants.RETURN_KEY; final public class MockInvoker implements Invoker { private final static ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/ProtocolUtils.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/ProtocolUtils.java index 33e42ca4b41..b9a51ca657c 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/ProtocolUtils.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/ProtocolUtils.java @@ -21,10 +21,10 @@ import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_NATIVE_JAVA; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_DEFAULT; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_BEAN; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_PROTOBUF; +import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_NATIVE_JAVA; +import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_DEFAULT; +import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_BEAN; +import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_PROTOBUF; public class ProtocolUtils { diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java index 86a506afec4..18e59ba4170 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java @@ -34,12 +34,12 @@ import java.util.concurrent.atomic.AtomicLong; import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE; -import static org.apache.dubbo.common.constants.RpcConstants.AUTO_ATTACH_INVOCATIONID_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.ID_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.ASYNC_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.FUTURE_GENERATED_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.FUTURE_RETURNTYPE_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.RETURN_KEY; +import static org.apache.dubbo.rpc.Constants.AUTO_ATTACH_INVOCATIONID_KEY; +import static org.apache.dubbo.rpc.Constants.ID_KEY; +import static org.apache.dubbo.rpc.Constants.ASYNC_KEY; +import static org.apache.dubbo.rpc.Constants.FUTURE_GENERATED_KEY; +import static org.apache.dubbo.rpc.Constants.FUTURE_RETURNTYPE_KEY; +import static org.apache.dubbo.rpc.Constants.RETURN_KEY; /** * RpcUtils */ diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/DeprecatedFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/DeprecatedFilterTest.java index eab8d32beb5..1c7b4d4a4c3 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/DeprecatedFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/DeprecatedFilterTest.java @@ -28,7 +28,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.apache.dubbo.common.constants.RpcConstants.DEPRECATED_KEY; +import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY; /** * DeprecatedFilterTest.java diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.java index ef3cd8fb1be..f7639f7f57f 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.java @@ -33,8 +33,8 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_NATIVE_JAVA; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; +import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_NATIVE_JAVA; +import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; public class GenericFilterTest { GenericFilter genericFilter = new GenericFilter(); diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java index c1afcdd3e87..5adbdb728ab 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java @@ -39,7 +39,7 @@ import static org.mockito.Mockito.when; import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; +import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; public class GenericImplFilterTest { diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TokenFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TokenFilterTest.java index 5c0b778ff89..275ddabcdc6 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TokenFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TokenFilterTest.java @@ -33,7 +33,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; -import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; +import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; public class TokenFilterTest { diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiterTest.java index 57543fefe6e..6633f587a9c 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiterTest.java @@ -24,8 +24,8 @@ import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.TPS_LIMIT_RATE_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.TPS_LIMIT_INTERVAL_KEY; +import static org.apache.dubbo.rpc.Constants.TPS_LIMIT_RATE_KEY; +import static org.apache.dubbo.rpc.Constants.TPS_LIMIT_INTERVAL_KEY; public class DefaultTPSLimiterTest { diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/TpsLimitFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/TpsLimitFilterTest.java index 16eda85dc7b..9515278588a 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/TpsLimitFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/TpsLimitFilterTest.java @@ -28,7 +28,7 @@ import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.TPS_LIMIT_RATE_KEY; +import static org.apache.dubbo.rpc.Constants.TPS_LIMIT_RATE_KEY; import static org.junit.jupiter.api.Assertions.assertTrue; public class TpsLimitFilterTest { diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java index 6df479cf06a..44e330724c8 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java @@ -27,7 +27,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; +import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** * MockInvocation.java diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/RpcUtilsTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/RpcUtilsTest.java index 1209ebd710d..a38c43777f2 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/RpcUtilsTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/RpcUtilsTest.java @@ -35,7 +35,7 @@ import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.apache.dubbo.common.constants.RpcConstants.AUTO_ATTACH_INVOCATIONID_KEY; +import static org.apache.dubbo.rpc.Constants.AUTO_ATTACH_INVOCATIONID_KEY; public class RpcUtilsTest { diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java index 0800c66783b..7e26606bd99 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java @@ -40,13 +40,13 @@ import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_SERVICE_KEY; +import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CALLBACK_SERVICE_KEY; import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_INSTANCES_LIMIT_KEY; import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_CALLBACK_INSTANCES; -import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_SERVICE_PROXY_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.IS_CALLBACK_SERVICE; -import static org.apache.dubbo.common.constants.RpcConstants.CHANNEL_CALLBACK_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.IS_SERVER_KEY; +import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CALLBACK_SERVICE_PROXY_KEY; +import static org.apache.dubbo.rpc.protocol.dubbo.Constants.IS_CALLBACK_SERVICE; +import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CHANNEL_CALLBACK_KEY; +import static org.apache.dubbo.rpc.Constants.IS_SERVER_KEY; /** * callback service helper diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java index 5879cc2d12b..b9f96235d89 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java @@ -38,9 +38,9 @@ import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_SERVICE_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.ASYNC_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; +import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CALLBACK_SERVICE_KEY; +import static org.apache.dubbo.rpc.Constants.ASYNC_KEY; +import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** * Wrap the existing invoker on the channel. diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/Constants.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/Constants.java new file mode 100644 index 00000000000..9d86b5d0228 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/Constants.java @@ -0,0 +1,65 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.rpc.protocol.dubbo; + +/** + * + */ +public interface Constants { + + String SHARE_CONNECTIONS_KEY = "shareconnections"; + + /** + * By default, a consumer JVM instance and a provider JVM instance share a long TCP connection (except when connections are set), + * which can set the number of long TCP connections shared to avoid the bottleneck of sharing a single long TCP connection. + */ + String DEFAULT_SHARE_CONNECTIONS = "1"; + + String DECODE_IN_IO_THREAD_KEY = "decode.in.io"; + + boolean DEFAULT_DECODE_IN_IO_THREAD = true; + + /** + * callback inst id + */ + String CALLBACK_SERVICE_KEY = "callback.service.instid"; + + String CALLBACK_SERVICE_PROXY_KEY = "callback.service.proxy"; + + String IS_CALLBACK_SERVICE = "is_callback_service"; + + /** + * Invokers in channel's callback + */ + String CHANNEL_CALLBACK_KEY = "channel.callback.invokers.key"; + + /** + * The initial state for lazy connection + */ + String LAZY_CONNECT_INITIAL_STATE_KEY = "connect.lazy.initial.state"; + + /** + * The default value of lazy connection's initial state: true + * + * @see #LAZY_CONNECT_INITIAL_STATE_KEY + */ + boolean DEFAULT_LAZY_CONNECT_INITIAL_STATE = true; + + String OPTIMIZER_KEY = "optimizer"; + +} diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java index 48e8bb227f3..1e12bb9736c 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java @@ -41,8 +41,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.CallbackServiceCodec.encodeInvocationArgument; -import static org.apache.dubbo.common.constants.RpcConstants.DECODE_IN_IO_THREAD_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_DECODE_IN_IO_THREAD; +import static org.apache.dubbo.rpc.protocol.dubbo.Constants.DECODE_IN_IO_THREAD_KEY; +import static org.apache.dubbo.rpc.protocol.dubbo.Constants.DEFAULT_DECODE_IN_IO_THREAD; import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; /** diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java index 25c1c2c8c43..dcf6f9d835c 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java @@ -45,7 +45,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; +import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** * DubboInvoker diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java index 4782bbd2907..c9670bfe9d8 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java @@ -66,16 +66,17 @@ import static org.apache.dubbo.common.constants.ConfigConstants.LAZY_CONNECT_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.ON_CONNECT_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.ON_DISCONNECT_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_SERVICE_KEY; +import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CALLBACK_SERVICE_KEY; import static org.apache.dubbo.common.constants.RpcConstants.CONNECTIONS_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_SHARE_CONNECTIONS; -import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_STUB_EVENT; -import static org.apache.dubbo.common.constants.RpcConstants.IS_CALLBACK_SERVICE; -import static org.apache.dubbo.common.constants.RpcConstants.IS_SERVER_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.OPTIMIZER_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.SHARE_CONNECTIONS_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.STUB_EVENT_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.STUB_EVENT_METHODS_KEY; +import static org.apache.dubbo.rpc.Constants.DEFAULT_STUB_EVENT; +import static org.apache.dubbo.rpc.protocol.dubbo.Constants.IS_CALLBACK_SERVICE; +import static org.apache.dubbo.rpc.Constants.IS_SERVER_KEY; +import static org.apache.dubbo.rpc.protocol.dubbo.Constants.OPTIMIZER_KEY; +import static org.apache.dubbo.rpc.Constants.STUB_EVENT_KEY; +import static org.apache.dubbo.rpc.Constants.STUB_EVENT_METHODS_KEY; +import static org.apache.dubbo.rpc.protocol.dubbo.Constants.SHARE_CONNECTIONS_KEY; +import static org.apache.dubbo.rpc.protocol.dubbo.Constants.DEFAULT_SHARE_CONNECTIONS; + /** * dubbo protocol support. diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java index 42db9617570..c73bb56a284 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java @@ -34,8 +34,8 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; -import static org.apache.dubbo.common.constants.RpcConstants.LAZY_CONNECT_INITIAL_STATE_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_LAZY_CONNECT_INITIAL_STATE; +import static org.apache.dubbo.rpc.protocol.dubbo.Constants.LAZY_CONNECT_INITIAL_STATE_KEY; +import static org.apache.dubbo.rpc.protocol.dubbo.Constants.DEFAULT_LAZY_CONNECT_INITIAL_STATE; /** * dubbo protocol support class. diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java index 519490b0efd..ae7934b2594 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java @@ -30,7 +30,7 @@ import java.net.InetSocketAddress; import java.util.concurrent.atomic.AtomicInteger; -import static org.apache.dubbo.common.constants.RpcConstants.LAZY_CONNECT_INITIAL_STATE_KEY; +import static org.apache.dubbo.rpc.protocol.dubbo.Constants.LAZY_CONNECT_INITIAL_STATE_KEY; /** * dubbo protocol support class. diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java index 50f592fcf64..1f01e658c45 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java @@ -39,7 +39,7 @@ import java.util.List; import java.util.Objects; -import static org.apache.dubbo.common.constants.RpcConstants.SHARE_CONNECTIONS_KEY; +import static org.apache.dubbo.rpc.protocol.dubbo.Constants.SHARE_CONNECTIONS_KEY; import static org.apache.dubbo.common.constants.RpcConstants.CONNECTIONS_KEY; diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/service/GenericServiceTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/service/GenericServiceTest.java index daa93046763..e99c6fce095 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/service/GenericServiceTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/service/GenericServiceTest.java @@ -42,8 +42,8 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicReference; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_NATIVE_JAVA; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_SERIALIZATION_BEAN; +import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_NATIVE_JAVA; +import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_BEAN; /** * GenericServiceTest diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/Constants.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/Constants.java new file mode 100644 index 00000000000..7b5eb6c4c20 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/Constants.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.rpc.protocol.hessian; + +/** + * + */ +public interface Constants { + + String HESSIAN2_REQUEST_KEY = "hessian2.request"; + + boolean DEFAULT_HESSIAN2_REQUEST = false; + + String HESSIAN_OVERLOAD_METHOD_KEY = "hessian.overload.method"; + + boolean DEFAULT_HESSIAN_OVERLOAD_METHOD = false; + + String DEFAULT_HTTP_CLIENT = "jdk"; + +} diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocol.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocol.java index 94b86aeecd3..90e9f1cef4b 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocol.java +++ b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocol.java @@ -46,12 +46,13 @@ import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.HESSIAN2_REQUEST_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_HESSIAN2_REQUEST; -import static org.apache.dubbo.common.constants.RpcConstants.HESSIAN_OVERLOAD_METHOD_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_HESSIAN_OVERLOAD_METHOD; -import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_HTTP_CLIENT; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; +import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; +import static org.apache.dubbo.rpc.protocol.hessian.Constants.HESSIAN2_REQUEST_KEY; +import static org.apache.dubbo.rpc.protocol.hessian.Constants.DEFAULT_HESSIAN2_REQUEST; +import static org.apache.dubbo.rpc.protocol.hessian.Constants.HESSIAN_OVERLOAD_METHOD_KEY; +import static org.apache.dubbo.rpc.protocol.hessian.Constants.DEFAULT_HESSIAN_OVERLOAD_METHOD; +import static org.apache.dubbo.rpc.protocol.hessian.Constants.DEFAULT_HTTP_CLIENT; + /** * http rpc support. */ diff --git a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java b/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java index 342afeaca60..19fa904c15b 100644 --- a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java +++ b/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java @@ -51,7 +51,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; +import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; /** * HttpProtocol diff --git a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpRemoteInvocation.java b/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpRemoteInvocation.java index b60120546e6..26561728a62 100644 --- a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpRemoteInvocation.java +++ b/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpRemoteInvocation.java @@ -27,7 +27,7 @@ import java.util.HashMap; import java.util.Map; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; +import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; public class HttpRemoteInvocation extends RemoteInvocation { diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java b/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java index 45c7134b9c0..96f5902e48f 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java @@ -32,8 +32,8 @@ import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_LOCAL; import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_REMOTE; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.LOCAL_PROTOCOL; +import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; +import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL; /** * InjvmProtocol diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocolTest.java b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocolTest.java index 6c3b72d53ca..283d33c65e8 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocolTest.java @@ -37,8 +37,8 @@ import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_LOCAL; import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_REMOTE; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.LOCAL_PROTOCOL; +import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; +import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/BaseRestServer.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/BaseRestServer.java index 41a67915d61..e3d1acc7df3 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/BaseRestServer.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/BaseRestServer.java @@ -22,7 +22,7 @@ import org.jboss.resteasy.spi.ResteasyDeployment; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; -import static org.apache.dubbo.common.constants.RpcConstants.EXTENSION_KEY; +import static org.apache.dubbo.rpc.protocol.rest.Constants.EXTENSION_KEY; public abstract class BaseRestServer implements RestServer { diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/Constants.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/Constants.java new file mode 100644 index 00000000000..90747c9a3ab --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/Constants.java @@ -0,0 +1,29 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.rpc.protocol.rest; + +/** + * + */ +public interface Constants { + String KEEP_ALIVE_KEY = "keepalive"; + + boolean DEFAULT_KEEP_ALIVE = true; + + String EXTENSION_KEY = "extension"; +} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/NettyServer.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/NettyServer.java index 370f26acc7c..7ee8c006ab3 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/NettyServer.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/NettyServer.java @@ -30,8 +30,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS; import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.KEEP_ALIVE_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_KEEP_ALIVE; +import static org.apache.dubbo.rpc.protocol.rest.Constants.KEEP_ALIVE_KEY; +import static org.apache.dubbo.rpc.protocol.rest.Constants.DEFAULT_KEEP_ALIVE; /** * Netty server can't support @Context injection of servlet objects since it's not a servlet container diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java index af72a465665..22d7607d841 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java @@ -56,7 +56,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.RpcConstants.CONNECTIONS_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.EXTENSION_KEY; +import static org.apache.dubbo.rpc.protocol.rest.Constants.EXTENSION_KEY; public class RestProtocol extends AbstractProxyProtocol { diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/RestProtocolTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/RestProtocolTest.java index 1b68c098e65..efcc87c24e2 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/RestProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/RestProtocolTest.java @@ -39,7 +39,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; -import static org.apache.dubbo.common.constants.RpcConstants.EXTENSION_KEY; +import static org.apache.dubbo.rpc.protocol.rest.Constants.EXTENSION_KEY; public class RestProtocolTest { private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest"); diff --git a/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocol.java b/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocol.java index 9b7f16b722c..cbf16872840 100644 --- a/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocol.java +++ b/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocol.java @@ -32,7 +32,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY; import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; +import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; import static org.apache.dubbo.common.Version.isRelease263OrHigher; import static org.apache.dubbo.common.Version.isRelease270OrHigher; diff --git a/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiRemoteInvocation.java b/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiRemoteInvocation.java index d03618ea2bc..cdb25183f6d 100644 --- a/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiRemoteInvocation.java +++ b/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiRemoteInvocation.java @@ -26,7 +26,7 @@ import java.util.HashMap; import java.util.Map; -import static org.apache.dubbo.common.constants.RpcConstants.GENERIC_KEY; +import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; public class RmiRemoteInvocation extends RemoteInvocation { private static final long serialVersionUID = 1L; diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java index a5306844b30..aa337f9e456 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java @@ -38,7 +38,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.TOKEN_KEY; +import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java index 9f56a736f0c..0d6206ae8a3 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java @@ -44,7 +44,7 @@ import java.util.concurrent.ConcurrentMap; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.IS_SERVER_KEY; +import static org.apache.dubbo.rpc.Constants.IS_SERVER_KEY; import static org.apache.dubbo.common.constants.RpcConstants.CONNECTIONS_KEY; /** From 4ef74fa9c612975fb86e486ae0206eda81a02e3d Mon Sep 17 00:00:00 2001 From: "ken.lj" Date: Thu, 16 May 2019 16:59:28 +0800 Subject: [PATCH 062/115] [Dubbo-3669] Only parse rules on init, does not override. (#3685) --- .../AbstractConfiguratorListener.java | 24 ++++++++++++------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java index 46beabd0e89..5258d24c9f4 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java @@ -44,7 +44,7 @@ protected final void initWith(String key) { dynamicConfiguration.addListener(key, this); String rawConfig = dynamicConfiguration.getConfig(key, CommonConstants.DUBBO); if (!StringUtils.isEmpty(rawConfig)) { - process(new ConfigChangeEvent(key, rawConfig)); + genConfiguratorsFromRawRule(rawConfig); } } @@ -58,13 +58,7 @@ public void process(ConfigChangeEvent event) { if (event.getChangeType().equals(ConfigChangeType.DELETED)) { configurators.clear(); } else { - try { - // parseConfigurators will recognize app/service config automatically. - configurators = Configurator.toConfigurators(ConfigParser.parseConfigurators(event.getValue())) - .orElse(configurators); - } catch (Exception e) { - logger.error("Failed to parse raw dynamic config and it will not take effect, the raw config is: " + - event.getValue(), e); + if (!genConfiguratorsFromRawRule(event.getValue())) { return; } } @@ -72,6 +66,20 @@ public void process(ConfigChangeEvent event) { notifyOverrides(); } + private boolean genConfiguratorsFromRawRule(String rawConfig) { + boolean parseSuccess = true; + try { + // parseConfigurators will recognize app/service config automatically. + configurators = Configurator.toConfigurators(ConfigParser.parseConfigurators(rawConfig)) + .orElse(configurators); + } catch (Exception e) { + logger.error("Failed to parse raw dynamic config and it will not take effect, the raw config is: " + + rawConfig, e); + parseSuccess = false; + } + return parseSuccess; + } + protected abstract void notifyOverrides(); public List getConfigurators() { From 228cad5ef439b7db6fe62566dcd158ce0a127b4b Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Thu, 16 May 2019 17:25:14 +0800 Subject: [PATCH 063/115] [DUBBO-3137]: step4 - move more constants from RemotingConstants into dubbo-remoting-api (#4077) * [DUBBO-3137]: step4 - move more constants from RemotingConstants into dubbo-remoting-api * optimize imports --- .../configurator/AbstractConfigurator.java | 4 +- .../rpc/cluster/support/ClusterUtils.java | 6 +- .../common/constants/RemotingConstants.java | 65 ------------------- .../dubbo/config/AbstractReferenceConfig.java | 4 +- .../apache/dubbo/config/ProtocolConfig.java | 16 ++--- .../apache/dubbo/config/ProviderConfig.java | 8 +-- .../apache/dubbo/config/ReferenceConfig.java | 4 +- .../apache/dubbo/config/RegistryConfig.java | 8 +-- .../apache/dubbo/config/ServiceConfig.java | 6 +- .../dubbo/config/annotation/Reference.java | 3 +- .../config/AbstractReferenceConfigTest.java | 4 +- .../dubbo/config/ServiceConfigTest.java | 4 +- .../integration/MetadataReportService.java | 6 +- .../monitor/dubbo/DubboMonitorFactory.java | 2 +- .../dubbo/monitor/dubbo/MetricsFilter.java | 4 +- .../integration/RegistryDirectory.java | 4 +- .../integration/RegistryProtocol.java | 12 ++-- .../registry/support/FailbackRegistry.java | 18 ++--- .../dubbo/registry/dubbo/DubboRegistry.java | 4 +- .../registry/dubbo/DubboRegistryFactory.java | 4 +- .../registry/dubbo/DubboRegistryTest.java | 6 +- .../registry/dubbo/RegistryDirectoryTest.java | 4 +- .../dubbo/registry/etcd/EtcdRegistry.java | 6 +- .../dubbo/registry/etcd/EtcdRegistryTest.java | 4 +- .../registry/zookeeper/ZookeeperRegistry.java | 6 +- .../java/org/apache/dubbo/remoting/Codec.java | 7 +- .../org/apache/dubbo/remoting/Codec2.java | 5 +- .../org/apache/dubbo/remoting/Constants.java | 63 ++++++++++++++++++ .../org/apache/dubbo/remoting/Dispatcher.java | 5 +- .../apache/dubbo/remoting/Transporter.java | 7 +- .../dubbo/remoting/exchange/Exchanger.java | 8 +-- .../dubbo/remoting/exchange/Exchangers.java | 10 +-- .../support/header/HeaderExchangeClient.java | 4 +- .../support/header/HeaderExchangeHandler.java | 4 +- .../support/header/HeaderExchangeServer.java | 6 +- .../telnet/support/TelnetHandlerAdapter.java | 4 +- .../remoting/transport/AbstractClient.java | 6 +- .../remoting/transport/AbstractCodec.java | 6 +- .../remoting/transport/AbstractEndpoint.java | 12 ++-- .../remoting/transport/AbstractPeer.java | 4 +- .../remoting/transport/AbstractServer.java | 8 +-- .../remoting/transport/CodecSupport.java | 6 +- .../dispatcher/WrappedChannelHandler.java | 4 +- .../dubbo/remoting/ChanelHandlerTest.java | 5 +- .../remoting/PerformanceClientCloseTest.java | 5 +- .../remoting/PerformanceClientFixedTest.java | 5 +- .../dubbo/remoting/PerformanceClientTest.java | 5 +- .../dubbo/remoting/PerformanceServerTest.java | 9 ++- .../remoting/codec/ExchangeCodecTest.java | 8 +-- .../handler/HeaderExchangeHandlerTest.java | 4 +- .../codec/DeprecatedTelnetCodec.java | 6 +- dubbo-remoting/dubbo-remoting-etcd3/pom.xml | 5 ++ .../apache/dubbo/remoting/etcd/Constants.java | 2 +- .../dubbo/remoting/etcd/EtcdTransporter.java | 4 +- .../grizzly/GrizzlyTransporterTest.java | 2 +- .../dubbo/remoting/http/HttpBinder.java | 6 +- .../remoting/http/jetty/JettyHttpServer.java | 14 ++-- .../http/servlet/ServletHttpServer.java | 6 +- .../http/jetty/JettyHttpBinderTest.java | 6 +- .../http/tomcat/TomcatHttpBinderTest.java | 6 +- .../remoting/transport/mina/MinaClient.java | 4 +- .../remoting/transport/mina/MinaServer.java | 2 +- .../remoting/transport/netty/NettyClient.java | 4 +- .../remoting/transport/netty/NettyServer.java | 4 +- .../support/header/HeartbeatHandlerTest.java | 3 +- .../transport/netty4/NettyClient.java | 6 +- .../transport/netty4/NettyServer.java | 4 +- .../netty4/NettyTransporterTest.java | 8 +-- .../exchange/support/ExchangeServerPeer.java | 4 +- .../remoting/p2p/support/ServerPeer.java | 4 +- .../dubbo-remoting-zookeeper/pom.xml | 5 ++ .../zookeeper/ZookeeperTransporter.java | 4 +- .../java/org/apache/dubbo/rpc/Constants.java | 5 +- .../dubbo/rpc/filter/CompatibleFilter.java | 4 +- .../dubbo/rpc/protocol/AbstractProtocol.java | 4 +- .../rpc/protocol/AbstractProxyProtocol.java | 6 +- .../protocol/dubbo/ChannelWrappedInvoker.java | 4 +- .../rpc/protocol/dubbo/DubboInvoker.java | 6 +- .../rpc/protocol/dubbo/DubboProtocol.java | 25 ++++--- .../dubbo/LazyConnectExchangeClient.java | 4 +- .../dubbo/ReferenceCountExchangeClient.java | 7 +- .../protocol/dubbo/filter/TraceFilter.java | 4 +- .../dubbo/status/ThreadPoolStatusChecker.java | 4 +- .../dubbo/DubboInvokerAvilableTest.java | 10 +-- .../rpc/protocol/dubbo/DubboProtocolTest.java | 6 +- .../DubboHessianURLConnectionFactory.java | 4 +- .../rpc/protocol/hessian/HessianProtocol.java | 9 +-- .../hessian/HttpClientConnectionFactory.java | 4 +- .../dubbo/rpc/protocol/http/HttpProtocol.java | 8 +-- .../rpc/protocol/redis/RedisProtocol.java | 4 +- .../rpc/protocol/redis/RedisProtocolTest.java | 7 +- .../dubbo/rpc/protocol/rest/NettyServer.java | 14 ++-- .../dubbo/rpc/protocol/rest/RestProtocol.java | 10 +-- .../rpc/protocol/rest/RestProtocolTest.java | 12 ++-- .../rpc/protocol/thrift/ThriftInvoker.java | 4 +- .../rpc/protocol/thrift/ThriftProtocol.java | 12 ++-- .../webservice/WebServiceProtocol.java | 4 +- 97 files changed, 361 insertions(+), 351 deletions(-) diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java index cc8b7c0a38f..0c70b89ec3c 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java @@ -17,9 +17,9 @@ package org.apache.dubbo.rpc.cluster.configurator; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.cluster.Configurator; import java.util.HashSet; @@ -119,7 +119,7 @@ private URL configureIfMatch(String host, URL url) { || configApplication.equals(currentApplication)) { Set conditionKeys = new HashSet(); conditionKeys.add(CATEGORY_KEY); - conditionKeys.add(RemotingConstants.CHECK_KEY); + conditionKeys.add(Constants.CHECK_KEY); conditionKeys.add(DYNAMIC_KEY); conditionKeys.add(ENABLED_KEY); conditionKeys.add(GROUP_KEY); diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java index 4ada4139c1a..ffea52f0cc7 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java @@ -17,8 +17,8 @@ package org.apache.dubbo.rpc.cluster.support; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.StringUtils; +import org.apache.dubbo.remoting.Constants; import java.util.HashMap; import java.util.Map; @@ -76,8 +76,8 @@ public static URL mergeUrl(URL remoteUrl, Map localMap) { map.remove(ALIVE_KEY); map.remove(DEFAULT_KEY_PREFIX + ALIVE_KEY); - map.remove(RemotingConstants.TRANSPORTER_KEY); - map.remove(DEFAULT_KEY_PREFIX + RemotingConstants.TRANSPORTER_KEY); + map.remove(Constants.TRANSPORTER_KEY); + map.remove(DEFAULT_KEY_PREFIX + Constants.TRANSPORTER_KEY); } if (localMap != null && localMap.size() > 0) { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RemotingConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RemotingConstants.java index c2532aa8779..aa4aeb66134 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RemotingConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RemotingConstants.java @@ -17,82 +17,17 @@ package org.apache.dubbo.common.constants; -import java.util.concurrent.ExecutorService; - /** * RemotingConstants */ public interface RemotingConstants { - String PAYLOAD_KEY = "payload"; - /** - * 8M - */ - int DEFAULT_PAYLOAD = 8 * 1024 * 1024; - - String CONNECT_TIMEOUT_KEY = "connect.timeout"; - - int DEFAULT_CONNECT_TIMEOUT = 3000; - String HEARTBEAT_KEY = "heartbeat"; int DEFAULT_HEARTBEAT = 60 * 1000; - String SERIALIZATION_KEY = "serialization"; - - String DEFAULT_REMOTING_SERIALIZATION = "hessian2"; - - String CODEC_KEY = "codec"; - - String SERVER_KEY = "server"; - - String DEFAULT_REMOTING_SERVER = "netty"; - - String CLIENT_KEY = "client"; - - String DEFAULT_REMOTING_CLIENT = "netty"; - - String TRANSPORTER_KEY = "transporter"; - - String DEFAULT_TRANSPORTER = "netty"; - - String EXCHANGER_KEY = "exchanger"; - - String DEFAULT_EXCHANGER = "header"; - - String DISPACTHER_KEY = "dispacther"; - - int DEFAULT_IO_THREADS = Math.min(Runtime.getRuntime().availableProcessors() + 1, 32); - - String BIND_IP_KEY = "bind.ip"; - - String BIND_PORT_KEY = "bind.port"; - - String SENT_KEY = "sent"; - - String DISPATCHER_KEY = "dispatcher"; - - String CHANNEL_ATTRIBUTE_READONLY_KEY = "channel.readonly"; - - String CHANNEL_READONLYEVENT_SENT_KEY = "channel.readonly.sent"; - - String CHANNEL_SEND_READONLYEVENT_KEY = "channel.readonly.send"; - - String EXECUTOR_SERVICE_COMPONENT_KEY = ExecutorService.class.getName(); - String BACKUP_KEY = "backup"; String HEARTBEAT_TIMEOUT_KEY = "heartbeat.timeout"; - String RECONNECT_KEY = "reconnect"; - - int DEFAULT_RECONNECT_PERIOD = 2000; - - String SEND_RECONNECT_KEY = "send.reconnect"; - - String CHECK_KEY = "check"; - - String PROMPT_KEY = "prompt"; - - String DEFAULT_PROMPT = "dubbo>"; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java index 57ece98b472..4b9f7694913 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.config; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.config.support.Parameter; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.InvokerListener; import org.apache.dubbo.rpc.support.ProtocolUtils; @@ -187,7 +187,7 @@ public Boolean getStubevent() { return stubevent; } - @Parameter(key = RemotingConstants.RECONNECT_KEY) + @Parameter(key = Constants.RECONNECT_KEY) public String getReconnect() { return reconnect; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java index a4cd9c150f3..73755984ae8 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.common.status.StatusChecker; @@ -24,6 +23,7 @@ import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.support.Parameter; import org.apache.dubbo.remoting.Codec; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.Dispatcher; import org.apache.dubbo.remoting.Transporter; import org.apache.dubbo.remoting.exchange.Exchanger; @@ -325,7 +325,7 @@ public String getCodec() { public void setCodec(String codec) { if (DUBBO_PROTOCOL.equals(name)) { - checkMultiExtension(Codec.class, RemotingConstants.CODEC_KEY, codec); + checkMultiExtension(Codec.class, Constants.CODEC_KEY, codec); } this.codec = codec; } @@ -336,7 +336,7 @@ public String getSerialization() { public void setSerialization(String serialization) { if (DUBBO_PROTOCOL.equals(name)) { - checkMultiExtension(Serialization.class, RemotingConstants.SERIALIZATION_KEY, serialization); + checkMultiExtension(Serialization.class, Constants.SERIALIZATION_KEY, serialization); } this.serialization = serialization; } @@ -379,7 +379,7 @@ public String getServer() { public void setServer(String server) { if (DUBBO_PROTOCOL.equals(name)) { - checkMultiExtension(Transporter.class, RemotingConstants.SERVER_KEY, server); + checkMultiExtension(Transporter.class, Constants.SERVER_KEY, server); } this.server = server; } @@ -390,7 +390,7 @@ public String getClient() { public void setClient(String client) { if (DUBBO_PROTOCOL.equals(name)) { - checkMultiExtension(Transporter.class, RemotingConstants.CLIENT_KEY, client); + checkMultiExtension(Transporter.class, Constants.CLIENT_KEY, client); } this.client = client; } @@ -443,7 +443,7 @@ public String getTransporter() { } public void setTransporter(String transporter) { - checkExtension(Transporter.class, RemotingConstants.TRANSPORTER_KEY, transporter); + checkExtension(Transporter.class, Constants.TRANSPORTER_KEY, transporter); this.transporter = transporter; } @@ -452,7 +452,7 @@ public String getExchanger() { } public void setExchanger(String exchanger) { - checkExtension(Exchanger.class, RemotingConstants.EXCHANGER_KEY, exchanger); + checkExtension(Exchanger.class, Constants.EXCHANGER_KEY, exchanger); this.exchanger = exchanger; } @@ -482,7 +482,7 @@ public String getDispatcher() { } public void setDispatcher(String dispatcher) { - checkExtension(Dispatcher.class, RemotingConstants.DISPACTHER_KEY, dispatcher); + checkExtension(Dispatcher.class, Constants.DISPACTHER_KEY, dispatcher); this.dispatcher = dispatcher; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProviderConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProviderConfig.java index 63d0bc894f6..c8c6380f571 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProviderConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProviderConfig.java @@ -16,10 +16,10 @@ */ package org.apache.dubbo.config; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.status.StatusChecker; import org.apache.dubbo.common.threadpool.ThreadPool; import org.apache.dubbo.config.support.Parameter; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.Dispatcher; import org.apache.dubbo.remoting.Transporter; import org.apache.dubbo.remoting.exchange.Exchanger; @@ -372,7 +372,7 @@ public String getTransporter() { } public void setTransporter(String transporter) { - checkExtension(Transporter.class, RemotingConstants.TRANSPORTER_KEY, transporter); + checkExtension(Transporter.class, Constants.TRANSPORTER_KEY, transporter); this.transporter = transporter; } @@ -381,7 +381,7 @@ public String getExchanger() { } public void setExchanger(String exchanger) { - checkExtension(Exchanger.class, RemotingConstants.EXCHANGER_KEY, exchanger); + checkExtension(Exchanger.class, Constants.EXCHANGER_KEY, exchanger); this.exchanger = exchanger; } @@ -411,7 +411,7 @@ public String getDispatcher() { } public void setDispatcher(String dispatcher) { - checkExtension(Dispatcher.class, RemotingConstants.DISPATCHER_KEY, dispatcher); + checkExtension(Dispatcher.class, Constants.DISPATCHER_KEY, dispatcher); checkExtension(Dispatcher.class, "dispather", dispatcher); this.dispatcher = dispatcher; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java index 1a5fb07957d..51a8204c712 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java @@ -19,7 +19,6 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.bytecode.Wrapper; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.CollectionUtils; @@ -30,6 +29,7 @@ import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.config.support.Parameter; import org.apache.dubbo.metadata.integration.MetadataReportService; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; @@ -579,7 +579,7 @@ public String getClient() { } public void setClient(String client) { - checkName(RemotingConstants.CLIENT_KEY, client); + checkName(Constants.CLIENT_KEY, client); this.client = client; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java index f0d7158a915..1d2109af22e 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java @@ -16,9 +16,9 @@ */ package org.apache.dubbo.config; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.support.Parameter; +import org.apache.dubbo.remoting.Constants; import java.util.Map; @@ -278,7 +278,7 @@ public String getTransporter() { } public void setTransporter(String transporter) { - checkName(RemotingConstants.TRANSPORTER_KEY, transporter); + checkName(Constants.TRANSPORTER_KEY, transporter); /*if(transporter != null && transporter.length() > 0 && ! ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(transporter)){ throw new IllegalStateException("No such transporter type : " + transporter); }*/ @@ -290,7 +290,7 @@ public String getServer() { } public void setServer(String server) { - checkName(RemotingConstants.SERVER_KEY, server); + checkName(Constants.SERVER_KEY, server); /*if(server != null && server.length() > 0 && ! ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(server)){ throw new IllegalStateException("No such server type : " + server); }*/ @@ -302,7 +302,7 @@ public String getClient() { } public void setClient(String client) { - checkName(RemotingConstants.CLIENT_KEY, client); + checkName(Constants.CLIENT_KEY, client); /*if(client != null && client.length() > 0 && ! ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(client)){ throw new IllegalStateException("No such client type : " + client); }*/ diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index 266099ee1e1..2a9ca02fdda 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -21,7 +21,6 @@ import org.apache.dubbo.common.Version; import org.apache.dubbo.common.bytecode.Wrapper; import org.apache.dubbo.common.config.Environment; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.CollectionUtils; @@ -33,6 +32,7 @@ import org.apache.dubbo.config.invoker.DelegateProviderMetaDataInvoker; import org.apache.dubbo.config.support.Parameter; import org.apache.dubbo.metadata.integration.MetadataReportService; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; @@ -710,7 +710,7 @@ private String findConfigedHosts(ProtocolConfig protocolConfig, List regist } } - map.put(RemotingConstants.BIND_IP_KEY, hostToBind); + map.put(Constants.BIND_IP_KEY, hostToBind); // registry ip is not used for bind ip by default String hostToRegistry = getValueFromConfig(protocolConfig, DUBBO_IP_TO_REGISTRY); @@ -762,7 +762,7 @@ private Integer findConfigedPorts(ProtocolConfig protocolConfig, String name, Ma } // save bind port, used as url's key later - map.put(RemotingConstants.BIND_PORT_KEY, String.valueOf(portToBind)); + map.put(Constants.BIND_PORT_KEY, String.valueOf(portToBind)); // registry port, not used as bind port by default String portToRegistryStr = getValueFromConfig(protocolConfig, DUBBO_PORT_TO_REGISTRY); diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java index eb17a000abb..3956b9f4955 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config.annotation; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.constants.RpcConstants; import org.apache.dubbo.rpc.ExporterListener; import org.apache.dubbo.rpc.Filter; @@ -103,7 +102,7 @@ * Whether to reconnect if connection is lost, if not specify, reconnect is enabled by default, and the interval * for retry connecting is 2000 ms * - * @see RemotingConstants#DEFAULT_RECONNECT_PERIOD + * @see org.apache.dubbo.remoting.Constants#DEFAULT_RECONNECT_PERIOD */ String reconnect() default ""; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java index 5cebcc12c40..9d1c1f0fee6 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java @@ -17,7 +17,7 @@ package org.apache.dubbo.config; -import org.apache.dubbo.common.constants.RemotingConstants; +import org.apache.dubbo.remoting.Constants; import org.junit.jupiter.api.Test; @@ -129,7 +129,7 @@ public void testReconnect() throws Exception { Map parameters = new HashMap(); AbstractInterfaceConfig.appendParameters(parameters, referenceConfig); assertThat(referenceConfig.getReconnect(), equalTo("reconnect")); - assertThat(parameters, hasKey(RemotingConstants.RECONNECT_KEY)); + assertThat(parameters, hasKey(Constants.RECONNECT_KEY)); } @Test diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java index cb8554cfc97..b60bbfda398 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java @@ -50,8 +50,8 @@ import static org.apache.dubbo.common.constants.ConfigConstants.EXPORT_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_TIMEOUT_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; -import static org.apache.dubbo.common.constants.RemotingConstants.BIND_IP_KEY; -import static org.apache.dubbo.common.constants.RemotingConstants.BIND_PORT_KEY; +import static org.apache.dubbo.remoting.Constants.BIND_IP_KEY; +import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_BEAN; import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_DEFAULT; diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/MetadataReportService.java b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/MetadataReportService.java index e8789925eb1..06d39b6f6ac 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/MetadataReportService.java +++ b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/MetadataReportService.java @@ -18,7 +18,6 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -28,6 +27,7 @@ import org.apache.dubbo.metadata.identifier.MetadataIdentifier; import org.apache.dubbo.metadata.store.MetadataReport; import org.apache.dubbo.metadata.store.MetadataReportFactory; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.RpcException; import java.util.function.Supplier; @@ -89,7 +89,7 @@ public static MetadataReportService instance(Supplier metadataReportUrl) { public void publishProvider(URL providerUrl) throws RpcException { //first add into the list // remove the individul param - providerUrl = providerUrl.removeParameters(PID_KEY, TIMESTAMP_KEY, RemotingConstants.BIND_IP_KEY, RemotingConstants.BIND_PORT_KEY, TIMESTAMP_KEY); + providerUrl = providerUrl.removeParameters(PID_KEY, TIMESTAMP_KEY, Constants.BIND_IP_KEY, Constants.BIND_PORT_KEY, TIMESTAMP_KEY); try { String interfaceName = providerUrl.getParameter(INTERFACE_KEY); @@ -109,7 +109,7 @@ public void publishProvider(URL providerUrl) throws RpcException { } public void publishConsumer(URL consumerURL) throws RpcException { - consumerURL = consumerURL.removeParameters(PID_KEY, TIMESTAMP_KEY, RemotingConstants.BIND_IP_KEY, RemotingConstants.BIND_PORT_KEY, TIMESTAMP_KEY); + consumerURL = consumerURL.removeParameters(PID_KEY, TIMESTAMP_KEY, Constants.BIND_IP_KEY, Constants.BIND_PORT_KEY, TIMESTAMP_KEY); metadataReport.storeConsumerMetadata(new MetadataIdentifier(consumerURL.getServiceInterface(), consumerURL.getParameter(VERSION_KEY), consumerURL.getParameter(GROUP_KEY), CONSUMER_SIDE, consumerURL.getParameter(APPLICATION_KEY)), consumerURL.getParameters()); diff --git a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java index ddcecc5ac20..0884d10ea28 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java +++ b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java @@ -28,7 +28,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; -import static org.apache.dubbo.common.constants.RemotingConstants.CHECK_KEY; +import static org.apache.dubbo.remoting.Constants.CHECK_KEY; import static org.apache.dubbo.rpc.Constants.REFERENCE_FILTER_KEY; /** diff --git a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java index 899cc645b20..fa16ae2f574 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java +++ b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java @@ -17,13 +17,13 @@ package org.apache.dubbo.monitor.dubbo; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.store.DataStore; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.monitor.MetricsService; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -178,7 +178,7 @@ private void setCompassQuantity(String groupName, String result, long duration, private List getThreadPoolMessage() { DataStore dataStore = ExtensionLoader.getExtensionLoader(DataStore.class).getDefaultExtension(); - Map executors = dataStore.get(RemotingConstants.EXECUTOR_SERVICE_COMPONENT_KEY); + Map executors = dataStore.get(Constants.EXECUTOR_SERVICE_COMPONENT_KEY); List threadPoolMtricList = new ArrayList<>(); for (Map.Entry entry : executors.entrySet()) { diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java index f65785fc33f..a8f8c6e76d2 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java @@ -19,7 +19,6 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.Version; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -31,6 +30,7 @@ import org.apache.dubbo.configcenter.DynamicConfiguration; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.Registry; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; @@ -447,7 +447,7 @@ private URL mergeUrl(URL providerUrl) { providerUrl = overrideWithConfigurator(providerUrl); - providerUrl = providerUrl.addParameter(RemotingConstants.CHECK_KEY, String.valueOf(false)); // Do not check whether the connection is successful or not, always create Invoker! + providerUrl = providerUrl.addParameter(Constants.CHECK_KEY, String.valueOf(false)); // Do not check whether the connection is successful or not, always create Invoker! // The combination of directoryUrl and override is at the end of notify, which can't be handled here this.overrideDirectoryUrl = this.overrideDirectoryUrl.addParametersIfAbsent(providerUrl.getParameters()); // Merge the provider side parameters diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java index 9c60abdac57..b0730c0f395 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java @@ -91,12 +91,12 @@ import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.SIMPLIFIED_KEY; -import static org.apache.dubbo.common.constants.RemotingConstants.BIND_IP_KEY; -import static org.apache.dubbo.common.constants.RemotingConstants.BIND_PORT_KEY; -import static org.apache.dubbo.common.constants.RemotingConstants.CHECK_KEY; -import static org.apache.dubbo.common.constants.RemotingConstants.CODEC_KEY; -import static org.apache.dubbo.common.constants.RemotingConstants.EXCHANGER_KEY; -import static org.apache.dubbo.common.constants.RemotingConstants.SERIALIZATION_KEY; +import static org.apache.dubbo.remoting.Constants.BIND_IP_KEY; +import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY; +import static org.apache.dubbo.remoting.Constants.CHECK_KEY; +import static org.apache.dubbo.remoting.Constants.CODEC_KEY; +import static org.apache.dubbo.remoting.Constants.EXCHANGER_KEY; +import static org.apache.dubbo.remoting.Constants.SERIALIZATION_KEY; import static org.apache.dubbo.common.constants.RpcConstants.CONNECTIONS_KEY; import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java index 293bf461d28..8f8304cace9 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java @@ -17,7 +17,6 @@ package org.apache.dubbo.registry.support; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.timer.HashedWheelTimer; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.NamedThreadFactory; @@ -27,6 +26,7 @@ import org.apache.dubbo.registry.retry.FailedSubscribedTask; import org.apache.dubbo.registry.retry.FailedUnregisteredTask; import org.apache.dubbo.registry.retry.FailedUnsubscribedTask; +import org.apache.dubbo.remoting.Constants; import java.util.HashMap; import java.util.HashSet; @@ -238,8 +238,8 @@ public void register(URL url) { Throwable t = e; // If the startup detection is opened, the Exception is thrown directly. - boolean check = getUrl().getParameter(RemotingConstants.CHECK_KEY, true) - && url.getParameter(RemotingConstants.CHECK_KEY, true) + boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) + && url.getParameter(Constants.CHECK_KEY, true) && !CONSUMER_PROTOCOL.equals(url.getProtocol()); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { @@ -268,8 +268,8 @@ public void unregister(URL url) { Throwable t = e; // If the startup detection is opened, the Exception is thrown directly. - boolean check = getUrl().getParameter(RemotingConstants.CHECK_KEY, true) - && url.getParameter(RemotingConstants.CHECK_KEY, true) + boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) + && url.getParameter(Constants.CHECK_KEY, true) && !CONSUMER_PROTOCOL.equals(url.getProtocol()); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { @@ -302,8 +302,8 @@ public void subscribe(URL url, NotifyListener listener) { logger.error("Failed to subscribe " + url + ", Using cached list: " + urls + " from cache file: " + getUrl().getParameter(FILE_KEY, System.getProperty("user.home") + "/dubbo-registry-" + url.getHost() + ".cache") + ", cause: " + t.getMessage(), t); } else { // If the startup detection is opened, the Exception is thrown directly. - boolean check = getUrl().getParameter(RemotingConstants.CHECK_KEY, true) - && url.getParameter(RemotingConstants.CHECK_KEY, true); + boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) + && url.getParameter(Constants.CHECK_KEY, true); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { @@ -331,8 +331,8 @@ public void unsubscribe(URL url, NotifyListener listener) { Throwable t = e; // If the startup detection is opened, the Exception is thrown directly. - boolean check = getUrl().getParameter(RemotingConstants.CHECK_KEY, true) - && url.getParameter(RemotingConstants.CHECK_KEY, true); + boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) + && url.getParameter(Constants.CHECK_KEY, true); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { diff --git a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistry.java b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistry.java index 86d77a1f42b..d6a5d69f9ca 100644 --- a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistry.java +++ b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistry.java @@ -18,7 +18,6 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ExecutorUtil; @@ -27,6 +26,7 @@ import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.RegistryService; import org.apache.dubbo.registry.support.FailbackRegistry; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Invoker; import java.util.List; @@ -102,7 +102,7 @@ protected final void connect() { clientLock.unlock(); } } catch (Throwable t) { // Ignore all the exceptions and wait for the next retry - if (getUrl().getParameter(RemotingConstants.CHECK_KEY, true)) { + if (getUrl().getParameter(Constants.CHECK_KEY, true)) { if (t instanceof RuntimeException) { throw (RuntimeException) t; } diff --git a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java index 1728e146e3f..72f8153289f 100644 --- a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java +++ b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java @@ -46,8 +46,8 @@ import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; -import static org.apache.dubbo.common.constants.RemotingConstants.CONNECT_TIMEOUT_KEY; -import static org.apache.dubbo.common.constants.RemotingConstants.RECONNECT_KEY; +import static org.apache.dubbo.remoting.Constants.CONNECT_TIMEOUT_KEY; +import static org.apache.dubbo.remoting.Constants.RECONNECT_KEY; import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_INSTANCES_LIMIT_KEY; /** diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DubboRegistryTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DubboRegistryTest.java index 74994b347ad..b757d4accfb 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DubboRegistryTest.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DubboRegistryTest.java @@ -17,13 +17,13 @@ package org.apache.dubbo.registry.dubbo; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.RegistryService; import org.apache.dubbo.registry.support.FailbackRegistry; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; @@ -55,10 +55,10 @@ public class DubboRegistryTest { @BeforeEach public void setUp() { registryURL = new URL(REGISTRY_PROTOCOL, NetUtils.getLocalHost(), NetUtils.getAvailablePort()) - .addParameter(RemotingConstants.CHECK_KEY, false) + .addParameter(Constants.CHECK_KEY, false) .setServiceInterface(RegistryService.class.getName()); serviceURL = new URL(DubboProtocol.NAME, NetUtils.getLocalHost(), NetUtils.getAvailablePort()) - .addParameter(RemotingConstants.CHECK_KEY, false) + .addParameter(Constants.CHECK_KEY, false) .setServiceInterface(RegistryService.class.getName()); registryService = new MockDubboRegistry(registryURL); diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java index 7ad418f7e39..8b93fd85c23 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java @@ -17,7 +17,6 @@ package org.apache.dubbo.registry.dubbo; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.LogUtil; import org.apache.dubbo.common.utils.NetUtils; @@ -25,6 +24,7 @@ import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.RegistryFactory; import org.apache.dubbo.registry.integration.RegistryDirectory; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.RpcException; @@ -389,7 +389,7 @@ public void testParametersMerge() { Invoker invoker = (Invoker) invokers.get(0); URL url = invoker.getUrl(); - Assertions.assertEquals(false, url.getParameter(RemotingConstants.CHECK_KEY, false)); + Assertions.assertEquals(false, url.getParameter(Constants.CHECK_KEY, false)); } { serviceUrls.clear(); diff --git a/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistry.java b/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistry.java index 1bb5bb155d7..cffc58e6c0f 100644 --- a/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistry.java +++ b/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistry.java @@ -34,7 +34,6 @@ package org.apache.dubbo.registry.etcd; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConcurrentHashSet; @@ -69,6 +68,7 @@ import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; +import static org.apache.dubbo.remoting.Constants.CHECK_KEY; /** @@ -193,7 +193,7 @@ public void doSubscribe(URL url, NotifyListener listener) { * eg: /dubbo/interface, /dubbo/interface and so on. */ subscribe(url.setPath(child).addParameters(INTERFACE_KEY, child, - RemotingConstants.CHECK_KEY, String.valueOf(false)), listener); + CHECK_KEY, String.valueOf(false)), listener); } } }); @@ -210,7 +210,7 @@ public void doSubscribe(URL url, NotifyListener listener) { service = URL.decode(service); anyServices.add(service); subscribe(url.setPath(service).addParameters(INTERFACE_KEY, service, - RemotingConstants.CHECK_KEY, String.valueOf(false)), listener); + CHECK_KEY, String.valueOf(false)), listener); } } else { List urls = new ArrayList<>(); diff --git a/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java b/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java index e0514aebd15..859cfd04c2e 100644 --- a/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java +++ b/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java @@ -51,12 +51,12 @@ package org.apache.dubbo.registry.etcd; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.RegistryFactory; import org.apache.dubbo.registry.support.AbstractRegistryFactory; +import org.apache.dubbo.remoting.Constants; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; @@ -106,7 +106,7 @@ public class EtcdRegistryTest { CLASSIFIER_KEY, ANY_VALUE, CATEGORY_KEY, PROVIDERS_CATEGORY + "," + CONSUMERS_CATEGORY + "," + ROUTERS_CATEGORY + "," + CONFIGURATORS_CATEGORY, ENABLED_KEY, ANY_VALUE, - RemotingConstants.CHECK_KEY, String.valueOf(false)); + Constants.CHECK_KEY, String.valueOf(false)); @Test public void test_register() { diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.java index 2731ffae116..4ddf1518e6d 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.java @@ -18,7 +18,6 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; @@ -26,6 +25,7 @@ import org.apache.dubbo.common.utils.UrlUtils; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.support.FailbackRegistry; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.zookeeper.ChildListener; import org.apache.dubbo.remoting.zookeeper.StateListener; import org.apache.dubbo.remoting.zookeeper.ZookeeperClient; @@ -145,7 +145,7 @@ public void doSubscribe(final URL url, final NotifyListener listener) { if (!anyServices.contains(child)) { anyServices.add(child); subscribe(url.setPath(child).addParameters(INTERFACE_KEY, child, - RemotingConstants.CHECK_KEY, String.valueOf(false)), listener); + Constants.CHECK_KEY, String.valueOf(false)), listener); } } }); @@ -158,7 +158,7 @@ public void doSubscribe(final URL url, final NotifyListener listener) { service = URL.decode(service); anyServices.add(service); subscribe(url.setPath(service).addParameters(INTERFACE_KEY, service, - RemotingConstants.CHECK_KEY, String.valueOf(false)), listener); + Constants.CHECK_KEY, String.valueOf(false)), listener); } } } else { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec.java index d40d4a27215..ad4098e4420 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.SPI; @@ -45,7 +44,7 @@ public interface Codec { * @param output output stream. * @param message message. */ - @Adaptive({RemotingConstants.CODEC_KEY}) + @Adaptive({Constants.CODEC_KEY}) void encode(Channel channel, OutputStream output, Object message) throws IOException; /** @@ -56,7 +55,7 @@ public interface Codec { * @return message or NEED_MORE_INPUT poison. * @see #NEED_MORE_INPUT */ - @Adaptive({RemotingConstants.CODEC_KEY}) + @Adaptive({Constants.CODEC_KEY}) Object decode(Channel channel, InputStream input) throws IOException; -} \ No newline at end of file +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec2.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec2.java index 7d6770b5fb5..f851b466172 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec2.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec2.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.remoting.buffer.ChannelBuffer; @@ -26,10 +25,10 @@ @SPI public interface Codec2 { - @Adaptive({RemotingConstants.CODEC_KEY}) + @Adaptive({Constants.CODEC_KEY}) void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException; - @Adaptive({RemotingConstants.CODEC_KEY}) + @Adaptive({Constants.CODEC_KEY}) Object decode(Channel channel, ChannelBuffer buffer) throws IOException; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Constants.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Constants.java index a057da14e81..663f4e0418c 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Constants.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Constants.java @@ -18,6 +18,8 @@ package org.apache.dubbo.remoting; +import java.util.concurrent.ExecutorService; + public interface Constants { String BUFFER_KEY = "buffer"; @@ -65,4 +67,65 @@ public interface Constants { * ticks per wheel. */ int TICKS_PER_WHEEL = 128; + String PAYLOAD_KEY = "payload"; + /** + * 8M + */ + int DEFAULT_PAYLOAD = 8 * 1024 * 1024; + + String CONNECT_TIMEOUT_KEY = "connect.timeout"; + + int DEFAULT_CONNECT_TIMEOUT = 3000; + + String SERIALIZATION_KEY = "serialization"; + + String DEFAULT_REMOTING_SERIALIZATION = "hessian2"; + + String CODEC_KEY = "codec"; + + String SERVER_KEY = "server"; + + String CLIENT_KEY = "client"; + + String DEFAULT_REMOTING_CLIENT = "netty"; + + String TRANSPORTER_KEY = "transporter"; + + String DEFAULT_TRANSPORTER = "netty"; + + String EXCHANGER_KEY = "exchanger"; + + String DEFAULT_EXCHANGER = "header"; + + String DISPACTHER_KEY = "dispacther"; + + int DEFAULT_IO_THREADS = Math.min(Runtime.getRuntime().availableProcessors() + 1, 32); + + String BIND_IP_KEY = "bind.ip"; + + String BIND_PORT_KEY = "bind.port"; + + String SENT_KEY = "sent"; + + String DISPATCHER_KEY = "dispatcher"; + + String CHANNEL_ATTRIBUTE_READONLY_KEY = "channel.readonly"; + + String CHANNEL_READONLYEVENT_SENT_KEY = "channel.readonly.sent"; + + String CHANNEL_SEND_READONLYEVENT_KEY = "channel.readonly.send"; + + String EXECUTOR_SERVICE_COMPONENT_KEY = ExecutorService.class.getName(); + + String RECONNECT_KEY = "reconnect"; + + int DEFAULT_RECONNECT_PERIOD = 2000; + + String SEND_RECONNECT_KEY = "send.reconnect"; + + String CHECK_KEY = "check"; + + String PROMPT_KEY = "prompt"; + + String DEFAULT_PROMPT = "dubbo>"; } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Dispatcher.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Dispatcher.java index 201b0979c35..c67f33e74ff 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Dispatcher.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Dispatcher.java @@ -17,7 +17,6 @@ package org.apache.dubbo.remoting; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.remoting.transport.dispatcher.all.AllDispatcher; @@ -35,8 +34,8 @@ public interface Dispatcher { * @param url * @return channel handler */ - @Adaptive({RemotingConstants.DISPATCHER_KEY, "dispather", "channel.handler"}) + @Adaptive({Constants.DISPATCHER_KEY, "dispather", "channel.handler"}) // The last two parameters are reserved for compatibility with the old configuration ChannelHandler dispatch(ChannelHandler handler, URL url); -} \ No newline at end of file +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Transporter.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Transporter.java index 6493ac51056..2266b824e14 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Transporter.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Transporter.java @@ -17,7 +17,6 @@ package org.apache.dubbo.remoting; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.SPI; @@ -41,7 +40,7 @@ public interface Transporter { * @throws RemotingException * @see org.apache.dubbo.remoting.Transporters#bind(URL, ChannelHandler...) */ - @Adaptive({RemotingConstants.SERVER_KEY, RemotingConstants.TRANSPORTER_KEY}) + @Adaptive({Constants.SERVER_KEY, Constants.TRANSPORTER_KEY}) Server bind(URL url, ChannelHandler handler) throws RemotingException; /** @@ -53,7 +52,7 @@ public interface Transporter { * @throws RemotingException * @see org.apache.dubbo.remoting.Transporters#connect(URL, ChannelHandler...) */ - @Adaptive({RemotingConstants.CLIENT_KEY, RemotingConstants.TRANSPORTER_KEY}) + @Adaptive({Constants.CLIENT_KEY, Constants.TRANSPORTER_KEY}) Client connect(URL url, ChannelHandler handler) throws RemotingException; -} \ No newline at end of file +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchanger.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchanger.java index 8c46273fff0..d524961a0da 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchanger.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchanger.java @@ -17,9 +17,9 @@ package org.apache.dubbo.remoting.exchange; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.SPI; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.support.header.HeaderExchanger; @@ -39,7 +39,7 @@ public interface Exchanger { * @param handler * @return message server */ - @Adaptive({RemotingConstants.EXCHANGER_KEY}) + @Adaptive({Constants.EXCHANGER_KEY}) ExchangeServer bind(URL url, ExchangeHandler handler) throws RemotingException; /** @@ -49,7 +49,7 @@ public interface Exchanger { * @param handler * @return message channel */ - @Adaptive({RemotingConstants.EXCHANGER_KEY}) + @Adaptive({Constants.EXCHANGER_KEY}) ExchangeClient connect(URL url, ExchangeHandler handler) throws RemotingException; -} \ No newline at end of file +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchangers.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchangers.java index c3fc864b514..36bcc74a78a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchangers.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchangers.java @@ -18,9 +18,9 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.remoting.ChannelHandler; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerDispatcher; import org.apache.dubbo.remoting.exchange.support.Replier; @@ -66,7 +66,7 @@ public static ExchangeServer bind(URL url, ExchangeHandler handler) throws Remot if (handler == null) { throw new IllegalArgumentException("handler == null"); } - url = url.addParameterIfAbsent(RemotingConstants.CODEC_KEY, "exchange"); + url = url.addParameterIfAbsent(Constants.CODEC_KEY, "exchange"); return getExchanger(url).bind(url, handler); } @@ -105,12 +105,12 @@ public static ExchangeClient connect(URL url, ExchangeHandler handler) throws Re if (handler == null) { throw new IllegalArgumentException("handler == null"); } - url = url.addParameterIfAbsent(RemotingConstants.CODEC_KEY, "exchange"); + url = url.addParameterIfAbsent(Constants.CODEC_KEY, "exchange"); return getExchanger(url).connect(url, handler); } public static Exchanger getExchanger(URL url) { - String type = url.getParameter(RemotingConstants.EXCHANGER_KEY, RemotingConstants.DEFAULT_EXCHANGER); + String type = url.getParameter(Constants.EXCHANGER_KEY, Constants.DEFAULT_EXCHANGER); return getExchanger(type); } @@ -118,4 +118,4 @@ public static Exchanger getExchanger(String type) { return ExtensionLoader.getExtensionLoader(Exchanger.class).getExtension(type); } -} \ No newline at end of file +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java index a57f82dec34..8bd5665ad7a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java @@ -17,12 +17,12 @@ package org.apache.dubbo.remoting.exchange.support.header; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.timer.HashedWheelTimer; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Client; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeClient; @@ -217,7 +217,7 @@ private long calculateLeastDuration(int time) { } private boolean shouldReconnect(URL url) { - return url.getParameter(RemotingConstants.RECONNECT_KEY, true); + return url.getParameter(Constants.RECONNECT_KEY, true); } @Override diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java index 0b19d6afe31..327eb7e3d22 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java @@ -17,13 +17,13 @@ package org.apache.dubbo.remoting.exchange.support.header; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.ExecutionException; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; @@ -73,7 +73,7 @@ private static boolean isClientSide(Channel channel) { void handlerEvent(Channel channel, Request req) throws RemotingException { if (req.getData() != null && req.getData().equals(Request.READONLY_EVENT)) { - channel.setAttribute(RemotingConstants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); + channel.setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java index 0f1e71f7962..0546a7ddccf 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java @@ -18,7 +18,6 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.timer.HashedWheelTimer; @@ -28,6 +27,7 @@ import org.apache.dubbo.common.utils.UrlUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.Server; import org.apache.dubbo.remoting.exchange.ExchangeChannel; @@ -104,7 +104,7 @@ public void close(final int timeout) { if (timeout > 0) { final long max = (long) timeout; final long start = System.currentTimeMillis(); - if (getUrl().getParameter(RemotingConstants.CHANNEL_SEND_READONLYEVENT_KEY, true)) { + if (getUrl().getParameter(Constants.CHANNEL_SEND_READONLYEVENT_KEY, true)) { sendChannelReadOnlyEvent(); } while (HeaderExchangeServer.this.isRunning() @@ -135,7 +135,7 @@ private void sendChannelReadOnlyEvent() { for (Channel channel : channels) { try { if (channel.isConnected()) { - channel.send(request, getUrl().getParameter(RemotingConstants.CHANNEL_READONLYEVENT_SENT_KEY, true)); + channel.send(request, getUrl().getParameter(Constants.CHANNEL_READONLYEVENT_SENT_KEY, true)); } } catch (RemotingException e) { logger.warn("send cannot write message error.", e); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java index a89c43f0a31..1575e450d8e 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java @@ -17,10 +17,10 @@ package org.apache.dubbo.remoting.telnet.support; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.telnet.TelnetHandler; import org.apache.dubbo.remoting.transport.ChannelHandlerAdapter; @@ -34,7 +34,7 @@ public class TelnetHandlerAdapter extends ChannelHandlerAdapter implements Telne @Override public String telnet(Channel channel, String message) throws RemotingException { - String prompt = channel.getUrl().getParameterAndDecoded(RemotingConstants.PROMPT_KEY, RemotingConstants.DEFAULT_PROMPT); + String prompt = channel.getUrl().getParameterAndDecoded(Constants.PROMPT_KEY, Constants.DEFAULT_PROMPT); boolean noprompt = message.contains("--no-prompt"); message = message.replace("--no-prompt", ""); StringBuilder buf = new StringBuilder(); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractClient.java index 876b5208ed9..e005ad533b0 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractClient.java @@ -18,7 +18,6 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -28,6 +27,7 @@ import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Client; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.transport.dispatcher.ChannelHandlers; @@ -54,7 +54,7 @@ public abstract class AbstractClient extends AbstractEndpoint implements Client public AbstractClient(URL url, ChannelHandler handler) throws RemotingException { super(url, handler); - needReconnect = url.getParameter(RemotingConstants.SEND_RECONNECT_KEY, false); + needReconnect = url.getParameter(Constants.SEND_RECONNECT_KEY, false); try { doOpen(); @@ -71,7 +71,7 @@ public AbstractClient(URL url, ChannelHandler handler) throws RemotingException logger.info("Start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() + " connect to the server " + getRemoteAddress()); } } catch (RemotingException t) { - if (url.getParameter(RemotingConstants.CHECK_KEY, true)) { + if (url.getParameter(Constants.CHECK_KEY, true)) { close(); throw t; } else { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractCodec.java index 04f700a97c4..9be96637109 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractCodec.java @@ -20,13 +20,13 @@ import java.net.InetSocketAddress; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Codec2; +import org.apache.dubbo.remoting.Constants; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; @@ -42,9 +42,9 @@ public abstract class AbstractCodec implements Codec2 { private static final String SERVER_SIDE = "server"; protected static void checkPayload(Channel channel, long size) throws IOException { - int payload = RemotingConstants.DEFAULT_PAYLOAD; + int payload = Constants.DEFAULT_PAYLOAD; if (channel != null && channel.getUrl() != null) { - payload = channel.getUrl().getParameter(RemotingConstants.PAYLOAD_KEY, RemotingConstants.DEFAULT_PAYLOAD); + payload = channel.getUrl().getParameter(Constants.PAYLOAD_KEY, Constants.DEFAULT_PAYLOAD); } if (payload > 0 && size > payload) { ExceedPayloadLimitException e = new ExceedPayloadLimitException( diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractEndpoint.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractEndpoint.java index f366e7ce7b7..94738a8df5c 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractEndpoint.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractEndpoint.java @@ -18,13 +18,13 @@ import org.apache.dubbo.common.Resetable; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Codec; import org.apache.dubbo.remoting.Codec2; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.transport.codec.CodecAdapter; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; @@ -47,11 +47,11 @@ public AbstractEndpoint(URL url, ChannelHandler handler) { super(url, handler); this.codec = getChannelCodec(url); this.timeout = url.getPositiveParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT); - this.connectTimeout = url.getPositiveParameter(RemotingConstants.CONNECT_TIMEOUT_KEY, RemotingConstants.DEFAULT_CONNECT_TIMEOUT); + this.connectTimeout = url.getPositiveParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT); } protected static Codec2 getChannelCodec(URL url) { - String codecName = url.getParameter(RemotingConstants.CODEC_KEY, "telnet"); + String codecName = url.getParameter(Constants.CODEC_KEY, "telnet"); if (ExtensionLoader.getExtensionLoader(Codec2.class).hasExtension(codecName)) { return ExtensionLoader.getExtensionLoader(Codec2.class).getExtension(codecName); } else { @@ -77,8 +77,8 @@ public void reset(URL url) { logger.error(t.getMessage(), t); } try { - if (url.hasParameter(RemotingConstants.CONNECT_TIMEOUT_KEY)) { - int t = url.getParameter(RemotingConstants.CONNECT_TIMEOUT_KEY, 0); + if (url.hasParameter(Constants.CONNECT_TIMEOUT_KEY)) { + int t = url.getParameter(Constants.CONNECT_TIMEOUT_KEY, 0); if (t > 0) { this.connectTimeout = t; } @@ -87,7 +87,7 @@ public void reset(URL url) { logger.error(t.getMessage(), t); } try { - if (url.hasParameter(RemotingConstants.CODEC_KEY)) { + if (url.hasParameter(Constants.CODEC_KEY)) { this.codec = getChannelCodec(url); } } catch (Throwable t) { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractPeer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractPeer.java index 2ec6fc603d0..ecad2365e85 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractPeer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractPeer.java @@ -17,9 +17,9 @@ package org.apache.dubbo.remoting.transport; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.Endpoint; import org.apache.dubbo.remoting.RemotingException; @@ -50,7 +50,7 @@ public AbstractPeer(URL url, ChannelHandler handler) { @Override public void send(Object message) throws RemotingException { - send(message, url.getParameter(RemotingConstants.SENT_KEY, false)); + send(message, url.getParameter(Constants.SENT_KEY, false)); } @Override diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractServer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractServer.java index ea801a05c8a..d1cbdbbb0e6 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractServer.java @@ -17,7 +17,6 @@ package org.apache.dubbo.remoting.transport; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -26,6 +25,7 @@ import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.Server; @@ -59,8 +59,8 @@ public AbstractServer(URL url, ChannelHandler handler) throws RemotingException super(url, handler); localAddress = getUrl().toInetSocketAddress(); - String bindIp = getUrl().getParameter(RemotingConstants.BIND_IP_KEY, getUrl().getHost()); - int bindPort = getUrl().getParameter(RemotingConstants.BIND_PORT_KEY, getUrl().getPort()); + String bindIp = getUrl().getParameter(Constants.BIND_IP_KEY, getUrl().getHost()); + int bindPort = getUrl().getParameter(Constants.BIND_PORT_KEY, getUrl().getPort()); if (url.getParameter(ANYHOST_KEY, false) || NetUtils.isInvalidLocalHost(bindIp)) { bindIp = ANYHOST_VALUE; } @@ -78,7 +78,7 @@ public AbstractServer(URL url, ChannelHandler handler) throws RemotingException } //fixme replace this with better method DataStore dataStore = ExtensionLoader.getExtensionLoader(DataStore.class).getDefaultExtension(); - executor = (ExecutorService) dataStore.get(RemotingConstants.EXECUTOR_SERVICE_COMPONENT_KEY, Integer.toString(url.getPort())); + executor = (ExecutorService) dataStore.get(Constants.EXECUTOR_SERVICE_COMPONENT_KEY, Integer.toString(url.getPort())); } protected abstract void doOpen() throws Throwable; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java index cfa6c604e0f..db4c71638c6 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java @@ -18,12 +18,12 @@ package org.apache.dubbo.remoting.transport; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.Serialization; +import org.apache.dubbo.remoting.Constants; import java.io.IOException; import java.io.InputStream; @@ -67,12 +67,12 @@ public static Serialization getSerializationById(Byte id) { public static Serialization getSerialization(URL url) { return ExtensionLoader.getExtensionLoader(Serialization.class).getExtension( - url.getParameter(RemotingConstants.SERIALIZATION_KEY, RemotingConstants.DEFAULT_REMOTING_SERIALIZATION)); + url.getParameter(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION)); } public static Serialization getSerialization(URL url, Byte id) throws IOException { Serialization serialization = getSerializationById(id); - String serializationName = url.getParameter(RemotingConstants.SERIALIZATION_KEY, RemotingConstants.DEFAULT_REMOTING_SERIALIZATION); + String serializationName = url.getParameter(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION); // Check if "serialization id" passed from network matches the id on this side(only take effect for JDK serialization), for security purpose. if (serialization == null || ((id == JAVA_SERIALIZATION_ID || id == NATIVE_JAVA_SERIALIZATION_ID || id == COMPACTED_JAVA_SERIALIZATION_ID) diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java index bd41ca25ac2..4fe83ecd3ec 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java @@ -17,7 +17,6 @@ package org.apache.dubbo.remoting.transport.dispatcher; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -26,6 +25,7 @@ import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.transport.ChannelHandlerDelegate; @@ -52,7 +52,7 @@ public WrappedChannelHandler(ChannelHandler handler, URL url) { this.url = url; executor = (ExecutorService) ExtensionLoader.getExtensionLoader(ThreadPool.class).getAdaptiveExtension().getExecutor(url); - String componentKey = RemotingConstants.EXECUTOR_SERVICE_COMPONENT_KEY; + String componentKey = Constants.EXECUTOR_SERVICE_COMPONENT_KEY; if (CONSUMER_SIDE.equalsIgnoreCase(url.getParameter(SIDE_KEY))) { componentKey = CONSUMER_SIDE; } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/ChanelHandlerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/ChanelHandlerTest.java index d4cd13a79c8..4d78c7daeac 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/ChanelHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/ChanelHandlerTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.exchange.ExchangeClient; @@ -81,8 +80,8 @@ public void testClient() throws Throwable { return; } final String server = System.getProperty("server", "127.0.0.1:9911"); - final String transporter = PerformanceUtils.getProperty(RemotingConstants.TRANSPORTER_KEY, RemotingConstants.DEFAULT_TRANSPORTER); - final String serialization = PerformanceUtils.getProperty(RemotingConstants.SERIALIZATION_KEY, RemotingConstants.DEFAULT_REMOTING_SERIALIZATION); + final String transporter = PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER); + final String serialization = PerformanceUtils.getProperty(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION); final int timeout = PerformanceUtils.getIntProperty(TIMEOUT_KEY, DEFAULT_TIMEOUT); int sleep = PerformanceUtils.getIntProperty("sleep", 60 * 1000 * 60); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientCloseTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientCloseTest.java index 46e1a10c016..0d153fac0cd 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientCloseTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientCloseTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.exchange.ExchangeClient; @@ -45,8 +44,8 @@ public void testClient() throws Throwable { return; } final String server = System.getProperty("server", "127.0.0.1:9911"); - final String transporter = PerformanceUtils.getProperty(RemotingConstants.TRANSPORTER_KEY, RemotingConstants.DEFAULT_TRANSPORTER); - final String serialization = PerformanceUtils.getProperty(RemotingConstants.SERIALIZATION_KEY, RemotingConstants.DEFAULT_REMOTING_SERIALIZATION); + final String transporter = PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER); + final String serialization = PerformanceUtils.getProperty(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION); final int timeout = PerformanceUtils.getIntProperty(TIMEOUT_KEY, DEFAULT_TIMEOUT); final int concurrent = PerformanceUtils.getIntProperty("concurrent", 1); final int runs = PerformanceUtils.getIntProperty("runs", Integer.MAX_VALUE); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java index 30be337f1a5..e5b87e19026 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.exchange.ExchangeClient; @@ -43,8 +42,8 @@ public void testClient() throws Exception { return; } final String server = System.getProperty("server", "127.0.0.1:9911"); - final String transporter = PerformanceUtils.getProperty(RemotingConstants.TRANSPORTER_KEY, RemotingConstants.DEFAULT_TRANSPORTER); - final String serialization = PerformanceUtils.getProperty(RemotingConstants.SERIALIZATION_KEY, RemotingConstants.DEFAULT_REMOTING_SERIALIZATION); + final String transporter = PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER); + final String serialization = PerformanceUtils.getProperty(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION); final int timeout = PerformanceUtils.getIntProperty(TIMEOUT_KEY, DEFAULT_TIMEOUT); //final int length = PerformanceUtils.getIntProperty("length", 1024); final int connectionCount = PerformanceUtils.getIntProperty(CONNECTIONS_KEY, 1); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java index ebbaae8b37b..4178358c1c4 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.exchange.ExchangeClient; @@ -55,8 +54,8 @@ public void testClient() throws Throwable { return; } final String server = System.getProperty("server", "127.0.0.1:9911"); - final String transporter = PerformanceUtils.getProperty(RemotingConstants.TRANSPORTER_KEY, RemotingConstants.DEFAULT_TRANSPORTER); - final String serialization = PerformanceUtils.getProperty(RemotingConstants.SERIALIZATION_KEY, RemotingConstants.DEFAULT_REMOTING_SERIALIZATION); + final String transporter = PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER); + final String serialization = PerformanceUtils.getProperty(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION); final int timeout = PerformanceUtils.getIntProperty(TIMEOUT_KEY, DEFAULT_TIMEOUT); final int length = PerformanceUtils.getIntProperty("length", 1024); final int connections = PerformanceUtils.getIntProperty(CONNECTIONS_KEY, 1); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.java index 8f3808a4ec0..9108a1bb2e9 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.exchange.ExchangeChannel; @@ -68,13 +67,13 @@ private static void restartServer(int times, int alive, int sleep) throws Except private static ExchangeServer statServer() throws Exception { final int port = PerformanceUtils.getIntProperty("port", 9911); - final String transporter = PerformanceUtils.getProperty(RemotingConstants.TRANSPORTER_KEY, RemotingConstants.DEFAULT_TRANSPORTER); - final String serialization = PerformanceUtils.getProperty(RemotingConstants.SERIALIZATION_KEY, RemotingConstants.DEFAULT_REMOTING_SERIALIZATION); + final String transporter = PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER); + final String serialization = PerformanceUtils.getProperty(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION); final String threadpool = PerformanceUtils.getProperty(THREADPOOL_KEY, DEFAULT_THREADPOOL); final int threads = PerformanceUtils.getIntProperty(THREADS_KEY, DEFAULT_THREADS); - final int iothreads = PerformanceUtils.getIntProperty(IO_THREADS_KEY, RemotingConstants.DEFAULT_IO_THREADS); + final int iothreads = PerformanceUtils.getIntProperty(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS); final int buffer = PerformanceUtils.getIntProperty(BUFFER_KEY, DEFAULT_BUFFER_SIZE); - final String channelHandler = PerformanceUtils.getProperty(RemotingConstants.DISPATCHER_KEY, ExecutionDispatcher.NAME); + final String channelHandler = PerformanceUtils.getProperty(Constants.DISPATCHER_KEY, ExecutionDispatcher.NAME); // Start server diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/ExchangeCodecTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/ExchangeCodecTest.java index 7b9cbca7f16..4fe272f3830 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/ExchangeCodecTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/ExchangeCodecTest.java @@ -18,13 +18,13 @@ import org.apache.dubbo.common.Version; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.io.Bytes; import org.apache.dubbo.common.io.UnsafeByteArrayOutputStream; import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.remoting.Channel; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBuffers; import org.apache.dubbo.remoting.exchange.Request; @@ -64,7 +64,7 @@ public class ExchangeCodecTest extends TelnetCodecTest { private static final short MAGIC = (short) 0xdabb; private static final byte MAGIC_HIGH = (byte) Bytes.short2bytes(MAGIC)[0]; private static final byte MAGIC_LOW = (byte) Bytes.short2bytes(MAGIC)[1]; - Serialization serialization = getSerialization(RemotingConstants.DEFAULT_REMOTING_SERIALIZATION); + Serialization serialization = getSerialization(Constants.DEFAULT_REMOTING_SERIALIZATION); private static Serialization getSerialization(String name) { Serialization serialization = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(name); @@ -442,7 +442,7 @@ public void testMessageLengthExceedPayloadLimitWhenEncode() throws Exception { Request request = new Request(1L); request.setData("hello"); ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(512); - AbstractMockChannel channel = getCliendSideChannel(url.addParameter(RemotingConstants.PAYLOAD_KEY, 4)); + AbstractMockChannel channel = getCliendSideChannel(url.addParameter(Constants.PAYLOAD_KEY, 4)); try { codec.encode(channel, encodeBuffer, request); Assertions.fail(); @@ -453,7 +453,7 @@ public void testMessageLengthExceedPayloadLimitWhenEncode() throws Exception { Response response = new Response(1L); response.setResult("hello"); encodeBuffer = ChannelBuffers.dynamicBuffer(512); - channel = getServerSideChannel(url.addParameter(RemotingConstants.PAYLOAD_KEY, 4)); + channel = getServerSideChannel(url.addParameter(Constants.PAYLOAD_KEY, 4)); codec.encode(channel, encodeBuffer, response); Assertions.assertTrue(channel.getReceivedMessage() instanceof Response); Response receiveMessage = (Response) channel.getReceivedMessage(); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/HeaderExchangeHandlerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/HeaderExchangeHandlerTest.java index c9c044d9a12..1b58bf78a23 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/HeaderExchangeHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/HeaderExchangeHandlerTest.java @@ -17,8 +17,8 @@ package org.apache.dubbo.remoting.handler; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.remoting.Channel; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeHandler; @@ -160,7 +160,7 @@ public void test_received_request_event_readonly() throws RemotingException { final Channel mchannel = new MockedChannel(); HeaderExchangeHandler hexhandler = new HeaderExchangeHandler(new MockedExchangeHandler()); hexhandler.received(mchannel, request); - Assertions.assertTrue(mchannel.hasAttribute(RemotingConstants.CHANNEL_ATTRIBUTE_READONLY_KEY)); + Assertions.assertTrue(mchannel.hasAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY)); } @Test diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java index 2b37e89b5c5..bf6b6beb90b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java @@ -17,7 +17,6 @@ package org.apache.dubbo.remoting.transport.codec; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.ObjectOutput; @@ -25,6 +24,7 @@ import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Codec; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.transport.CodecSupport; @@ -58,9 +58,9 @@ public class DeprecatedTelnetCodec implements Codec { private static final List EXIT = Arrays.asList(new Object[]{new byte[]{3} /* Windows Ctrl+C */, new byte[]{-1, -12, -1, -3, 6} /* Linux Ctrl+C */, new byte[]{-1, -19, -1, -3, 6} /* Linux Pause */}); static void checkPayload(Channel channel, long size) throws IOException { - int payload = RemotingConstants.DEFAULT_PAYLOAD; + int payload = Constants.DEFAULT_PAYLOAD; if (channel != null && channel.getUrl() != null) { - payload = channel.getUrl().getPositiveParameter(RemotingConstants.PAYLOAD_KEY, RemotingConstants.DEFAULT_PAYLOAD); + payload = channel.getUrl().getPositiveParameter(Constants.PAYLOAD_KEY, Constants.DEFAULT_PAYLOAD); } if (size > payload) { IOException e = new IOException("Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel); diff --git a/dubbo-remoting/dubbo-remoting-etcd3/pom.xml b/dubbo-remoting/dubbo-remoting-etcd3/pom.xml index 2f827a9fbb3..73a2539bdac 100644 --- a/dubbo-remoting/dubbo-remoting-etcd3/pom.xml +++ b/dubbo-remoting/dubbo-remoting-etcd3/pom.xml @@ -33,6 +33,11 @@ false + + org.apache.dubbo + dubbo-remoting-api + ${project.parent.version} + org.apache.dubbo dubbo-common diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/Constants.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/Constants.java index 48115a91560..b022678122e 100644 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/Constants.java +++ b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/Constants.java @@ -17,7 +17,7 @@ package org.apache.dubbo.remoting.etcd; -import static org.apache.dubbo.common.constants.RemotingConstants.DEFAULT_IO_THREADS; +import static org.apache.dubbo.remoting.Constants.DEFAULT_IO_THREADS; public interface Constants { String ETCD3_NOTIFY_MAXTHREADS_KEYS = "etcd3.notify.maxthreads"; diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/EtcdTransporter.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/EtcdTransporter.java index 821fc0524e0..754ba646621 100644 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/EtcdTransporter.java +++ b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/EtcdTransporter.java @@ -34,14 +34,14 @@ package org.apache.dubbo.remoting.etcd; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.SPI; +import org.apache.dubbo.remoting.Constants; @SPI("jetcd") public interface EtcdTransporter { - @Adaptive({RemotingConstants.CLIENT_KEY, RemotingConstants.TRANSPORTER_KEY}) + @Adaptive({Constants.CLIENT_KEY, Constants.TRANSPORTER_KEY}) EtcdClient connect(URL url); } diff --git a/dubbo-remoting/dubbo-remoting-grizzly/src/main/test/org/apache/dubbo/remoting/transport/grizzly/GrizzlyTransporterTest.java b/dubbo-remoting/dubbo-remoting-grizzly/src/main/test/org/apache/dubbo/remoting/transport/grizzly/GrizzlyTransporterTest.java index 971a8b35c4a..b0468c3680e 100644 --- a/dubbo-remoting/dubbo-remoting-grizzly/src/main/test/org/apache/dubbo/remoting/transport/grizzly/GrizzlyTransporterTest.java +++ b/dubbo-remoting/dubbo-remoting-grizzly/src/main/test/org/apache/dubbo/remoting/transport/grizzly/GrizzlyTransporterTest.java @@ -23,7 +23,7 @@ import org.junit.jupiter.api.Test; -import static org.apache.dubbo.common.constants.RemotingConstants.BIND_PORT_KEY; +import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpBinder.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpBinder.java index 4f1392bf847..5e5bec4192b 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpBinder.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpBinder.java @@ -17,9 +17,9 @@ package org.apache.dubbo.remoting.http; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.SPI; +import org.apache.dubbo.remoting.Constants; /** * HttpBinder @@ -33,7 +33,7 @@ public interface HttpBinder { * @param url server url. * @return server. */ - @Adaptive({RemotingConstants.SERVER_KEY}) + @Adaptive({Constants.SERVER_KEY}) HttpServer bind(URL url, HttpHandler handler); -} \ No newline at end of file +} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpServer.java index 77442e29dec..e3c6719eeba 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpServer.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpServer.java @@ -17,10 +17,10 @@ package org.apache.dubbo.remoting.http.jetty; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NetUtils; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.remoting.http.servlet.DispatcherServlet; import org.apache.dubbo.remoting.http.servlet.ServletManager; @@ -54,7 +54,7 @@ public JettyHttpServer(URL url, final HttpHandler handler) { Log.setLog(new StdErrLog()); Log.getLog().setDebugEnabled(false); - DispatcherServlet.addHttpHandler(url.getParameter(RemotingConstants.BIND_PORT_KEY, url.getPort()), handler); + DispatcherServlet.addHttpHandler(url.getParameter(Constants.BIND_PORT_KEY, url.getPort()), handler); int threads = url.getParameter(THREADS_KEY, DEFAULT_THREADS); QueuedThreadPool threadPool = new QueuedThreadPool(); @@ -66,11 +66,11 @@ public JettyHttpServer(URL url, final HttpHandler handler) { ServerConnector connector = new ServerConnector(server); - String bindIp = url.getParameter(RemotingConstants.BIND_IP_KEY, url.getHost()); + String bindIp = url.getParameter(Constants.BIND_IP_KEY, url.getHost()); if (!url.isAnyHost() && NetUtils.isValidLocalHost(bindIp)) { connector.setHost(bindIp); } - connector.setPort(url.getParameter(RemotingConstants.BIND_PORT_KEY, url.getPort())); + connector.setPort(url.getParameter(Constants.BIND_PORT_KEY, url.getPort())); server.addConnector(connector); @@ -83,12 +83,12 @@ public JettyHttpServer(URL url, final HttpHandler handler) { // TODO Context.SESSIONS is the best option here? (In jetty 9.x, it becomes ServletContextHandler.SESSIONS) ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS); context.setServletHandler(servletHandler); - ServletManager.getInstance().addServletContext(url.getParameter(RemotingConstants.BIND_PORT_KEY, url.getPort()), context.getServletContext()); + ServletManager.getInstance().addServletContext(url.getParameter(Constants.BIND_PORT_KEY, url.getPort()), context.getServletContext()); try { server.start(); } catch (Exception e) { - throw new IllegalStateException("Failed to start jetty server on " + url.getParameter(RemotingConstants.BIND_IP_KEY) + ":" + url.getParameter(RemotingConstants.BIND_PORT_KEY) + ", cause: " + throw new IllegalStateException("Failed to start jetty server on " + url.getParameter(Constants.BIND_IP_KEY) + ":" + url.getParameter(Constants.BIND_PORT_KEY) + ", cause: " + e.getMessage(), e); } } @@ -98,7 +98,7 @@ public void close() { super.close(); // - ServletManager.getInstance().removeServletContext(url.getParameter(RemotingConstants.BIND_PORT_KEY, url.getPort())); + ServletManager.getInstance().removeServletContext(url.getParameter(Constants.BIND_PORT_KEY, url.getPort())); if (server != null) { try { diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpServer.java index cd23699e72a..0f8ad7d609b 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpServer.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpServer.java @@ -17,7 +17,7 @@ package org.apache.dubbo.remoting.http.servlet; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.remoting.http.support.AbstractHttpServer; @@ -25,7 +25,7 @@ public class ServletHttpServer extends AbstractHttpServer { public ServletHttpServer(URL url, HttpHandler handler) { super(url, handler); - DispatcherServlet.addHttpHandler(url.getParameter(RemotingConstants.BIND_PORT_KEY, 8080), handler); + DispatcherServlet.addHttpHandler(url.getParameter(Constants.BIND_PORT_KEY, 8080), handler); } -} \ No newline at end of file +} diff --git a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinderTest.java b/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinderTest.java index 63dae7b7e58..d26d4f5623e 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinderTest.java +++ b/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinderTest.java @@ -17,8 +17,8 @@ package org.apache.dubbo.remoting.http.jetty; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.NetUtils; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.remoting.http.HttpServer; import org.apache.http.client.fluent.Request; @@ -36,7 +36,7 @@ public class JettyHttpBinderTest { public void shouldAbleHandleRequestForJettyBinder() throws Exception { int port = NetUtils.getAvailablePort(); URL url = new URL("http", "localhost", port, - new String[]{RemotingConstants.BIND_PORT_KEY, String.valueOf(port)}); + new String[]{Constants.BIND_PORT_KEY, String.valueOf(port)}); HttpServer httpServer = new JettyHttpServer(url, new HttpHandler() { @Override public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { @@ -50,4 +50,4 @@ public void handle(HttpServletRequest request, HttpServletResponse response) thr httpServer.close(); } -} \ No newline at end of file +} diff --git a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinderTest.java b/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinderTest.java index 086f624334e..f31b6ce23cc 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinderTest.java +++ b/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinderTest.java @@ -17,8 +17,8 @@ package org.apache.dubbo.remoting.http.tomcat; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.NetUtils; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.remoting.http.HttpServer; @@ -37,7 +37,7 @@ public class TomcatHttpBinderTest { public void shouldAbleHandleRequestForTomcatBinder() throws Exception { int port = NetUtils.getAvailablePort(); URL url = new URL("http", "localhost", port, - new String[]{RemotingConstants.BIND_PORT_KEY, String.valueOf(port)}); + new String[]{Constants.BIND_PORT_KEY, String.valueOf(port)}); HttpServer httpServer = new TomcatHttpBinder().bind(url, new HttpHandler() { @Override @@ -52,4 +52,4 @@ public void handle(HttpServletRequest request, HttpServletResponse response) thr httpServer.close(); } -} \ No newline at end of file +} diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaClient.java b/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaClient.java index ee926a26477..76f1dbc1939 100644 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaClient.java +++ b/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaClient.java @@ -18,13 +18,13 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.transport.AbstractClient; @@ -71,7 +71,7 @@ protected void doOpen() throws Throwable { connector = c; } else { // set thread pool. - connector = new SocketConnector(RemotingConstants.DEFAULT_IO_THREADS, + connector = new SocketConnector(Constants.DEFAULT_IO_THREADS, Executors.newCachedThreadPool(new NamedThreadFactory("MinaClientWorker", true))); // config SocketConnectorConfig cfg = (SocketConnectorConfig) connector.getDefaultConfig(); diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaServer.java b/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaServer.java index 2365ddf56bf..304d9ca416c 100644 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaServer.java +++ b/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaServer.java @@ -39,7 +39,7 @@ import java.util.Set; import java.util.concurrent.Executors; -import static org.apache.dubbo.common.constants.RemotingConstants.DEFAULT_IO_THREADS; +import static org.apache.dubbo.remoting.Constants.DEFAULT_IO_THREADS; import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY; /** diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyClient.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyClient.java index 80b8ae60474..e31edcc809a 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyClient.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyClient.java @@ -18,12 +18,12 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.ChannelHandler; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.transport.AbstractClient; @@ -50,7 +50,7 @@ public class NettyClient extends AbstractClient { // https://issues.jboss.org/browse/NETTY-424 private static final ChannelFactory CHANNEL_FACTORY = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(new NamedThreadFactory("NettyClientBoss", true)), Executors.newCachedThreadPool(new NamedThreadFactory("NettyClientWorker", true)), - RemotingConstants.DEFAULT_IO_THREADS); + Constants.DEFAULT_IO_THREADS); private ClientBootstrap bootstrap; private volatile Channel channel; // volatile, please copy reference to use diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyServer.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyServer.java index 9e782ccfbea..8d1cc3f3a73 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyServer.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyServer.java @@ -17,7 +17,6 @@ package org.apache.dubbo.remoting.transport.netty; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; @@ -26,6 +25,7 @@ import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.Server; import org.apache.dubbo.remoting.transport.AbstractServer; @@ -69,7 +69,7 @@ protected void doOpen() throws Throwable { NettyHelper.setNettyLoggerFactory(); ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerBoss", true)); ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true)); - ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(IO_THREADS_KEY, RemotingConstants.DEFAULT_IO_THREADS)); + ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS)); bootstrap = new ServerBootstrap(channelFactory); final NettyHandler nettyHandler = new NettyHandler(getUrl(), this); diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java index 7a1134e8fae..8a2cb256ef7 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java @@ -22,6 +22,7 @@ import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.Channel; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeClient; @@ -71,7 +72,7 @@ public void testServerHeartbeat() throws Exception { // Let the client not reply to the heartbeat, and turn off automatic reconnect to simulate the client dropped. serverURL = serverURL.addParameter(RemotingConstants.HEARTBEAT_KEY, 600 * 1000); - serverURL = serverURL.addParameter(RemotingConstants.RECONNECT_KEY, false); + serverURL = serverURL.addParameter(Constants.RECONNECT_KEY, false); client = Exchangers.connect(serverURL); Thread.sleep(10000); diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java index e772905bcec..62574a4da82 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java @@ -18,13 +18,13 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.UrlUtils; import org.apache.dubbo.remoting.ChannelHandler; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.transport.AbstractClient; @@ -51,8 +51,8 @@ public class NettyClient extends AbstractClient { private static final Logger logger = LoggerFactory.getLogger(NettyClient.class); - private static final NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup(RemotingConstants.DEFAULT_IO_THREADS, new DefaultThreadFactory("NettyClientWorker", true)); - + private static final NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup(Constants.DEFAULT_IO_THREADS, new DefaultThreadFactory("NettyClientWorker", true)); + private static final String SOCKS_PROXY_HOST = "socksProxyHost"; private static final String SOCKS_PROXY_PORT = "socksProxyPort"; diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java index 6bc5f895731..616fd18a080 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java @@ -17,7 +17,6 @@ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ExecutorUtil; @@ -25,6 +24,7 @@ import org.apache.dubbo.common.utils.UrlUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.Server; import org.apache.dubbo.remoting.transport.AbstractServer; @@ -75,7 +75,7 @@ protected void doOpen() throws Throwable { bootstrap = new ServerBootstrap(); bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss", true)); - workerGroup = new NioEventLoopGroup(getUrl().getPositiveParameter(IO_THREADS_KEY, RemotingConstants.DEFAULT_IO_THREADS), + workerGroup = new NioEventLoopGroup(getUrl().getPositiveParameter(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS), new DefaultThreadFactory("NettyServerWorker", true)); final NettyServerHandler nettyServerHandler = new NettyServerHandler(getUrl(), this); diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporterTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporterTest.java index db942c554e5..41937aa9fb3 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporterTest.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporterTest.java @@ -17,9 +17,9 @@ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.Server; import org.apache.dubbo.remoting.transport.ChannelHandlerAdapter; @@ -36,7 +36,7 @@ public class NettyTransporterTest { public void shouldAbleToBindNetty4() throws Exception { int port = NetUtils.getAvailablePort(); URL url = new URL("http", "localhost", port, - new String[]{RemotingConstants.BIND_PORT_KEY, String.valueOf(port)}); + new String[]{Constants.BIND_PORT_KEY, String.valueOf(port)}); Server server = new NettyTransporter().bind(url, new ChannelHandlerAdapter()); @@ -49,7 +49,7 @@ public void shouldConnectToNetty4Server() throws Exception { int port = NetUtils.getAvailablePort(); URL url = new URL("http", "localhost", port, - new String[]{RemotingConstants.BIND_PORT_KEY, String.valueOf(port)}); + new String[]{Constants.BIND_PORT_KEY, String.valueOf(port)}); new NettyTransporter().bind(url, new ChannelHandlerAdapter() { @@ -68,4 +68,4 @@ public void sent(Channel channel, Object message) throws RemotingException { lock.await(); } -} \ No newline at end of file +} diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/ExchangeServerPeer.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/ExchangeServerPeer.java index 2f534c9e8bd..82038410de7 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/ExchangeServerPeer.java +++ b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/ExchangeServerPeer.java @@ -17,11 +17,11 @@ package org.apache.dubbo.remoting.p2p.exchange.support; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Client; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeClient; @@ -105,7 +105,7 @@ public ExchangeChannel getExchangeChannel(InetSocketAddress remoteAddress) { @Override public void send(Object message) throws RemotingException { - send(message, getUrl().getParameter(RemotingConstants.SENT_KEY, false)); + send(message, getUrl().getParameter(Constants.SENT_KEY, false)); } @Override diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/ServerPeer.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/ServerPeer.java index a6d215fb611..cff334246a4 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/ServerPeer.java +++ b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/ServerPeer.java @@ -17,11 +17,11 @@ package org.apache.dubbo.remoting.p2p.support; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Client; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.Server; import org.apache.dubbo.remoting.p2p.Group; @@ -92,7 +92,7 @@ public Channel getChannel(InetSocketAddress remoteAddress) { @Override public void send(Object message) throws RemotingException { - send(message, getUrl().getParameter(RemotingConstants.SENT_KEY, false)); + send(message, getUrl().getParameter(Constants.SENT_KEY, false)); } @Override diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml index 497bc83f94e..bf4cffb3893 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml +++ b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml @@ -29,6 +29,11 @@ false + + org.apache.dubbo + dubbo-remoting-api + ${project.parent.version} + org.apache.dubbo dubbo-common diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/ZookeeperTransporter.java b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/ZookeeperTransporter.java index 96a459c93bc..638f3ed29f6 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/ZookeeperTransporter.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/ZookeeperTransporter.java @@ -17,14 +17,14 @@ package org.apache.dubbo.remoting.zookeeper; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.SPI; +import org.apache.dubbo.remoting.Constants; @SPI("curator") public interface ZookeeperTransporter { - @Adaptive({RemotingConstants.CLIENT_KEY, RemotingConstants.TRANSPORTER_KEY}) + @Adaptive({Constants.CLIENT_KEY, Constants.TRANSPORTER_KEY}) ZookeeperClient connect(URL url); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Constants.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Constants.java index c87ccdbbe4b..8a75ef7e2b1 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Constants.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Constants.java @@ -17,9 +17,6 @@ package org.apache.dubbo.rpc; -/** - * - */ public interface Constants { String LOCAL_KEY = "local"; @@ -101,5 +98,5 @@ public interface Constants { String LOCAL_PROTOCOL = "injvm"; - + String DEFAULT_REMOTING_SERVER = "netty"; } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/CompatibleFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/CompatibleFilter.java index 74ab6d6f4de..5842b32c04d 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/CompatibleFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/CompatibleFilter.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.rpc.filter; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CompatibleTypeUtils; import org.apache.dubbo.common.utils.PojoUtils; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -59,7 +59,7 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept Method method = invoker.getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes()); Class type = method.getReturnType(); Object newValue; - String serialization = invoker.getUrl().getParameter(RemotingConstants.SERIALIZATION_KEY); + String serialization = invoker.getUrl().getParameter(Constants.SERIALIZATION_KEY); if ("json".equals(serialization) || "fastjson".equals(serialization)) { // If the serialization key is json or fastjson diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java index 5c1b780dc5c..5c49e473ddb 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java @@ -17,10 +17,10 @@ package org.apache.dubbo.rpc.protocol; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConcurrentHashSet; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; @@ -47,7 +47,7 @@ public abstract class AbstractProtocol implements Protocol { protected final Set> invokers = new ConcurrentHashSet>(); protected static String serviceKey(URL url) { - int port = url.getParameter(RemotingConstants.BIND_PORT_KEY, url.getPort()); + int port = url.getParameter(Constants.BIND_PORT_KEY, url.getPort()); return serviceKey(port, url.getPath(), url.getParameter(VERSION_KEY), url.getParameter(GROUP_KEY)); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java index dafbd328516..735b9fe4b7f 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java @@ -18,8 +18,8 @@ package org.apache.dubbo.rpc.protocol; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.NetUtils; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -133,11 +133,11 @@ protected RpcException getRpcException(Class type, URL url, Invocation invoca } protected String getAddr(URL url) { - String bindIp = url.getParameter(RemotingConstants.BIND_IP_KEY, url.getHost()); + String bindIp = url.getParameter(Constants.BIND_IP_KEY, url.getHost()); if (url.getParameter(ANYHOST_KEY, false)) { bindIp = ANYHOST_VALUE; } - return NetUtils.getIpByHost(bindIp) + ":" + url.getParameter(RemotingConstants.BIND_PORT_KEY, url.getPort()); + return NetUtils.getIpByHost(bindIp) + ":" + url.getParameter(Constants.BIND_PORT_KEY, url.getPort()); } protected int getErrorCode(Throwable e) { diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java index b9f96235d89..54d74d3ef6c 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java @@ -17,7 +17,6 @@ package org.apache.dubbo.rpc.protocol.dubbo; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; @@ -38,6 +37,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.remoting.Constants.SENT_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CALLBACK_SERVICE_KEY; import static org.apache.dubbo.rpc.Constants.ASYNC_KEY; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; @@ -67,7 +67,7 @@ protected Result doInvoke(Invocation invocation) throws Throwable { try { if (getUrl().getMethodParameter(invocation.getMethodName(), ASYNC_KEY, false)) { // may have concurrency issue - currentClient.send(inv, getUrl().getMethodParameter(invocation.getMethodName(), RemotingConstants.SENT_KEY, false)); + currentClient.send(inv, getUrl().getMethodParameter(invocation.getMethodName(), SENT_KEY, false)); return new RpcResult(); } int timeout = getUrl().getMethodParameter(invocation.getMethodName(), TIMEOUT_KEY, DEFAULT_TIMEOUT); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java index dcf6f9d835c..cc0b9e7e225 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java @@ -18,8 +18,8 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.AtomicPositiveInteger; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.TimeoutException; import org.apache.dubbo.remoting.exchange.ExchangeClient; @@ -93,7 +93,7 @@ protected Result doInvoke(final Invocation invocation) throws Throwable { boolean isOneway = RpcUtils.isOneway(getUrl(), invocation); int timeout = getUrl().getMethodParameter(methodName, TIMEOUT_KEY, DEFAULT_TIMEOUT); if (isOneway) { - boolean isSent = getUrl().getMethodParameter(methodName, RemotingConstants.SENT_KEY, false); + boolean isSent = getUrl().getMethodParameter(methodName, Constants.SENT_KEY, false); currentClient.send(inv, isSent); RpcContext.getContext().setFuture(null); return new RpcResult(); @@ -128,7 +128,7 @@ public boolean isAvailable() { return false; } for (ExchangeClient client : clients) { - if (client.isConnected() && !client.hasAttribute(RemotingConstants.CHANNEL_ATTRIBUTE_READONLY_KEY)) { + if (client.isConnected() && !client.hasAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY)) { //cannot write == not Available ? return true; } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java index c9670bfe9d8..dad2f4e0fe4 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java @@ -19,7 +19,6 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.config.ConfigurationUtils; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.serialize.support.SerializableClassRegistry; import org.apache.dubbo.common.serialize.support.SerializationOptimizer; @@ -66,6 +65,14 @@ import static org.apache.dubbo.common.constants.ConfigConstants.LAZY_CONNECT_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.ON_CONNECT_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.ON_DISCONNECT_KEY; +import static org.apache.dubbo.common.constants.RemotingConstants.DEFAULT_HEARTBEAT; +import static org.apache.dubbo.common.constants.RemotingConstants.HEARTBEAT_KEY; +import static org.apache.dubbo.remoting.Constants.CHANNEL_READONLYEVENT_SENT_KEY; +import static org.apache.dubbo.remoting.Constants.CLIENT_KEY; +import static org.apache.dubbo.remoting.Constants.CODEC_KEY; +import static org.apache.dubbo.remoting.Constants.DEFAULT_REMOTING_CLIENT; +import static org.apache.dubbo.remoting.Constants.SERVER_KEY; +import static org.apache.dubbo.rpc.Constants.DEFAULT_REMOTING_SERVER; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CALLBACK_SERVICE_KEY; import static org.apache.dubbo.common.constants.RpcConstants.CONNECTIONS_KEY; import static org.apache.dubbo.rpc.Constants.DEFAULT_STUB_EVENT; @@ -333,12 +340,12 @@ private void openServer(URL url) { private ExchangeServer createServer(URL url) { url = URLBuilder.from(url) // send readonly event when server closes, it's enabled by default - .addParameterIfAbsent(RemotingConstants.CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString()) + .addParameterIfAbsent(CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString()) // enable heartbeat by default - .addParameterIfAbsent(RemotingConstants.HEARTBEAT_KEY, String.valueOf(RemotingConstants.DEFAULT_HEARTBEAT)) - .addParameter(RemotingConstants.CODEC_KEY, DubboCodec.NAME) + .addParameterIfAbsent(HEARTBEAT_KEY, String.valueOf(DEFAULT_HEARTBEAT)) + .addParameter(CODEC_KEY, DubboCodec.NAME) .build(); - String str = url.getParameter(RemotingConstants.SERVER_KEY, RemotingConstants.DEFAULT_REMOTING_SERVER); + String str = url.getParameter(SERVER_KEY, DEFAULT_REMOTING_SERVER); if (str != null && str.length() > 0 && !ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str)) { throw new RpcException("Unsupported server type: " + str + ", url: " + url); @@ -351,7 +358,7 @@ private ExchangeServer createServer(URL url) { throw new RpcException("Fail to start server(url: " + url + ") " + e.getMessage(), e); } - str = url.getParameter(RemotingConstants.CLIENT_KEY); + str = url.getParameter(CLIENT_KEY); if (str != null && str.length() > 0) { Set supportedTypes = ExtensionLoader.getExtensionLoader(Transporter.class).getSupportedExtensions(); if (!supportedTypes.contains(str)) { @@ -573,11 +580,11 @@ private ReferenceCountExchangeClient buildReferenceCountExchangeClient(URL url) private ExchangeClient initClient(URL url) { // client type setting. - String str = url.getParameter(RemotingConstants.CLIENT_KEY, url.getParameter(RemotingConstants.SERVER_KEY, RemotingConstants.DEFAULT_REMOTING_CLIENT)); + String str = url.getParameter(CLIENT_KEY, url.getParameter(SERVER_KEY, DEFAULT_REMOTING_CLIENT)); - url = url.addParameter(RemotingConstants.CODEC_KEY, DubboCodec.NAME); + url = url.addParameter(CODEC_KEY, DubboCodec.NAME); // enable heartbeat by default - url = url.addParameterIfAbsent(RemotingConstants.HEARTBEAT_KEY, String.valueOf(RemotingConstants.DEFAULT_HEARTBEAT)); + url = url.addParameterIfAbsent(HEARTBEAT_KEY, String.valueOf(DEFAULT_HEARTBEAT)); // BIO is not allowed since it has severe performance issue. if (str != null && str.length() > 0 && !ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str)) { diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java index c73bb56a284..eadbf20681a 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java @@ -18,7 +18,6 @@ import org.apache.dubbo.common.Parameters; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NetUtils; @@ -34,6 +33,7 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; +import static org.apache.dubbo.remoting.Constants.SEND_RECONNECT_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.LAZY_CONNECT_INITIAL_STATE_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.DEFAULT_LAZY_CONNECT_INITIAL_STATE; @@ -62,7 +62,7 @@ final class LazyConnectExchangeClient implements ExchangeClient { public LazyConnectExchangeClient(URL url, ExchangeHandler requestHandler) { // lazy connect, need set send.reconnect = true, to avoid channel bad status. - this.url = url.addParameter(RemotingConstants.SEND_RECONNECT_KEY, Boolean.TRUE.toString()); + this.url = url.addParameter(SEND_RECONNECT_KEY, Boolean.TRUE.toString()); this.requestHandler = requestHandler; this.initialState = url.getParameter(LAZY_CONNECT_INITIAL_STATE_KEY, DEFAULT_LAZY_CONNECT_INITIAL_STATE); this.requestWithWarning = url.getParameter(REQUEST_WITH_WARNING_KEY, false); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java index ae7934b2594..fd32951b320 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java @@ -20,7 +20,6 @@ import org.apache.dubbo.common.Parameters; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeClient; @@ -30,6 +29,8 @@ import java.net.InetSocketAddress; import java.util.concurrent.atomic.AtomicInteger; +import static org.apache.dubbo.remoting.Constants.RECONNECT_KEY; +import static org.apache.dubbo.remoting.Constants.SEND_RECONNECT_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.LAZY_CONNECT_INITIAL_STATE_KEY; /** @@ -171,8 +172,8 @@ private void replaceWithLazyClient() { // this is a defensive operation to avoid client is closed by accident, the initial state of the client is false URL lazyUrl = URLBuilder.from(url) .addParameter(LAZY_CONNECT_INITIAL_STATE_KEY, Boolean.FALSE) - .addParameter(RemotingConstants.RECONNECT_KEY, Boolean.FALSE) - .addParameter(RemotingConstants.SEND_RECONNECT_KEY, Boolean.TRUE.toString()) + .addParameter(RECONNECT_KEY, Boolean.FALSE) + .addParameter(SEND_RECONNECT_KEY, Boolean.TRUE.toString()) .addParameter("warning", Boolean.TRUE.toString()) .addParameter(LazyConnectExchangeClient.REQUEST_WITH_WARNING_KEY, true) .addParameter("_client_memo", "referencecounthandler.replacewithlazyclient") diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java index b2aae4496d6..ac412f4b4bf 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.dubbo.filter; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.Logger; @@ -24,6 +23,7 @@ import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.remoting.Channel; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -104,7 +104,7 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept } count = c.getAndIncrement(); if (count < max) { - String prompt = channel.getUrl().getParameter(RemotingConstants.PROMPT_KEY, RemotingConstants.DEFAULT_PROMPT); + String prompt = channel.getUrl().getParameter(Constants.PROMPT_KEY, Constants.DEFAULT_PROMPT); channel.send("\r\n" + RpcContext.getContext().getRemoteAddress() + " -> " + invoker.getInterface().getName() + "." + invocation.getMethodName() diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/status/ThreadPoolStatusChecker.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/status/ThreadPoolStatusChecker.java index 6797782f3a5..8506f1be420 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/status/ThreadPoolStatusChecker.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/status/ThreadPoolStatusChecker.java @@ -16,12 +16,12 @@ */ package org.apache.dubbo.rpc.protocol.dubbo.status; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.status.Status; import org.apache.dubbo.common.status.StatusChecker; import org.apache.dubbo.common.store.DataStore; +import org.apache.dubbo.remoting.Constants; import java.util.Map; import java.util.concurrent.ExecutorService; @@ -36,7 +36,7 @@ public class ThreadPoolStatusChecker implements StatusChecker { @Override public Status check() { DataStore dataStore = ExtensionLoader.getExtensionLoader(DataStore.class).getDefaultExtension(); - Map executors = dataStore.get(RemotingConstants.EXECUTOR_SERVICE_COMPONENT_KEY); + Map executors = dataStore.get(Constants.EXECUTOR_SERVICE_COMPONENT_KEY); StringBuilder msg = new StringBuilder(); Status.Level level = Status.Level.OK; diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java index 4f00cad3d29..804f05856b7 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java @@ -18,9 +18,9 @@ import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.ProxyFactory; @@ -77,12 +77,12 @@ public void test_Normal_ChannelReadOnly() throws Exception { DubboInvoker invoker = (DubboInvoker) protocol.refer(IDemoService.class, url); Assertions.assertEquals(true, invoker.isAvailable()); - getClients(invoker)[0].setAttribute(RemotingConstants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); + getClients(invoker)[0].setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); Assertions.assertEquals(false, invoker.isAvailable()); // reset status since connection is shared among invokers - getClients(invoker)[0].removeAttribute(RemotingConstants.CHANNEL_ATTRIBUTE_READONLY_KEY); + getClients(invoker)[0].removeAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY); } @Disabled @@ -131,7 +131,7 @@ public void test_Lazy_ChannelReadOnly() throws Exception { Assertions.assertEquals(true, invoker.isAvailable()); try { - getClients(invoker)[0].setAttribute(RemotingConstants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); + getClients(invoker)[0].setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); fail(); } catch (IllegalStateException e) { @@ -141,7 +141,7 @@ public void test_Lazy_ChannelReadOnly() throws Exception { Assertions.assertEquals("ok", service.get()); Assertions.assertEquals(true, invoker.isAvailable()); - getClients(invoker)[0].setAttribute(RemotingConstants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); + getClients(invoker)[0].setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); Assertions.assertEquals(false, invoker.isAvailable()); } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocolTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocolTest.java index b5df719f3ea..bd609721d96 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocolTest.java @@ -18,8 +18,8 @@ import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.RpcException; @@ -96,8 +96,8 @@ public void testDubboProtocol() throws Exception { @Test public void testDubboProtocolWithMina() throws Exception { DemoService service = new DemoServiceImpl(); - protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:9011/" + DemoService.class.getName()).addParameter(RemotingConstants.SERVER_KEY, "mina"))); - service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:9011/" + DemoService.class.getName()).addParameter(RemotingConstants.CLIENT_KEY, "mina").addParameter("timeout", 3000l))); + protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:9011/" + DemoService.class.getName()).addParameter(Constants.SERVER_KEY, "mina"))); + service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:9011/" + DemoService.class.getName()).addParameter(Constants.CLIENT_KEY, "mina").addParameter("timeout", 3000l))); for (int i = 0; i < 10; i++) { assertEquals(service.enumlength(new Type[]{}), Type.Lower); assertEquals(service.getSize(null), -1); diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/DubboHessianURLConnectionFactory.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/DubboHessianURLConnectionFactory.java index 10d1a1bffe3..e56841414bd 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/DubboHessianURLConnectionFactory.java +++ b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/DubboHessianURLConnectionFactory.java @@ -17,7 +17,7 @@ package org.apache.dubbo.rpc.protocol.hessian; -import org.apache.dubbo.common.constants.RemotingConstants; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.RpcContext; import com.caucho.hessian.client.HessianConnection; @@ -33,7 +33,7 @@ public HessianConnection open(URL url) throws IOException { HessianConnection connection = super.open(url); RpcContext context = RpcContext.getContext(); for (String key : context.getAttachments().keySet()) { - connection.addHeader(RemotingConstants.DEFAULT_EXCHANGER + key, context.getAttachment(key)); + connection.addHeader(Constants.DEFAULT_EXCHANGER + key, context.getAttachment(key)); } return connection; diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocol.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocol.java index 90e9f1cef4b..de298680d60 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocol.java +++ b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocol.java @@ -17,7 +17,6 @@ package org.apache.dubbo.rpc.protocol.hessian; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.remoting.http.HttpBinder; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.remoting.http.HttpServer; @@ -46,6 +45,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.remoting.Constants.CLIENT_KEY; +import static org.apache.dubbo.remoting.Constants.DEFAULT_EXCHANGER; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; import static org.apache.dubbo.rpc.protocol.hessian.Constants.HESSIAN2_REQUEST_KEY; import static org.apache.dubbo.rpc.protocol.hessian.Constants.DEFAULT_HESSIAN2_REQUEST; @@ -116,7 +117,7 @@ protected T doRefer(Class serviceType, URL url) throws RpcException { hessianProxyFactory.setHessian2Request(isHessian2Request); boolean isOverloadEnabled = url.getParameter(HESSIAN_OVERLOAD_METHOD_KEY, DEFAULT_HESSIAN_OVERLOAD_METHOD); hessianProxyFactory.setOverloadEnabled(isOverloadEnabled); - String client = url.getParameter(RemotingConstants.CLIENT_KEY, DEFAULT_HTTP_CLIENT); + String client = url.getParameter(CLIENT_KEY, DEFAULT_HTTP_CLIENT); if ("httpclient".equals(client)) { HessianConnectionFactory factory = new HttpClientConnectionFactory(); factory.setHessianProxyFactory(hessianProxyFactory); @@ -183,8 +184,8 @@ public void handle(HttpServletRequest request, HttpServletResponse response) Enumeration enumeration = request.getHeaderNames(); while (enumeration.hasMoreElements()) { String key = enumeration.nextElement(); - if (key.startsWith(RemotingConstants.DEFAULT_EXCHANGER)) { - RpcContext.getContext().setAttachment(key.substring(RemotingConstants.DEFAULT_EXCHANGER.length()), + if (key.startsWith(DEFAULT_EXCHANGER)) { + RpcContext.getContext().setAttachment(key.substring(DEFAULT_EXCHANGER.length()), request.getHeader(key)); } } diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HttpClientConnectionFactory.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HttpClientConnectionFactory.java index b5bec3e2c5e..b51e6d48efb 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HttpClientConnectionFactory.java +++ b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HttpClientConnectionFactory.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.rpc.protocol.hessian; -import org.apache.dubbo.common.constants.RemotingConstants; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.RpcContext; import com.caucho.hessian.client.HessianConnection; @@ -49,7 +49,7 @@ public HessianConnection open(URL url) { HttpClientConnection httpClientConnection = new HttpClientConnection(httpClient, url); RpcContext context = RpcContext.getContext(); for (String key : context.getAttachments().keySet()) { - httpClientConnection.addHeader(RemotingConstants.DEFAULT_EXCHANGER + key, context.getAttachment(key)); + httpClientConnection.addHeader(Constants.DEFAULT_EXCHANGER + key, context.getAttachment(key)); } return httpClientConnection; } diff --git a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java b/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java index 19fa904c15b..abbfe82dac6 100644 --- a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java +++ b/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java @@ -17,9 +17,9 @@ package org.apache.dubbo.rpc.protocol.http; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.Version; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.http.HttpBinder; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.remoting.http.HttpServer; @@ -159,7 +159,7 @@ public RemoteInvocation createRemoteInvocation(MethodInvocation methodInvocation httpProxyFactoryBean.setServiceUrl(key); httpProxyFactoryBean.setServiceInterface(serviceType); - String client = url.getParameter(RemotingConstants.CLIENT_KEY); + String client = url.getParameter(Constants.CLIENT_KEY); if (StringUtils.isEmpty(client) || "simple".equals(client)) { SimpleHttpInvokerRequestExecutor httpInvokerRequestExecutor = new SimpleHttpInvokerRequestExecutor() { @Override @@ -167,14 +167,14 @@ protected void prepareConnection(HttpURLConnection con, int contentLength) throws IOException { super.prepareConnection(con, contentLength); con.setReadTimeout(url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT)); - con.setConnectTimeout(url.getParameter(RemotingConstants.CONNECT_TIMEOUT_KEY, RemotingConstants.DEFAULT_CONNECT_TIMEOUT)); + con.setConnectTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT)); } }; httpProxyFactoryBean.setHttpInvokerRequestExecutor(httpInvokerRequestExecutor); } else if ("commons".equals(client)) { HttpComponentsHttpInvokerRequestExecutor httpInvokerRequestExecutor = new HttpComponentsHttpInvokerRequestExecutor(); httpInvokerRequestExecutor.setReadTimeout(url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT)); - httpInvokerRequestExecutor.setConnectTimeout(url.getParameter(RemotingConstants.CONNECT_TIMEOUT_KEY, RemotingConstants.DEFAULT_CONNECT_TIMEOUT)); + httpInvokerRequestExecutor.setConnectTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT)); httpProxyFactoryBean.setHttpInvokerRequestExecutor(httpInvokerRequestExecutor); } else { throw new IllegalStateException("Unsupported http protocol client " + client + ", only supported: simple, commons"); diff --git a/dubbo-rpc/dubbo-rpc-redis/src/main/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocol.java b/dubbo-rpc/dubbo-rpc-redis/src/main/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocol.java index 5678beb979c..2601a09b48f 100644 --- a/dubbo-rpc/dubbo-rpc-redis/src/main/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocol.java +++ b/dubbo-rpc/dubbo-rpc-redis/src/main/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocol.java @@ -17,12 +17,12 @@ package org.apache.dubbo.rpc.protocol.redis; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.common.utils.StringUtils; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -67,7 +67,7 @@ public Exporter export(final Invoker invoker) throws RpcException { } private Serialization getSerialization(URL url) { - return ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(url.getParameter(RemotingConstants.SERIALIZATION_KEY, "java")); + return ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(url.getParameter(Constants.SERIALIZATION_KEY, "java")); } @Override diff --git a/dubbo-rpc/dubbo-rpc-redis/src/test/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocolTest.java b/dubbo-rpc/dubbo-rpc-redis/src/test/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocolTest.java index f42cc821b87..bc8ac800325 100644 --- a/dubbo-rpc/dubbo-rpc-redis/src/test/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-redis/src/test/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocolTest.java @@ -17,11 +17,11 @@ package org.apache.dubbo.rpc.protocol.redis; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.common.utils.NetUtils; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; @@ -31,7 +31,6 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; import redis.clients.jedis.Jedis; @@ -177,7 +176,7 @@ public void testAuthRedis() { JedisPool pool = new JedisPool(new GenericObjectPoolConfig(), "localhost", registryUrl.getPort(), 2000, password, database, (String) null); try (Jedis jedis = pool.getResource()) { byte[] valueByte = jedis.get("key".getBytes()); - Serialization serialization = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(this.registryUrl.getParameter(RemotingConstants.SERIALIZATION_KEY, "java")); + Serialization serialization = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(this.registryUrl.getParameter(Constants.SERIALIZATION_KEY, "java")); ObjectInput oin = serialization.deserialize(this.registryUrl, new ByteArrayInputStream(valueByte)); String actual = (String) oin.readObject(); assertThat(value, is(actual)); @@ -217,4 +216,4 @@ public void testWrongAuthRedis() { refer.destroy(); } -} \ No newline at end of file +} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/NettyServer.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/NettyServer.java index 7ee8c006ab3..dedf44a6824 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/NettyServer.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/NettyServer.java @@ -17,7 +17,6 @@ package org.apache.dubbo.rpc.protocol.rest; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.NetUtils; import io.netty.channel.ChannelOption; @@ -30,6 +29,11 @@ import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS; import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; +import static org.apache.dubbo.remoting.Constants.BIND_IP_KEY; +import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY; +import static org.apache.dubbo.remoting.Constants.DEFAULT_IO_THREADS; +import static org.apache.dubbo.remoting.Constants.DEFAULT_PAYLOAD; +import static org.apache.dubbo.remoting.Constants.PAYLOAD_KEY; import static org.apache.dubbo.rpc.protocol.rest.Constants.KEEP_ALIVE_KEY; import static org.apache.dubbo.rpc.protocol.rest.Constants.DEFAULT_KEEP_ALIVE; @@ -43,17 +47,17 @@ public class NettyServer extends BaseRestServer { @Override protected void doStart(URL url) { - String bindIp = url.getParameter(RemotingConstants.BIND_IP_KEY, url.getHost()); + String bindIp = url.getParameter(BIND_IP_KEY, url.getHost()); if (!url.isAnyHost() && NetUtils.isValidLocalHost(bindIp)) { server.setHostname(bindIp); } - server.setPort(url.getParameter(RemotingConstants.BIND_PORT_KEY, url.getPort())); + server.setPort(url.getParameter(BIND_PORT_KEY, url.getPort())); Map channelOption = new HashMap(); channelOption.put(ChannelOption.SO_KEEPALIVE, url.getParameter(KEEP_ALIVE_KEY, DEFAULT_KEEP_ALIVE)); server.setChildChannelOptions(channelOption); server.setExecutorThreadCount(url.getParameter(THREADS_KEY, DEFAULT_THREADS)); - server.setIoWorkerCount(url.getParameter(IO_THREADS_KEY, RemotingConstants.DEFAULT_IO_THREADS)); - server.setMaxRequestSize(url.getParameter(RemotingConstants.PAYLOAD_KEY, RemotingConstants.DEFAULT_PAYLOAD)); + server.setIoWorkerCount(url.getParameter(IO_THREADS_KEY, DEFAULT_IO_THREADS)); + server.setMaxRequestSize(url.getParameter(PAYLOAD_KEY, DEFAULT_PAYLOAD)); server.start(); } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java index 22d7607d841..ec34f95b185 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java @@ -17,7 +17,6 @@ package org.apache.dubbo.rpc.protocol.rest; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.http.HttpBinder; import org.apache.dubbo.remoting.http.servlet.BootstrapListener; @@ -56,6 +55,9 @@ import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.RpcConstants.CONNECTIONS_KEY; +import static org.apache.dubbo.remoting.Constants.CONNECT_TIMEOUT_KEY; +import static org.apache.dubbo.remoting.Constants.DEFAULT_CONNECT_TIMEOUT; +import static org.apache.dubbo.remoting.Constants.SERVER_KEY; import static org.apache.dubbo.rpc.protocol.rest.Constants.EXTENSION_KEY; public class RestProtocol extends AbstractProxyProtocol { @@ -96,13 +98,13 @@ protected Runnable doExport(T impl, Class type, URL url) throws RpcExcept String addr = getAddr(url); Class implClass = ApplicationModel.getProviderModel(url.getPathKey()).getServiceInstance().getClass(); RestServer server = servers.computeIfAbsent(addr, restServer -> { - RestServer s = serverFactory.createServer(url.getParameter(RemotingConstants.SERVER_KEY, DEFAULT_SERVER)); + RestServer s = serverFactory.createServer(url.getParameter(SERVER_KEY, DEFAULT_SERVER)); s.start(url); return s; }); String contextPath = getContextPath(url); - if ("servlet".equalsIgnoreCase(url.getParameter(RemotingConstants.SERVER_KEY, DEFAULT_SERVER))) { + if ("servlet".equalsIgnoreCase(url.getParameter(SERVER_KEY, DEFAULT_SERVER))) { ServletContext servletContext = ServletManager.getInstance().getServletContext(ServletManager.EXTERNAL_SERVER_PORT); if (servletContext == null) { throw new RpcException("No servlet context found. Since you are using server='servlet', " + @@ -149,7 +151,7 @@ protected T doRefer(Class serviceType, URL url) throws RpcException { } connectionMonitor.addConnectionManager(connectionManager); RequestConfig requestConfig = RequestConfig.custom() - .setConnectTimeout(url.getParameter(RemotingConstants.CONNECT_TIMEOUT_KEY, RemotingConstants.DEFAULT_CONNECT_TIMEOUT)) + .setConnectTimeout(url.getParameter(CONNECT_TIMEOUT_KEY, DEFAULT_CONNECT_TIMEOUT)) .setSocketTimeout(url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT)) .build(); diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/RestProtocolTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/RestProtocolTest.java index efcc87c24e2..a1682af2808 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/RestProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/RestProtocolTest.java @@ -17,7 +17,6 @@ package org.apache.dubbo.rpc.protocol.rest; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.Exporter; @@ -36,6 +35,7 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import static org.apache.dubbo.remoting.Constants.SERVER_KEY; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -114,7 +114,7 @@ public void testNettyServer() { ProviderModel providerModel = new ProviderModel(exportUrl.getServiceKey(), server, DemoService.class); ApplicationModel.initProviderModel(exportUrl.getServiceKey(), providerModel); - URL nettyUrl = exportUrl.addParameter(RemotingConstants.SERVER_KEY, "netty"); + URL nettyUrl = exportUrl.addParameter(SERVER_KEY, "netty"); Exporter exporter = protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); @@ -132,7 +132,7 @@ public void testServletWithoutWebConfig() { ProviderModel providerModel = new ProviderModel(exportUrl.getServiceKey(), server, DemoService.class); ApplicationModel.initProviderModel(exportUrl.getPathKey(), providerModel); - URL servletUrl = exportUrl.addParameter(RemotingConstants.SERVER_KEY, "servlet"); + URL servletUrl = exportUrl.addParameter(SERVER_KEY, "servlet"); protocol.export(proxy.getInvoker(server, DemoService.class, servletUrl)); }); @@ -145,7 +145,7 @@ public void testErrorHandler() { ProviderModel providerModel = new ProviderModel(exportUrl.getServiceKey(), server, DemoService.class); ApplicationModel.initProviderModel(exportUrl.getServiceKey(), providerModel); - URL nettyUrl = exportUrl.addParameter(RemotingConstants.SERVER_KEY, "netty"); + URL nettyUrl = exportUrl.addParameter(SERVER_KEY, "netty"); Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); @@ -175,7 +175,7 @@ public void testFilter() { ProviderModel providerModel = new ProviderModel(exportUrl.getServiceKey(), server, DemoService.class); ApplicationModel.initProviderModel(exportUrl.getServiceKey(), providerModel); - URL nettyUrl = exportUrl.addParameter(RemotingConstants.SERVER_KEY, "netty") + URL nettyUrl = exportUrl.addParameter(SERVER_KEY, "netty") .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.support.LoggingFilter"); Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); @@ -195,7 +195,7 @@ public void testRpcContextFilter() { ApplicationModel.initProviderModel(exportUrl.getServiceKey(), providerModel); // use RpcContextFilter - URL nettyUrl = exportUrl.addParameter(RemotingConstants.SERVER_KEY, "netty") + URL nettyUrl = exportUrl.addParameter(SERVER_KEY, "netty") .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.RpcContextFilter"); Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java index aa337f9e456..7d29f5813af 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java @@ -17,8 +17,8 @@ package org.apache.dubbo.rpc.protocol.thrift; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.AtomicPositiveInteger; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.TimeoutException; import org.apache.dubbo.remoting.exchange.ExchangeClient; @@ -112,7 +112,7 @@ public boolean isAvailable() { for (ExchangeClient client : clients) { if (client.isConnected() - && !client.hasAttribute(RemotingConstants.CHANNEL_ATTRIBUTE_READONLY_KEY)) { + && !client.hasAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY)) { //cannot write == not Available ? return true; } diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java index 0d6206ae8a3..0da5ee8be6f 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java @@ -18,9 +18,9 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.remoting.Channel; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.Transporter; import org.apache.dubbo.remoting.exchange.ExchangeChannel; @@ -121,7 +121,7 @@ public int getDefaultPort() { public Exporter export(Invoker invoker) throws RpcException { // can use thrift codec only - URL url = invoker.getUrl().addParameter(RemotingConstants.CODEC_KEY, ThriftCodec.NAME); + URL url = invoker.getUrl().addParameter(Constants.CODEC_KEY, ThriftCodec.NAME); // find server. String key = url.getAddress(); // client can expose a service for server to invoke only. @@ -188,7 +188,7 @@ private ExchangeClient initClient(URL url) { ExchangeClient client; - url = url.addParameter(RemotingConstants.CODEC_KEY, ThriftCodec.NAME); + url = url.addParameter(Constants.CODEC_KEY, ThriftCodec.NAME); try { client = Exchangers.connect(url); @@ -203,8 +203,8 @@ private ExchangeClient initClient(URL url) { private ExchangeServer getServer(URL url) { // enable sending readonly event when server closes by default - url = url.addParameterIfAbsent(RemotingConstants.CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString()); - String str = url.getParameter(RemotingConstants.SERVER_KEY, RemotingConstants.DEFAULT_REMOTING_SERVER); + url = url.addParameterIfAbsent(Constants.CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString()); + String str = url.getParameter(Constants.SERVER_KEY, org.apache.dubbo.rpc.Constants.DEFAULT_REMOTING_SERVER); if (str != null && str.length() > 0 && !ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str)) { throw new RpcException("Unsupported server type: " + str + ", url: " + url); @@ -216,7 +216,7 @@ private ExchangeServer getServer(URL url) { } catch (RemotingException e) { throw new RpcException("Fail to start server(url: " + url + ") " + e.getMessage(), e); } - str = url.getParameter(RemotingConstants.CLIENT_KEY); + str = url.getParameter(Constants.CLIENT_KEY); if (str != null && str.length() > 0) { Set supportedTypes = ExtensionLoader.getExtensionLoader(Transporter.class).getSupportedExtensions(); if (!supportedTypes.contains(str)) { diff --git a/dubbo-rpc/dubbo-rpc-webservice/src/main/java/org/apache/dubbo/rpc/protocol/webservice/WebServiceProtocol.java b/dubbo-rpc/dubbo-rpc-webservice/src/main/java/org/apache/dubbo/rpc/protocol/webservice/WebServiceProtocol.java index 928b01c45ff..08dc57cfdf9 100644 --- a/dubbo-rpc/dubbo-rpc-webservice/src/main/java/org/apache/dubbo/rpc/protocol/webservice/WebServiceProtocol.java +++ b/dubbo-rpc/dubbo-rpc-webservice/src/main/java/org/apache/dubbo/rpc/protocol/webservice/WebServiceProtocol.java @@ -17,7 +17,7 @@ package org.apache.dubbo.rpc.protocol.webservice; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.http.HttpBinder; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.remoting.http.HttpServer; @@ -119,7 +119,7 @@ protected T doRefer(final Class serviceType, final URL url) throws RpcExc Client proxy = ClientProxy.getClient(ref); HTTPConduit conduit = (HTTPConduit) proxy.getConduit(); HTTPClientPolicy policy = new HTTPClientPolicy(); - policy.setConnectionTimeout(url.getParameter(RemotingConstants.CONNECT_TIMEOUT_KEY, RemotingConstants.DEFAULT_CONNECT_TIMEOUT)); + policy.setConnectionTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT)); policy.setReceiveTimeout(url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT)); conduit.setClient(policy); return ref; From 8b780cc8100f8b8698c505b50d49a42713c798b7 Mon Sep 17 00:00:00 2001 From: huazhongming Date: Thu, 16 May 2019 22:37:40 +0800 Subject: [PATCH 064/115] constant step4 config (#4079) --- .../common/constants/ConfigConstants.java | 93 -------------- .../apache/dubbo/config/MethodConfigTest.java | 12 +- .../dubbo/config/AbstractInterfaceConfig.java | 8 +- .../dubbo/config/ApplicationConfig.java | 16 +-- .../dubbo/config/ConfigCenterConfig.java | 8 +- .../org/apache/dubbo/config/Constants.java | 116 ++++++++++++++++++ .../org/apache/dubbo/config/MethodConfig.java | 12 +- .../org/apache/dubbo/config/ModuleConfig.java | 6 +- .../apache/dubbo/config/ProtocolConfig.java | 2 +- .../apache/dubbo/config/ProviderConfig.java | 4 +- .../apache/dubbo/config/ReferenceConfig.java | 2 +- .../apache/dubbo/config/RegistryConfig.java | 2 +- .../apache/dubbo/config/ServiceConfig.java | 12 +- .../config/builders/ApplicationBuilder.java | 2 +- .../apache/dubbo/config/MethodConfigTest.java | 14 +-- .../dubbo/config/RegistryConfigTest.java | 2 +- .../dubbo/config/ServiceConfigTest.java | 2 +- .../dubbo/rpc/protocol/dubbo/Constants.java | 4 + .../rpc/protocol/dubbo/DubboProtocol.java | 4 +- .../rpc/protocol/dubbo/FutureFilterTest.java | 2 +- 20 files changed, 175 insertions(+), 148 deletions(-) create mode 100644 dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/Constants.java diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ConfigConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ConfigConstants.java index 7f6351e605f..44deb2c8041 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ConfigConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ConfigConstants.java @@ -23,67 +23,11 @@ public interface ConfigConstants { String CLUSTER_KEY = "cluster"; - String STATUS_KEY = "status"; - - String CONTEXTPATH_KEY = "contextpath"; - - String LISTENER_KEY = "listener"; - - String LAYER_KEY = "layer"; - - /** - * General - */ - /** - * Application name; - */ - String NAME = "name"; - - /** - * Application owner name; - */ - String OWNER = "owner"; - - /** - * Running application organization name. - */ - String ORGANIZATION = "organization"; - - /** - * Application architecture name. - */ - String ARCHITECTURE = "architecture"; - - /** - * Environment name - */ - String ENVIRONMENT = "environment"; - - /** - * Test environment key. - */ - String TEST_ENVIRONMENT = "test"; - - /** - * Development environment key. - */ - String DEVELOPMENT_ENVIRONMENT = "develop"; - - /** - * Production environment key. - */ - String PRODUCTION_ENVIRONMENT = "product"; - String CONFIG_CLUSTER_KEY = "config.cluster"; String CONFIG_NAMESPACE_KEY = "config.namespace"; String CONFIG_GROUP_KEY = "config.group"; String CONFIG_CHECK_KEY = "config.check"; - String CONFIG_CONFIGFILE_KEY = "config.config-file"; - String CONFIG_ENABLE_KEY = "config.highest-priority"; - String CONFIG_TIMEOUT_KEY = "config.timeout"; - String CONFIG_APPNAME_KEY = "config.app-name"; - String USERNAME_KEY = "username"; String PASSWORD_KEY = "password"; @@ -92,42 +36,16 @@ public interface ConfigConstants { String PORT_KEY = "port"; - String MULTICAST = "multicast"; - String REGISTER_IP_KEY = "register.ip"; - String DUBBO_IP_TO_REGISTRY = "DUBBO_IP_TO_REGISTRY"; - - String DUBBO_PORT_TO_REGISTRY = "DUBBO_PORT_TO_REGISTRY"; - String DUBBO_IP_TO_BIND = "DUBBO_IP_TO_BIND"; - String DUBBO_PORT_TO_BIND = "DUBBO_PORT_TO_BIND"; - String SCOPE_KEY = "scope"; String SCOPE_LOCAL = "local"; String SCOPE_REMOTE = "remote"; - String SCOPE_NONE = "none"; - - String ON_CONNECT_KEY = "onconnect"; - - String ON_DISCONNECT_KEY = "ondisconnect"; - - String ON_INVOKE_METHOD_KEY = "oninvoke.method"; - - String ON_RETURN_METHOD_KEY = "onreturn.method"; - - String ON_THROW_METHOD_KEY = "onthrow.method"; - - String ON_INVOKE_INSTANCE_KEY = "oninvoke.instance"; - - String ON_RETURN_INSTANCE_KEY = "onreturn.instance"; - - String ON_THROW_INSTANCE_KEY = "onthrow.instance"; - @Deprecated String SHUTDOWN_WAIT_SECONDS_KEY = "dubbo.service.shutdown.wait.seconds"; @@ -152,17 +70,6 @@ public interface ConfigConstants { String ZOOKEEPER_PROTOCOL = "zookeeper"; - // FIXME: is this still useful? - String SHUTDOWN_TIMEOUT_KEY = "shutdown.timeout"; - - int DEFAULT_SHUTDOWN_TIMEOUT = 1000 * 60 * 15; - - String PROTOCOLS_SUFFIX = "dubbo.protocols."; - - String PROTOCOL_SUFFIX = "dubbo.protocol."; - - String REGISTRIES_SUFFIX = "dubbo.registries."; - String TELNET = "telnet"; String QOS_ENABLE = "qos.enable"; diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/MethodConfigTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/MethodConfigTest.java index 1681dd4d9dd..06eada996ec 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/MethodConfigTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/MethodConfigTest.java @@ -29,12 +29,12 @@ import java.util.HashMap; import java.util.Map; -import static org.apache.dubbo.common.constants.ConfigConstants.ON_INVOKE_INSTANCE_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.ON_INVOKE_METHOD_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.ON_RETURN_INSTANCE_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.ON_RETURN_METHOD_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.ON_THROW_INSTANCE_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.ON_THROW_METHOD_KEY; +import static org.apache.dubbo.config.Constants.ON_INVOKE_INSTANCE_KEY; +import static org.apache.dubbo.config.Constants.ON_INVOKE_METHOD_KEY; +import static org.apache.dubbo.config.Constants.ON_RETURN_INSTANCE_KEY; +import static org.apache.dubbo.config.Constants.ON_RETURN_METHOD_KEY; +import static org.apache.dubbo.config.Constants.ON_THROW_INSTANCE_KEY; +import static org.apache.dubbo.config.Constants.ON_THROW_METHOD_KEY; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java index f94f148ec6e..143d085f088 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java @@ -65,13 +65,13 @@ import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.CLUSTER_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_IP_TO_REGISTRY; +import static org.apache.dubbo.config.Constants.DUBBO_IP_TO_REGISTRY; import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; -import static org.apache.dubbo.common.constants.ConfigConstants.LAYER_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.LISTENER_KEY; +import static org.apache.dubbo.config.Constants.LAYER_KEY; +import static org.apache.dubbo.config.Constants.LISTENER_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.REGISTER_IP_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.REGISTRIES_SUFFIX; +import static org.apache.dubbo.config.Constants.REGISTRIES_SUFFIX; import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_SECONDS_KEY; import static org.apache.dubbo.monitor.Constants.LOGSTAT_PROTOCOL; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java index 5c13c0bd9c7..2b50e50ed72 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java @@ -29,17 +29,17 @@ import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DUMP_DIRECTORY; import static org.apache.dubbo.common.constants.ConfigConstants.ACCEPT_FOREIGN_IP; -import static org.apache.dubbo.common.constants.ConfigConstants.ARCHITECTURE; -import static org.apache.dubbo.common.constants.ConfigConstants.DEVELOPMENT_ENVIRONMENT; -import static org.apache.dubbo.common.constants.ConfigConstants.ENVIRONMENT; -import static org.apache.dubbo.common.constants.ConfigConstants.NAME; -import static org.apache.dubbo.common.constants.ConfigConstants.ORGANIZATION; -import static org.apache.dubbo.common.constants.ConfigConstants.OWNER; -import static org.apache.dubbo.common.constants.ConfigConstants.PRODUCTION_ENVIRONMENT; +import static org.apache.dubbo.config.Constants.ARCHITECTURE; +import static org.apache.dubbo.config.Constants.DEVELOPMENT_ENVIRONMENT; +import static org.apache.dubbo.config.Constants.ENVIRONMENT; +import static org.apache.dubbo.config.Constants.NAME; +import static org.apache.dubbo.config.Constants.ORGANIZATION; +import static org.apache.dubbo.config.Constants.OWNER; +import static org.apache.dubbo.config.Constants.PRODUCTION_ENVIRONMENT; import static org.apache.dubbo.common.constants.ConfigConstants.QOS_ENABLE; import static org.apache.dubbo.common.constants.ConfigConstants.QOS_PORT; import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.TEST_ENVIRONMENT; +import static org.apache.dubbo.config.Constants.TEST_ENVIRONMENT; /** diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java index 5334f0492c5..d65f2e2018d 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java @@ -28,14 +28,14 @@ import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_APPNAME_KEY; +import static org.apache.dubbo.config.Constants.CONFIG_APPNAME_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_CHECK_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_CLUSTER_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_CONFIGFILE_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_ENABLE_KEY; +import static org.apache.dubbo.config.Constants.CONFIG_CONFIGFILE_KEY; +import static org.apache.dubbo.config.Constants.CONFIG_ENABLE_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_GROUP_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_NAMESPACE_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_TIMEOUT_KEY; +import static org.apache.dubbo.config.Constants.CONFIG_TIMEOUT_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.ZOOKEEPER_PROTOCOL; /** diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/Constants.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/Constants.java new file mode 100644 index 00000000000..3842e01dd16 --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/Constants.java @@ -0,0 +1,116 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.config; + +/** + * + */ +public interface Constants { + + String STATUS_KEY = "status"; + + String CONTEXTPATH_KEY = "contextpath"; + + String LISTENER_KEY = "listener"; + + String LAYER_KEY = "layer"; + + /** + * General + */ + /** + * Application name; + */ + String NAME = "name"; + + /** + * Application owner name; + */ + String OWNER = "owner"; + + /** + * Running application organization name. + */ + String ORGANIZATION = "organization"; + + /** + * Application architecture name. + */ + String ARCHITECTURE = "architecture"; + + /** + * Environment name + */ + String ENVIRONMENT = "environment"; + + /** + * Test environment key. + */ + String TEST_ENVIRONMENT = "test"; + + /** + * Development environment key. + */ + String DEVELOPMENT_ENVIRONMENT = "develop"; + + /** + * Production environment key. + */ + String PRODUCTION_ENVIRONMENT = "product"; + + String CONFIG_CONFIGFILE_KEY = "config.config-file"; + String CONFIG_ENABLE_KEY = "config.highest-priority"; + String CONFIG_TIMEOUT_KEY = "config.timeout"; + String CONFIG_APPNAME_KEY = "config.app-name"; + + String MULTICAST = "multicast"; + + + String DUBBO_IP_TO_REGISTRY = "DUBBO_IP_TO_REGISTRY"; + + String DUBBO_PORT_TO_REGISTRY = "DUBBO_PORT_TO_REGISTRY"; + + + String DUBBO_PORT_TO_BIND = "DUBBO_PORT_TO_BIND"; + + String SCOPE_NONE = "none"; + + + String ON_INVOKE_METHOD_KEY = "oninvoke.method"; + + String ON_RETURN_METHOD_KEY = "onreturn.method"; + + String ON_THROW_METHOD_KEY = "onthrow.method"; + + String ON_INVOKE_INSTANCE_KEY = "oninvoke.instance"; + + String ON_RETURN_INSTANCE_KEY = "onreturn.instance"; + + String ON_THROW_INSTANCE_KEY = "onthrow.instance"; + + + // FIXME: is this still useful? + String SHUTDOWN_TIMEOUT_KEY = "shutdown.timeout"; + + + String PROTOCOLS_SUFFIX = "dubbo.protocols."; + + + String REGISTRIES_SUFFIX = "dubbo.registries."; + +} diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MethodConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MethodConfig.java index c9dfdaa6d79..c942794d1c2 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MethodConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MethodConfig.java @@ -25,12 +25,12 @@ import java.util.Collections; import java.util.List; -import static org.apache.dubbo.common.constants.ConfigConstants.ON_INVOKE_INSTANCE_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.ON_INVOKE_METHOD_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.ON_RETURN_INSTANCE_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.ON_RETURN_METHOD_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.ON_THROW_INSTANCE_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.ON_THROW_METHOD_KEY; +import static org.apache.dubbo.config.Constants.ON_INVOKE_INSTANCE_KEY; +import static org.apache.dubbo.config.Constants.ON_INVOKE_METHOD_KEY; +import static org.apache.dubbo.config.Constants.ON_RETURN_INSTANCE_KEY; +import static org.apache.dubbo.config.Constants.ON_RETURN_METHOD_KEY; +import static org.apache.dubbo.config.Constants.ON_THROW_INSTANCE_KEY; +import static org.apache.dubbo.config.Constants.ON_THROW_METHOD_KEY; /** * The method configuration diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ModuleConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ModuleConfig.java index 23b5743f6f7..1aecc549177 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ModuleConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ModuleConfig.java @@ -23,9 +23,9 @@ import java.util.ArrayList; import java.util.List; -import static org.apache.dubbo.common.constants.ConfigConstants.NAME; -import static org.apache.dubbo.common.constants.ConfigConstants.ORGANIZATION; -import static org.apache.dubbo.common.constants.ConfigConstants.OWNER; +import static org.apache.dubbo.config.Constants.NAME; +import static org.apache.dubbo.config.Constants.ORGANIZATION; +import static org.apache.dubbo.config.Constants.OWNER; /** * The module info diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java index 73755984ae8..d957f1f1cda 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java @@ -35,7 +35,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; import static org.apache.dubbo.common.constants.ConfigConstants.HOST_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.PROTOCOLS_SUFFIX; +import static org.apache.dubbo.config.Constants.PROTOCOLS_SUFFIX; import static org.apache.dubbo.common.constants.ConfigConstants.TELNET; import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProviderConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProviderConfig.java index c8c6380f571..3e75dfdd66c 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProviderConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProviderConfig.java @@ -29,8 +29,8 @@ import java.util.Arrays; import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.CONTEXTPATH_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.STATUS_KEY; +import static org.apache.dubbo.config.Constants.CONTEXTPATH_KEY; +import static org.apache.dubbo.config.Constants.STATUS_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.TELNET; /** diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java index 51a8204c712..2d50ae596ee 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java @@ -66,7 +66,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.SEMICOLON_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.CLUSTER_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_IP_TO_REGISTRY; +import static org.apache.dubbo.config.Constants.DUBBO_IP_TO_REGISTRY; import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.REGISTER_IP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java index 1d2109af22e..90a7fd97043 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java @@ -25,7 +25,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.FILE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.PASSWORD_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.REGISTRIES_SUFFIX; +import static org.apache.dubbo.config.Constants.REGISTRIES_SUFFIX; import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.USERNAME_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.ZOOKEEPER_PROTOCOL; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index 2a9ca02fdda..e70195d5407 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -72,15 +72,15 @@ import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_IP_TO_BIND; -import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_IP_TO_REGISTRY; -import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PORT_TO_BIND; -import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PORT_TO_REGISTRY; +import static org.apache.dubbo.config.Constants.DUBBO_IP_TO_REGISTRY; +import static org.apache.dubbo.config.Constants.DUBBO_PORT_TO_BIND; +import static org.apache.dubbo.config.Constants.DUBBO_PORT_TO_REGISTRY; import static org.apache.dubbo.common.constants.ConfigConstants.EXPORT_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.MULTICAST; -import static org.apache.dubbo.common.constants.ConfigConstants.PROTOCOLS_SUFFIX; +import static org.apache.dubbo.config.Constants.MULTICAST; +import static org.apache.dubbo.config.Constants.PROTOCOLS_SUFFIX; import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_LOCAL; -import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_NONE; +import static org.apache.dubbo.config.Constants.SCOPE_NONE; import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_REMOTE; import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ApplicationBuilder.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ApplicationBuilder.java index 45992a4f516..7ab59a6bf8c 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ApplicationBuilder.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ApplicationBuilder.java @@ -25,7 +25,7 @@ import java.util.List; import java.util.Map; -import static org.apache.dubbo.common.constants.ConfigConstants.PRODUCTION_ENVIRONMENT; +import static org.apache.dubbo.config.Constants.PRODUCTION_ENVIRONMENT; /** * This is a builder for build {@link ApplicationConfig}. diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MethodConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MethodConfigTest.java index e50caa1e3a5..c0e777bd637 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MethodConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MethodConfigTest.java @@ -17,7 +17,6 @@ package org.apache.dubbo.config; -import org.apache.dubbo.common.constants.ConfigConstants; import org.apache.dubbo.config.annotation.Argument; import org.apache.dubbo.config.annotation.Method; import org.apache.dubbo.config.annotation.Reference; @@ -30,11 +29,12 @@ import java.util.List; import java.util.Map; -import static org.apache.dubbo.common.constants.ConfigConstants.ON_INVOKE_INSTANCE_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.ON_RETURN_INSTANCE_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.ON_RETURN_METHOD_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.ON_THROW_INSTANCE_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.ON_THROW_METHOD_KEY; +import static org.apache.dubbo.config.Constants.ON_INVOKE_INSTANCE_KEY; +import static org.apache.dubbo.config.Constants.ON_RETURN_INSTANCE_KEY; +import static org.apache.dubbo.config.Constants.ON_RETURN_METHOD_KEY; +import static org.apache.dubbo.config.Constants.ON_THROW_INSTANCE_KEY; +import static org.apache.dubbo.config.Constants.ON_THROW_METHOD_KEY; +import static org.apache.dubbo.config.Constants.ON_INVOKE_METHOD_KEY; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; @@ -225,7 +225,7 @@ public void testOninvokeMethod() throws Exception { assertThat(method.getOninvokeMethod(), equalTo("on-invoke-method")); Map attribute = new HashMap(); MethodConfig.appendAttributes(attribute, method); - assertThat(attribute, hasEntry((Object) ConfigConstants.ON_INVOKE_METHOD_KEY, (Object) "on-invoke-method")); + assertThat(attribute, hasEntry((Object) ON_INVOKE_METHOD_KEY, (Object) "on-invoke-method")); Map parameters = new HashMap(); MethodConfig.appendParameters(parameters, method); assertThat(parameters.size(), is(0)); diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java index 70567fac1ec..9b3e0e75d63 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java @@ -23,7 +23,7 @@ import java.util.HashMap; import java.util.Map; -import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_TIMEOUT_KEY; +import static org.apache.dubbo.config.Constants.SHUTDOWN_TIMEOUT_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java index b60bbfda398..e4361195e87 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java @@ -48,7 +48,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.EXPORT_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_TIMEOUT_KEY; +import static org.apache.dubbo.config.Constants.SHUTDOWN_TIMEOUT_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.remoting.Constants.BIND_IP_KEY; import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY; diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/Constants.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/Constants.java index 9d86b5d0228..f8cc1cec27f 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/Constants.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/Constants.java @@ -62,4 +62,8 @@ public interface Constants { String OPTIMIZER_KEY = "optimizer"; + String ON_CONNECT_KEY = "onconnect"; + + String ON_DISCONNECT_KEY = "ondisconnect"; + } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java index dad2f4e0fe4..e3c945b873f 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java @@ -63,8 +63,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.LAZY_CONNECT_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.ON_CONNECT_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.ON_DISCONNECT_KEY; +import static org.apache.dubbo.rpc.protocol.dubbo.Constants.ON_CONNECT_KEY; +import static org.apache.dubbo.rpc.protocol.dubbo.Constants.ON_DISCONNECT_KEY; import static org.apache.dubbo.common.constants.RemotingConstants.DEFAULT_HEARTBEAT; import static org.apache.dubbo.common.constants.RemotingConstants.HEARTBEAT_KEY; import static org.apache.dubbo.remoting.Constants.CHANNEL_READONLYEVENT_SENT_KEY; diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/FutureFilterTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/FutureFilterTest.java index 39dc86187aa..2429b4b9580 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/FutureFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/FutureFilterTest.java @@ -30,7 +30,7 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import static org.apache.dubbo.common.constants.ConfigConstants.ON_THROW_METHOD_KEY; +import static org.apache.dubbo.config.Constants.ON_THROW_METHOD_KEY; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; From 086fdcb9c455edf36be59c529803fe0d179a6e27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=97=B6=E6=97=A0=E4=B8=A4=E4=B8=B6?= <442367943@qq.com> Date: Fri, 17 May 2019 11:04:50 +0800 Subject: [PATCH 065/115] Shorten the life cycle of TimeoutTask to avoid frequent gc. (#4040) --- .../exchange/support/DefaultFuture.java | 25 +++++++++++++------ 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture.java index 6a554469845..7a860a396fd 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture.java @@ -54,6 +54,8 @@ public class DefaultFuture implements ResponseFuture { private static final Map FUTURES = new ConcurrentHashMap<>(); + private static final Map PENDING_TASKS = new ConcurrentHashMap<>(); + public static final Timer TIME_OUT_TIMER = new HashedWheelTimer( new NamedThreadFactory("dubbo-future-timeout", true), 30, @@ -86,7 +88,8 @@ private DefaultFuture(Channel channel, Request request, int timeout) { */ private static void timeoutCheck(DefaultFuture future) { TimeoutCheckTask task = new TimeoutCheckTask(future); - TIME_OUT_TIMER.newTimeout(task, future.getTimeout(), TimeUnit.MILLISECONDS); + Timeout t = TIME_OUT_TIMER.newTimeout(task, future.getTimeout(), TimeUnit.MILLISECONDS); + PENDING_TASKS.put(future.getId(), t); } /** @@ -149,6 +152,11 @@ public static void received(Channel channel, Response response) { DefaultFuture future = FUTURES.remove(response.getId()); if (future != null) { future.doReceived(response); + Timeout t = PENDING_TASKS.remove(future.getId()); + if (t != null) { + // decrease Time + t.cancel(); + } } else { logger.warn("The timeout response finally returned at " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date())) @@ -238,7 +246,10 @@ private static class TimeoutCheckTask implements TimerTask { @Override public void run(Timeout timeout) { - if (future == null || future.isDone()) { + // remove from pending task + PENDING_TASKS.remove(future.getId()); + + if (future.isDone()) { return; } // create exception response. @@ -248,13 +259,11 @@ public void run(Timeout timeout) { timeoutResponse.setErrorMessage(future.getTimeoutMessage(true)); // handle response. DefaultFuture.received(future.getChannel(), timeoutResponse); - } } private void invokeCallback(ResponseCallback c) { - ResponseCallback callbackCopy = c; - if (callbackCopy == null) { + if (c == null) { throw new NullPointerException("callback cannot be null."); } Response res = response; @@ -264,21 +273,21 @@ private void invokeCallback(ResponseCallback c) { if (res.getStatus() == Response.OK) { try { - callbackCopy.done(res.getResult()); + c.done(res.getResult()); } catch (Exception e) { logger.error("callback invoke error .result:" + res.getResult() + ",url:" + channel.getUrl(), e); } } else if (res.getStatus() == Response.CLIENT_TIMEOUT || res.getStatus() == Response.SERVER_TIMEOUT) { try { TimeoutException te = new TimeoutException(res.getStatus() == Response.SERVER_TIMEOUT, channel, res.getErrorMessage()); - callbackCopy.caught(te); + c.caught(te); } catch (Exception e) { logger.error("callback invoke error ,url:" + channel.getUrl(), e); } } else { try { RuntimeException re = new RuntimeException(res.getErrorMessage()); - callbackCopy.caught(re); + c.caught(re); } catch (Exception e) { logger.error("callback invoke error ,url:" + channel.getUrl(), e); } From 8456a11a492b33270435dba8d01417cb35025289 Mon Sep 17 00:00:00 2001 From: cvictory Date: Fri, 17 May 2019 15:43:13 +0800 Subject: [PATCH 066/115] Merge pull request #4014, Zipkin compatible. fixes #3728. --- .../remoting/exchange/ResponseCallback.java | 25 ++++++ .../com/alibaba/dubbo/rpc/Invocation.java | 2 +- .../com/alibaba/dubbo/rpc/RpcContext.java | 29 ++++++ .../rpc/protocol/dubbo/FutureAdapter.java | 29 ++++++ .../alibaba/dubbo/rpc/support/RpcUtils.java | 88 +++++++++++++++++++ .../java/org/apache/dubbo/rpc/RpcContext.java | 4 + 6 files changed, 176 insertions(+), 1 deletion(-) create mode 100644 dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseCallback.java create mode 100644 dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/FutureAdapter.java create mode 100644 dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/support/RpcUtils.java diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseCallback.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseCallback.java new file mode 100644 index 00000000000..893b262094b --- /dev/null +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseCallback.java @@ -0,0 +1,25 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.dubbo.remoting.exchange; + +/** + * 2019-04-18 + */ +@Deprecated +public interface ResponseCallback extends org.apache.dubbo.remoting.exchange.ResponseCallback { +} diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invocation.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invocation.java index b96d14d1ee4..9d960c219df 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invocation.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invocation.java @@ -29,7 +29,7 @@ default org.apache.dubbo.rpc.Invocation getOriginal() { return null; } - class CompatibleInvocation implements Invocation { + class CompatibleInvocation implements Invocation, org.apache.dubbo.rpc.Invocation { private org.apache.dubbo.rpc.Invocation delegate; diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java index a5db891beb0..bf6160c06ac 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java @@ -19,4 +19,33 @@ @Deprecated public class RpcContext extends org.apache.dubbo.rpc.RpcContext { + + + public static RpcContext getContext() { + return newInstance(org.apache.dubbo.rpc.RpcContext.getContext()); + } + + private static RpcContext newInstance(org.apache.dubbo.rpc.RpcContext rpcContext) { + RpcContext copy = new RpcContext(); + copy.getAttachments().putAll(rpcContext.getAttachments()); + copy.get().putAll(rpcContext.get()); + copy.setFuture(rpcContext.getFuture()); + copy.setUrls(rpcContext.getUrls()); + copy.setUrl(rpcContext.getUrl()); + copy.setMethodName(rpcContext.getMethodName()); + copy.setParameterTypes(rpcContext.getParameterTypes()); + copy.setArguments(rpcContext.getArguments()); + copy.setLocalAddress(rpcContext.getLocalAddress()); + copy.setRemoteAddress(rpcContext.getRemoteAddress()); + copy.setRemoteApplicationName(rpcContext.getRemoteApplicationName()); + copy.setInvokers(rpcContext.getInvokers()); + copy.setInvoker(rpcContext.getInvoker()); + copy.setInvocation(rpcContext.getInvocation()); + + copy.setRequest(rpcContext.getRequest()); + copy.setResponse(rpcContext.getResponse()); + copy.setAsyncContext(rpcContext.getAsyncContext()); + + return copy; + } } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/FutureAdapter.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/FutureAdapter.java new file mode 100644 index 00000000000..07a69871af7 --- /dev/null +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/FutureAdapter.java @@ -0,0 +1,29 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.dubbo.rpc.protocol.dubbo; + +import org.apache.dubbo.remoting.exchange.ResponseFuture; + +/** + * 2019-04-18 + */ +public class FutureAdapter extends org.apache.dubbo.rpc.protocol.dubbo.FutureAdapter { + public FutureAdapter(ResponseFuture future) { + super(future); + } +} diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/support/RpcUtils.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/support/RpcUtils.java new file mode 100644 index 00000000000..7f1ab98de5c --- /dev/null +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/support/RpcUtils.java @@ -0,0 +1,88 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.dubbo.rpc.support; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.rpc.Invocation; + +import java.lang.reflect.Method; +import java.lang.reflect.Type; +import java.util.Map; + +/** + * 2019-04-18 + */ +public class RpcUtils extends org.apache.dubbo.rpc.support.RpcUtils { + + + public static Class getReturnType(Invocation invocation) { + return org.apache.dubbo.rpc.support.RpcUtils.getReturnType(invocation); + } + + // TODO why not get return type when initialize Invocation? + public static Type[] getReturnTypes(Invocation invocation) { + return org.apache.dubbo.rpc.support.RpcUtils.getReturnTypes(invocation); + } + + public static Long getInvocationId(Invocation inv) { + return org.apache.dubbo.rpc.support.RpcUtils.getInvocationId(inv); + } + + /** + * Idempotent operation: invocation id will be added in async operation by default + * + * @param url + * @param inv + */ + public static void attachInvocationIdIfAsync(URL url, Invocation inv) { + org.apache.dubbo.rpc.support.RpcUtils.attachInvocationIdIfAsync(url.getOriginalURL(), inv); + } + + + public static String getMethodName(Invocation invocation) { + return org.apache.dubbo.rpc.support.RpcUtils.getMethodName(invocation); + } + + public static Object[] getArguments(Invocation invocation) { + return org.apache.dubbo.rpc.support.RpcUtils.getArguments(invocation); + } + + public static Class[] getParameterTypes(Invocation invocation) { + return org.apache.dubbo.rpc.support.RpcUtils.getParameterTypes(invocation); + } + + public static boolean isAsync(URL url, Invocation inv) { + return org.apache.dubbo.rpc.support.RpcUtils.isAsync(url.getOriginalURL(), inv); + } + + public static boolean isReturnTypeFuture(Invocation inv) { + return org.apache.dubbo.rpc.support.RpcUtils.isReturnTypeFuture(inv); + } + + public static boolean hasFutureReturnType(Method method) { + return org.apache.dubbo.rpc.support.RpcUtils.hasFutureReturnType(method); + } + + public static boolean isOneway(URL url, Invocation inv) { + return org.apache.dubbo.rpc.support.RpcUtils.isOneway(url.getOriginalURL(), inv); + } + + public static Map getNecessaryAttachments(Invocation inv) { + return org.apache.dubbo.rpc.support.RpcUtils.getNecessaryAttachments(inv); + } +} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java index a468baa0719..fc658db052d 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java @@ -758,6 +758,10 @@ public static AsyncContext startAsync() throws IllegalStateException { return currentContext.asyncContext; } + protected void setAsyncContext(AsyncContext asyncContext) { + this.asyncContext = asyncContext; + } + public boolean isAsyncStarted() { if (this.asyncContext == null) { return false; From 86462778281953b3b4602dbccb456fab65bd7c32 Mon Sep 17 00:00:00 2001 From: Haiyang Date: Fri, 17 May 2019 15:54:34 +0800 Subject: [PATCH 067/115] reference config initialized. (#4067) --- .../main/java/org/apache/dubbo/config/ReferenceConfig.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java index 2d50ae596ee..8ec800c75ca 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java @@ -273,7 +273,6 @@ private void init() { if (initialized) { return; } - initialized = true; checkStubAndLocal(interfaceClass); checkMock(interfaceClass); Map map = new HashMap(); @@ -331,6 +330,7 @@ private void init() { String serviceKey = URL.buildKey(interfaceName, group, version); ApplicationModel.initConsumerModel(serviceKey, buildConsumerModel(serviceKey, attributes)); + initialized = true; } private ConsumerModel buildConsumerModel(String serviceKey, Map attributes) { @@ -414,8 +414,6 @@ private T createProxy(Map map) { } if (shouldCheck() && !invoker.isAvailable()) { - // make it possible for consumer to retry later if provider is temporarily unavailable - initialized = false; throw new IllegalStateException("Failed to check the status of the service " + interfaceName + ". No provider available for the service " + (group == null ? "" : group + "/") + interfaceName + (version == null ? "" : ":" + version) + " from the url " + invoker.getUrl() + " to the consumer " + NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion()); } if (logger.isInfoEnabled()) { From bfb60773d8dd6ff15a1510986423ea64cb23e6fc Mon Sep 17 00:00:00 2001 From: cvictory Date: Fri, 17 May 2019 15:58:26 +0800 Subject: [PATCH 068/115] [compatible] Registry compatibility #3882 (#4015) Fixes #3882 --- .../alibaba/dubbo/common/utils/UrlUtils.java | 110 +++++++++++ .../dubbo/registry/NotifyListener.java | 16 ++ .../registry/support/AbstractRegistry.java | 145 ++++++++++++++ .../support/AbstractRegistryFactory.java | 34 ++++ .../registry/support/FailbackRegistry.java | 187 ++++++++++++++++++ .../registry/support/FailbackRegistry.java | 10 +- 6 files changed, 497 insertions(+), 5 deletions(-) create mode 100644 dubbo-compatible/src/main/java/com/alibaba/dubbo/common/utils/UrlUtils.java create mode 100644 dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistry.java create mode 100644 dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistryFactory.java create mode 100644 dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/FailbackRegistry.java diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/utils/UrlUtils.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/utils/UrlUtils.java new file mode 100644 index 00000000000..c8417610b52 --- /dev/null +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/utils/UrlUtils.java @@ -0,0 +1,110 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.utils; + +import com.alibaba.dubbo.common.URL; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * 2019-04-17 + */ +@Deprecated +public class UrlUtils { + + public static URL parseURL(String address, Map defaults) { + return new URL(org.apache.dubbo.common.utils.UrlUtils.parseURL(address, defaults)); + } + + public static List parseURLs(String address, Map defaults) { + return org.apache.dubbo.common.utils.UrlUtils.parseURLs(address, defaults).stream().map(e -> new URL(e)).collect(Collectors.toList()); + } + + public static Map> convertRegister(Map> register) { + return org.apache.dubbo.common.utils.UrlUtils.convertRegister(register); + } + + public static Map convertSubscribe(Map subscribe) { + return org.apache.dubbo.common.utils.UrlUtils.convertSubscribe(subscribe); + } + + public static Map> revertRegister(Map> register) { + return org.apache.dubbo.common.utils.UrlUtils.revertRegister(register); + } + + public static Map revertSubscribe(Map subscribe) { + return org.apache.dubbo.common.utils.UrlUtils.revertSubscribe(subscribe); + } + + public static Map> revertNotify(Map> notify) { + return org.apache.dubbo.common.utils.UrlUtils.revertNotify(notify); + } + + //compatible for dubbo-2.0.0 + public static List revertForbid(List forbid, Set subscribed) { + Set urls = subscribed.stream().map(e -> e.getOriginalURL()).collect(Collectors.toSet()); + return org.apache.dubbo.common.utils.UrlUtils.revertForbid(forbid, urls); + } + + public static URL getEmptyUrl(String service, String category) { + return new URL(org.apache.dubbo.common.utils.UrlUtils.getEmptyUrl(service, category)); + } + + public static boolean isMatchCategory(String category, String categories) { + return org.apache.dubbo.common.utils.UrlUtils.isMatchCategory(category, categories); + } + + public static boolean isMatch(URL consumerUrl, URL providerUrl) { + return org.apache.dubbo.common.utils.UrlUtils.isMatch(consumerUrl.getOriginalURL(), providerUrl.getOriginalURL()); + } + + public static boolean isMatchGlobPattern(String pattern, String value, URL param) { + return org.apache.dubbo.common.utils.UrlUtils.isMatchGlobPattern(pattern, value, param.getOriginalURL()); + } + + public static boolean isMatchGlobPattern(String pattern, String value) { + return org.apache.dubbo.common.utils.UrlUtils.isMatchGlobPattern(pattern, value); + } + + public static boolean isServiceKeyMatch(URL pattern, URL value) { + return org.apache.dubbo.common.utils.UrlUtils.isServiceKeyMatch(pattern.getOriginalURL(), value.getOriginalURL()); + } + + + public static boolean isConfigurator(URL url) { + return org.apache.dubbo.common.utils.UrlUtils.isConfigurator(url.getOriginalURL()); + } + + public static boolean isRoute(URL url) { + return org.apache.dubbo.common.utils.UrlUtils.isRoute(url.getOriginalURL()); + } + + public static boolean isProvider(URL url) { + return org.apache.dubbo.common.utils.UrlUtils.isProvider(url.getOriginalURL()); + } + + public static int getHeartbeat(URL url) { + return org.apache.dubbo.common.utils.UrlUtils.getHeartbeat(url.getOriginalURL()); + } + + public static int getIdleTimeout(URL url) { + return org.apache.dubbo.common.utils.UrlUtils.getIdleTimeout(url.getOriginalURL()); + } +} diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/NotifyListener.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/NotifyListener.java index d7e82b5e144..633dc1b656e 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/NotifyListener.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/NotifyListener.java @@ -42,4 +42,20 @@ public void notify(List urls) { } } } + + class ReverseCompatibleNotifyListener implements org.apache.dubbo.registry.NotifyListener { + + private NotifyListener listener; + + public ReverseCompatibleNotifyListener(NotifyListener listener) { + this.listener = listener; + } + + @Override + public void notify(List urls) { + if (listener != null) { + listener.notify(urls.stream().map(url -> new URL(url)).collect(Collectors.toList())); + } + } + } } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistry.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistry.java new file mode 100644 index 00000000000..ef1bb3d9e75 --- /dev/null +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistry.java @@ -0,0 +1,145 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.registry.support; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.registry.NotifyListener; +import org.apache.dubbo.registry.Registry; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * 2019-04-16 + */ +@Deprecated +public abstract class AbstractRegistry implements Registry { + + private CompatibleAbstractRegistry abstractRegistry; + + public AbstractRegistry(com.alibaba.dubbo.common.URL url) { + abstractRegistry = new CompatibleAbstractRegistry(url.getOriginalURL()); + } + + @Override + public com.alibaba.dubbo.common.URL getUrl() { + return new com.alibaba.dubbo.common.URL(abstractRegistry.getUrl()); + } + + protected void setUrl(com.alibaba.dubbo.common.URL url) { + abstractRegistry.setUrl(url.getOriginalURL()); + } + + public Set getRegistered() { + return abstractRegistry.getRegistered().stream().map(url -> new com.alibaba.dubbo.common.URL(url)).collect(Collectors.toSet()); + } + + public Map> getSubscribed() { + return abstractRegistry.getSubscribed().entrySet() + .stream() + .collect(Collectors.toMap(entry -> new com.alibaba.dubbo.common.URL(entry.getKey()), + entry -> convertToNotifyListeners(entry.getValue()))); + } + + public Map>> getNotified() { + return abstractRegistry.getNotified().entrySet().stream() + .collect(Collectors.toMap(entry -> new com.alibaba.dubbo.common.URL(entry.getKey()), + entry -> { + return entry.getValue().entrySet() + .stream() + .collect(Collectors.toMap(e -> e.getKey(), e -> { + return e.getValue().stream().map(url -> new com.alibaba.dubbo.common.URL(url)).collect(Collectors.toList()); + })); + })); + } + + + public List getCacheUrls(com.alibaba.dubbo.common.URL url) { + return abstractRegistry.lookup(url.getOriginalURL()).stream().map(tmpUrl -> new com.alibaba.dubbo.common.URL(tmpUrl)).collect(Collectors.toList()); + } + + public List lookup(com.alibaba.dubbo.common.URL url) { + return abstractRegistry.lookup(url.getOriginalURL()).stream().map(tmpUrl -> new com.alibaba.dubbo.common.URL(tmpUrl)).collect(Collectors.toList()); + } + + protected void notify(com.alibaba.dubbo.common.URL url, com.alibaba.dubbo.registry.NotifyListener listener, List urls) { + abstractRegistry.notify(url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener), urls.stream().map(tmpUrl -> tmpUrl.getOriginalURL()).collect(Collectors.toList())); + } + + public void register(com.alibaba.dubbo.common.URL url) { + abstractRegistry.register(url.getOriginalURL()); + } + + public void unregister(com.alibaba.dubbo.common.URL url) { + abstractRegistry.unregister(url.getOriginalURL()); + } + + public void subscribe(com.alibaba.dubbo.common.URL url, com.alibaba.dubbo.registry.NotifyListener listener) { + abstractRegistry.subscribe(url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener)); + } + + public void unsubscribe(com.alibaba.dubbo.common.URL url, com.alibaba.dubbo.registry.NotifyListener listener) { + abstractRegistry.unsubscribe(url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener)); + } + + + @Override + public void register(URL url) { + this.register(new com.alibaba.dubbo.common.URL(url)); + } + + @Override + public void unregister(URL url) { + this.unregister(new com.alibaba.dubbo.common.URL(url)); + } + + @Override + public void subscribe(URL url, NotifyListener listener) { + this.subscribe(new com.alibaba.dubbo.common.URL(url), new com.alibaba.dubbo.registry.NotifyListener.CompatibleNotifyListener(listener)); + } + + @Override + public void unsubscribe(URL url, NotifyListener listener) { + this.unsubscribe(new com.alibaba.dubbo.common.URL(url), new com.alibaba.dubbo.registry.NotifyListener.CompatibleNotifyListener(listener)); + } + + final Set convertToNotifyListeners(Set notifyListeners) { + return notifyListeners.stream().map(listener -> new com.alibaba.dubbo.registry.NotifyListener.CompatibleNotifyListener(listener)).collect(Collectors.toSet()); + } + + + static class CompatibleAbstractRegistry extends org.apache.dubbo.registry.support.AbstractRegistry { + public CompatibleAbstractRegistry(URL url) { + super(url); + } + + @Override + public boolean isAvailable() { + return false; + } + + public void notify(URL url, NotifyListener listener, List urls) { + super.notify(url, listener, urls); + } + + public void setUrl(URL url) { + super.setUrl(url); + } + } +} diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistryFactory.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistryFactory.java new file mode 100644 index 00000000000..9b0b698e63d --- /dev/null +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistryFactory.java @@ -0,0 +1,34 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.registry.support; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.registry.Registry; + +/** + * 2019-04-16 + */ +@Deprecated +public abstract class AbstractRegistryFactory extends org.apache.dubbo.registry.support.AbstractRegistryFactory { + + + protected abstract com.alibaba.dubbo.registry.Registry createRegistry(com.alibaba.dubbo.common.URL url); + + protected Registry createRegistry(URL url) { + return createRegistry(new com.alibaba.dubbo.common.URL(url)); + } +} diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/FailbackRegistry.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/FailbackRegistry.java new file mode 100644 index 00000000000..0156ddb4624 --- /dev/null +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/FailbackRegistry.java @@ -0,0 +1,187 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.registry.support; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.registry.NotifyListener; +import com.alibaba.dubbo.registry.Registry; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * 2019-04-17 + */ +@Deprecated +public abstract class FailbackRegistry implements org.apache.dubbo.registry.Registry, Registry { + + private CompatibleFailbackRegistry failbackRegistry; + + public FailbackRegistry(URL url) { + failbackRegistry = new CompatibleFailbackRegistry(url.getOriginalURL(), this); + } + + public void removeFailedRegisteredTask(URL url) { + failbackRegistry.removeFailedRegisteredTask(url.getOriginalURL()); + } + + public void removeFailedUnregisteredTask(URL url) { + failbackRegistry.removeFailedUnregisteredTask(url.getOriginalURL()); + } + + public void removeFailedSubscribedTask(URL url, NotifyListener listener) { + failbackRegistry.removeFailedSubscribedTask(url.getOriginalURL(), new NotifyListener.ReverseCompatibleNotifyListener(listener)); + } + + public void removeFailedUnsubscribedTask(URL url, NotifyListener listener) { + failbackRegistry.removeFailedUnsubscribedTask(url.getOriginalURL(), new NotifyListener.ReverseCompatibleNotifyListener(listener)); + } + + public void removeFailedNotifiedTask(URL url, NotifyListener listener) { + failbackRegistry.removeFailedNotifiedTask(url.getOriginalURL(), new NotifyListener.ReverseCompatibleNotifyListener(listener)); + } + + public void register(URL url) { + failbackRegistry.register(url.getOriginalURL()); + } + + public void unregister(URL url) { + failbackRegistry.unregister(url.getOriginalURL()); + } + + public void subscribe(URL url, NotifyListener listener) { + failbackRegistry.subscribe(url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener)); + } + + public void unsubscribe(URL url, NotifyListener listener) { + failbackRegistry.unsubscribe(url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener)); + } + + protected void notify(URL url, NotifyListener listener, List urls) { + List urlResult = urls.stream().map(e -> e.getOriginalURL()).collect(Collectors.toList()); + failbackRegistry.notify(url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener), urlResult); + } + + protected void doNotify(URL url, NotifyListener listener, List urls) { + List urlResult = urls.stream().map(e -> e.getOriginalURL()).collect(Collectors.toList()); + failbackRegistry.doNotify(url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener), urlResult); + } + + protected void recover() throws Exception { + failbackRegistry.recover(); + } + + public List lookup(URL url) { + return failbackRegistry.lookup(url.getOriginalURL()).stream().map(e -> new URL(e)).collect(Collectors.toList()); + } + + public URL getUrl() { + return new URL(failbackRegistry.getUrl()); + } + + @Override + public void destroy() { + failbackRegistry.destroy(); + } + + // ==== Template method ==== + + public abstract void doRegister(URL url); + + public abstract void doUnregister(URL url); + + public abstract void doSubscribe(URL url, NotifyListener listener); + + public abstract void doUnsubscribe(URL url, NotifyListener listener); + + @Override + public void register(org.apache.dubbo.common.URL url) { + this.register(new URL(url)); + } + + @Override + public void unregister(org.apache.dubbo.common.URL url) { + this.unregister(new URL(url)); + } + + @Override + public void subscribe(org.apache.dubbo.common.URL url, org.apache.dubbo.registry.NotifyListener listener) { + this.subscribe(new URL(url), new NotifyListener.CompatibleNotifyListener(listener)); + } + + @Override + public void unsubscribe(org.apache.dubbo.common.URL url, org.apache.dubbo.registry.NotifyListener listener) { + this.unsubscribe(new URL(url), new NotifyListener.CompatibleNotifyListener(listener)); + } + + @Override + public List lookup(org.apache.dubbo.common.URL url) { + return failbackRegistry.lookup(url); + } + + + static class CompatibleFailbackRegistry extends org.apache.dubbo.registry.support.FailbackRegistry { + + private FailbackRegistry compatibleFailbackRegistry; + + public CompatibleFailbackRegistry(org.apache.dubbo.common.URL url, FailbackRegistry compatibleFailbackRegistry) { + super(url); + this.compatibleFailbackRegistry = compatibleFailbackRegistry; + } + + @Override + public void doRegister(org.apache.dubbo.common.URL url) { + this.compatibleFailbackRegistry.doRegister(new URL(url)); + } + + @Override + public void doUnregister(org.apache.dubbo.common.URL url) { + this.compatibleFailbackRegistry.doUnregister(new URL(url)); + } + + @Override + public void doSubscribe(org.apache.dubbo.common.URL url, org.apache.dubbo.registry.NotifyListener listener) { + this.compatibleFailbackRegistry.doSubscribe(new URL(url), new NotifyListener.CompatibleNotifyListener(listener)); + } + + @Override + public void doUnsubscribe(org.apache.dubbo.common.URL url, org.apache.dubbo.registry.NotifyListener listener) { + this.compatibleFailbackRegistry.doUnsubscribe(new URL(url), new NotifyListener.CompatibleNotifyListener(listener)); + } + + @Override + public void notify(org.apache.dubbo.common.URL url, org.apache.dubbo.registry.NotifyListener listener, List urls) { + super.notify(url, listener, urls); + } + + @Override + public void doNotify(org.apache.dubbo.common.URL url, org.apache.dubbo.registry.NotifyListener listener, List urls) { + super.doNotify(url, listener, urls); + } + + @Override + public boolean isAvailable() { + return false; + } + + @Override + public void recover() throws Exception { + super.recover(); + } + } + +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java index 8f8304cace9..903d4775301 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java @@ -206,23 +206,23 @@ private void removeFailedNotified(URL url, NotifyListener listener) { } } - public ConcurrentMap getFailedRegistered() { + ConcurrentMap getFailedRegistered() { return failedRegistered; } - public ConcurrentMap getFailedUnregistered() { + ConcurrentMap getFailedUnregistered() { return failedUnregistered; } - public ConcurrentMap getFailedSubscribed() { + ConcurrentMap getFailedSubscribed() { return failedSubscribed; } - public ConcurrentMap getFailedUnsubscribed() { + ConcurrentMap getFailedUnsubscribed() { return failedUnsubscribed; } - public ConcurrentMap getFailedNotified() { + ConcurrentMap getFailedNotified() { return failedNotified; } From 13f32380f85778826a3deef93a517bf781f126cb Mon Sep 17 00:00:00 2001 From: myPrecious Date: Sat, 18 May 2019 09:05:41 +0800 Subject: [PATCH 069/115] Add comment for disabled Nacos test, fix this later (#4088) --- .../support/nacos/NacosDynamicConfigurationTest.java | 3 ++- .../dubbo/metadata/store/nacos/NacosMetadataReportTest.java | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java index 53758a9e288..ea9ac24a522 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java @@ -36,7 +36,8 @@ /** * Unit test for nacos config center support */ -@Disabled +//FIXME: waiting for embedded Nacos suport, then we can open the switch. +@Disabled("https://github.com/alibaba/nacos/issues/1188") public class NacosDynamicConfigurationTest { private static NacosDynamicConfiguration config; diff --git a/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java b/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java index 6e46bd7417f..6f48dbd1ad0 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java +++ b/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java @@ -37,7 +37,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.common.constants.RegistryConstants.SESSION_TIMEOUT_KEY; -@Disabled +//FIXME: waiting for embedded Nacos suport, then we can open the switch. +@Disabled("https://github.com/alibaba/nacos/issues/1188") public class NacosMetadataReportTest { private static final String TEST_SERVICE = "org.apache.dubbo.metadata.store.nacos.NacosMetadata4TstService"; private NacosMetadataReport nacosMetadataReport; From 23903ba32aa3dd4878263e93e3267cfc8a7e0f26 Mon Sep 17 00:00:00 2001 From: "ken.lj" Date: Mon, 20 May 2019 09:59:30 +0800 Subject: [PATCH 070/115] [Dubbo-3266] Change DynamicConfiguration definition to better adapt to Apollo's namespace storage model. (#3271) --- .../dubbo/config/AbstractInterfaceConfig.java | 4 +- .../dubbo/config/ConfigCenterConfig.java | 51 ++++++++++++------- .../config/builders/ConfigCenterBuilder.java | 6 --- .../dubbo/config/AbstractConfigTest.java | 20 ++++++++ .../builders/ConfigCenterBuilderTest.java | 10 +--- .../dubbo/config/spring/ConfigCenterBean.java | 39 ++------------ .../main/resources/META-INF/compat/dubbo.xsd | 9 ++-- .../src/main/resources/META-INF/dubbo.xsd | 9 ++-- .../configcenter/DynamicConfiguration.java | 29 +++++++++-- .../support/nop/NopDynamicConfiguration.java | 5 ++ .../mock/MockDynamicConfiguration.java | 5 ++ .../apollo/ApolloDynamicConfiguration.java | 32 ++++++++++-- .../consul/ConsulDynamicConfiguration.java | 5 ++ .../etcd/EtcdDynamicConfiguration.java | 5 ++ .../nacos/NacosDynamicConfiguration.java | 5 ++ .../ZookeeperDynamicConfiguration.java | 14 +++++ .../ZookeeperDynamicConfigurationTest.java | 2 +- 17 files changed, 165 insertions(+), 85 deletions(-) diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java index 143d085f088..cc39451f231 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java @@ -287,12 +287,12 @@ private void prepareEnvironment() { return; } DynamicConfiguration dynamicConfiguration = getDynamicConfiguration(configCenter.toUrl()); - String configContent = dynamicConfiguration.getConfig(configCenter.getConfigFile(), configCenter.getGroup()); + String configContent = dynamicConfiguration.getConfigs(configCenter.getConfigFile(), configCenter.getGroup()); String appGroup = application != null ? application.getName() : null; String appConfigContent = null; if (StringUtils.isNotEmpty(appGroup)) { - appConfigContent = dynamicConfiguration.getConfig + appConfigContent = dynamicConfiguration.getConfigs (StringUtils.isNotEmpty(configCenter.getAppConfigFile()) ? configCenter.getAppConfigFile() : configCenter.getConfigFile(), appGroup ); diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java index d65f2e2018d..ed511fd65d9 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.Environment; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.utils.UrlUtils; import org.apache.dubbo.config.support.Parameter; @@ -28,15 +29,14 @@ import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; -import static org.apache.dubbo.config.Constants.CONFIG_APPNAME_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_CHECK_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_CLUSTER_KEY; -import static org.apache.dubbo.config.Constants.CONFIG_CONFIGFILE_KEY; -import static org.apache.dubbo.config.Constants.CONFIG_ENABLE_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_GROUP_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_NAMESPACE_KEY; -import static org.apache.dubbo.config.Constants.CONFIG_TIMEOUT_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.ZOOKEEPER_PROTOCOL; +import static org.apache.dubbo.config.Constants.CONFIG_CONFIGFILE_KEY; +import static org.apache.dubbo.config.Constants.CONFIG_ENABLE_KEY; +import static org.apache.dubbo.config.Constants.CONFIG_TIMEOUT_KEY; /** * ConfigCenterConfig @@ -46,20 +46,44 @@ public class ConfigCenterConfig extends AbstractConfig { private String protocol; private String address; + + /* The config center cluster, it's real meaning may very on different Config Center products. */ private String cluster; - private String namespace = "dubbo"; - private String group = "dubbo"; + + /* The namespace of the config center, generally it's used for multi-tenant, + but it's real meaning depends on the actual Config Center you use. + */ + + private String namespace = CommonConstants.DUBBO; + /* The group of the config center, generally it's used to identify an isolated space for a batch of config items, + but it's real meaning depends on the actual Config Center you use. + */ + private String group = CommonConstants.DUBBO; private String username; private String password; private Long timeout = 3000L; + + // If the Config Center is given the highest priority, it will override all the other configurations private Boolean highestPriority = true; + + // Decide the behaviour when initial connection try fails, 'true' means interrupt the whole process once fail. private Boolean check = true; - private String appName; - private String configFile = "dubbo.properties"; + /* Used to specify the key that your properties file mapping to, most of the time you do not need to change this parameter. + Notice that for Apollo, this parameter is meaningless, set the 'namespace' is enough. + */ + private String configFile = CommonConstants.DEFAULT_DUBBO_PROPERTIES; + + /* the .properties file under 'configFile' is global shared while .properties under this one is limited only to this application + */ private String appConfigFile; - // customized parameters + /* If the Config Center product you use have some special parameters that is not covered by this class, you can add it to here. + For example, with XML: + + + + */ private Map parameters; public ConfigCenterConfig() { @@ -195,15 +219,6 @@ public void setAppConfigFile(String appConfigFile) { this.appConfigFile = appConfigFile; } - @Parameter(key = CONFIG_APPNAME_KEY, useKeyAsProperty = false) - public String getAppName() { - return appName; - } - - public void setAppName(String appName) { - this.appName = appName; - } - public Map getParameters() { return parameters; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ConfigCenterBuilder.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ConfigCenterBuilder.java index 44110e1797d..87ac00f2906 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ConfigCenterBuilder.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ConfigCenterBuilder.java @@ -94,11 +94,6 @@ public ConfigCenterBuilder check(Boolean check) { return getThis(); } - public ConfigCenterBuilder appName(String appName) { - this.appName = appName; - return getThis(); - } - public ConfigCenterBuilder configFile(String configFile) { this.configFile = configFile; return getThis(); @@ -133,7 +128,6 @@ public ConfigCenterConfig build() { configCenter.setTimeout(timeout); configCenter.setHighestPriority(highestPriority); configCenter.setCheck(check); - configCenter.setAppName(appName); configCenter.setConfigFile(configFile); configCenter.setAppConfigFile(appConfigFile); configCenter.setParameters(parameters); diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractConfigTest.java index 10cac653e99..9c57b32269e 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractConfigTest.java @@ -467,6 +467,26 @@ public void tetMetaData() { Assertions.assertNull(metaData.get("key2")); } + @Test + public void testEquals() { + ApplicationConfig application1 = new ApplicationConfig(); + ApplicationConfig application2 = new ApplicationConfig(); + application1.setName("app1"); + application2.setName("app2"); + Assertions.assertNotEquals(application1, application2); + application1.setName("sameName"); + application2.setName("sameName"); + Assertions.assertEquals(application1, application2); + + ProtocolConfig protocol1 = new ProtocolConfig(); + protocol1.setHost("127.0.0.1");// excluded + protocol1.setName("dubbo"); + ProtocolConfig protocol2 = new ProtocolConfig(); + protocol2.setHost("127.0.0.2");// excluded + protocol2.setName("dubbo"); + Assertions.assertEquals(protocol1, protocol2); + } + @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.ANNOTATION_TYPE}) public @interface ConfigField { diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/builders/ConfigCenterBuilderTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/builders/ConfigCenterBuilderTest.java index daf1fa817ee..1ab5accb046 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/builders/ConfigCenterBuilderTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/builders/ConfigCenterBuilderTest.java @@ -96,13 +96,6 @@ void check() { Assertions.assertTrue(builder.build().isCheck()); } - @Test - void appName() { - ConfigCenterBuilder builder = new ConfigCenterBuilder(); - builder.appName("appName"); - Assertions.assertEquals("appName", builder.build().getAppName()); - } - @Test void configFile() { ConfigCenterBuilder builder = new ConfigCenterBuilder(); @@ -146,7 +139,7 @@ void appendParameters() { @Test void build() { ConfigCenterBuilder builder = new ConfigCenterBuilder(); - builder.check(true).protocol("protocol").address("address").appConfigFile("appConfigFile").appName("appName") + builder.check(true).protocol("protocol").address("address").appConfigFile("appConfigFile") .cluster("cluster").configFile("configFile").group("group").highestPriority(false) .namespace("namespace").password("password").timeout(1000L).username("usernama") .appendParameter("default.num", "one").id("id").prefix("prefix"); @@ -160,7 +153,6 @@ void build() { Assertions.assertEquals("protocol", config.getProtocol()); Assertions.assertEquals("address", config.getAddress()); Assertions.assertEquals("appConfigFile", config.getAppConfigFile()); - Assertions.assertEquals("appName", config.getAppName()); Assertions.assertEquals("cluster", config.getCluster()); Assertions.assertEquals("configFile", config.getConfigFile()); Assertions.assertEquals("group", config.getGroup()); diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ConfigCenterBean.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ConfigCenterBean.java index 1ea2485c0d2..062c9da0feb 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ConfigCenterBean.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ConfigCenterBean.java @@ -18,13 +18,10 @@ import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ConfigCenterConfig; import org.apache.dubbo.config.spring.extension.SpringExtensionFactory; -import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.DisposableBean; -import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.EnvironmentAware; @@ -41,12 +38,11 @@ *

    * If use ConfigCenterConfig directly, you should make sure ConfigCenterConfig.init() is called before actually export/refer any Dubbo service. */ -public class ConfigCenterBean extends ConfigCenterConfig implements InitializingBean, ApplicationContextAware, DisposableBean, EnvironmentAware { +public class ConfigCenterBean extends ConfigCenterConfig implements ApplicationContextAware, DisposableBean, EnvironmentAware { private transient ApplicationContext applicationContext; private Boolean includeSpringEnv = false; - private ApplicationConfig application; @Override public void setApplicationContext(ApplicationContext applicationContext) { @@ -54,27 +50,6 @@ public void setApplicationContext(ApplicationContext applicationContext) { SpringExtensionFactory.addApplicationContext(applicationContext); } - @Override - public void afterPropertiesSet() throws Exception { - if (getApplication() == null) { - Map applicationConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ApplicationConfig.class, false, false); - if (applicationConfigMap != null && applicationConfigMap.size() > 0) { - ApplicationConfig applicationConfig = null; - for (ApplicationConfig config : applicationConfigMap.values()) { - if (config.isDefault() == null || config.isDefault()) { - if (applicationConfig != null) { - throw new IllegalStateException("Duplicate application configs: " + applicationConfig + " and " + config); - } - applicationConfig = config; - } - } - if (applicationConfig != null) { - setApplication(applicationConfig); - } - } - } - } - @Override public void destroy() throws Exception { @@ -83,8 +58,11 @@ public void destroy() throws Exception { @Override public void setEnvironment(Environment environment) { if (includeSpringEnv) { + // Get PropertySource mapped to 'dubbo.properties' in Spring Environment. Map externalProperties = getConfigurations(getConfigFile(), environment); - Map appExternalProperties = getConfigurations(StringUtils.isNotEmpty(getAppConfigFile()) ? getAppConfigFile() : (StringUtils.isEmpty(getAppName()) ? ("application." + getConfigFile()) : (getAppName() + "." + getConfigFile())), environment); + // Get PropertySource mapped to 'application.dubbo.properties' in Spring Environment. + Map appExternalProperties = getConfigurations(StringUtils.isNotEmpty(getAppConfigFile()) ? getAppConfigFile() : ("application." + getConfigFile()), environment); + // Refresh Dubbo Environment org.apache.dubbo.common.config.Environment.getInstance().setExternalConfigMap(externalProperties); org.apache.dubbo.common.config.Environment.getInstance().setAppExternalConfigMap(appExternalProperties); } @@ -130,11 +108,4 @@ public void setIncludeSpringEnv(Boolean includeSpringEnv) { this.includeSpringEnv = includeSpringEnv; } - public ApplicationConfig getApplication() { - return application; - } - - public void setApplication(ApplicationConfig application) { - this.application = application; - } } diff --git a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/compat/dubbo.xsd b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/compat/dubbo.xsd index 9e179ef287a..c12389f805e 100644 --- a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/compat/dubbo.xsd +++ b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/compat/dubbo.xsd @@ -650,18 +650,19 @@ - + - + - + - + + diff --git a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd index e517f0cb4f3..5cc621fc872 100644 --- a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd +++ b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd @@ -644,18 +644,19 @@ - + - + - + - + + diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/DynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/DynamicConfiguration.java index 620e8c24809..23fc0f5e8bd 100644 --- a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/DynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/DynamicConfiguration.java @@ -24,7 +24,14 @@ import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; /** - * Dynamic configuration + * Dynamic Configuration + *
    + * From the use scenario internally in framework, there're mainly three kinds of methods: + *

      + *
    • 1. getConfig, get governance rules or single config item from Config Center.
    • + *
    • 2. getConfigFile, get configuration file from Config Center at start up.
    • + *
    • 3. addListener/removeListener, add or remove listeners for governance rules or config items that need to watch.
    • + *
    */ public interface DynamicConfiguration extends Configuration { String DEFAULT_GROUP = "dubbo"; @@ -78,7 +85,7 @@ default void removeListener(String key, ConfigurationListener listener) { * @return target configuration mapped to the given key */ default String getConfig(String key) { - return getConfig(key, null, 0L); + return getConfig(key, null, -1L); } /** @@ -89,7 +96,7 @@ default String getConfig(String key) { * @return target configuration mapped to the given key and the given group */ default String getConfig(String key, String group) { - return getConfig(key, group, 0L); + return getConfig(key, group, -1L); } /** @@ -104,6 +111,22 @@ default String getConfig(String key, String group) { */ String getConfig(String key, String group, long timeout) throws IllegalStateException; + /** + * {@see #getConfig(String, String, long)} + * + * This method are mostly used to get a compound config file, such as a complete dubbo.properties file. + */ + default String getConfigs(String key, String group) throws IllegalStateException { + return getConfigs(key, group, -1L); + } + + /** + * {@see #getConfig(String, String, long)} + * + * This method are mostly used to get a compound config file, such as a complete dubbo.properties file. + */ + String getConfigs(String key, String group, long timeout) throws IllegalStateException; + /** * Find DynamicConfiguration instance * diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfiguration.java index baa6f16cd26..dbb91fdffee 100644 --- a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfiguration.java @@ -50,4 +50,9 @@ public void removeListener(String key, String group, ConfigurationListener liste public String getConfig(String key, String group, long timeout) throws IllegalStateException { return null; } + + @Override + public String getConfigs(String key, String group, long timeout) throws IllegalStateException { + return null; + } } diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/mock/MockDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/mock/MockDynamicConfiguration.java index ecc939f2451..05ce68b32d7 100644 --- a/dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/mock/MockDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/mock/MockDynamicConfiguration.java @@ -46,4 +46,9 @@ public void removeListener(String key, String group, ConfigurationListener liste public String getConfig(String key, String group, long timeout) throws IllegalStateException { return null; } + + @Override + public String getConfigs(String key, String group, long timeout) throws IllegalStateException { + return null; + } } diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java index b89477be751..120e025c9c4 100644 --- a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java @@ -27,7 +27,9 @@ import com.ctrip.framework.apollo.Config; import com.ctrip.framework.apollo.ConfigChangeListener; +import com.ctrip.framework.apollo.ConfigFile; import com.ctrip.framework.apollo.ConfigService; +import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; import com.ctrip.framework.apollo.enums.ConfigSourceType; import com.ctrip.framework.apollo.enums.PropertyChangeType; import com.ctrip.framework.apollo.model.ConfigChange; @@ -41,10 +43,10 @@ import java.util.stream.Collectors; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_CHECK_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_CLUSTER_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_GROUP_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_NAMESPACE_KEY; /** @@ -56,9 +58,11 @@ public class ApolloDynamicConfiguration implements DynamicConfiguration { private static final String APOLLO_ADDR_KEY = "apollo.meta"; private static final String APOLLO_CLUSTER_KEY = "apollo.cluster"; private static final String APOLLO_PROTOCOL_PREFIX = "http://"; + private static final String APOLLO_APPLICATION_KEY = "application"; private URL url; private Config dubboConfig; + private ConfigFile dubboConfigFile; private ConcurrentMap listeners = new ConcurrentHashMap<>(); ApolloDynamicConfiguration(URL url) { @@ -78,6 +82,7 @@ public class ApolloDynamicConfiguration implements DynamicConfiguration { } dubboConfig = ConfigService.getConfig(url.getParameter(CONFIG_NAMESPACE_KEY, DEFAULT_GROUP)); + dubboConfigFile = ConfigService.getConfigFile(url.getParameter(CONFIG_NAMESPACE_KEY, DEFAULT_GROUP), ConfigFileFormat.Properties); // Decide to fail or to continue when failed to connect to remote server. boolean check = url.getParameter(CONFIG_CHECK_KEY, true); if (dubboConfig.getSourceType() != ConfigSourceType.REMOTE) { @@ -136,13 +141,32 @@ public void removeListener(String key, String group, ConfigurationListener liste */ @Override public String getConfig(String key, String group, long timeout) throws IllegalStateException { - if (StringUtils.isNotEmpty(group) && !url.getParameter(CONFIG_GROUP_KEY, DEFAULT_GROUP).equals(group)) { - Config config = ConfigService.getAppConfig(); - return config.getProperty(key, null); + if (StringUtils.isNotEmpty(group)) { + if (group.equals(url.getParameter(APPLICATION_KEY))) { + return ConfigService.getAppConfig().getProperty(key, null); + } else { + return ConfigService.getConfig(group).getProperty(key, null); + } } return dubboConfig.getProperty(key, null); } + @Override + public String getConfigs(String key, String group, long timeout) throws IllegalStateException { + if(StringUtils.isEmpty(group)) { + return dubboConfigFile.getContent(); + } + if (group.equals(url.getParameter(APPLICATION_KEY))) { + return ConfigService.getConfigFile(APOLLO_APPLICATION_KEY, ConfigFileFormat.Properties).getContent(); + } + + ConfigFile configFile = ConfigService.getConfigFile(group, ConfigFileFormat.Properties); + if (configFile == null) { + throw new IllegalStateException("There is no namespace named " + group + " in Apollo."); + } + return configFile.getContent(); + } + /** * This method will be used by Configuration to get valid value at runtime. * The group is expected to be 'app level', which can be fetched from the 'config.appnamespace' in url if necessary. diff --git a/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfiguration.java index 6727ed42c2a..bdf337fc8b0 100644 --- a/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfiguration.java @@ -103,6 +103,11 @@ public String getConfig(String key, String group, long timeout) throws IllegalSt return (String) getInternalProperty(rootPath + PATH_SEPARATOR + key); } + @Override + public String getConfigs(String key, String group, long timeout) throws IllegalStateException { + return getConfig(key, group, timeout); + } + @Override public Object getInternalProperty(String key) { logger.info("get config from: " + key); diff --git a/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfiguration.java index 78f5242c3ed..2e373ed6d83 100644 --- a/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfiguration.java @@ -106,6 +106,11 @@ public String getConfig(String key, String group, long timeout) throws IllegalSt return (String) getInternalProperty(rootPath + PATH_SEPARATOR + key); } + @Override + public String getConfigs(String key, String group, long timeout) throws IllegalStateException { + return getConfig(key, group, timeout); + } + @Override public Object getInternalProperty(String key) { return etcdClient.getKVValue(key); diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java index afdc97f7ac3..5f9307ac6a8 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java @@ -201,6 +201,11 @@ public String getConfig(String key, String group, long timeout) throws IllegalSt return (String) getInternalProperty(rootPath + PROPERTIES_CHAR_SEPERATOR + key); } + @Override + public String getConfigs(String key, String group, long timeout) throws IllegalStateException { + return getConfig(key, group, timeout); + } + @Override public Object getInternalProperty(String key) { try { diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java index 2ee64263563..c912addbb0c 100644 --- a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java @@ -110,4 +110,18 @@ public String getConfig(String key, String group, long timeout) throws IllegalSt return (String) getInternalProperty(rootPath + "/" + key); } + + /** + * For zookeeper, {@link #getConfig(String, String, long)} and {@link #getConfigs(String, String, long)} have the same meaning. + * + * @param key + * @param group + * @param timeout + * @return + * @throws IllegalStateException + */ + @Override + public String getConfigs(String key, String group, long timeout) throws IllegalStateException { + return (String) getConfig(key, group, timeout); + } } diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/test/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/test/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationTest.java index 40f9f04a95a..64e0becc64f 100644 --- a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/test/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationTest.java +++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/test/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationTest.java @@ -87,7 +87,7 @@ private static void setData(String path, String data) throws Exception { @Test public void testGetConfig() throws Exception { Assertions.assertEquals("Never change value from configurators", configuration.getConfig("never.change.DemoService.configurators")); - Assertions.assertEquals("The content from dubbo.properties", configuration.getConfig("dubbo.properties", "dubbo")); + Assertions.assertEquals("The content from dubbo.properties", configuration.getConfigs("dubbo.properties", "dubbo")); } @Test From d0d1a65e16cee5f18fc181a349add143adeb57a8 Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Mon, 20 May 2019 13:49:33 +0800 Subject: [PATCH 071/115] [DUBBO-3137]: move more constants out of ConfigConstants (#4092) --- .../cluster/directory/AbstractDirectory.java | 2 +- .../support/AbstractClusterInvokerTest.java | 2 +- .../common/constants/ConfigConstants.java | 32 ------------------- .../common/constants/RegistryConstants.java | 9 ++++++ .../dubbo/config/AbstractInterfaceConfig.java | 4 +-- .../dubbo/config/AbstractReferenceConfig.java | 2 +- .../dubbo/config/ConfigCenterConfig.java | 10 +++--- .../org/apache/dubbo/config/Constants.java | 1 + .../apache/dubbo/config/ProtocolConfig.java | 2 +- .../apache/dubbo/config/ProviderConfig.java | 2 +- .../apache/dubbo/config/ReferenceConfig.java | 4 +-- .../apache/dubbo/config/RegistryConfig.java | 2 +- .../apache/dubbo/config/ServiceConfig.java | 8 ++--- .../dubbo/config/ServiceConfigTest.java | 2 +- .../config/url/InvokerSideConfigUrlTest.java | 2 +- .../apache/dubbo/configcenter/Constants.java | 24 ++++++++++++++ .../apollo/ApolloDynamicConfiguration.java | 6 ++-- .../consul/ConsulDynamicConfiguration.java | 2 +- .../etcd/EtcdDynamicConfiguration.java | 2 +- .../nacos/NacosDynamicConfiguration.java | 2 +- .../ZookeeperDynamicConfiguration.java | 2 +- .../AbstractMetadataReportFactory.java | 4 +-- .../org/apache/dubbo/registry/Constants.java | 22 +++++++++++++ .../integration/RegistryDirectory.java | 2 +- .../integration/RegistryProtocol.java | 6 ++-- .../support/AbstractRegistryFactory.java | 4 +-- .../registry/dubbo/DubboRegistryFactory.java | 6 ++-- .../registry/dubbo/RegistryDirectoryTest.java | 2 +- .../registry/dubbo/RegistryProtocolTest.java | 2 +- .../org/apache/dubbo/remoting/Constants.java | 1 + .../telnet/support/TelnetHandlerAdapter.java | 2 +- .../java/org/apache/dubbo/rpc/Constants.java | 8 +++++ .../rpc/protocol/dubbo/DubboProtocol.java | 2 +- .../protocol/dubbo/DubboLazyConnectTest.java | 2 +- .../rpc/protocol/injvm/InjvmProtocol.java | 6 ++-- .../rpc/protocol/injvm/InjvmProtocolTest.java | 6 ++-- 36 files changed, 115 insertions(+), 82 deletions(-) create mode 100644 dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/Constants.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Constants.java diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java index 71089fc0eaf..b25c5980c24 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java @@ -31,7 +31,7 @@ import java.util.List; import java.util.Map; -import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.REFER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java index ca47ba8ab9a..c31038d238e 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java @@ -49,7 +49,7 @@ import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_AVAILABLE_CHECK_KEY; import static org.apache.dubbo.rpc.cluster.Constants.INVOCATION_NEED_MOCK; -import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.REFER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ConfigConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ConfigConstants.java index 44deb2c8041..44ba466e580 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ConfigConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ConfigConstants.java @@ -23,11 +23,6 @@ public interface ConfigConstants { String CLUSTER_KEY = "cluster"; - String CONFIG_CLUSTER_KEY = "config.cluster"; - String CONFIG_NAMESPACE_KEY = "config.namespace"; - String CONFIG_GROUP_KEY = "config.group"; - String CONFIG_CHECK_KEY = "config.check"; - String USERNAME_KEY = "username"; String PASSWORD_KEY = "password"; @@ -36,42 +31,15 @@ public interface ConfigConstants { String PORT_KEY = "port"; - String REGISTER_IP_KEY = "register.ip"; - String DUBBO_IP_TO_BIND = "DUBBO_IP_TO_BIND"; - String SCOPE_KEY = "scope"; - - String SCOPE_LOCAL = "local"; - - String SCOPE_REMOTE = "remote"; - @Deprecated String SHUTDOWN_WAIT_SECONDS_KEY = "dubbo.service.shutdown.wait.seconds"; String SHUTDOWN_WAIT_KEY = "dubbo.service.shutdown.wait"; - /** - * The key name for export URL in register center - */ - String EXPORT_KEY = "export"; - - /** - * The key name for reference URL in register center - */ - String REFER_KEY = "refer"; - - /** - * To decide whether to make connection when the client is created - */ - String LAZY_CONNECT_KEY = "lazy"; - String DUBBO_PROTOCOL = "dubbo"; - String ZOOKEEPER_PROTOCOL = "zookeeper"; - - String TELNET = "telnet"; - String QOS_ENABLE = "qos.enable"; String QOS_PORT = "qos.port"; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java index d04856f81a1..ff5c2126908 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java @@ -133,4 +133,13 @@ public interface RegistryConstants { * key for router type, for e.g., "script"/"file", corresponding to ScriptRouterFactory.NAME, FileRouterFactory.NAME */ String ROUTER_KEY = "router"; + + /** + * The key name for export URL in register center + */ + String EXPORT_KEY = "export"; + /** + * The key name for reference URL in register center + */ + String REFER_KEY = "refer"; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java index cc39451f231..d708b1f0d5a 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java @@ -69,8 +69,8 @@ import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; import static org.apache.dubbo.config.Constants.LAYER_KEY; import static org.apache.dubbo.config.Constants.LISTENER_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.REGISTER_IP_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.REFER_KEY; +import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY; import static org.apache.dubbo.config.Constants.REGISTRIES_SUFFIX; import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_SECONDS_KEY; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java index 4b9f7694913..545c2bc26ea 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java @@ -24,7 +24,7 @@ import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_STICKY_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.LAZY_CONNECT_KEY; +import static org.apache.dubbo.rpc.Constants.LAZY_CONNECT_KEY; import static org.apache.dubbo.rpc.Constants.INVOKER_LISTENER_KEY; import static org.apache.dubbo.rpc.Constants.REFERENCE_FILTER_KEY; import static org.apache.dubbo.rpc.Constants.STUB_EVENT_KEY; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java index ed511fd65d9..7caae5634ec 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java @@ -29,11 +29,11 @@ import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_CHECK_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_CLUSTER_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_GROUP_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_NAMESPACE_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.ZOOKEEPER_PROTOCOL; +import static org.apache.dubbo.configcenter.Constants.CONFIG_CHECK_KEY; +import static org.apache.dubbo.configcenter.Constants.CONFIG_CLUSTER_KEY; +import static org.apache.dubbo.configcenter.Constants.CONFIG_GROUP_KEY; +import static org.apache.dubbo.configcenter.Constants.CONFIG_NAMESPACE_KEY; +import static org.apache.dubbo.config.Constants.ZOOKEEPER_PROTOCOL; import static org.apache.dubbo.config.Constants.CONFIG_CONFIGFILE_KEY; import static org.apache.dubbo.config.Constants.CONFIG_ENABLE_KEY; import static org.apache.dubbo.config.Constants.CONFIG_TIMEOUT_KEY; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/Constants.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/Constants.java index 3842e01dd16..09a9f024166 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/Constants.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/Constants.java @@ -113,4 +113,5 @@ public interface Constants { String REGISTRIES_SUFFIX = "dubbo.registries."; + String ZOOKEEPER_PROTOCOL = "zookeeper"; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java index d957f1f1cda..265db331161 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java @@ -36,7 +36,7 @@ import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; import static org.apache.dubbo.common.constants.ConfigConstants.HOST_KEY; import static org.apache.dubbo.config.Constants.PROTOCOLS_SUFFIX; -import static org.apache.dubbo.common.constants.ConfigConstants.TELNET; +import static org.apache.dubbo.remoting.Constants.TELNET; import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; /** diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProviderConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProviderConfig.java index 3e75dfdd66c..2ac5131026e 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProviderConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProviderConfig.java @@ -31,7 +31,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; import static org.apache.dubbo.config.Constants.CONTEXTPATH_KEY; import static org.apache.dubbo.config.Constants.STATUS_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.TELNET; +import static org.apache.dubbo.remoting.Constants.TELNET; /** * The service provider default configuration diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java index 8ec800c75ca..45f24cf0657 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java @@ -67,8 +67,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.CLUSTER_KEY; import static org.apache.dubbo.config.Constants.DUBBO_IP_TO_REGISTRY; -import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.REGISTER_IP_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.REFER_KEY; +import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java index 90a7fd97043..291bbfdb0b4 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java @@ -28,7 +28,7 @@ import static org.apache.dubbo.config.Constants.REGISTRIES_SUFFIX; import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.USERNAME_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.ZOOKEEPER_PROTOCOL; +import static org.apache.dubbo.config.Constants.ZOOKEEPER_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.EXTRA_KEYS_KEY; /** diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index e70195d5407..d485be70246 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -75,13 +75,13 @@ import static org.apache.dubbo.config.Constants.DUBBO_IP_TO_REGISTRY; import static org.apache.dubbo.config.Constants.DUBBO_PORT_TO_BIND; import static org.apache.dubbo.config.Constants.DUBBO_PORT_TO_REGISTRY; -import static org.apache.dubbo.common.constants.ConfigConstants.EXPORT_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.EXPORT_KEY; import static org.apache.dubbo.config.Constants.MULTICAST; import static org.apache.dubbo.config.Constants.PROTOCOLS_SUFFIX; -import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_LOCAL; +import static org.apache.dubbo.rpc.Constants.SCOPE_KEY; +import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL; import static org.apache.dubbo.config.Constants.SCOPE_NONE; -import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_REMOTE; +import static org.apache.dubbo.rpc.Constants.SCOPE_REMOTE; import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java index e4361195e87..7c4b5b49024 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java @@ -47,7 +47,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.EXPORT_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.EXPORT_KEY; import static org.apache.dubbo.config.Constants.SHUTDOWN_TIMEOUT_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.remoting.Constants.BIND_IP_KEY; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/InvokerSideConfigUrlTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/InvokerSideConfigUrlTest.java index 3d8c1e645ec..3c027279cb7 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/InvokerSideConfigUrlTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/InvokerSideConfigUrlTest.java @@ -34,7 +34,7 @@ import java.util.Arrays; -import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_REMOTE; +import static org.apache.dubbo.rpc.Constants.SCOPE_REMOTE; public class InvokerSideConfigUrlTest extends UrlTestBase { diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/Constants.java b/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/Constants.java new file mode 100644 index 00000000000..fcf1a51fc56 --- /dev/null +++ b/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/Constants.java @@ -0,0 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.configcenter; + +public interface Constants { + String CONFIG_CLUSTER_KEY = "config.cluster"; + String CONFIG_NAMESPACE_KEY = "config.namespace"; + String CONFIG_GROUP_KEY = "config.group"; + String CONFIG_CHECK_KEY = "config.check"; +} diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java index 120e025c9c4..f67c1e03236 100644 --- a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java @@ -45,9 +45,9 @@ import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; -import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_CHECK_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_CLUSTER_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_NAMESPACE_KEY; +import static org.apache.dubbo.configcenter.Constants.CONFIG_CHECK_KEY; +import static org.apache.dubbo.configcenter.Constants.CONFIG_CLUSTER_KEY; +import static org.apache.dubbo.configcenter.Constants.CONFIG_NAMESPACE_KEY; /** * Apollo implementation, https://github.com/ctripcorp/apollo diff --git a/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfiguration.java index bdf337fc8b0..2e67bbd7c89 100644 --- a/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfiguration.java @@ -40,7 +40,7 @@ import static java.util.concurrent.Executors.newCachedThreadPool; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; -import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_NAMESPACE_KEY; +import static org.apache.dubbo.configcenter.Constants.CONFIG_NAMESPACE_KEY; import static org.apache.dubbo.configcenter.ConfigChangeType.ADDED; /** diff --git a/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfiguration.java index 2e373ed6d83..10c50b66dd0 100644 --- a/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfiguration.java @@ -41,7 +41,7 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; -import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_NAMESPACE_KEY; +import static org.apache.dubbo.configcenter.Constants.CONFIG_NAMESPACE_KEY; /** * The etcd implementation of {@link DynamicConfiguration} diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java index 5f9307ac6a8..96bec25f1dd 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java @@ -48,7 +48,7 @@ import static com.alibaba.nacos.client.naming.utils.UtilAndComs.NACOS_NAMING_LOG_NAME; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_CHAR_SEPERATOR; import static org.apache.dubbo.common.constants.CommonConstants.PROPERTIES_CHAR_SEPERATOR; -import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_NAMESPACE_KEY; +import static org.apache.dubbo.configcenter.Constants.CONFIG_NAMESPACE_KEY; import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; /** diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java index c912addbb0c..a06537b432c 100644 --- a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java @@ -31,7 +31,7 @@ import java.util.concurrent.Executor; import java.util.concurrent.Executors; -import static org.apache.dubbo.common.constants.ConfigConstants.CONFIG_NAMESPACE_KEY; +import static org.apache.dubbo.configcenter.Constants.CONFIG_NAMESPACE_KEY; /** * diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactory.java b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactory.java index 7ca49fcda93..37f761c4a87 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactory.java +++ b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactory.java @@ -24,8 +24,8 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; -import static org.apache.dubbo.common.constants.ConfigConstants.EXPORT_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.EXPORT_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.REFER_KEY; /** */ diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Constants.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Constants.java new file mode 100644 index 00000000000..c1bfb3fe43d --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Constants.java @@ -0,0 +1,22 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.registry; + +public interface Constants { + String REGISTER_IP_KEY = "register.ip"; +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java index a8f8c6e76d2..2ee10d72db9 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java @@ -67,7 +67,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; -import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.REFER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.APP_DYNAMIC_CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java index b0730c0f395..0c94708f6fb 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java @@ -69,11 +69,11 @@ import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.ACCEPT_FOREIGN_IP; import static org.apache.dubbo.common.constants.ConfigConstants.CLUSTER_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.EXPORT_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.EXPORT_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.QOS_ENABLE; import static org.apache.dubbo.common.constants.ConfigConstants.QOS_PORT; -import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.REGISTER_IP_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.REFER_KEY; +import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY; import static org.apache.dubbo.common.constants.FilterConstants.VALIDATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.java index 3837f2c0ff0..3b540c3b36b 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.java @@ -31,8 +31,8 @@ import java.util.concurrent.locks.ReentrantLock; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.EXPORT_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.EXPORT_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.REFER_KEY; /** * AbstractRegistryFactory. (SPI, Singleton, ThreadSafe) diff --git a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java index 72f8153289f..8f3d6827724 100644 --- a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java +++ b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java @@ -41,9 +41,9 @@ import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.EXPORT_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.LAZY_CONNECT_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.EXPORT_KEY; +import static org.apache.dubbo.rpc.Constants.LAZY_CONNECT_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.REFER_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; import static org.apache.dubbo.remoting.Constants.CONNECT_TIMEOUT_KEY; diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java index 8b93fd85c23..e04ca82cbd3 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java @@ -61,7 +61,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.DISABLED_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.REFER_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.REFER_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java index 2e5dfd23659..4aff5607de8 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java @@ -41,7 +41,7 @@ import java.util.ArrayList; import java.util.List; -import static org.apache.dubbo.common.constants.ConfigConstants.EXPORT_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.EXPORT_KEY; import static org.apache.dubbo.registry.integration.RegistryProtocol.DEFAULT_REGISTER_PROVIDER_KEYS; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Constants.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Constants.java index 663f4e0418c..592b0d5217d 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Constants.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Constants.java @@ -128,4 +128,5 @@ public interface Constants { String PROMPT_KEY = "prompt"; String DEFAULT_PROMPT = "dubbo>"; + String TELNET = "telnet"; } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java index 1575e450d8e..95eb57540e8 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java @@ -26,7 +26,7 @@ import org.apache.dubbo.remoting.transport.ChannelHandlerAdapter; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; -import static org.apache.dubbo.common.constants.ConfigConstants.TELNET; +import static org.apache.dubbo.remoting.Constants.TELNET; public class TelnetHandlerAdapter extends ChannelHandlerAdapter implements TelnetHandler { diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Constants.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Constants.java index 8a75ef7e2b1..67a2f03c2aa 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Constants.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Constants.java @@ -99,4 +99,12 @@ public interface Constants { String LOCAL_PROTOCOL = "injvm"; String DEFAULT_REMOTING_SERVER = "netty"; + + String SCOPE_KEY = "scope"; + String SCOPE_LOCAL = "local"; + String SCOPE_REMOTE = "remote"; + /** + * To decide whether to make connection when the client is created + */ + String LAZY_CONNECT_KEY = "lazy"; } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java index e3c945b873f..f1a627d8c7a 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java @@ -62,7 +62,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.LAZY_CONNECT_KEY; +import static org.apache.dubbo.rpc.Constants.LAZY_CONNECT_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.ON_CONNECT_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.ON_DISCONNECT_KEY; import static org.apache.dubbo.common.constants.RemotingConstants.DEFAULT_HEARTBEAT; diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboLazyConnectTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboLazyConnectTest.java index b539a7fa9ef..99b10249c43 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboLazyConnectTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboLazyConnectTest.java @@ -28,7 +28,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.apache.dubbo.common.constants.ConfigConstants.LAZY_CONNECT_KEY; +import static org.apache.dubbo.rpc.Constants.LAZY_CONNECT_KEY; /** * dubbo protocol lazy connect test diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java b/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java index 96f5902e48f..cc273aafbe3 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java @@ -29,9 +29,9 @@ import java.util.Map; -import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_LOCAL; -import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_REMOTE; +import static org.apache.dubbo.rpc.Constants.SCOPE_KEY; +import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL; +import static org.apache.dubbo.rpc.Constants.SCOPE_REMOTE; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL; diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocolTest.java b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocolTest.java index 283d33c65e8..df5bb559a2a 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocolTest.java @@ -34,9 +34,9 @@ import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_LOCAL; -import static org.apache.dubbo.common.constants.ConfigConstants.SCOPE_REMOTE; +import static org.apache.dubbo.rpc.Constants.SCOPE_KEY; +import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL; +import static org.apache.dubbo.rpc.Constants.SCOPE_REMOTE; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL; import static org.junit.jupiter.api.Assertions.assertEquals; From fcef1a18418969df75a53f5df429b251a1a5d752 Mon Sep 17 00:00:00 2001 From: uglycow Date: Mon, 20 May 2019 16:40:15 +0800 Subject: [PATCH 072/115] update erlang link (#4100) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 440da311822..b7b9c8e9f52 100644 --- a/README.md +++ b/README.md @@ -223,7 +223,7 @@ Please report security vulnerability to [us](mailto:security@dubbo.incubator.apa * [Python](https://github.com/dubbo/dubbo-client-py) * [PHP](https://github.com/dubbo/dubbo-php-framework) * [Go](https://github.com/dubbo/dubbo-go) -* [Erlang](https://github.com/dubboerl/dubboerl) +* [Erlang](https://github.com/apache/incubator-dubbo-erlang) ## License From 956d28b11ecda2b4aa3c76481c95f06fc3833210 Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Tue, 21 May 2019 16:18:25 +0800 Subject: [PATCH 073/115] [DUBBO-3137]: move constants from RegistryConstants back to dubbo-registry-api (#4101) * [DUBBO-3137]: move constants from RegistryConstants back to dubbo-registry-api * fix imports --- .../apache/dubbo/rpc/cluster/Constants.java | 12 +++ .../cluster/directory/AbstractDirectory.java | 2 +- .../router/file/FileRouterFactory.java | 2 +- .../support/AbstractClusterInvokerTest.java | 2 +- .../common/constants/RegistryConstants.java | 90 ------------------- .../dubbo/config/AbstractInterfaceConfig.java | 6 +- .../apache/dubbo/config/ReferenceConfig.java | 4 +- .../apache/dubbo/config/RegistryConfig.java | 2 +- .../apache/dubbo/config/ServiceConfig.java | 2 +- .../dubbo/config/ServiceConfigTest.java | 2 +- .../etcd/EtcdDynamicConfigurationTest.java | 2 +- .../nacos/NacosDynamicConfigurationTest.java | 2 +- .../AbstractMetadataReportFactory.java | 7 +- .../store/nacos/NacosMetadataReportTest.java | 2 +- .../org/apache/dubbo/registry/Constants.java | 76 ++++++++++++++++ .../integration/RegistryDirectory.java | 6 +- .../integration/RegistryProtocol.java | 18 ++-- .../registry/retry/AbstractRetryTask.java | 8 +- .../registry/support/AbstractRegistry.java | 2 +- .../support/AbstractRegistryFactory.java | 4 +- .../registry/support/FailbackRegistry.java | 6 +- .../support/FailbackRegistryTest.java | 4 +- .../dubbo/registry/consul/ConsulRegistry.java | 4 +- .../dubbo/registry/dubbo/DubboRegistry.java | 2 +- .../registry/dubbo/DubboRegistryFactory.java | 6 +- .../registry/dubbo/RegistryDirectoryTest.java | 4 +- .../registry/dubbo/RegistryProtocolTest.java | 2 +- .../dubbo/registry/etcd/EtcdRegistry.java | 2 +- .../dubbo/registry/etcd/EtcdRegistryTest.java | 2 +- .../registry/multicast/MulticastRegistry.java | 16 ++-- .../dubbo/registry/nacos/NacosRegistry.java | 2 +- .../dubbo/registry/redis/RedisRegistry.java | 12 +-- .../dubbo/registry/sofa/SofaRegistry.java | 8 +- .../apache/dubbo/remoting/etcd/Constants.java | 24 +++++ .../remoting/etcd/jetcd/JEtcdClient.java | 8 +- .../etcd/jetcd/JEtcdClientWrapper.java | 21 ++--- .../dubbo/remoting/etcd/option/Constants.java | 32 ------- .../etcd/support/AbstractEtcdClient.java | 8 +- .../remoting/etcd/jetcd/JEtcdClientTest.java | 2 +- .../etcd/jetcd/JEtcdClientWrapperTest.java | 2 +- 40 files changed, 203 insertions(+), 215 deletions(-) delete mode 100644 dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/option/Constants.java diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Constants.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Constants.java index 8849c267145..9303a9a5a9d 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Constants.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Constants.java @@ -100,4 +100,16 @@ public interface Constants { String OVERRIDE_PROVIDERS_KEY = "providerAddresses"; String TAG_KEY = "dubbo.tag"; + /** + * key for router type, for e.g., "script"/"file", corresponding to ScriptRouterFactory.NAME, FileRouterFactory.NAME + */ + String ROUTER_KEY = "router"; + /** + * The key name for reference URL in register center + */ + String REFER_KEY = "refer"; + /** + * The key name for export URL in register center + */ + String EXPORT_KEY = "export"; } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java index b25c5980c24..4e304e954ea 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java @@ -31,7 +31,7 @@ import java.util.List; import java.util.Map; -import static org.apache.dubbo.common.constants.RegistryConstants.REFER_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterFactory.java index 13e929c6121..95d81009d7d 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterFactory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterFactory.java @@ -27,7 +27,7 @@ import java.io.FileReader; import java.io.IOException; -import static org.apache.dubbo.common.constants.RegistryConstants.ROUTER_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.ROUTER_KEY; import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY; import static org.apache.dubbo.rpc.cluster.Constants.RUNTIME_KEY; import static org.apache.dubbo.rpc.cluster.Constants.TYPE_KEY; diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java index c31038d238e..1ec574d022a 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java @@ -49,7 +49,7 @@ import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_AVAILABLE_CHECK_KEY; import static org.apache.dubbo.rpc.cluster.Constants.INVOCATION_NEED_MOCK; -import static org.apache.dubbo.common.constants.RegistryConstants.REFER_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java index ff5c2126908..647ac81c7b9 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java @@ -18,26 +18,13 @@ package org.apache.dubbo.common.constants; public interface RegistryConstants { - String REGISTER_KEY = "register"; - - String SUBSCRIBE_KEY = "subscribe"; String REGISTRY_KEY = "registry"; - String DEFAULT_REGISTRY = "dubbo"; - String REGISTRY_PROTOCOL = "registry"; String DYNAMIC_KEY = "dynamic"; - String REGISTER = "register"; - - String UNREGISTER = "unregister"; - - String SUBSCRIBE = "subscribe"; - - String UNSUBSCRIBE = "unsubscribe"; - String CATEGORY_KEY = "category"; String PROVIDERS_CATEGORY = "providers"; @@ -56,90 +43,13 @@ public interface RegistryConstants { String APP_DYNAMIC_CONFIGURATORS_CATEGORY = "appdynamicconfigurators"; - String CONFIGURATORS_SUFFIX = ".configurators"; - String ROUTERS_SUFFIX = ".routers"; - String TRACE_PROTOCOL = "trace"; - String EMPTY_PROTOCOL = "empty"; - String ADMIN_PROTOCOL = "admin"; - - String PROVIDER_PROTOCOL = "provider"; - - String CONSUMER_PROTOCOL = "consumer"; - String ROUTE_PROTOCOL = "route"; - String SCRIPT_PROTOCOL = "script"; - - String CONDITION_PROTOCOL = "condition"; - - /** - * simple the registry for provider. - * - * @since 2.7.0 - */ - String SIMPLIFIED_KEY = "simplified"; - - /** - * After simplify the registry, should add some paramter individually for provider. - * - * @since 2.7.0 - */ - String EXTRA_KEYS_KEY = "extra-keys"; - String OVERRIDE_PROTOCOL = "override"; String COMPATIBLE_CONFIG_KEY = "compatible_config"; - - /** - * To decide whether register center saves file synchronously, the default value is asynchronously - */ - String REGISTRY_FILESAVE_SYNC_KEY = "save.file"; - - /** - * Period of registry center's retry interval - */ - String REGISTRY_RETRY_PERIOD_KEY = "retry.period"; - - /** - * Most retry times - */ - String REGISTRY_RETRY_TIMES_KEY = "retry.times"; - - /** - * Default value for the period of retry interval in milliseconds: 5000 - */ - int DEFAULT_REGISTRY_RETRY_PERIOD = 5 * 1000; - - /** - * Default value for the times of retry: 3 - */ - int DEFAULT_REGISTRY_RETRY_TIMES = 3; - - /** - * Reconnection period in milliseconds for register center - */ - String REGISTRY_RECONNECT_PERIOD_KEY = "reconnect.period"; - - int DEFAULT_REGISTRY_RECONNECT_PERIOD = 3 * 1000; - - String SESSION_TIMEOUT_KEY = "session"; - - int DEFAULT_SESSION_TIMEOUT = 60 * 1000; - /** - * key for router type, for e.g., "script"/"file", corresponding to ScriptRouterFactory.NAME, FileRouterFactory.NAME - */ - String ROUTER_KEY = "router"; - - /** - * The key name for export URL in register center - */ - String EXPORT_KEY = "export"; - /** - * The key name for reference URL in register center - */ - String REFER_KEY = "refer"; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java index d708b1f0d5a..90577cd786d 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java @@ -69,16 +69,16 @@ import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; import static org.apache.dubbo.config.Constants.LAYER_KEY; import static org.apache.dubbo.config.Constants.LISTENER_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.REFER_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY; import static org.apache.dubbo.config.Constants.REGISTRIES_SUFFIX; import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_SECONDS_KEY; import static org.apache.dubbo.monitor.Constants.LOGSTAT_PROTOCOL; -import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_KEY; +import static org.apache.dubbo.registry.Constants.REGISTER_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; -import static org.apache.dubbo.common.constants.RegistryConstants.SUBSCRIBE_KEY; +import static org.apache.dubbo.registry.Constants.SUBSCRIBE_KEY; import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.rpc.Constants.INVOKER_LISTENER_KEY; import static org.apache.dubbo.rpc.Constants.LOCAL_KEY; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java index 45f24cf0657..3b8eb93add7 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java @@ -67,10 +67,10 @@ import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.CLUSTER_KEY; import static org.apache.dubbo.config.Constants.DUBBO_IP_TO_REGISTRY; -import static org.apache.dubbo.common.constants.RegistryConstants.REFER_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; +import static org.apache.dubbo.registry.Constants.CONSUMER_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL; import static org.apache.dubbo.common.utils.NetUtils.isInvalidLocalHost; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java index 291bbfdb0b4..94d0f2cbe9e 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java @@ -29,7 +29,7 @@ import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.USERNAME_KEY; import static org.apache.dubbo.config.Constants.ZOOKEEPER_PROTOCOL; -import static org.apache.dubbo.common.constants.RegistryConstants.EXTRA_KEYS_KEY; +import static org.apache.dubbo.registry.Constants.EXTRA_KEYS_KEY; /** * RegistryConfig diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index d485be70246..f95e15e0e55 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -75,7 +75,7 @@ import static org.apache.dubbo.config.Constants.DUBBO_IP_TO_REGISTRY; import static org.apache.dubbo.config.Constants.DUBBO_PORT_TO_BIND; import static org.apache.dubbo.config.Constants.DUBBO_PORT_TO_REGISTRY; -import static org.apache.dubbo.common.constants.RegistryConstants.EXPORT_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY; import static org.apache.dubbo.config.Constants.MULTICAST; import static org.apache.dubbo.config.Constants.PROTOCOLS_SUFFIX; import static org.apache.dubbo.rpc.Constants.SCOPE_KEY; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java index 7c4b5b49024..147648b67fb 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java @@ -47,7 +47,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.EXPORT_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY; import static org.apache.dubbo.config.Constants.SHUTDOWN_TIMEOUT_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.remoting.Constants.BIND_IP_KEY; diff --git a/dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java index 6e5a3dc3f96..d56f3c4649c 100644 --- a/dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java +++ b/dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java @@ -38,7 +38,7 @@ import java.util.concurrent.TimeUnit; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.apache.dubbo.common.constants.RegistryConstants.SESSION_TIMEOUT_KEY; +import static org.apache.dubbo.remoting.etcd.Constants.SESSION_TIMEOUT_KEY; /** * Unit test for etcd config center support diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java index ea9ac24a522..ff785b974a6 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java @@ -31,7 +31,6 @@ import java.util.Map; import java.util.concurrent.CountDownLatch; -import static org.apache.dubbo.common.constants.RegistryConstants.SESSION_TIMEOUT_KEY; /** * Unit test for nacos config center support @@ -39,6 +38,7 @@ //FIXME: waiting for embedded Nacos suport, then we can open the switch. @Disabled("https://github.com/alibaba/nacos/issues/1188") public class NacosDynamicConfigurationTest { + private static final String SESSION_TIMEOUT_KEY = "session"; private static NacosDynamicConfiguration config; diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactory.java b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactory.java index 37f761c4a87..fd4895c584c 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactory.java +++ b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactory.java @@ -24,12 +24,9 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; -import static org.apache.dubbo.common.constants.RegistryConstants.EXPORT_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.REFER_KEY; - -/** - */ public abstract class AbstractMetadataReportFactory implements MetadataReportFactory { + private static final String EXPORT_KEY = "export"; + private static final String REFER_KEY = "refer"; // The lock for the acquisition process of the registry private static final ReentrantLock LOCK = new ReentrantLock(); diff --git a/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java b/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java index 6f48dbd1ad0..07d6f8b839a 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java +++ b/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java @@ -35,11 +35,11 @@ import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; -import static org.apache.dubbo.common.constants.RegistryConstants.SESSION_TIMEOUT_KEY; //FIXME: waiting for embedded Nacos suport, then we can open the switch. @Disabled("https://github.com/alibaba/nacos/issues/1188") public class NacosMetadataReportTest { + private static final String SESSION_TIMEOUT_KEY = "session"; private static final String TEST_SERVICE = "org.apache.dubbo.metadata.store.nacos.NacosMetadata4TstService"; private NacosMetadataReport nacosMetadataReport; private NacosMetadataReportFactory nacosMetadataReportFactory; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Constants.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Constants.java index c1bfb3fe43d..dbfec2e0ab1 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Constants.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Constants.java @@ -19,4 +19,80 @@ public interface Constants { String REGISTER_IP_KEY = "register.ip"; + + String REGISTER_KEY = "register"; + + String SUBSCRIBE_KEY = "subscribe"; + + String DEFAULT_REGISTRY = "dubbo"; + + String REGISTER = "register"; + + String UNREGISTER = "unregister"; + + String SUBSCRIBE = "subscribe"; + + String UNSUBSCRIBE = "unsubscribe"; + + String CONFIGURATORS_SUFFIX = ".configurators"; + + String ADMIN_PROTOCOL = "admin"; + + String PROVIDER_PROTOCOL = "provider"; + + String CONSUMER_PROTOCOL = "consumer"; + + String SCRIPT_PROTOCOL = "script"; + + String CONDITION_PROTOCOL = "condition"; + String TRACE_PROTOCOL = "trace"; + /** + * simple the registry for provider. + * + * @since 2.7.0 + */ + String SIMPLIFIED_KEY = "simplified"; + + /** + * After simplify the registry, should add some paramter individually for provider. + * + * @since 2.7.0 + */ + String EXTRA_KEYS_KEY = "extra-keys"; + + /** + * To decide whether register center saves file synchronously, the default value is asynchronously + */ + String REGISTRY_FILESAVE_SYNC_KEY = "save.file"; + + /** + * Reconnection period in milliseconds for register center + */ + String REGISTRY_RECONNECT_PERIOD_KEY = "reconnect.period"; + + int DEFAULT_SESSION_TIMEOUT = 60 * 1000; + + /** + * Default value for the times of retry: 3 + */ + int DEFAULT_REGISTRY_RETRY_TIMES = 3; + + int DEFAULT_REGISTRY_RECONNECT_PERIOD = 3 * 1000; + + /** + * Default value for the period of retry interval in milliseconds: 5000 + */ + int DEFAULT_REGISTRY_RETRY_PERIOD = 5 * 1000; + + /** + * Most retry times + */ + String REGISTRY_RETRY_TIMES_KEY = "retry.times"; + + /** + * Period of registry center's retry interval + */ + String REGISTRY_RETRY_PERIOD_KEY = "retry.period"; + + String SESSION_TIMEOUT_KEY = "session"; } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java index 2ee10d72db9..6dd235a885c 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java @@ -58,7 +58,7 @@ import java.util.Set; import java.util.stream.Collectors; -import static org.apache.dubbo.common.constants.RegistryConstants.ROUTER_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.ROUTER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DISABLED_KEY; @@ -67,13 +67,13 @@ import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; -import static org.apache.dubbo.common.constants.RegistryConstants.REFER_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.APP_DYNAMIC_CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.COMPATIBLE_CONFIG_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; -import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_SUFFIX; +import static org.apache.dubbo.registry.Constants.CONFIGURATORS_SUFFIX; import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java index 0c94708f6fb..f55fad4558b 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java @@ -69,28 +69,28 @@ import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.ACCEPT_FOREIGN_IP; import static org.apache.dubbo.common.constants.ConfigConstants.CLUSTER_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.EXPORT_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.QOS_ENABLE; import static org.apache.dubbo.common.constants.ConfigConstants.QOS_PORT; -import static org.apache.dubbo.common.constants.RegistryConstants.REFER_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY; import static org.apache.dubbo.common.constants.FilterConstants.VALIDATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; -import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_SUFFIX; +import static org.apache.dubbo.registry.Constants.CONFIGURATORS_SUFFIX; import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY; -import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; -import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTRY; -import static org.apache.dubbo.common.constants.RegistryConstants.EXTRA_KEYS_KEY; +import static org.apache.dubbo.registry.Constants.CONSUMER_PROTOCOL; +import static org.apache.dubbo.registry.Constants.DEFAULT_REGISTRY; +import static org.apache.dubbo.registry.Constants.EXTRA_KEYS_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.OVERRIDE_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; -import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDER_PROTOCOL; -import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_KEY; +import static org.apache.dubbo.registry.Constants.PROVIDER_PROTOCOL; +import static org.apache.dubbo.registry.Constants.REGISTER_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; -import static org.apache.dubbo.common.constants.RegistryConstants.SIMPLIFIED_KEY; +import static org.apache.dubbo.registry.Constants.SIMPLIFIED_KEY; import static org.apache.dubbo.remoting.Constants.BIND_IP_KEY; import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY; import static org.apache.dubbo.remoting.Constants.CHECK_KEY; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/AbstractRetryTask.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/AbstractRetryTask.java index f367d17873d..4c1f75e1e57 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/AbstractRetryTask.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/AbstractRetryTask.java @@ -28,10 +28,10 @@ import java.util.concurrent.TimeUnit; -import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTRY_RETRY_PERIOD; -import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTRY_RETRY_TIMES; -import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_RETRY_PERIOD_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_RETRY_TIMES_KEY; +import static org.apache.dubbo.registry.Constants.DEFAULT_REGISTRY_RETRY_PERIOD; +import static org.apache.dubbo.registry.Constants.DEFAULT_REGISTRY_RETRY_TIMES; +import static org.apache.dubbo.registry.Constants.REGISTRY_RETRY_PERIOD_KEY; +import static org.apache.dubbo.registry.Constants.REGISTRY_RETRY_TIMES_KEY; /** * AbstractRetryTask diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.java index 27a6b1a6c70..aec82d5e854 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.java @@ -58,7 +58,7 @@ import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; -import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_FILESAVE_SYNC_KEY; +import static org.apache.dubbo.registry.Constants.REGISTRY_FILESAVE_SYNC_KEY; /** * AbstractRegistry. (SPI, Prototype, ThreadSafe) diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.java index 3b540c3b36b..06915098da1 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.java @@ -31,8 +31,8 @@ import java.util.concurrent.locks.ReentrantLock; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.EXPORT_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.REFER_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; /** * AbstractRegistryFactory. (SPI, Singleton, ThreadSafe) diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java index 903d4775301..f4c21b7b201 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java @@ -38,9 +38,9 @@ import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.FILE_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; -import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTRY_RETRY_PERIOD; -import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_RETRY_PERIOD_KEY; +import static org.apache.dubbo.registry.Constants.CONSUMER_PROTOCOL; +import static org.apache.dubbo.registry.Constants.DEFAULT_REGISTRY_RETRY_PERIOD; +import static org.apache.dubbo.registry.Constants.REGISTRY_RETRY_PERIOD_KEY; /** * FailbackRegistry. (SPI, Prototype, ThreadSafe) diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/FailbackRegistryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/FailbackRegistryTest.java index e6ceb6b2c5c..3e4843328a6 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/FailbackRegistryTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/FailbackRegistryTest.java @@ -30,8 +30,8 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; -import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; -import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_RETRY_PERIOD_KEY; +import static org.apache.dubbo.registry.Constants.CONSUMER_PROTOCOL; +import static org.apache.dubbo.registry.Constants.REGISTRY_RETRY_PERIOD_KEY; import static org.junit.jupiter.api.Assertions.assertEquals; public class FailbackRegistryTest { diff --git a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java b/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java index e79dac7a2a4..e7cf986cc45 100644 --- a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java +++ b/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java @@ -49,8 +49,8 @@ import static java.util.concurrent.Executors.newCachedThreadPool; import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; -import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; -import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDER_PROTOCOL; +import static org.apache.dubbo.registry.Constants.CONSUMER_PROTOCOL; +import static org.apache.dubbo.registry.Constants.PROVIDER_PROTOCOL; /** * registry center implementation for consul diff --git a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistry.java b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistry.java index d6a5d69f9ca..ef9238ee04e 100644 --- a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistry.java +++ b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistry.java @@ -36,7 +36,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; -import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_RECONNECT_PERIOD_KEY; +import static org.apache.dubbo.registry.Constants.REGISTRY_RECONNECT_PERIOD_KEY; /** * DubboRegistry diff --git a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java index 8f3d6827724..82a80a74ee2 100644 --- a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java +++ b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java @@ -41,10 +41,10 @@ import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.EXPORT_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY; import static org.apache.dubbo.rpc.Constants.LAZY_CONNECT_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.REFER_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; +import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; +import static org.apache.dubbo.registry.Constants.CONSUMER_PROTOCOL; import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; import static org.apache.dubbo.remoting.Constants.CONNECT_TIMEOUT_KEY; import static org.apache.dubbo.remoting.Constants.RECONNECT_KEY; diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java index e04ca82cbd3..6a2b4e6a2e8 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java @@ -52,7 +52,7 @@ import static org.apache.dubbo.rpc.cluster.Constants.INVOCATION_NEED_MOCK; import static org.apache.dubbo.rpc.cluster.Constants.LOADBALANCE_KEY; import static org.apache.dubbo.rpc.cluster.Constants.MOCK_PROTOCOL; -import static org.apache.dubbo.common.constants.RegistryConstants.ROUTER_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.ROUTER_KEY; import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY; import static org.apache.dubbo.rpc.cluster.Constants.TYPE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; @@ -61,7 +61,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.DISABLED_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.REFER_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java index 4aff5607de8..ee4e043fd95 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java @@ -41,7 +41,7 @@ import java.util.ArrayList; import java.util.List; -import static org.apache.dubbo.common.constants.RegistryConstants.EXPORT_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY; import static org.apache.dubbo.registry.integration.RegistryProtocol.DEFAULT_REGISTER_PROVIDER_KEYS; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistry.java b/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistry.java index cffc58e6c0f..44a347c73db 100644 --- a/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistry.java +++ b/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistry.java @@ -41,10 +41,10 @@ import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.support.FailbackRegistry; import org.apache.dubbo.remoting.etcd.ChildListener; +import org.apache.dubbo.remoting.etcd.Constants; import org.apache.dubbo.remoting.etcd.EtcdClient; import org.apache.dubbo.remoting.etcd.EtcdTransporter; import org.apache.dubbo.remoting.etcd.StateListener; -import org.apache.dubbo.remoting.etcd.option.Constants; import org.apache.dubbo.remoting.etcd.option.OptionUtil; import org.apache.dubbo.rpc.RpcException; diff --git a/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java b/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java index 859cfd04c2e..15427903b81 100644 --- a/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java +++ b/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java @@ -79,7 +79,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.ADMIN_PROTOCOL; +import static org.apache.dubbo.registry.Constants.ADMIN_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY; diff --git a/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java b/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java index 3f4eb269bc6..27aded1dea4 100644 --- a/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java +++ b/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java @@ -51,18 +51,18 @@ import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; -import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_SESSION_TIMEOUT; +import static org.apache.dubbo.registry.Constants.CONSUMER_PROTOCOL; +import static org.apache.dubbo.registry.Constants.DEFAULT_SESSION_TIMEOUT; import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.OVERRIDE_PROTOCOL; -import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER; -import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_KEY; +import static org.apache.dubbo.registry.Constants.REGISTER; +import static org.apache.dubbo.registry.Constants.REGISTER_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.ROUTE_PROTOCOL; -import static org.apache.dubbo.common.constants.RegistryConstants.SESSION_TIMEOUT_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.SUBSCRIBE; -import static org.apache.dubbo.common.constants.RegistryConstants.UNREGISTER; -import static org.apache.dubbo.common.constants.RegistryConstants.UNSUBSCRIBE; +import static org.apache.dubbo.registry.Constants.SESSION_TIMEOUT_KEY; +import static org.apache.dubbo.registry.Constants.SUBSCRIBE; +import static org.apache.dubbo.registry.Constants.UNREGISTER; +import static org.apache.dubbo.registry.Constants.UNSUBSCRIBE; /** * MulticastRegistry diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java index 1af3ec2059c..ff53d64421e 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java @@ -52,7 +52,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.ADMIN_PROTOCOL; +import static org.apache.dubbo.registry.Constants.ADMIN_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY; diff --git a/dubbo-registry/dubbo-registry-redis/src/main/java/org/apache/dubbo/registry/redis/RedisRegistry.java b/dubbo-registry/dubbo-registry-redis/src/main/java/org/apache/dubbo/registry/redis/RedisRegistry.java index 50a542fac3a..dc5d5a14c78 100644 --- a/dubbo-registry/dubbo-registry-redis/src/main/java/org/apache/dubbo/registry/redis/RedisRegistry.java +++ b/dubbo-registry/dubbo-registry-redis/src/main/java/org/apache/dubbo/registry/redis/RedisRegistry.java @@ -63,14 +63,14 @@ import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; -import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTRY_RECONNECT_PERIOD; -import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_SESSION_TIMEOUT; +import static org.apache.dubbo.registry.Constants.DEFAULT_REGISTRY_RECONNECT_PERIOD; +import static org.apache.dubbo.registry.Constants.DEFAULT_SESSION_TIMEOUT; import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; -import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER; -import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_RECONNECT_PERIOD_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.SESSION_TIMEOUT_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.UNREGISTER; +import static org.apache.dubbo.registry.Constants.REGISTER; +import static org.apache.dubbo.registry.Constants.REGISTRY_RECONNECT_PERIOD_KEY; +import static org.apache.dubbo.registry.Constants.SESSION_TIMEOUT_KEY; +import static org.apache.dubbo.registry.Constants.UNREGISTER; /** * RedisRegistry diff --git a/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistry.java b/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistry.java index c708688e6a7..4c784b34b2f 100644 --- a/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistry.java +++ b/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistry.java @@ -46,10 +46,10 @@ import static org.apache.dubbo.common.constants.CommonConstants.DUBBO; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; -import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDER_PROTOCOL; -import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.SUBSCRIBE_KEY; +import static org.apache.dubbo.registry.Constants.CONSUMER_PROTOCOL; +import static org.apache.dubbo.registry.Constants.PROVIDER_PROTOCOL; +import static org.apache.dubbo.registry.Constants.REGISTER_KEY; +import static org.apache.dubbo.registry.Constants.SUBSCRIBE_KEY; import static org.apache.dubbo.registry.sofa.SofaRegistryConstants.ADDRESS_WAIT_TIME_KEY; import static org.apache.dubbo.registry.sofa.SofaRegistryConstants.DEFAULT_GROUP; import static org.apache.dubbo.registry.sofa.SofaRegistryConstants.LOCAL_DATA_CENTER; diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/Constants.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/Constants.java index b022678122e..3450bb5b36f 100644 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/Constants.java +++ b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/Constants.java @@ -27,5 +27,29 @@ public interface Constants { String DEFAULT_ETCD3_NOTIFY_QUEUES_KEY = "etcd3.notify.queues"; int DEFAULT_GRPC_QUEUES = 300_0000; + + String RETRY_PERIOD_KEY = "retry.period"; + + int DEFAULT_RETRY_PERIOD = 5 * 1000; + + int DEFAULT_SESSION_TIMEOUT = 60 * 1000; + + String HTTP_SUBFIX_KEY = "://"; + + String HTTP_KEY = "http://"; + + int DEFAULT_KEEPALIVE_TIMEOUT = DEFAULT_SESSION_TIMEOUT / 2; + + String SESSION_TIMEOUT_KEY = "session"; + + int DEFAULT_RECONNECT_PERIOD = 3 * 1000; + + String ROUTERS_CATEGORY = "routers"; + + String PROVIDERS_CATEGORY = "providers"; + + String CONSUMERS_CATEGORY = "consumers"; + + String CONFIGURATORS_CATEGORY = "configurators"; } diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java index 7e584cc1ed8..d0ec61969da 100644 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java +++ b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java @@ -60,13 +60,13 @@ import static java.util.stream.Collectors.toList; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; -import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTRY_RETRY_PERIOD; -import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_SESSION_TIMEOUT; -import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_RETRY_PERIOD_KEY; import static org.apache.dubbo.remoting.etcd.Constants.DEFAULT_ETCD3_NOTIFY_QUEUES_KEY; import static org.apache.dubbo.remoting.etcd.Constants.DEFAULT_ETCD3_NOTIFY_THREADS; import static org.apache.dubbo.remoting.etcd.Constants.DEFAULT_GRPC_QUEUES; +import static org.apache.dubbo.remoting.etcd.Constants.DEFAULT_RETRY_PERIOD; +import static org.apache.dubbo.remoting.etcd.Constants.DEFAULT_SESSION_TIMEOUT; import static org.apache.dubbo.remoting.etcd.Constants.ETCD3_NOTIFY_MAXTHREADS_KEYS; +import static org.apache.dubbo.remoting.etcd.Constants.RETRY_PERIOD_KEY; import static org.apache.dubbo.remoting.etcd.jetcd.JEtcdClientWrapper.UTF_8; /** @@ -93,7 +93,7 @@ public JEtcdClient(URL url) { JEtcdClient.this.stateChanged(StateListener.DISCONNECTED); } }); - delayPeriod = getUrl().getParameter(REGISTRY_RETRY_PERIOD_KEY, DEFAULT_REGISTRY_RETRY_PERIOD); + delayPeriod = getUrl().getParameter(RETRY_PERIOD_KEY, DEFAULT_RETRY_PERIOD); reconnectSchedule = Executors.newScheduledThreadPool(1, new NamedThreadFactory("etcd3-watch-auto-reconnect")); diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapper.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapper.java index 58e0443422d..7ef6777b131 100644 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapper.java +++ b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapper.java @@ -25,7 +25,6 @@ import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.etcd.RetryPolicy; import org.apache.dubbo.remoting.etcd.StateListener; -import org.apache.dubbo.remoting.etcd.option.Constants; import io.etcd.jetcd.ByteSequence; import io.etcd.jetcd.Client; @@ -68,11 +67,13 @@ import static java.util.stream.Collectors.toList; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; -import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTRY_RECONNECT_PERIOD; -import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTRY_RETRY_PERIOD; -import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_RETRY_PERIOD_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.SESSION_TIMEOUT_KEY; -import static org.apache.dubbo.remoting.etcd.option.Constants.DEFAULT_KEEPALIVE_TIMEOUT; +import static org.apache.dubbo.remoting.etcd.Constants.DEFAULT_KEEPALIVE_TIMEOUT; +import static org.apache.dubbo.remoting.etcd.Constants.DEFAULT_RECONNECT_PERIOD; +import static org.apache.dubbo.remoting.etcd.Constants.DEFAULT_RETRY_PERIOD; +import static org.apache.dubbo.remoting.etcd.Constants.HTTP_KEY; +import static org.apache.dubbo.remoting.etcd.Constants.HTTP_SUBFIX_KEY; +import static org.apache.dubbo.remoting.etcd.Constants.RETRY_PERIOD_KEY; +import static org.apache.dubbo.remoting.etcd.Constants.SESSION_TIMEOUT_KEY; public class JEtcdClientWrapper { @@ -127,7 +128,7 @@ public JEtcdClientWrapper(URL url) { this.retryPolicy = new RetryNTimes(1, 1000, TimeUnit.MILLISECONDS); this.failed = new IllegalStateException("Etcd3 registry is not connected yet, url:" + url); - int retryPeriod = url.getParameter(REGISTRY_RETRY_PERIOD_KEY, DEFAULT_REGISTRY_RETRY_PERIOD); + int retryPeriod = url.getParameter(RETRY_PERIOD_KEY, DEFAULT_RETRY_PERIOD); this.retryFuture = retryExecutor.scheduleWithFixedDelay(() -> { try { @@ -488,9 +489,9 @@ public void delete(String path) { public String[] endPoints(String backupAddress) { String[] endpoints = backupAddress.split(COMMA_SEPARATOR); List addresses = Arrays.stream(endpoints) - .map(address -> address.contains(Constants.HTTP_SUBFIX_KEY) + .map(address -> address.contains(HTTP_SUBFIX_KEY) ? address - : Constants.HTTP_KEY + address) + : HTTP_KEY + address) .collect(toList()); Collections.shuffle(addresses); return addresses.toArray(new String[0]); @@ -536,7 +537,7 @@ public void start() { } connectState = connected; } - }, DEFAULT_REGISTRY_RECONNECT_PERIOD, DEFAULT_REGISTRY_RECONNECT_PERIOD, TimeUnit.MILLISECONDS); + }, DEFAULT_RECONNECT_PERIOD, DEFAULT_RECONNECT_PERIOD, TimeUnit.MILLISECONDS); } catch (Throwable t) { logger.error("monitor reconnect status failed.", t); } diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/option/Constants.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/option/Constants.java deleted file mode 100644 index 50af9a6057f..00000000000 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/option/Constants.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.remoting.etcd.option; - -import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_SESSION_TIMEOUT; - -/** - * Etcd registry constants. - */ -public interface Constants { - - String HTTP_SUBFIX_KEY = "://"; - - String HTTP_KEY = "http://"; - - int DEFAULT_KEEPALIVE_TIMEOUT = DEFAULT_SESSION_TIMEOUT / 2; - -} diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/support/AbstractEtcdClient.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/support/AbstractEtcdClient.java index 1f764c60099..362b2689a6c 100644 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/support/AbstractEtcdClient.java +++ b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/support/AbstractEtcdClient.java @@ -49,10 +49,10 @@ import java.util.concurrent.ConcurrentMap; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; -import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; -import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY; -import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; -import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; +import static org.apache.dubbo.remoting.etcd.Constants.CONFIGURATORS_CATEGORY; +import static org.apache.dubbo.remoting.etcd.Constants.CONSUMERS_CATEGORY; +import static org.apache.dubbo.remoting.etcd.Constants.PROVIDERS_CATEGORY; +import static org.apache.dubbo.remoting.etcd.Constants.ROUTERS_CATEGORY; public abstract class AbstractEtcdClient implements EtcdClient { diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientTest.java b/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientTest.java index 743d3fe03e1..6dcf812987a 100644 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientTest.java +++ b/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientTest.java @@ -64,7 +64,7 @@ import java.util.concurrent.atomic.AtomicLong; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.apache.dubbo.common.constants.RegistryConstants.SESSION_TIMEOUT_KEY; +import static org.apache.dubbo.remoting.etcd.Constants.SESSION_TIMEOUT_KEY; @Disabled public class JEtcdClientTest { diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapperTest.java b/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapperTest.java index f76c362a6d5..337b6decea1 100644 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapperTest.java +++ b/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapperTest.java @@ -49,7 +49,7 @@ import java.util.concurrent.TimeoutException; import java.util.concurrent.locks.LockSupport; -import static org.apache.dubbo.common.constants.RegistryConstants.SESSION_TIMEOUT_KEY; +import static org.apache.dubbo.remoting.etcd.Constants.SESSION_TIMEOUT_KEY; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.spy; From 3fc69095cfa6d1acb604260f843627bc61abf6a3 Mon Sep 17 00:00:00 2001 From: Huang YunKun Date: Wed, 22 May 2019 10:57:19 +0800 Subject: [PATCH 074/115] Add dependencies check script (#3941) * add plugin to do dependencies check * remove third-party properties file * polish config * polish config * use missing info in bash --- .gitignore | 5 ++- licenseCheck.sh | 96 +++++++++++++++++++++++++++++++++++++++++++++++++ pom.xml | 35 ++++++++++++++++++ 3 files changed, 135 insertions(+), 1 deletion(-) create mode 100755 licenseCheck.sh diff --git a/.gitignore b/.gitignore index 0938f7891e2..89899353305 100644 --- a/.gitignore +++ b/.gitignore @@ -31,4 +31,7 @@ Thumbs.db *.orig # flatten ignore -.flattened-pom.xml \ No newline at end of file +.flattened-pom.xml + +# license check result +license-list.txt \ No newline at end of file diff --git a/licenseCheck.sh b/licenseCheck.sh new file mode 100755 index 00000000000..9992f10040e --- /dev/null +++ b/licenseCheck.sh @@ -0,0 +1,96 @@ +#!/bin/bash + +APPEND_ARG="" +FOLDER="./" +LINE_FLAG="==============================================" +TARGET_FILE="./license-list.txt" + +red=`tput setaf 1` +green=`tput setaf 2` +reset=`tput sgr0` + + +if [ -n "$1" ]; then + echo "checking module $1" + APPEND_ARG="-f $1" + FOLDER="$1" +else + echo "checking whole project" +fi + +echo "Running command: ./mvnw clean package -DskipTests=true -PlicenseCheck $APPEND_ARG" + +./mvnw clean package -DskipTests=true -PlicenseCheck $APPEND_ARG + +status=$? +if [ $status -eq 0 ]; then + echo "mvn command exec success" +else + echo "${red}mvn command exec fail${reset}" + exit 1 +fi + + +#contact and generate license file +rm -rf $TARGET_FILE +LICENSE_FILES=`find $FOLDER -type f -name "THIRD-PARTY.txt"|grep generated-sources` + +echo "Find license files:" +echo "$LICENSE_FILES" + +for i in $LICENSE_FILES + do + echo "$LINE_FLAG" >> $TARGET_FILE + echo $i >> $TARGET_FILE + cat $i >> $TARGET_FILE + done + +echo "license files generated at $TARGET_FILE" + +#fix missing license dependencies +missingLicense=( + "(Unknown license) jsr173_api:(Apache License, Version 2.0) jsr173_api" + "(Unknown license) \"Java Concurrency in Practice\" book annotations:(BEA licensed) \"Java Concurrency in Practice\" book annotations" + "(Unknown license) Java Portlet Specification V2.0:(Apache License, Version 2.0) Java Portlet Specification V2.0" +) + +for i in "${missingLicense[@]}"; do + search=`echo $i |awk -F: '{print $1}'` + replace=`echo $i |awk -F: '{print $2}'` + sed -i -e 's/'"$search"'/'"$replace"'/g' $TARGET_FILE +done + +check_unknown_license=`cat $TARGET_FILE | grep "Unknown license"` + +#checking unknown license +if grep -q "Unknown license" $TARGET_FILE +then + echo "${red}Find unknown license${reset}" + echo "$check_unknown_license" + exit 1 +fi + +allowLicense=( + "CDDL" + "Apache" + "Common Development and Distribution License" + "Eclipse Public License" + "MIT" + "The 3-Clause BSD License" + "Public domain" +) + +#filter allow license +license_need_check=`cat $TARGET_FILE | grep -v "generated-sources/license/THIRD-PARTY.txt" | grep -v "third-party dependencies" | grep -v $LINE_FLAG` + +for i in "${allowLicense[@]}"; do + license_need_check=`echo "$license_need_check"|grep -vi "$i"` +done + +if test -z "$license_need_check" +then + echo "${green}All dependencies license looks good${reset}" +else + echo "${red}Please check below license${reset}" + echo "$license_need_check" +fi \ No newline at end of file diff --git a/pom.xml b/pom.xml index a1f7b56820d..e9a1661e033 100644 --- a/pom.xml +++ b/pom.xml @@ -302,6 +302,41 @@ + + licenseCheck + + + + org.codehaus.mojo + license-maven-plugin + 1.20 + + + license-check + generate-sources + + add-third-party + + + false + false + false + + Apache License, Version 2.0|The Apache Software License, Version + 2.0|ASF 2.0|Apache 2|Apache-2.0|Apache 2.0 License|Apache 2.0|Apache License v2.0|Apache License 2.0|The Apache License, Version 2.0|The Apache Software License, Version 2.0 + + The MIT License|MIT License + The 3-Clause BSD License|New BSD License|3-Clause BSD + License|BSD|3-Clause BSD License|The New BSD License + + + + + + + + + From 52cbfc9a677a8c17b986fc7e1d823ed0c63a6998 Mon Sep 17 00:00:00 2001 From: huaifeng Date: Wed, 22 May 2019 13:27:28 +0800 Subject: [PATCH 075/115] rm incubating word (#4110) * rm incubating word * dubbo.incubator.apache.org to dubbo.apache.org --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index b7b9c8e9f52..3010a784558 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Apache Dubbo (incubating) Project +# Apache Dubbo Project [![Build Status](https://travis-ci.org/apache/incubator-dubbo.svg?branch=master)](https://travis-ci.org/apache/incubator-dubbo) [![codecov](https://codecov.io/gh/apache/incubator-dubbo/branch/master/graph/badge.svg)](https://codecov.io/gh/apache/incubator-dubbo) @@ -10,7 +10,7 @@ [![](https://img.shields.io/twitter/follow/ApacheDubbo.svg?label=Follow&style=social&logoWidth=0)](https://twitter.com/intent/follow?screen_name=ApacheDubbo) [![Gitter](https://badges.gitter.im/alibaba/dubbo.svg)](https://gitter.im/alibaba/dubbo?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) -Apache Dubbo (incubating) is a high-performance, Java based open source RPC framework. Please visit [official site](http://dubbo.incubator.apache.org) for quick start and documentations, as well as [Wiki](https://github.com/apache/incubator-dubbo/wiki) for news, FAQ, and release notes. +Apache Dubbo is a high-performance, Java based open source RPC framework. Please visit [official site](http://dubbo.apache.org) for quick start and documentations, as well as [Wiki](https://github.com/apache/incubator-dubbo/wiki) for news, FAQ, and release notes. We are now collecting dubbo user info in order to help us to improve Dubbo better, pls. kindly help us by providing yours on [issue#1012: Wanted: who's using dubbo](https://github.com/apache/incubator-dubbo/issues/1012), thanks :) @@ -175,7 +175,7 @@ If you want to try out the cutting-edge features, you can built with the followi ## Contact * Mailing list: - * dev list: for dev/user discussion. [subscribe](mailto:dev-subscribe@dubbo.incubator.apache.org), [unsubscribe](mailto:dev-unsubscribe@dubbo.incubator.apache.org), [archive](https://lists.apache.org/list.html?dev@dubbo.apache.org), [guide](https://github.com/apache/incubator-dubbo/wiki/Mailing-list-subscription-guide) + * dev list: for dev/user discussion. [subscribe](mailto:dev-subscribe@dubbo.apache.org), [unsubscribe](mailto:dev-unsubscribe@dubbo.apache.org), [archive](https://lists.apache.org/list.html?dev@dubbo.apache.org), [guide](https://github.com/apache/incubator-dubbo/wiki/Mailing-list-subscription-guide) * Bugs: [Issues](https://github.com/apache/incubator-dubbo/issues/new?template=dubbo-issue-report-template.md) * Gitter: [Gitter channel](https://gitter.im/alibaba/dubbo) @@ -199,7 +199,7 @@ See [CONTRIBUTING](https://github.com/apache/incubator-dubbo/blob/master/CONTRI * Improve the [dubbo-admin/dubbo-monitor](https://github.com/apache/incubator-dubbo-admin). * Contribute to the projects listed in [ecosystem](https://github.com/dubbo). * Any form of contribution that is not mentioned above. -* If you would like to contribute, please send an email to dev@dubbo.incubator.apache.org to let us know! +* If you would like to contribute, please send an email to dev@dubbo.apache.org to let us know! ## Reporting bugs @@ -207,13 +207,13 @@ Please follow the [template](https://github.com/apache/incubator-dubbo/issues/ne ## Reporting a security vulnerability -Please report security vulnerability to [us](mailto:security@dubbo.incubator.apache.org) privately. +Please report security vulnerability to [us](mailto:security@dubbo.apache.org) privately. ## Dubbo ecosystem * [Dubbo Ecosystem Entry](https://github.com/dubbo) - A GitHub group `dubbo` to gather all Dubbo relevant projects not appropriate in [apache](https://github.com/apache) group yet -* [Dubbo Website](https://github.com/apache/incubator-dubbo-website) - Apache Dubbo (incubating) official website -* [Dubbo Samples](https://github.com/apache/incubator-dubbo-samples) - samples for Apache Dubbo (incubating) +* [Dubbo Website](https://github.com/apache/incubator-dubbo-website) - Apache Dubbo official website +* [Dubbo Samples](https://github.com/apache/incubator-dubbo-samples) - samples for Apache Dubbo * [Dubbo Spring Boot](https://github.com/apache/incubator-dubbo-spring-boot-project) - Spring Boot Project for Dubbo * [Dubbo Admin](https://github.com/apache/incubator-dubbo-admin) - The reference implementation for Dubbo admin From a7f56a36be1408602b4b31baaf7947ee9bba5985 Mon Sep 17 00:00:00 2001 From: violin Date: Wed, 22 May 2019 14:45:37 +0800 Subject: [PATCH 076/115] [DUBBO-4010] TypeDefinitonBuilder support google protobuf entity build # (#4011) * add protobuf typeDefinitionBuilder * fix pull request comment add test case to test NestPbType --- .../dubbo-metadata-definition/pom.xml | 1 - .../definition/TypeDefinitionBuilder.java | 21 +- .../builder/CollectionTypeBuilder.java | 9 +- .../definition/builder/MapTypeBuilder.java | 9 +- .../definition/builder/TypeBuilder.java | 2 + ...bo.metadata.definition.builder.TypeBuilder | 4 + .../dubbo-serialization-protobuf-json/pom.xml | 5 + .../protobuf/support/ProtobufTypeBuilder.java | 308 ++++++++++++++++++ ...bo.metadata.definition.builder.TypeBuilder | 1 + .../support/ProtobufTypeBuilderTest.java | 69 ++++ .../support/model/ServiceInterface.java | 21 ++ 11 files changed, 426 insertions(+), 24 deletions(-) create mode 100644 dubbo-metadata-report/dubbo-metadata-definition/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.definition.builder.TypeBuilder create mode 100644 dubbo-serialization/dubbo-serialization-protobuf-json/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/ProtobufTypeBuilder.java create mode 100644 dubbo-serialization/dubbo-serialization-protobuf-json/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.definition.builder.TypeBuilder create mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protobuf/support/ProtobufTypeBuilderTest.java create mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protobuf/support/model/ServiceInterface.java diff --git a/dubbo-metadata-report/dubbo-metadata-definition/pom.xml b/dubbo-metadata-report/dubbo-metadata-definition/pom.xml index 6e9a58fa818..093c7e29824 100644 --- a/dubbo-metadata-report/dubbo-metadata-definition/pom.xml +++ b/dubbo-metadata-report/dubbo-metadata-definition/pom.xml @@ -21,7 +21,6 @@ ${revision} 4.0.0 - dubbo-metadata-definition diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/TypeDefinitionBuilder.java b/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/TypeDefinitionBuilder.java index 53e8c88b8f3..19e5f8abd95 100755 --- a/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/TypeDefinitionBuilder.java +++ b/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/TypeDefinitionBuilder.java @@ -16,17 +16,13 @@ */ package org.apache.dubbo.metadata.definition; -import org.apache.dubbo.metadata.definition.builder.ArrayTypeBuilder; -import org.apache.dubbo.metadata.definition.builder.CollectionTypeBuilder; +import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.metadata.definition.builder.DefaultTypeBuilder; -import org.apache.dubbo.metadata.definition.builder.EnumTypeBuilder; -import org.apache.dubbo.metadata.definition.builder.MapTypeBuilder; import org.apache.dubbo.metadata.definition.builder.TypeBuilder; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import java.lang.reflect.Type; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -35,13 +31,16 @@ * 2015/1/27. */ public class TypeDefinitionBuilder { + private static final List BUILDERS; - private static final TypeBuilder ARRAY_BUILDER = new ArrayTypeBuilder(); - private static final TypeBuilder COLLECTION_BUILDER = new CollectionTypeBuilder(); - private static final TypeBuilder MAP_BUILDER = new MapTypeBuilder(); - private static final TypeBuilder ENUM_BUILDER = new EnumTypeBuilder(); - - private static final List BUILDERS = Arrays.asList(ARRAY_BUILDER, COLLECTION_BUILDER, MAP_BUILDER, ENUM_BUILDER); + static{ + List builders = new ArrayList<>(); + ExtensionLoader extensionLoader = ExtensionLoader.getExtensionLoader(TypeBuilder.class); + for(String extensionName : extensionLoader.getSupportedExtensions()){ + builders.add(extensionLoader.getExtension(extensionName)); + } + BUILDERS = builders; + } public static TypeDefinition build(Type type, Class clazz, Map, TypeDefinition> typeCache) { TypeBuilder builder = getGenericTypeBuilder(type, clazz); diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/builder/CollectionTypeBuilder.java b/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/builder/CollectionTypeBuilder.java index de7dc73c1b3..1e746840e41 100755 --- a/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/builder/CollectionTypeBuilder.java +++ b/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/builder/CollectionTypeBuilder.java @@ -49,7 +49,8 @@ public TypeDefinition build(Type type, Class clazz, Map, TypeDefinit Type[] actualTypeArgs = parameterizedType.getActualTypeArguments(); if (actualTypeArgs == null || actualTypeArgs.length != 1) { throw new IllegalArgumentException(MessageFormat.format( - "[ServiceDefinitionBuilder] Collection type [{0}] with unexpected amount of arguments [{1}]." + Arrays.toString(actualTypeArgs), + "[ServiceDefinitionBuilder] Collection type [{0}] with unexpected amount of arguments [{1}]." + + Arrays.toString(actualTypeArgs), type, actualTypeArgs)); } @@ -60,11 +61,7 @@ public TypeDefinition build(Type type, Class clazz, Map, TypeDefinit TypeDefinitionBuilder.build(actualType, rawType, typeCache); } else if (actualType instanceof Class) { Class actualClass = (Class) actualType; - if (actualClass.isArray() || actualClass.isEnum()) { - TypeDefinitionBuilder.build(null, actualClass, typeCache); - } else { - DefaultTypeBuilder.build(actualClass, typeCache); - } + TypeDefinitionBuilder.build(null, actualClass, typeCache); } return new TypeDefinition(type.toString()); diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/builder/MapTypeBuilder.java b/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/builder/MapTypeBuilder.java index 905ad0728e0..a2070829ffa 100755 --- a/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/builder/MapTypeBuilder.java +++ b/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/builder/MapTypeBuilder.java @@ -48,7 +48,8 @@ public TypeDefinition build(Type type, Class clazz, Map, TypeDefinit Type[] actualTypeArgs = parameterizedType.getActualTypeArguments(); if (actualTypeArgs == null || actualTypeArgs.length != 2) { throw new IllegalArgumentException(MessageFormat.format( - "[ServiceDefinitionBuilder] Map type [{0}] with unexpected amount of arguments [{1}]." + Arrays.toString(actualTypeArgs), type, actualTypeArgs)); + "[ServiceDefinitionBuilder] Map type [{0}] with unexpected amount of arguments [{1}]." + + Arrays.toString(actualTypeArgs), type, actualTypeArgs)); } for (Type actualType : actualTypeArgs) { @@ -58,11 +59,7 @@ public TypeDefinition build(Type type, Class clazz, Map, TypeDefinit TypeDefinitionBuilder.build(actualType, rawType, typeCache); } else if (actualType instanceof Class) { Class actualClass = (Class) actualType; - if (actualClass.isArray() || actualClass.isEnum()) { - TypeDefinitionBuilder.build(null, actualClass, typeCache); - } else { - DefaultTypeBuilder.build(actualClass, typeCache); - } + TypeDefinitionBuilder.build(null, actualClass, typeCache); } } diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/builder/TypeBuilder.java b/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/builder/TypeBuilder.java index ef79a3f2183..d7022bd9555 100755 --- a/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/builder/TypeBuilder.java +++ b/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/builder/TypeBuilder.java @@ -16,6 +16,7 @@ */ package org.apache.dubbo.metadata.definition.builder; +import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import java.lang.reflect.Type; @@ -24,6 +25,7 @@ /** * 2015/1/27. */ +@SPI public interface TypeBuilder { /** diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.definition.builder.TypeBuilder b/dubbo-metadata-report/dubbo-metadata-definition/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.definition.builder.TypeBuilder new file mode 100644 index 00000000000..a0d82d266d1 --- /dev/null +++ b/dubbo-metadata-report/dubbo-metadata-definition/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.definition.builder.TypeBuilder @@ -0,0 +1,4 @@ +array=org.apache.dubbo.metadata.definition.builder.ArrayTypeBuilder +collection=org.apache.dubbo.metadata.definition.builder.CollectionTypeBuilder +map=org.apache.dubbo.metadata.definition.builder.MapTypeBuilder +enum=org.apache.dubbo.metadata.definition.builder.EnumTypeBuilder \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-protobuf-json/pom.xml b/dubbo-serialization/dubbo-serialization-protobuf-json/pom.xml index 6580e8705a1..75b290b0a42 100644 --- a/dubbo-serialization/dubbo-serialization-protobuf-json/pom.xml +++ b/dubbo-serialization/dubbo-serialization-protobuf-json/pom.xml @@ -42,5 +42,10 @@ limitations under the License. com.google.protobuf protobuf-java-util
    + + org.apache.dubbo + dubbo-metadata-definition + ${project.parent.version} +
    \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-protobuf-json/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/ProtobufTypeBuilder.java b/dubbo-serialization/dubbo-serialization-protobuf-json/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/ProtobufTypeBuilder.java new file mode 100644 index 00000000000..75fcc5f49ce --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-protobuf-json/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/ProtobufTypeBuilder.java @@ -0,0 +1,308 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.serialize.protobuf.support; + +import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.metadata.definition.TypeDefinitionBuilder; +import org.apache.dubbo.metadata.definition.builder.TypeBuilder; +import org.apache.dubbo.metadata.definition.model.TypeDefinition; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Descriptors; +import com.google.protobuf.GeneratedMessageV3; +import com.google.protobuf.ProtocolStringList; +import com.google.protobuf.UnknownFieldSet; + +import java.lang.reflect.Method; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ProtobufTypeBuilder implements TypeBuilder { + private final Logger logger = LoggerFactory.getLogger(getClass()); + private static final Pattern MAP_PATTERN = Pattern.compile("^java\\.util\\.Map<(\\S+), (\\S+)>$"); + private static final Pattern LIST_PATTERN = Pattern.compile("^java\\.util\\.List<(\\S+)>$"); + private static final List list = null; + /** + * provide a List type for TypeDefinitionBuilder.build(type,class,cache) + * "repeated string" transform to ProtocolStringList, should be build as List type. + */ + private static Type STRING_LIST_TYPE; + + static { + try { + STRING_LIST_TYPE = ProtobufTypeBuilder.class.getDeclaredField("list").getGenericType(); + } catch (NoSuchFieldException e) { + // do nothing + } + } + + @Override + public boolean accept(Type type, Class clazz) { + if (clazz == null) { + return false; + } + + return GeneratedMessageV3.class.isAssignableFrom(clazz); + } + + @Override + public TypeDefinition build(Type type, Class clazz, Map, TypeDefinition> typeCache) { + TypeDefinition typeDefinition = new TypeDefinition(clazz.getName()); + try { + GeneratedMessageV3.Builder builder = getMessageBuilder(clazz); + typeDefinition = buildProtobufTypeDefinition(clazz, builder, typeCache); + } catch (Exception e) { + logger.info("TypeDefinition build failed.", e); + } + + return typeDefinition; + } + + private GeneratedMessageV3.Builder getMessageBuilder(Class requestType) throws Exception { + Method method = requestType.getMethod("newBuilder"); + return (GeneratedMessageV3.Builder) method.invoke(null, null); + } + + private TypeDefinition buildProtobufTypeDefinition(Class clazz, GeneratedMessageV3.Builder builder, Map, TypeDefinition> typeCache) { + TypeDefinition typeDefinition = new TypeDefinition(clazz.getName()); + if (builder == null) { + return typeDefinition; + } + + Map properties = new HashMap<>(); + Method[] methods = builder.getClass().getDeclaredMethods(); + for (Method method : methods) { + String methodName = method.getName(); + + if (isSimplePropertySettingMethod(method)) { + // property of custom type or primitive type + properties.put(generateSimpleFiledName(methodName), TypeDefinitionBuilder.build(method.getGenericParameterTypes()[0], method.getParameterTypes()[0], typeCache)); + } else if (isMapPropertySettingMethod(method)) { + // property of map + Type type = method.getGenericParameterTypes()[0]; + String fieldName = generateMapFieldName(methodName); + validateMapType(fieldName, type.toString()); + properties.put(fieldName, TypeDefinitionBuilder.build(type, method.getParameterTypes()[0], typeCache)); + } else if (isListPropertySettingMethod(method)) { + // property of list + Type type = method.getGenericReturnType(); + String fieldName = generateListFieldName(methodName); + validateListType(fieldName, type.toString()); + TypeDefinition td; + if (ProtocolStringList.class.isAssignableFrom(method.getReturnType())) { + // property defined as "repeated string" transform to ProtocolStringList, + // should be build as List. + td = TypeDefinitionBuilder.build(STRING_LIST_TYPE, List.class, typeCache); + } else { + td = TypeDefinitionBuilder.build(type, method.getReturnType(), typeCache); + } + properties.put(fieldName, td); + } + } + typeDefinition.setProperties(properties); + typeCache.put(clazz, typeDefinition); + return typeDefinition; + } + + /** + * 1. Unsupported List with value type is Bytes
    + * Bytes is a primitive type in Proto, transform to ByteString.class in java
    + * + * @param fieldName + * @param typeName + * @return + */ + private void validateListType(String fieldName, String typeName) { + Matcher matcher = LIST_PATTERN.matcher(typeName); + if (!matcher.matches()) { + throw new IllegalArgumentException("List protobuf property " + fieldName + "of Type " + + typeName + " can't be parsed.The type name should mathch[" + LIST_PATTERN.toString() + "]."); + } + + if (ByteString.class.getName().equals(matcher.group(1))) { + throw new IllegalArgumentException("List protobuf property " + fieldName + "of Type " + + typeName + " can't be parsed.List of ByteString is not supported."); + } + } + + /** + * 1. Unsupported Map with value type is Bytes
    + * 2. Unsupported Map with key type is not String
    + * Bytes is a primitive type in Proto, transform to ByteString.class in java
    + * + * @param fieldName + * @param typeName + * @return + */ + private void validateMapType(String fieldName, String typeName) { + Matcher matcher = MAP_PATTERN.matcher(typeName); + if (!matcher.matches()) { + throw new IllegalArgumentException("Map protobuf property " + fieldName + "of Type " + + typeName + " can't be parsed.The type name should mathch[" + MAP_PATTERN.toString() + "]."); + } + + if (!String.class.getName().equals(matcher.group(1)) || ByteString.class.getName().equals(matcher.group(2))) { + throw new IllegalArgumentException("Map protobuf property " + fieldName + "of Type " + + typeName + " can't be parsed.Map with unString key or ByteString value is not supported."); + } + } + + /** + * get unCollection unMap property name from setting method.
    + * ex:setXXX();
    + * + * @param methodName + * @return + */ + private String generateSimpleFiledName(String methodName) { + return toCamelCase(methodName.substring(3)); + } + + /** + * get map property name from setting method.
    + * ex: putAllXXX();
    + * + * @param methodName + * @return + */ + private String generateMapFieldName(String methodName) { + return toCamelCase(methodName.substring(6)); + } + + /** + * get list property name from setting method.
    + * ex: getXXXList()
    + * + * @param methodName + * @return + */ + private String generateListFieldName(String methodName) { + return toCamelCase(methodName.substring(3, methodName.length() - 4)); + } + + + private String toCamelCase(String nameString) { + char[] chars = nameString.toCharArray(); + chars[0] = Character.toLowerCase(chars[0]); + return new String(chars); + } + + /** + * judge custom type or primitive type property
    + * 1. proto3 grammar ex: string name = 1
    + * 2. proto3 grammar ex: optional string name =1
    + * generated setting method setNameValue(String name); + * + * @param method + * @return + */ + private boolean isSimplePropertySettingMethod(Method method) { + String methodName = method.getName(); + Class[] types = method.getParameterTypes(); + + if (!methodName.startsWith("set") || types.length != 1) { + return false; + } + + // filter general setting method + // 1. - setUnknownFields( com.google.protobuf.UnknownFieldSet unknownFields) + // 2. - setField(com.google.protobuf.Descriptors.FieldDescriptor field,java.lang.Object value) + // 3. - setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,int index,java.lang.Object value) + if (methodName.equals("setField") && types[0].equals(Descriptors.FieldDescriptor.class) + || methodName.equals("setUnknownFields") && types[0].equals(UnknownFieldSet.class) + || methodName.equals("setRepeatedField") && types[0].equals(Descriptors.FieldDescriptor.class)) { + return false; + } + + // String property has two setting method. + // skip setXXXBytes(com.google.protobuf.ByteString value) + // parse setXXX(String string) + if (methodName.endsWith("Bytes") && types[0].equals(ByteString.class)) { + return false; + } + + // Protobuf property has two setting method. + // skip setXXX(com.google.protobuf.Builder value) + // parse setXXX(com.google.protobuf.Message value) + if (GeneratedMessageV3.Builder.class.isAssignableFrom(types[0])) { + return false; + } + + // Enum property has two setting method. + // skip setXXX(int value) + // parse setXXX(SomeEnum value) + if (methodName.endsWith("Value") && types[0] == int.class) { + return false; + } + + return true; + } + + + /** + * judge List property
    + * proto3 grammar ex: repeated string names;
    + * generated setting method:List getNamesList() + * + * @param method + * @return + */ + boolean isListPropertySettingMethod(Method method) { + String methodName = method.getName(); + Class type = method.getReturnType(); + + + if (!methodName.startsWith("get") || !methodName.endsWith("List")) { + return false; + } + + // skip the setting method with Pb entity builder as parameter + if (methodName.endsWith("BuilderList")) { + return false; + } + + // if field name end with List, should skip + if (!List.class.isAssignableFrom(type)) { + return false; + } + + return true; + } + + /** + * judge map property
    + * proto3 grammar : map card = 1;
    + * generated setting method: putAllCards(java.util.Map values)
    + * + * @param methodTemp + * @return + */ + private boolean isMapPropertySettingMethod(Method methodTemp) { + String methodName = methodTemp.getName(); + Class[] parameters = methodTemp.getParameterTypes(); + if (methodName.startsWith("putAll") && parameters.length == 1 && Map.class.isAssignableFrom(parameters[0])) { + return true; + } + + return false; + } +} diff --git a/dubbo-serialization/dubbo-serialization-protobuf-json/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.definition.builder.TypeBuilder b/dubbo-serialization/dubbo-serialization-protobuf-json/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.definition.builder.TypeBuilder new file mode 100644 index 00000000000..97795f2a428 --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-protobuf-json/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.definition.builder.TypeBuilder @@ -0,0 +1 @@ +protobuf=org.apache.dubbo.common.serialize.protobuf.support.ProtobufTypeBuilder \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protobuf/support/ProtobufTypeBuilderTest.java b/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protobuf/support/ProtobufTypeBuilderTest.java new file mode 100644 index 00000000000..0d59c088e4f --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protobuf/support/ProtobufTypeBuilderTest.java @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.serialize.protobuf.support; + +import org.apache.dubbo.common.serialize.protobuf.support.model.ServiceInterface; +import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder; +import org.apache.dubbo.metadata.definition.model.FullServiceDefinition; +import org.apache.dubbo.metadata.definition.model.MethodDefinition; +import org.apache.dubbo.metadata.definition.model.TypeDefinition; + +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + + +public class ProtobufTypeBuilderTest { + @Test + public void testProtobufBuilder() { + // TEST Pb Service metaData builder + FullServiceDefinition serviceDefinition = ServiceDefinitionBuilder.buildFullDefinition(ServiceInterface.class); + MethodDefinition methodDefinition = serviceDefinition.getMethods().get(0); + String parameterName = methodDefinition.getParameterTypes()[0]; + TypeDefinition typeDefinition = null; + for (TypeDefinition type : serviceDefinition.getTypes()) { + if (parameterName.equals(type.getType())) { + typeDefinition = type; + break; + } + } + Map propertiesMap = typeDefinition.getProperties(); + assertThat(propertiesMap.size(), is(9)); + assertThat(propertiesMap.containsKey("money"), is(true)); + assertThat(propertiesMap.get("money").getType(), equalTo("double")); + assertThat(propertiesMap.containsKey("cash"), is(true)); + assertThat(propertiesMap.get("cash").getType(), equalTo("float")); + assertThat(propertiesMap.containsKey("age"), is(true)); + assertThat(propertiesMap.get("age").getType(), equalTo("int")); + assertThat(propertiesMap.containsKey("num"), is(true)); + assertThat(propertiesMap.get("num").getType(), equalTo("long")); + assertThat(propertiesMap.containsKey("sex"), is(true)); + assertThat(propertiesMap.get("sex").getType(), equalTo("boolean")); + assertThat(propertiesMap.containsKey("name"), is(true)); + assertThat(propertiesMap.get("name").getType(), equalTo("java.lang.String")); + assertThat(propertiesMap.containsKey("msg"), is(true)); + assertThat(propertiesMap.get("msg").getType(), equalTo("com.google.protobuf.ByteString")); + assertThat(propertiesMap.containsKey("phone"), is(true)); + assertThat(propertiesMap.get("phone").getType(), equalTo("java.util.List")); + assertThat(propertiesMap.containsKey("doubleMap"), is(true)); + assertThat(propertiesMap.get("doubleMap").getType(), equalTo("java.util.Map")); + } +} diff --git a/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protobuf/support/model/ServiceInterface.java b/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protobuf/support/model/ServiceInterface.java new file mode 100644 index 00000000000..ffdbdd4c7c4 --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protobuf/support/model/ServiceInterface.java @@ -0,0 +1,21 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.serialize.protobuf.support.model; + +public interface ServiceInterface { + GooglePB.PBResponseType sayHello(GooglePB.PBRequestType requestType); +} From df084addc804ef727ae9f1959b10f88ffd5a0ddc Mon Sep 17 00:00:00 2001 From: cvictory Date: Wed, 22 May 2019 15:31:37 +0800 Subject: [PATCH 077/115] Support Redis cluster in Metadata Report (#3863) fixes #3817 --- .../dubbo/config/MetadataReportConfig.java | 13 ++++++ .../main/resources/META-INF/compat/dubbo.xsd | 5 ++ .../src/main/resources/META-INF/dubbo.xsd | 5 ++ .../identifier/MetadataIdentifier.java | 4 +- .../store/redis/RedisMetadataReport.java | 46 +++++++++++++++++-- 5 files changed, 67 insertions(+), 6 deletions(-) diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MetadataReportConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MetadataReportConfig.java index a7c72f6f41b..5233171e011 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MetadataReportConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MetadataReportConfig.java @@ -71,6 +71,11 @@ public class MetadataReportConfig extends AbstractConfig { */ private Boolean syncReport; + /** + * cluster + */ + private Boolean cluster; + public MetadataReportConfig() { } @@ -174,4 +179,12 @@ public String getGroup() { public void setGroup(String group) { this.group = group; } + + public Boolean getCluster() { + return cluster; + } + + public void setCluster(Boolean cluster) { + this.cluster = cluster; + } } diff --git a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/compat/dubbo.xsd b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/compat/dubbo.xsd index c12389f805e..756f6dae665 100644 --- a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/compat/dubbo.xsd +++ b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/compat/dubbo.xsd @@ -632,6 +632,11 @@ + + + + + diff --git a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd index 5cc621fc872..4a8cf56c8d8 100644 --- a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd +++ b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd @@ -626,6 +626,11 @@ + + + + + diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/identifier/MetadataIdentifier.java b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/identifier/MetadataIdentifier.java index 602e4b298b7..3b20bc7a373 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/identifier/MetadataIdentifier.java +++ b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/identifier/MetadataIdentifier.java @@ -31,8 +31,8 @@ public class MetadataIdentifier { public static final String SEPARATOR = ":"; - final static String DEFAULT_PATH_TAG = "metadata"; - final static String META_DATA_STORE_TAG = ".metaData"; + public final static String DEFAULT_PATH_TAG = "metadata"; + public final static String META_DATA_STORE_TAG = ".metaData"; private String serviceInterface; private String version; diff --git a/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java b/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java index c0b992da466..a9245eb28d8 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java +++ b/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java @@ -22,12 +22,22 @@ import org.apache.dubbo.metadata.identifier.MetadataIdentifier; import org.apache.dubbo.metadata.support.AbstractMetadataReport; import org.apache.dubbo.rpc.RpcException; + +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; +import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisCluster; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.CLUSTER_KEY; +import static org.apache.dubbo.metadata.identifier.MetadataIdentifier.META_DATA_STORE_TAG; /** * RedisMetadataReport @@ -36,12 +46,24 @@ public class RedisMetadataReport extends AbstractMetadataReport { private final static Logger logger = LoggerFactory.getLogger(RedisMetadataReport.class); - final JedisPool pool; + JedisPool pool; + Set jedisClusterNodes; + private int timeout; + private String password; + public RedisMetadataReport(URL url) { super(url); - int timeout = url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT); - pool = new JedisPool(new JedisPoolConfig(), url.getHost(), url.getPort(), timeout, url.getPassword()); + timeout = url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT); + if (url.getParameter(CLUSTER_KEY, false)) { + jedisClusterNodes = new HashSet(); + List urls = url.getBackupUrls(); + for (URL tmpUrl : urls) { + jedisClusterNodes.add(new HostAndPort(tmpUrl.getHost(), tmpUrl.getPort())); + } + } else { + pool = new JedisPool(new JedisPoolConfig(), url.getHost(), url.getPort(), timeout, url.getPassword()); + } } @Override @@ -55,6 +77,23 @@ protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdenti } private void storeMetadata(MetadataIdentifier metadataIdentifier, String v) { + if (pool != null) { + storeMetadataStandalone(metadataIdentifier, v); + } else { + storeMetadataInCluster(metadataIdentifier, v); + } + } + + private void storeMetadataInCluster(MetadataIdentifier metadataIdentifier, String v) { + try (JedisCluster jedisCluster = new JedisCluster(jedisClusterNodes, timeout, timeout, 2, password, new GenericObjectPoolConfig())) { + jedisCluster.set(metadataIdentifier.getIdentifierKey() + META_DATA_STORE_TAG, v); + } catch (Throwable e) { + logger.error("Failed to put " + metadataIdentifier + " to redis cluster " + v + ", cause: " + e.getMessage(), e); + throw new RpcException("Failed to put " + metadataIdentifier + " to redis cluster " + v + ", cause: " + e.getMessage(), e); + } + } + + private void storeMetadataStandalone(MetadataIdentifier metadataIdentifier, String v) { try (Jedis jedis = pool.getResource()) { jedis.set(metadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY), v); } catch (Throwable e) { @@ -63,5 +102,4 @@ private void storeMetadata(MetadataIdentifier metadataIdentifier, String v) { } } - } From ebafc18c4dd3d8fc0f6bd399a56068af67958091 Mon Sep 17 00:00:00 2001 From: "ken.lj" Date: Thu, 23 May 2019 10:19:04 +0800 Subject: [PATCH 078/115] merge async changes in 3.x to 2.7 (#3997) --- .../support/FailbackClusterInvoker.java | 4 +- .../support/FailsafeClusterInvoker.java | 6 +- .../support/ForkingClusterInvoker.java | 3 +- .../support/MergeableClusterInvoker.java | 36 ++- .../support/wrapper/MockClusterInvoker.java | 4 +- .../apache/dubbo/rpc/cluster/StickyTest.java | 4 +- .../cluster/directory/MockDirInvocation.java | 10 + .../router/file/FileRouterEngineTest.java | 4 +- .../support/FailSafeClusterInvokerTest.java | 4 +- .../support/FailbackClusterInvokerTest.java | 4 +- .../support/FailfastClusterInvokerTest.java | 4 +- .../support/FailoverClusterInvokerTest.java | 4 +- .../support/ForkingClusterInvokerTest.java | 6 +- .../support/MergeableClusterInvokerTest.java | 11 +- .../dubbo/common/constants/RpcConstants.java | 56 ++++ .../apache/dubbo/common/logger/Logger.java | 2 +- .../dubbo/common/utils/ReflectUtils.java | 23 ++ .../dubbo/common/utils/ReflectUtilsTest.java | 28 ++ .../com/alibaba/dubbo/rpc/Invocation.java | 9 + .../java/com/alibaba/dubbo/rpc/Result.java | 36 ++- .../com/alibaba/dubbo/rpc/RpcContext.java | 2 +- .../alibaba/dubbo/rpc/support/RpcUtils.java | 5 - .../apache/dubbo/filter/LegacyInvoker.java | 4 +- .../apache/dubbo/service/MockInvocation.java | 10 + .../dubbo/cache/filter/CacheFilter.java | 18 +- .../dubbo/cache/filter/CacheFilterTest.java | 31 +-- .../validation/filter/ValidationFilter.java | 4 +- .../filter/ValidationFilterTest.java | 12 +- .../apache/dubbo/monitor/MonitorService.java | 1 + .../dubbo/monitor/support/MonitorFilter.java | 197 +++++++------- .../monitor/support/MonitorFilterTest.java | 15 +- .../dubbo/monitor/dubbo/MetricsFilter.java | 11 +- .../dubbo/registry/dubbo/MockChannel.java | 8 +- .../dubbo/registry/dubbo/MockedClient.java | 18 +- dubbo-registry/dubbo-registry-sofa/pom.xml | 2 +- .../dubbo/remoting/RemotingException.java | 3 +- .../dubbo/remoting/TimeoutException.java | 3 +- .../remoting/exchange/ExchangeChannel.java | 6 +- .../remoting/exchange/ResponseCallback.java | 38 --- .../remoting/exchange/ResponseFuture.java | 58 ----- .../exchange/support/DefaultFuture.java | 185 +++---------- .../exchange/support/SimpleFuture.java | 54 ---- .../support/header/HeaderExchangeChannel.java | 6 +- .../support/header/HeaderExchangeClient.java | 6 +- .../support/header/HeaderExchangeHandler.java | 15 +- .../java/org/apache/dubbo/remoting/Main.java | 4 +- .../org/apache/dubbo/remoting/MockResult.java | 2 +- .../exchange/support/DefaultFutureTest.java | 4 +- .../handler/HeaderExchangeHandlerTest.java | 2 +- .../transport/mina/ClientToServerTest.java | 5 +- .../support/header/HeartbeatHandlerTest.java | 1 + .../transport/netty/ClientToServerTest.java | 6 +- .../transport/netty4/ClientToServerTest.java | 5 +- .../org/apache/dubbo/rpc/AbstractResult.java | 53 +--- .../org/apache/dubbo/rpc/AppResponse.java | 146 +++++++++++ .../org/apache/dubbo/rpc/AsyncRpcResult.java | 243 ++++++++++-------- .../java/org/apache/dubbo/rpc/Filter.java | 38 ++- .../org/apache/dubbo/rpc/FutureContext.java | 54 ++++ .../java/org/apache/dubbo/rpc/Invocation.java | 4 + .../java/org/apache/dubbo/rpc/InvokeMode.java | 10 +- .../apache/dubbo/rpc/ListenableFilter.java | 16 +- .../java/org/apache/dubbo/rpc/Result.java | 51 +++- .../java/org/apache/dubbo/rpc/RpcContext.java | 35 +-- .../org/apache/dubbo/rpc/RpcInvocation.java | 21 ++ .../java/org/apache/dubbo/rpc/RpcResult.java | 128 --------- .../dubbo/rpc/SimpleAsyncRpcResult.java | 50 ---- .../dubbo/rpc/filter/ActiveLimitFilter.java | 67 +++-- .../dubbo/rpc/filter/CompatibleFilter.java | 73 +++--- .../rpc/filter/ConsumerContextFilter.java | 31 ++- .../dubbo/rpc/filter/ContextFilter.java | 24 +- .../apache/dubbo/rpc/filter/EchoFilter.java | 4 +- .../dubbo/rpc/filter/ExceptionFilter.java | 126 +++++---- .../dubbo/rpc/filter/ExecuteLimitFilter.java | 35 ++- .../dubbo/rpc/filter/GenericFilter.java | 71 +++-- .../dubbo/rpc/filter/GenericImplFilter.java | 178 +++++++------ .../dubbo/rpc/filter/TimeoutFilter.java | 49 ++-- .../dubbo/rpc/protocol/AbstractInvoker.java | 17 +- .../dubbo/rpc/protocol/AbstractProtocol.java | 8 + .../rpc/protocol/AbstractProxyProtocol.java | 3 +- .../rpc/protocol/AsyncToSyncInvoker.java | 89 +++++++ .../rpc/protocol/ProtocolFilterWrapper.java | 33 ++- .../dubbo/rpc/proxy/AbstractProxyInvoker.java | 47 +++- .../rpc/proxy/InvokerInvocationHandler.java | 16 +- .../dubbo/rpc/service/GenericService.java | 10 + .../apache/dubbo/rpc/support/MockInvoker.java | 6 +- .../dubbo/rpc/support/MockProtocol.java | 2 +- .../apache/dubbo/rpc/support/RpcUtils.java | 46 ++-- ...pcResultTest.java => AppResponseTest.java} | 26 +- .../rpc/filter/ActiveLimitFilterTest.java | 24 +- .../filter/CompatibleFilterFilterTest.java | 39 +-- .../rpc/filter/ConsumerContextFilterTest.java | 15 +- .../dubbo/rpc/filter/ContextFilterTest.java | 4 +- .../dubbo/rpc/filter/EchoFilterTest.java | 6 +- .../dubbo/rpc/filter/ExceptionFilterTest.java | 47 ++-- .../rpc/filter/ExecuteLimitFilterTest.java | 7 +- .../dubbo/rpc/filter/GenericFilterTest.java | 24 +- .../rpc/filter/GenericImplFilterTest.java | 20 +- .../dubbo/rpc/filter/TimeoutFilterTest.java | 6 +- .../dubbo/rpc/filter/TokenFilterTest.java | 8 +- .../dubbo/rpc/support/BlockMyInvoker.java | 10 +- .../dubbo/rpc/support/MockInvocation.java | 10 + .../apache/dubbo/rpc/support/MyInvoker.java | 8 +- .../protocol/dubbo/CallbackServiceCodec.java | 3 +- .../protocol/dubbo/ChannelWrappedInvoker.java | 29 ++- .../protocol/dubbo/DecodeableRpcResult.java | 4 +- .../rpc/protocol/dubbo/DubboCountCodec.java | 4 +- .../rpc/protocol/dubbo/DubboInvoker.java | 36 +-- .../rpc/protocol/dubbo/DubboProtocol.java | 15 +- .../rpc/protocol/dubbo/FutureAdapter.java | 60 ++--- .../dubbo/LazyConnectExchangeClient.java | 6 +- .../dubbo/ReferenceCountExchangeClient.java | 6 +- .../protocol/dubbo/filter/FutureFilter.java | 56 ++-- .../dubbo/telnet/InvokeTelnetHandler.java | 7 +- .../dubbo/DubboInvokerAvilableTest.java | 16 +- .../rpc/protocol/dubbo/FutureFilterTest.java | 6 +- .../protocol/dubbo/ImplicitCallBackTest.java | 2 +- .../ReferenceCountExchangeClientTest.java | 5 +- .../dubbo/rpc/protocol/http/HttpProtocol.java | 2 +- .../rpc/protocol/injvm/InjvmProtocol.java | 2 +- .../protocol/memcached/MemcachedProtocol.java | 10 +- dubbo-rpc/dubbo-rpc-native-thrift/pom.xml | 2 +- .../protocol/nativethrift/ThriftProtocol.java | 1 + .../rpc/protocol/redis/RedisProtocol.java | 12 +- dubbo-rpc/dubbo-rpc-rest/pom.xml | 24 +- .../dubbo/rpc/protocol/rmi/RmiProtocol.java | 5 +- .../rpc/protocol/thrift/ThriftCodec.java | 16 +- .../rpc/protocol/thrift/ThriftInvoker.java | 12 +- .../rpc/protocol/thrift/ThriftProtocol.java | 10 +- .../rpc/protocol/thrift/ThriftCodecTest.java | 28 +- .../rpc/protocol/xmlrpc/XmlRpcProtocol.java | 20 +- 130 files changed, 1797 insertions(+), 1639 deletions(-) delete mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ResponseCallback.java delete mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ResponseFuture.java delete mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/SimpleFuture.java create mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AppResponse.java create mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/FutureContext.java rename dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseCallback.java => dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/InvokeMode.java (82%) rename dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/FutureAdapter.java => dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ListenableFilter.java (74%) delete mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcResult.java delete mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/SimpleAsyncRpcResult.java create mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AsyncToSyncInvoker.java rename dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/{RpcResultTest.java => AppResponseTest.java} (78%) diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvoker.java index a17c4abcbd2..3b98859728b 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvoker.java @@ -23,11 +23,11 @@ import org.apache.dubbo.common.timer.Timer; import org.apache.dubbo.common.timer.TimerTask; import org.apache.dubbo.common.utils.NamedThreadFactory; +import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.cluster.Directory; import org.apache.dubbo.rpc.cluster.LoadBalance; @@ -103,7 +103,7 @@ protected Result doInvoke(Invocation invocation, List> invokers, Load logger.error("Failback to invoke method " + invocation.getMethodName() + ", wait for retry in background. Ignored exception: " + e.getMessage() + ", ", e); addFailed(loadbalance, invocation, invokers, invoker); - return new RpcResult(); // ignore + return AsyncRpcResult.newDefaultAsyncResult(null, null, invocation); // ignore } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailsafeClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailsafeClusterInvoker.java index 0f5378a19a0..539686ed0e4 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailsafeClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailsafeClusterInvoker.java @@ -18,18 +18,18 @@ import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.cluster.Directory; import org.apache.dubbo.rpc.cluster.LoadBalance; import java.util.List; /** - * When invoke fails, log the error message and ignore this error by returning an empty RpcResult. + * When invoke fails, log the error message and ignore this error by returning an empty Result. * Usually used to write audit logs and other operations * * Fail-safe @@ -50,7 +50,7 @@ public Result doInvoke(Invocation invocation, List> invokers, LoadBal return invoker.invoke(invocation); } catch (Throwable e) { logger.error("Failsafe ignore exception: " + e.getMessage(), e); - return new RpcResult(); // ignore + return AsyncRpcResult.newDefaultAsyncResult(null, null, invocation); // ignore } } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvoker.java index 70a6eaa75ff..2c352b2cee9 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvoker.java @@ -40,6 +40,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; /** + * NOTICE! This implementation does not work well with async call. + * * Invoke a specific number of invokers concurrently, usually used for demanding real-time operations, but need to waste more service resources. * * Fork @@ -70,7 +72,6 @@ public Result doInvoke(final Invocation invocation, List> invokers, L } else { selected = new ArrayList<>(); for (int i = 0; i < forks; i++) { - // TODO. Add some comment here, refer chinese version for more details. Invoker invoker = select(loadbalance, invocation, invokers, selected); if (!selected.contains(invoker)) { //Avoid add the same invoker several times. diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java index d23459e909d..d3243c4c086 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java @@ -22,12 +22,12 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.NamedThreadFactory; +import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.cluster.Directory; import org.apache.dubbo.rpc.cluster.LoadBalance; import org.apache.dubbo.rpc.cluster.Merger; @@ -40,17 +40,16 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; +import static org.apache.dubbo.rpc.Constants.ASYNC_KEY; import static org.apache.dubbo.rpc.Constants.MERGER_KEY; +/** + * @param + */ @SuppressWarnings("unchecked") public class MergeableClusterInvoker extends AbstractClusterInvoker { @@ -90,26 +89,21 @@ protected Result doInvoke(Invocation invocation, List> invokers, Load returnType = null; } - Map> results = new HashMap>(); + Map results = new HashMap<>(); for (final Invoker invoker : invokers) { - Future future = executor.submit(new Callable() { - @Override - public Result call() throws Exception { - return invoker.invoke(new RpcInvocation(invocation, invoker)); - } - }); - results.put(invoker.getUrl().getServiceKey(), future); + RpcInvocation subInvocation = new RpcInvocation(invocation, invoker); + subInvocation.setAttachment(ASYNC_KEY, "true"); + results.put(invoker.getUrl().getServiceKey(), invoker.invoke(subInvocation)); } Object result = null; List resultList = new ArrayList(results.size()); - int timeout = getUrl().getMethodParameter(invocation.getMethodName(), TIMEOUT_KEY, DEFAULT_TIMEOUT); - for (Map.Entry> entry : results.entrySet()) { - Future future = entry.getValue(); + for (Map.Entry entry : results.entrySet()) { + Result asyncResult = entry.getValue(); try { - Result r = future.get(timeout, TimeUnit.MILLISECONDS); + Result r = asyncResult.get(); if (r.hasException()) { log.error("Invoke " + getGroupDescFromServiceKey(entry.getKey()) + " failed: " + r.getException().getMessage(), @@ -123,13 +117,13 @@ public Result call() throws Exception { } if (resultList.isEmpty()) { - return new RpcResult((Object) null); + return AsyncRpcResult.newDefaultAsyncResult(invocation); } else if (resultList.size() == 1) { return resultList.iterator().next(); } if (returnType == void.class) { - return new RpcResult((Object) null); + return AsyncRpcResult.newDefaultAsyncResult(invocation); } if (merger.startsWith(".")) { @@ -177,7 +171,7 @@ public Result call() throws Exception { throw new RpcException("There is no merger to merge result."); } } - return new RpcResult(result); + return AsyncRpcResult.newDefaultAsyncResult(result, invocation); } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java index c85eed476bb..77eceb0e75c 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java @@ -21,12 +21,12 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; +import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.cluster.Directory; import org.apache.dubbo.rpc.support.MockInvoker; @@ -115,7 +115,7 @@ private Result doMockInvoke(Invocation invocation, RpcException e) { result = minvoker.invoke(invocation); } catch (RpcException me) { if (me.isBiz()) { - result = new RpcResult(me.getCause()); + result = AsyncRpcResult.newDefaultAsyncResult(me.getCause(), invocation); } else { throw new RpcException(me.getCode(), getMockExceptionMessage(e, me), me.getCause()); } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/StickyTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/StickyTest.java index 878e3742df6..cb2656f33b9 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/StickyTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/StickyTest.java @@ -19,12 +19,12 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; +import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker; import org.junit.jupiter.api.Assertions; @@ -48,7 +48,7 @@ public class StickyTest { private Invoker invoker2 = mock(Invoker.class); private RpcInvocation invocation; private Directory dic; - private Result result = new RpcResult(); + private Result result = new AppResponse(); private StickyClusterInvoker clusterinvoker = null; private URL url = URL.valueOf("test://test:11/test?" + "&loadbalance=roundrobin" diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java index ec3541eed1f..5245a2cb69d 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java @@ -57,6 +57,16 @@ public Map getAttachments() { return attachments; } + @Override + public void setAttachment(String key, String value) { + + } + + @Override + public void setAttachmentIfAbsent(String key, String value) { + + } + public Invoker getInvoker() { return null; } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java index 635014863b1..6a03001ddf3 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java @@ -18,12 +18,12 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; +import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.cluster.Directory; import org.apache.dubbo.rpc.cluster.LoadBalance; import org.apache.dubbo.rpc.cluster.RouterFactory; @@ -52,7 +52,7 @@ public class FileRouterEngineTest { Invoker invoker2 = mock(Invoker.class); Invocation invocation; StaticDirectory dic; - Result result = new RpcResult(); + Result result = new AppResponse(); private RouterFactory routerFactory = ExtensionLoader.getExtensionLoader(RouterFactory.class).getAdaptiveExtension(); @BeforeAll diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailSafeClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailSafeClusterInvokerTest.java index 413d9b9dc8a..8ab596bec1e 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailSafeClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailSafeClusterInvokerTest.java @@ -18,11 +18,11 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.LogUtil; +import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.cluster.Directory; import org.apache.dubbo.rpc.cluster.filter.DemoService; @@ -48,7 +48,7 @@ public class FailSafeClusterInvokerTest { Invoker invoker = mock(Invoker.class); RpcInvocation invocation = new RpcInvocation(); Directory dic; - Result result = new RpcResult(); + Result result = new AppResponse(); /** * @throws java.lang.Exception diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvokerTest.java index ad96a66830d..b745b0e1b26 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvokerTest.java @@ -20,11 +20,11 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.DubboAppender; import org.apache.dubbo.common.utils.LogUtil; +import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.cluster.Directory; import org.apache.log4j.Level; @@ -59,7 +59,7 @@ public class FailbackClusterInvokerTest { Invoker invoker = mock(Invoker.class); RpcInvocation invocation = new RpcInvocation(); Directory dic; - Result result = new RpcResult(); + Result result = new AppResponse(); /** * @throws java.lang.Exception diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailfastClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailfastClusterInvokerTest.java index 9b6d2e88b73..6a706868bb9 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailfastClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailfastClusterInvokerTest.java @@ -17,12 +17,12 @@ package org.apache.dubbo.rpc.cluster.support; import org.apache.dubbo.common.URL; +import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.cluster.Directory; import org.junit.jupiter.api.Assertions; @@ -47,7 +47,7 @@ public class FailfastClusterInvokerTest { Invoker invoker1 = mock(Invoker.class); RpcInvocation invocation = new RpcInvocation(); Directory dic; - Result result = new RpcResult(); + Result result = new AppResponse(); /** * @throws java.lang.Exception diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvokerTest.java index ff29a6183a9..6a2e76e0474 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvokerTest.java @@ -17,12 +17,12 @@ package org.apache.dubbo.rpc.cluster.support; import org.apache.dubbo.common.URL; +import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.cluster.Directory; import org.apache.dubbo.rpc.cluster.directory.StaticDirectory; import org.apache.dubbo.rpc.protocol.AbstractInvoker; @@ -55,7 +55,7 @@ public class FailoverClusterInvokerTest { private Invoker invoker2 = mock(Invoker.class); private RpcInvocation invocation = new RpcInvocation(); private Directory dic; - private Result result = new RpcResult(); + private Result result = new AppResponse(); /** * @throws java.lang.Exception diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvokerTest.java index b3d343a3bbe..aa27fabe458 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvokerTest.java @@ -17,12 +17,12 @@ package org.apache.dubbo.rpc.cluster.support; import org.apache.dubbo.common.URL; +import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; +import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.RpcResult; -import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.cluster.Directory; import org.junit.jupiter.api.Assertions; @@ -50,7 +50,7 @@ public class ForkingClusterInvokerTest { private Invoker invoker3 = mock(Invoker.class); private RpcInvocation invocation = new RpcInvocation(); private Directory dic; - private Result result = new RpcResult(); + private Result result = new AppResponse(); @BeforeEach public void setUp() throws Exception { diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.java index 07bae73e2f5..3223b27ca8f 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.java @@ -17,10 +17,11 @@ package org.apache.dubbo.rpc.cluster.support; import org.apache.dubbo.common.URL; +import org.apache.dubbo.rpc.AppResponse; +import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.cluster.Directory; import org.junit.jupiter.api.Assertions; @@ -120,7 +121,7 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl return MenuService.class; } if ("invoke".equals(method.getName())) { - return new RpcResult(firstMenu); + return AsyncRpcResult.newDefaultAsyncResult(firstMenu, invocation); } return null; } @@ -136,7 +137,7 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl return MenuService.class; } if ("invoke".equals(method.getName())) { - return new RpcResult(secondMenu); + return AsyncRpcResult.newDefaultAsyncResult(secondMenu, invocation); } return null; } @@ -196,14 +197,14 @@ public void testAddMenu() throws Exception { given(firstInvoker.getUrl()).willReturn( url.addParameter(GROUP_KEY, "first")); given(firstInvoker.getInterface()).willReturn(MenuService.class); - given(firstInvoker.invoke(invocation)).willReturn(new RpcResult()) + given(firstInvoker.invoke(invocation)).willReturn(new AppResponse()) ; given(firstInvoker.isAvailable()).willReturn(true); given(secondInvoker.getUrl()).willReturn( url.addParameter(GROUP_KEY, "second")); given(secondInvoker.getInterface()).willReturn(MenuService.class); - given(secondInvoker.invoke(invocation)).willReturn(new RpcResult()) + given(secondInvoker.invoke(invocation)).willReturn(new AppResponse()) ; given(secondInvoker.isAvailable()).willReturn(true); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RpcConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RpcConstants.java index 75c70852666..b40a9c1d58c 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RpcConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RpcConstants.java @@ -42,6 +42,62 @@ public interface RpcConstants { String $INVOKE = "$invoke"; + String $INVOKE_ASYNC = "$invokeAsync"; + + String $ECHO = "$echo"; + + String RETURN_PREFIX = "return "; + + String THROW_PREFIX = "throw"; + + String FAIL_PREFIX = "fail:"; + + String FORCE_PREFIX = "force:"; + + String MERGER_KEY = "merger"; + + String IS_SERVER_KEY = "isserver"; + + String FORCE_USE_TAG = "dubbo.force.tag"; + + String GENERIC_SERIALIZATION_NATIVE_JAVA = "nativejava"; + + String GENERIC_SERIALIZATION_DEFAULT = "true"; + + String GENERIC_SERIALIZATION_BEAN = "bean"; + + String GENERIC_SERIALIZATION_PROTOBUF = "protobuf-json"; + + String TPS_LIMIT_RATE_KEY = "tps"; + + String TPS_LIMIT_INTERVAL_KEY = "tps.interval"; + + long DEFAULT_TPS_LIMIT_INTERVAL = 60 * 1000; + + String AUTO_ATTACH_INVOCATIONID_KEY = "invocationid.autoattach"; + + String STUB_EVENT_KEY = "dubbo.stub.event"; + + boolean DEFAULT_STUB_EVENT = false; + + String STUB_EVENT_METHODS_KEY = "dubbo.stub.event.methods"; + + String PROXY_KEY = "proxy"; + + String EXECUTES_KEY = "executes"; + + String REFERENCE_FILTER_KEY = "reference.filter"; + + String INVOKER_LISTENER_KEY = "invoker.listener"; + + String SERVICE_FILTER_KEY = "service.filter"; + + String EXPORTER_LISTENER_KEY = "exporter.listener"; + + String ACCESS_LOG_KEY = "accesslog"; + + String ACTIVES_KEY = "actives"; + String CONNECTIONS_KEY = "connections"; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/Logger.java b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/Logger.java index c505326d0c3..874ab564a2e 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/Logger.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/Logger.java @@ -142,7 +142,7 @@ public interface Logger { /** * Is debug logging currently enabled? - * + *  * @return true if debug is enabled */ boolean isDebugEnabled(); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.java index ccec6875ca8..0c1a13dfe25 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.java @@ -28,6 +28,7 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; import java.net.URL; import java.security.CodeSource; import java.security.ProtectionDomain; @@ -39,6 +40,7 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.Future; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -1096,4 +1098,25 @@ public static Map getBeanPropertyReadMethods(Class cl) { return properties; } + + public static Type[] getReturnTypes(Method method) { + Class returnType = method.getReturnType(); + Type genericReturnType = method.getGenericReturnType(); + if (Future.class.isAssignableFrom(returnType)) { + if (genericReturnType instanceof ParameterizedType) { + Type actualArgType = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0]; + if (actualArgType instanceof ParameterizedType) { + returnType = (Class) ((ParameterizedType) actualArgType).getRawType(); + genericReturnType = actualArgType; + } else { + returnType = (Class) actualArgType; + genericReturnType = returnType; + } + } else { + returnType = null; + genericReturnType = null; + } + } + return new Type[]{returnType, genericReturnType}; + } } \ No newline at end of file diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ReflectUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ReflectUtilsTest.java index f46235daaa1..298f15c2f02 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ReflectUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ReflectUtilsTest.java @@ -22,12 +22,14 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; +import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.CompletableFuture; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; @@ -401,6 +403,32 @@ public void testForName2() { }); } + @Test + public void testGetReturnTypes () throws Exception{ + Class clazz = TypeClass.class; + + Type[] types = ReflectUtils.getReturnTypes(clazz.getMethod("getFuture")); + Assertions.assertEquals("java.lang.String", types[0].getTypeName()); + Assertions.assertEquals("java.lang.String", types[1].getTypeName()); + + Type[] types1 = ReflectUtils.getReturnTypes(clazz.getMethod("getString")); + Assertions.assertEquals("java.lang.String", types1[0].getTypeName()); + Assertions.assertEquals("java.lang.String", types1[1].getTypeName()); + + Type[] types2 = ReflectUtils.getReturnTypes(clazz.getMethod("getListFuture")); + Assertions.assertEquals("java.util.List", types2[0].getTypeName()); + Assertions.assertEquals("java.util.List", types2[1].getTypeName()); + } + + public static interface TypeClass { + + CompletableFuture getFuture(); + + String getString(); + + CompletableFuture> getListFuture(); + } + public static class EmptyClass { private EmptyProperty property; public boolean set; diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invocation.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invocation.java index 9d960c219df..d283c63b26a 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invocation.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invocation.java @@ -29,6 +29,15 @@ default org.apache.dubbo.rpc.Invocation getOriginal() { return null; } + @Override + default void setAttachmentIfAbsent(String key, String value) { + } + + @Override + default void setAttachment(String key, String value) { + + } + class CompatibleInvocation implements Invocation, org.apache.dubbo.rpc.Invocation { private org.apache.dubbo.rpc.Invocation delegate; diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Result.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Result.java index a661b2b6b5b..07f5df9bf5a 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Result.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Result.java @@ -18,11 +18,30 @@ package com.alibaba.dubbo.rpc; import java.util.Map; +import java.util.function.Function; @Deprecated public interface Result extends org.apache.dubbo.rpc.Result { - class CompatibleResult implements Result { + @Override + default void setValue(Object value) { + + } + + @Override + default void setException(Throwable t) { + + } + + abstract class AbstractResult extends org.apache.dubbo.rpc.AbstractResult implements Result { + + @Override + public org.apache.dubbo.rpc.Result thenApplyWithContext(Function fn) { + return null; + } + } + + class CompatibleResult extends AbstractResult { private org.apache.dubbo.rpc.Result delegate; public CompatibleResult(org.apache.dubbo.rpc.Result result) { @@ -38,11 +57,21 @@ public Object getValue() { return delegate.getValue(); } + @Override + public void setValue(Object value) { + delegate.setValue(value); + } + @Override public Throwable getException() { return delegate.getException(); } + @Override + public void setException(Throwable t) { + delegate.setException(t); + } + @Override public boolean hasException() { return delegate.hasException(); @@ -53,11 +82,6 @@ public Object recreate() throws Throwable { return delegate.recreate(); } - @Override - public Object getResult() { - return delegate.getResult(); - } - @Override public Map getAttachments() { return delegate.getAttachments(); diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java index bf6160c06ac..28ae5f1757a 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java @@ -29,7 +29,7 @@ private static RpcContext newInstance(org.apache.dubbo.rpc.RpcContext rpcContext RpcContext copy = new RpcContext(); copy.getAttachments().putAll(rpcContext.getAttachments()); copy.get().putAll(rpcContext.get()); - copy.setFuture(rpcContext.getFuture()); + copy.setFuture(rpcContext.getCompletableFuture()); copy.setUrls(rpcContext.getUrls()); copy.setUrl(rpcContext.getUrl()); copy.setMethodName(rpcContext.getMethodName()); diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/support/RpcUtils.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/support/RpcUtils.java index 7f1ab98de5c..d7db04fe106 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/support/RpcUtils.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/support/RpcUtils.java @@ -20,7 +20,6 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.rpc.Invocation; -import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.Map; @@ -74,10 +73,6 @@ public static boolean isReturnTypeFuture(Invocation inv) { return org.apache.dubbo.rpc.support.RpcUtils.isReturnTypeFuture(inv); } - public static boolean hasFutureReturnType(Method method) { - return org.apache.dubbo.rpc.support.RpcUtils.hasFutureReturnType(method); - } - public static boolean isOneway(URL url, Invocation inv) { return org.apache.dubbo.rpc.support.RpcUtils.isOneway(url.getOriginalURL(), inv); } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvoker.java b/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvoker.java index ee1288affff..f77e0a523d0 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvoker.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvoker.java @@ -17,7 +17,7 @@ package org.apache.dubbo.filter; -import org.apache.dubbo.rpc.RpcResult; +import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.service.DemoService; import com.alibaba.dubbo.common.URL; @@ -58,7 +58,7 @@ public boolean isAvailable() { } public Result invoke(Invocation invocation) throws RpcException { - RpcResult result = new RpcResult(); + AppResponse result = new AppResponse(); if (hasException == false) { result.setValue("alibaba"); } else { diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java b/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java index 761ce4b99e7..c088917e51d 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java @@ -63,6 +63,16 @@ public Map getAttachments() { return attachments; } + @Override + public void setAttachment(String key, String value) { + + } + + @Override + public void setAttachmentIfAbsent(String key, String value) { + + } + public Invoker getInvoker() { return null; } diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java index 24fa51cd531..772a16b5789 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java @@ -21,12 +21,12 @@ import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.StringUtils; +import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.RpcResult; import java.io.Serializable; @@ -48,10 +48,10 @@ * 3)<dubbo:provider cache="expiring" /> * 4)<dubbo:consumer cache="jcache" /> * - * If cache type is defined in method level then method level type will get precedence. According to above provided - * example, if service has two method, method1 and method2, method2 will have cache type as threadlocal where others will - * be backed by lru - * + *If cache type is defined in method level then method level type will get precedence. According to above provided + *example, if service has two method, method1 and method2, method2 will have cache type as threadlocal where others will + *be backed by lru + * * * @see org.apache.dubbo.rpc.Filter * @see org.apache.dubbo.cache.support.lru.LruCacheFactory @@ -62,6 +62,7 @@ * @see org.apache.dubbo.cache.support.threadlocal.ThreadLocalCache * @see org.apache.dubbo.cache.support.expiring.ExpiringCacheFactory * @see org.apache.dubbo.cache.support.expiring.ExpiringCache + * */ @Activate(group = {CONSUMER, PROVIDER}, value = CACHE_KEY) public class CacheFilter implements Filter { @@ -83,7 +84,6 @@ public void setCacheFactory(CacheFactory cacheFactory) { * If cache is configured, dubbo will invoke method on each method call. If cache value is returned by cache store * then it will return otherwise call the remote method and return value. If remote method's return valeu has error * then it will not cache the value. - * * @param invoker service * @param invocation invocation. * @return Cache returned value if found by the underlying cache store. If cache miss it will call target method. @@ -98,9 +98,9 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept Object value = cache.get(key); if (value != null) { if (value instanceof ValueWrapper) { - return new RpcResult(((ValueWrapper) value).get()); + return AsyncRpcResult.newDefaultAsyncResult(((ValueWrapper) value).get(), invocation); } else { - return new RpcResult(value); + return AsyncRpcResult.newDefaultAsyncResult(value, invocation); } } Result result = invoker.invoke(invocation); @@ -122,7 +122,7 @@ static class ValueWrapper implements Serializable { private final Object value; - public ValueWrapper(Object value) { + public ValueWrapper (Object value) { this.value = value; } diff --git a/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/filter/CacheFilterTest.java b/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/filter/CacheFilterTest.java index c64647309f0..217919f1d6f 100644 --- a/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/filter/CacheFilterTest.java +++ b/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/filter/CacheFilterTest.java @@ -22,9 +22,10 @@ import org.apache.dubbo.cache.support.lru.LruCacheFactory; import org.apache.dubbo.cache.support.threadlocal.ThreadLocalCacheFactory; import org.apache.dubbo.common.URL; +import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.RpcResult; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; @@ -60,19 +61,19 @@ public void setUp(String cacheType, CacheFactory cacheFactory) { URL url = URL.valueOf("test://test:11/test?cache=" + cacheType); - given(invoker.invoke(invocation)).willReturn(new RpcResult("value")); + given(invoker.invoke(invocation)).willReturn(AsyncRpcResult.newDefaultAsyncResult("value", invocation)); given(invoker.getUrl()).willReturn(url); - given(invoker1.invoke(invocation)).willReturn(new RpcResult("value1")); + given(invoker1.invoke(invocation)).willReturn(AsyncRpcResult.newDefaultAsyncResult("value1", invocation)); given(invoker1.getUrl()).willReturn(url); - given(invoker2.invoke(invocation)).willReturn(new RpcResult("value2")); + given(invoker2.invoke(invocation)).willReturn(AsyncRpcResult.newDefaultAsyncResult("value2", invocation)); given(invoker2.getUrl()).willReturn(url); - given(invoker3.invoke(invocation)).willReturn(new RpcResult(new RuntimeException())); + given(invoker3.invoke(invocation)).willReturn(AsyncRpcResult.newDefaultAsyncResult(new RuntimeException(), invocation)); given(invoker3.getUrl()).willReturn(url); - given(invoker4.invoke(invocation)).willReturn(new RpcResult()); + given(invoker4.invoke(invocation)).willReturn(AsyncRpcResult.newDefaultAsyncResult(invocation)); given(invoker4.getUrl()).willReturn(url); } @@ -85,8 +86,8 @@ public void testNonArgsMethod(String cacheType, CacheFactory cacheFactory) { invocation.setArguments(new Object[]{}); cacheFilter.invoke(invoker, invocation); - RpcResult rpcResult1 = (RpcResult) cacheFilter.invoke(invoker1, invocation); - RpcResult rpcResult2 = (RpcResult) cacheFilter.invoke(invoker2, invocation); + Result rpcResult1 = cacheFilter.invoke(invoker1, invocation); + Result rpcResult2 = cacheFilter.invoke(invoker2, invocation); Assertions.assertEquals(rpcResult1.getValue(), rpcResult2.getValue()); Assertions.assertEquals(rpcResult1.getValue(), "value"); } @@ -100,8 +101,8 @@ public void testMethodWithArgs(String cacheType, CacheFactory cacheFactory) { invocation.setArguments(new Object[]{"arg1"}); cacheFilter.invoke(invoker, invocation); - RpcResult rpcResult1 = (RpcResult) cacheFilter.invoke(invoker1, invocation); - RpcResult rpcResult2 = (RpcResult) cacheFilter.invoke(invoker2, invocation); + Result rpcResult1 = cacheFilter.invoke(invoker1, invocation); + Result rpcResult2 = cacheFilter.invoke(invoker2, invocation); Assertions.assertEquals(rpcResult1.getValue(), rpcResult2.getValue()); Assertions.assertEquals(rpcResult1.getValue(), "value"); } @@ -115,7 +116,7 @@ public void testException(String cacheType, CacheFactory cacheFactory) { invocation.setArguments(new Object[]{"arg2"}); cacheFilter.invoke(invoker3, invocation); - RpcResult rpcResult = (RpcResult) cacheFilter.invoke(invoker2, invocation); + Result rpcResult = cacheFilter.invoke(invoker2, invocation); Assertions.assertEquals(rpcResult.getValue(), "value2"); } @@ -128,9 +129,9 @@ public void testNull(String cacheType, CacheFactory cacheFactory) { invocation.setArguments(new Object[]{"arg3"}); cacheFilter.invoke(invoker4, invocation); - RpcResult rpcResult1 = (RpcResult) cacheFilter.invoke(invoker1, invocation); - RpcResult rpcResult2 = (RpcResult) cacheFilter.invoke(invoker2, invocation); - Assertions.assertEquals(rpcResult1.getValue(), null); - Assertions.assertEquals(rpcResult2.getValue(), null); + Result result1 = cacheFilter.invoke(invoker1, invocation); + Result result2 = cacheFilter.invoke(invoker2, invocation); + Assertions.assertEquals(result1.getValue(), null); + Assertions.assertEquals(result2.getValue(), null); } } diff --git a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java index 5d2551dd149..d2f0539d83a 100644 --- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java +++ b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java @@ -18,12 +18,12 @@ import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.ConfigUtils; +import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.validation.Validation; import org.apache.dubbo.validation.Validator; @@ -90,7 +90,7 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept } catch (RpcException e) { throw e; } catch (Throwable t) { - return new RpcResult(t); + return AsyncRpcResult.newDefaultAsyncResult(t, invocation); } } return invoker.invoke(invocation); diff --git a/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/filter/ValidationFilterTest.java b/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/filter/ValidationFilterTest.java index cade5936402..b757536e9da 100644 --- a/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/filter/ValidationFilterTest.java +++ b/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/filter/ValidationFilterTest.java @@ -17,11 +17,11 @@ package org.apache.dubbo.validation.filter; import org.apache.dubbo.common.URL; +import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.validation.Validation; import org.apache.dubbo.validation.Validator; @@ -52,7 +52,7 @@ public void testItWithNotExistClass() throws Exception { URL url = URL.valueOf("test://test:11/test?default.validation=true"); given(validation.getValidator(url)).willThrow(new IllegalStateException("Not found class test, cause: test")); - given(invoker.invoke(invocation)).willReturn(new RpcResult("success")); + given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); given(invoker.getUrl()).willReturn(url); given(invocation.getMethodName()).willReturn("echo1"); given(invocation.getParameterTypes()).willReturn(new Class[]{String.class}); @@ -70,7 +70,7 @@ public void testItWithExistClass() throws Exception { URL url = URL.valueOf("test://test:11/test?default.validation=true"); given(validation.getValidator(url)).willReturn(validator); - given(invoker.invoke(invocation)).willReturn(new RpcResult("success")); + given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); given(invoker.getUrl()).willReturn(url); given(invocation.getMethodName()).willReturn("echo1"); given(invocation.getParameterTypes()).willReturn(new Class[]{String.class}); @@ -87,7 +87,7 @@ public void testItWithoutUrlParameters() throws Exception { URL url = URL.valueOf("test://test:11/test"); given(validation.getValidator(url)).willReturn(validator); - given(invoker.invoke(invocation)).willReturn(new RpcResult("success")); + given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); given(invoker.getUrl()).willReturn(url); given(invocation.getMethodName()).willReturn("echo1"); given(invocation.getParameterTypes()).willReturn(new Class[]{String.class}); @@ -104,7 +104,7 @@ public void testItWhileMethodNameStartWithDollar() throws Exception { URL url = URL.valueOf("test://test:11/test"); given(validation.getValidator(url)).willReturn(validator); - given(invoker.invoke(invocation)).willReturn(new RpcResult("success")); + given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); given(invoker.getUrl()).willReturn(url); given(invocation.getMethodName()).willReturn("$echo1"); given(invocation.getParameterTypes()).willReturn(new Class[]{String.class}); @@ -124,7 +124,7 @@ public void testItWhileThrowoutRpcException() throws Exception { URL url = URL.valueOf("test://test:11/test?default.validation=true"); given(validation.getValidator(url)).willThrow(new RpcException("rpc exception")); - given(invoker.invoke(invocation)).willReturn(new RpcResult("success")); + given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); given(invoker.getUrl()).willReturn(url); given(invocation.getMethodName()).willReturn("echo1"); given(invocation.getParameterTypes()).willReturn(new Class[]{String.class}); diff --git a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MonitorService.java b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MonitorService.java index 2221089426c..7e606a53b94 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MonitorService.java +++ b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MonitorService.java @@ -88,4 +88,5 @@ public interface MonitorService { */ List lookup(URL query); + } \ No newline at end of file diff --git a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java index ef498063dbd..8c1f19a2892 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java +++ b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java @@ -24,9 +24,9 @@ import org.apache.dubbo.monitor.Monitor; import org.apache.dubbo.monitor.MonitorFactory; import org.apache.dubbo.monitor.MonitorService; -import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.ListenableFilter; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; @@ -52,10 +52,14 @@ * MonitorFilter. (SPI, Singleton, ThreadSafe) */ @Activate(group = {PROVIDER, CONSUMER}) -public class MonitorFilter implements Filter { +public class MonitorFilter extends ListenableFilter { private static final Logger logger = LoggerFactory.getLogger(MonitorFilter.class); + private static final String MONITOR_FILTER_START_TIME = "monitor_filter_start_time"; + public MonitorFilter() { + super.listener = new MonitorListener(); + } /** * The Concurrent counter */ @@ -70,6 +74,7 @@ public void setMonitorFactory(MonitorFactory monitorFactory) { this.monitorFactory = monitorFactory; } + /** * The invocation interceptor,it will collect the invoke data about this invocation and send it to monitor center * @@ -81,105 +86,10 @@ public void setMonitorFactory(MonitorFactory monitorFactory) { @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { if (invoker.getUrl().hasParameter(MONITOR_KEY)) { - RpcContext context = RpcContext.getContext(); // provider must fetch context before invoke() gets called - String remoteHost = context.getRemoteHost(); - long start = System.currentTimeMillis(); // record start timestamp + invocation.setAttachment(MONITOR_FILTER_START_TIME, String.valueOf(System.currentTimeMillis())); getConcurrent(invoker, invocation).incrementAndGet(); // count up - try { - Result result = invoker.invoke(invocation); // proceed invocation chain - collect(invoker, invocation, result, remoteHost, start, false); - return result; - } catch (RpcException e) { - collect(invoker, invocation, null, remoteHost, start, true); - throw e; - } finally { - getConcurrent(invoker, invocation).decrementAndGet(); // count down - } - } else { - return invoker.invoke(invocation); - } - } - - /** - * The collector logic, it will be handled by the default monitor - * - * @param invoker - * @param invocation - * @param result the invoke result - * @param remoteHost the remote host address - * @param start the timestamp the invoke begin - * @param error if there is an error on the invoke - */ - private void collect(Invoker invoker, Invocation invocation, Result result, String remoteHost, long start, boolean error) { - try { - URL monitorUrl = invoker.getUrl().getUrlParameter(MONITOR_KEY); - Monitor monitor = monitorFactory.getMonitor(monitorUrl); - if (monitor == null) { - return; - } - URL statisticsURL = createStatisticsUrl(invoker, invocation, result, remoteHost, start, error); - monitor.collect(statisticsURL); - } catch (Throwable t) { - logger.warn("Failed to monitor count service " + invoker.getUrl() + ", cause: " + t.getMessage(), t); } - } - - /** - * Create statistics url - * - * @param invoker - * @param invocation - * @param result - * @param remoteHost - * @param start - * @param error - * @return - */ - private URL createStatisticsUrl(Invoker invoker, Invocation invocation, Result result, String remoteHost, long start, boolean error) { - // ---- service statistics ---- - long elapsed = System.currentTimeMillis() - start; // invocation cost - int concurrent = getConcurrent(invoker, invocation).get(); // current concurrent count - String application = invoker.getUrl().getParameter(APPLICATION_KEY); - String service = invoker.getInterface().getName(); // service name - String method = RpcUtils.getMethodName(invocation); // method name - String group = invoker.getUrl().getParameter(GROUP_KEY); - String version = invoker.getUrl().getParameter(VERSION_KEY); - - int localPort; - String remoteKey, remoteValue; - if (CONSUMER_SIDE.equals(invoker.getUrl().getParameter(SIDE_KEY))) { - // ---- for service consumer ---- - localPort = 0; - remoteKey = MonitorService.PROVIDER; - remoteValue = invoker.getUrl().getAddress(); - } else { - // ---- for service provider ---- - localPort = invoker.getUrl().getPort(); - remoteKey = MonitorService.CONSUMER; - remoteValue = remoteHost; - } - String input = "", output = ""; - if (invocation.getAttachment(INPUT_KEY) != null) { - input = invocation.getAttachment(INPUT_KEY); - } - if (result != null && result.getAttachment(OUTPUT_KEY) != null) { - output = result.getAttachment(OUTPUT_KEY); - } - - return new URL(COUNT_PROTOCOL, - NetUtils.getLocalHost(), localPort, - service + PATH_SEPARATOR + method, - MonitorService.APPLICATION, application, - MonitorService.INTERFACE, service, - MonitorService.METHOD, method, - remoteKey, remoteValue, - error ? MonitorService.FAILURE : MonitorService.SUCCESS, "1", - MonitorService.ELAPSED, String.valueOf(elapsed), - MonitorService.CONCURRENT, String.valueOf(concurrent), - INPUT_KEY, input, - OUTPUT_KEY, output, - GROUP_KEY, group, - VERSION_KEY, version); + return invoker.invoke(invocation); // proceed invocation chain } // concurrent counter @@ -193,4 +103,93 @@ private AtomicInteger getConcurrent(Invoker invoker, Invocation invocation) { return concurrent; } + class MonitorListener implements Listener { + + @Override + public void onResponse(Result result, Invoker invoker, Invocation invocation) { + if (invoker.getUrl().hasParameter(MONITOR_KEY)) { + collect(invoker, invocation, result, RpcContext.getContext().getRemoteHost(), Long.valueOf(invocation.getAttachment(MONITOR_FILTER_START_TIME)), false); + getConcurrent(invoker, invocation).decrementAndGet(); // count down + } + } + + @Override + public void onError(Throwable t, Invoker invoker, Invocation invocation) { + if (invoker.getUrl().hasParameter(MONITOR_KEY)) { + collect(invoker, invocation, null, RpcContext.getContext().getRemoteHost(), Long.valueOf(invocation.getAttachment(MONITOR_FILTER_START_TIME)), true); + getConcurrent(invoker, invocation).decrementAndGet(); // count down + } + } + + /** + * The collector logic, it will be handled by the default monitor + * + * @param invoker + * @param invocation + * @param result the invoke result + * @param remoteHost the remote host address + * @param start the timestamp the invoke begin + * @param error if there is an error on the invoke + */ + private void collect(Invoker invoker, Invocation invocation, Result result, String remoteHost, long start, boolean error) { + try { + URL monitorUrl = invoker.getUrl().getUrlParameter(MONITOR_KEY); + Monitor monitor = monitorFactory.getMonitor(monitorUrl); + if (monitor == null) { + return; + } + URL statisticsURL = createStatisticsUrl(invoker, invocation, result, remoteHost, start, error); + monitor.collect(statisticsURL); + } catch (Throwable t) { + logger.warn("Failed to monitor count service " + invoker.getUrl() + ", cause: " + t.getMessage(), t); + } + } + + /** + * Create statistics url + * + * @param invoker + * @param invocation + * @param result + * @param remoteHost + * @param start + * @param error + * @return + */ + private URL createStatisticsUrl(Invoker invoker, Invocation invocation, Result result, String remoteHost, long start, boolean error) { + // ---- service statistics ---- + long elapsed = System.currentTimeMillis() - start; // invocation cost + int concurrent = getConcurrent(invoker, invocation).get(); // current concurrent count + String application = invoker.getUrl().getParameter(APPLICATION_KEY); + String service = invoker.getInterface().getName(); // service name + String method = RpcUtils.getMethodName(invocation); // method name + String group = invoker.getUrl().getParameter(GROUP_KEY); + String version = invoker.getUrl().getParameter(VERSION_KEY); + + int localPort; + String remoteKey, remoteValue; + if (CONSUMER_SIDE.equals(invoker.getUrl().getParameter(SIDE_KEY))) { + // ---- for service consumer ---- + localPort = 0; + remoteKey = MonitorService.PROVIDER; + remoteValue = invoker.getUrl().getAddress(); + } else { + // ---- for service provider ---- + localPort = invoker.getUrl().getPort(); + remoteKey = MonitorService.CONSUMER; + remoteValue = remoteHost; + } + String input = "", output = ""; + if (invocation.getAttachment(INPUT_KEY) != null) { + input = invocation.getAttachment(INPUT_KEY); + } + if (result != null && result.getAttachment(OUTPUT_KEY) != null) { + output = result.getAttachment(OUTPUT_KEY); + } + + return new URL(COUNT_PROTOCOL, NetUtils.getLocalHost(), localPort, service + PATH_SEPARATOR + method, MonitorService.APPLICATION, application, MonitorService.INTERFACE, service, MonitorService.METHOD, method, remoteKey, remoteValue, error ? MonitorService.FAILURE : MonitorService.SUCCESS, "1", MonitorService.ELAPSED, String.valueOf(elapsed), MonitorService.CONCURRENT, String.valueOf(concurrent), INPUT_KEY, input, OUTPUT_KEY, output, GROUP_KEY, group, VERSION_KEY, version); + } + + } + } diff --git a/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java b/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java index 586ea60d10d..56d372c1d2b 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java +++ b/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java @@ -21,6 +21,7 @@ import org.apache.dubbo.monitor.Monitor; import org.apache.dubbo.monitor.MonitorFactory; import org.apache.dubbo.monitor.MonitorService; +import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; @@ -77,7 +78,7 @@ public boolean isAvailable() { public Result invoke(Invocation invocation) throws RpcException { lastInvocation = invocation; - return null; + return AsyncRpcResult.newDefaultAsyncResult(invocation); } @Override @@ -119,7 +120,11 @@ public void testFilter() throws Exception { monitorFilter.setMonitorFactory(monitorFactory); Invocation invocation = new RpcInvocation("aaa", new Class[0], new Object[0]); RpcContext.getContext().setRemoteAddress(NetUtils.getLocalHost(), 20880).setLocalAddress(NetUtils.getLocalHost(), 2345); - monitorFilter.invoke(serviceInvoker, invocation); + Result result = monitorFilter.invoke(serviceInvoker, invocation); + result.thenApplyWithContext((r) -> { + monitorFilter.listener().onResponse(r, serviceInvoker, invocation); + return r; + }); while (lastStatistics == null) { Thread.sleep(10); } @@ -155,7 +160,11 @@ public void testGenericFilter() throws Exception { monitorFilter.setMonitorFactory(monitorFactory); Invocation invocation = new RpcInvocation("$invoke", new Class[]{String.class, String[].class, Object[].class}, new Object[]{"xxx", new String[]{}, new Object[]{}}); RpcContext.getContext().setRemoteAddress(NetUtils.getLocalHost(), 20880).setLocalAddress(NetUtils.getLocalHost(), 2345); - monitorFilter.invoke(serviceInvoker, invocation); + Result result = monitorFilter.invoke(serviceInvoker, invocation); + result.thenApplyWithContext((r) -> { + monitorFilter.listener().onResponse(r, serviceInvoker, invocation); + return r; + }); while (lastStatistics == null) { Thread.sleep(10); } diff --git a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java index fa16ae2f574..761de5945dc 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java +++ b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java @@ -23,7 +23,7 @@ import org.apache.dubbo.common.store.DataStore; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.monitor.MetricsService; -import org.apache.dubbo.remoting.Constants; +import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -31,7 +31,6 @@ import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.support.RpcUtils; import com.alibaba.fastjson.JSON; @@ -66,6 +65,7 @@ import static org.apache.dubbo.monitor.Constants.METRICS_PORT; import static org.apache.dubbo.monitor.Constants.METRICS_PROTOCOL; import static org.apache.dubbo.monitor.Constants.SERVICE; +import static org.apache.dubbo.remoting.Constants.EXECUTOR_SERVICE_COMPONENT_KEY; public class MetricsFilter implements Filter { @@ -178,7 +178,7 @@ private void setCompassQuantity(String groupName, String result, long duration, private List getThreadPoolMessage() { DataStore dataStore = ExtensionLoader.getExtensionLoader(DataStore.class).getDefaultExtension(); - Map executors = dataStore.get(Constants.EXECUTOR_SERVICE_COMPONENT_KEY); + Map executors = dataStore.get(EXECUTOR_SERVICE_COMPONENT_KEY); List threadPoolMtricList = new ArrayList<>(); for (Map.Entry entry : executors.entrySet()) { @@ -235,12 +235,9 @@ public Result invoke(Invocation invocation) throws RpcException { collector.collect(entry.getKey(), entry.getValue(), timestamp); } - RpcResult result = new RpcResult(); - List res = collector.build(); res.addAll(getThreadPoolMessage()); - result.setValue(JSON.toJSONString(res)); - return result; + return AsyncRpcResult.newDefaultAsyncResult(JSON.toJSONString(res), invocation); } @Override diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/MockChannel.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/MockChannel.java index fa061b99696..7a4961bf954 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/MockChannel.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/MockChannel.java @@ -21,9 +21,9 @@ import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeHandler; -import org.apache.dubbo.remoting.exchange.ResponseFuture; import java.net.InetSocketAddress; +import java.util.concurrent.CompletableFuture; public class MockChannel implements ExchangeChannel { @@ -76,7 +76,7 @@ public URL getUrl() { return null; } - public ResponseFuture send(Object request, int timeout) throws RemotingException { + public CompletableFuture send(Object request, int timeout) throws RemotingException { return null; } @@ -85,11 +85,11 @@ public ChannelHandler getChannelHandler() { return null; } - public ResponseFuture request(Object request) throws RemotingException { + public CompletableFuture request(Object request) throws RemotingException { return null; } - public ResponseFuture request(Object request, int timeout) throws RemotingException { + public CompletableFuture request(Object request, int timeout) throws RemotingException { return null; } diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/MockedClient.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/MockedClient.java index f1341ef71f8..1afe0d550c8 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/MockedClient.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/MockedClient.java @@ -23,12 +23,13 @@ import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.remoting.exchange.ExchangeHandler; -import org.apache.dubbo.remoting.exchange.ResponseCallback; -import org.apache.dubbo.remoting.exchange.ResponseFuture; import org.apache.dubbo.remoting.exchange.support.Replier; import java.net.InetSocketAddress; import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; /** * MockedClient @@ -79,27 +80,24 @@ public void send(Object msg) throws RemotingException { this.sent = msg; } - public ResponseFuture request(Object msg) throws RemotingException { + public CompletableFuture request(Object msg) throws RemotingException { return request(msg, 0); } - public ResponseFuture request(Object msg, int timeout) throws RemotingException { + public CompletableFuture request(Object msg, int timeout) throws RemotingException { this.invoked = msg; - return new ResponseFuture() { - public Object get() throws RemotingException { + return new CompletableFuture() { + public Object get() throws InterruptedException, ExecutionException { return received; } - public Object get(int timeoutInMillis) throws RemotingException { + public Object get(int timeoutInMillis) throws InterruptedException, ExecutionException, TimeoutException { return received; } public boolean isDone() { return true; } - - public void setCallback(ResponseCallback callback) { - } }; } diff --git a/dubbo-registry/dubbo-registry-sofa/pom.xml b/dubbo-registry/dubbo-registry-sofa/pom.xml index 7a2415fc216..9faccea3868 100644 --- a/dubbo-registry/dubbo-registry-sofa/pom.xml +++ b/dubbo-registry/dubbo-registry-sofa/pom.xml @@ -32,7 +32,7 @@ 2.1 -Dnetwork_interface_denylist=docker0 - + org.apache.dubbo diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/RemotingException.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/RemotingException.java index fb288bb9643..1bbd4c25473 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/RemotingException.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/RemotingException.java @@ -22,8 +22,7 @@ * RemotingException. (API, Prototype, ThreadSafe) * * @export - * @see org.apache.dubbo.remoting.exchange.ResponseFuture#get() - * @see org.apache.dubbo.remoting.exchange.ResponseFuture#get(int) + * @see org.apache.dubbo.remoting.exchange.support.DefaultFuture#get() * @see org.apache.dubbo.remoting.Channel#send(Object, boolean) * @see org.apache.dubbo.remoting.exchange.ExchangeChannel#request(Object) * @see org.apache.dubbo.remoting.exchange.ExchangeChannel#request(Object, int) diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/TimeoutException.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/TimeoutException.java index 464452e1afe..a14371645fa 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/TimeoutException.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/TimeoutException.java @@ -22,8 +22,7 @@ * TimeoutException. (API, Prototype, ThreadSafe) * * @export - * @see org.apache.dubbo.remoting.exchange.ResponseFuture#get() - * @see org.apache.dubbo.remoting.exchange.ResponseFuture#get(int) + * @see org.apache.dubbo.remoting.exchange.support.DefaultFuture#get() */ public class TimeoutException extends RemotingException { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ExchangeChannel.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ExchangeChannel.java index 3922626fdfb..0e4917d200f 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ExchangeChannel.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ExchangeChannel.java @@ -19,6 +19,8 @@ import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.RemotingException; +import java.util.concurrent.CompletableFuture; + /** * ExchangeChannel. (API/SPI, Prototype, ThreadSafe) */ @@ -31,7 +33,7 @@ public interface ExchangeChannel extends Channel { * @return response future * @throws RemotingException */ - ResponseFuture request(Object request) throws RemotingException; + CompletableFuture request(Object request) throws RemotingException; /** * send request. @@ -41,7 +43,7 @@ public interface ExchangeChannel extends Channel { * @return response future * @throws RemotingException */ - ResponseFuture request(Object request, int timeout) throws RemotingException; + CompletableFuture request(Object request, int timeout) throws RemotingException; /** * get message handler. diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ResponseCallback.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ResponseCallback.java deleted file mode 100644 index 37fe6cc6e34..00000000000 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ResponseCallback.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.remoting.exchange; - -/** - * Callback - */ -public interface ResponseCallback { - - /** - * done. - * - * @param response - */ - void done(Object response); - - /** - * caught exception. - * - * @param exception - */ - void caught(Throwable exception); - -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ResponseFuture.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ResponseFuture.java deleted file mode 100644 index 9e641dd3579..00000000000 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ResponseFuture.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.remoting.exchange; - -import org.apache.dubbo.remoting.RemotingException; - -/** - * Future. (API/SPI, Prototype, ThreadSafe) - * - * @see org.apache.dubbo.remoting.exchange.ExchangeChannel#request(Object) - * @see org.apache.dubbo.remoting.exchange.ExchangeChannel#request(Object, int) - */ -public interface ResponseFuture { - - /** - * get result. - * - * @return result. - */ - Object get() throws RemotingException; - - /** - * get result with the specified timeout. - * - * @param timeoutInMillis timeout. - * @return result. - */ - Object get(int timeoutInMillis) throws RemotingException; - - /** - * set callback. - * - * @param callback - */ - void setCallback(ResponseCallback callback); - - /** - * check is done. - * - * @return done or not. - */ - boolean isDone(); - -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture.java index 7a860a396fd..1dab931a9c4 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture.java @@ -28,17 +28,13 @@ import org.apache.dubbo.remoting.TimeoutException; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; -import org.apache.dubbo.remoting.exchange.ResponseCallback; -import org.apache.dubbo.remoting.exchange.ResponseFuture; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; @@ -46,7 +42,7 @@ /** * DefaultFuture. */ -public class DefaultFuture implements ResponseFuture { +public class DefaultFuture extends CompletableFuture { private static final Logger logger = LoggerFactory.getLogger(DefaultFuture.class); @@ -66,12 +62,8 @@ public class DefaultFuture implements ResponseFuture { private final Channel channel; private final Request request; private final int timeout; - private final Lock lock = new ReentrantLock(); - private final Condition done = lock.newCondition(); private final long start = System.currentTimeMillis(); private volatile long sent; - private volatile Response response; - private volatile ResponseCallback callback; private DefaultFuture(Channel channel, Request request, int timeout) { this.channel = channel; @@ -170,144 +162,34 @@ public static void received(Channel channel, Response response) { } @Override - public Object get() throws RemotingException { - return get(timeout); - } - - @Override - public Object get(int timeout) throws RemotingException { - if (timeout <= 0) { - timeout = DEFAULT_TIMEOUT; - } - if (!isDone()) { - long start = System.currentTimeMillis(); - lock.lock(); - try { - while (!isDone()) { - done.await(timeout, TimeUnit.MILLISECONDS); - if (isDone() || System.currentTimeMillis() - start > timeout) { - break; - } - } - } catch (InterruptedException e) { - throw new RuntimeException(e); - } finally { - lock.unlock(); - } - if (!isDone()) { - throw new TimeoutException(sent > 0, channel, getTimeoutMessage(false)); - } - } - return returnFromResponse(); - } - - public void cancel() { + public boolean cancel(boolean mayInterruptIfRunning) { Response errorResult = new Response(id); + errorResult.setStatus(Response.CLIENT_ERROR); errorResult.setErrorMessage("request future has been canceled."); - response = errorResult; + this.doReceived(errorResult); FUTURES.remove(id); CHANNELS.remove(id); + return true; } - @Override - public boolean isDone() { - return response != null; - } - - @Override - public void setCallback(ResponseCallback callback) { - if (isDone()) { - invokeCallback(callback); - } else { - boolean isdone = false; - lock.lock(); - try { - if (!isDone()) { - this.callback = callback; - } else { - isdone = true; - } - } finally { - lock.unlock(); - } - if (isdone) { - invokeCallback(callback); - } - } + public void cancel() { + this.cancel(true); } - private static class TimeoutCheckTask implements TimerTask { - private DefaultFuture future; - - TimeoutCheckTask(DefaultFuture future) { - this.future = future; - } - - @Override - public void run(Timeout timeout) { - // remove from pending task - PENDING_TASKS.remove(future.getId()); - - if (future.isDone()) { - return; - } - // create exception response. - Response timeoutResponse = new Response(future.getId()); - // set timeout status. - timeoutResponse.setStatus(future.isSent() ? Response.SERVER_TIMEOUT : Response.CLIENT_TIMEOUT); - timeoutResponse.setErrorMessage(future.getTimeoutMessage(true)); - // handle response. - DefaultFuture.received(future.getChannel(), timeoutResponse); - } - } - - private void invokeCallback(ResponseCallback c) { - if (c == null) { - throw new NullPointerException("callback cannot be null."); - } - Response res = response; + private void doReceived(Response res) { if (res == null) { - throw new IllegalStateException("response cannot be null. url:" + channel.getUrl()); + throw new IllegalStateException("response cannot be null"); } - if (res.getStatus() == Response.OK) { - try { - c.done(res.getResult()); - } catch (Exception e) { - logger.error("callback invoke error .result:" + res.getResult() + ",url:" + channel.getUrl(), e); - } + this.complete(res.getResult()); } else if (res.getStatus() == Response.CLIENT_TIMEOUT || res.getStatus() == Response.SERVER_TIMEOUT) { - try { - TimeoutException te = new TimeoutException(res.getStatus() == Response.SERVER_TIMEOUT, channel, res.getErrorMessage()); - c.caught(te); - } catch (Exception e) { - logger.error("callback invoke error ,url:" + channel.getUrl(), e); - } + this.completeExceptionally(new TimeoutException(res.getStatus() == Response.SERVER_TIMEOUT, channel, res.getErrorMessage())); } else { - try { - RuntimeException re = new RuntimeException(res.getErrorMessage()); - c.caught(re); - } catch (Exception e) { - logger.error("callback invoke error ,url:" + channel.getUrl(), e); - } + this.completeExceptionally(new RemotingException(channel, res.getErrorMessage())); } } - private Object returnFromResponse() throws RemotingException { - Response res = response; - if (res == null) { - throw new IllegalStateException("response cannot be null"); - } - if (res.getStatus() == Response.OK) { - return res.getResult(); - } - if (res.getStatus() == Response.CLIENT_TIMEOUT || res.getStatus() == Response.SERVER_TIMEOUT) { - throw new TimeoutException(res.getStatus() == Response.SERVER_TIMEOUT, channel, res.getErrorMessage()); - } - throw new RemotingException(channel, res.getErrorMessage()); - } - private long getId() { return id; } @@ -328,27 +210,10 @@ private int getTimeout() { return timeout; } - private long getStartTimestamp() { - return start; - } - private void doSent() { sent = System.currentTimeMillis(); } - private void doReceived(Response res) { - lock.lock(); - try { - response = res; - done.signalAll(); - } finally { - lock.unlock(); - } - if (callback != null) { - invokeCallback(callback); - } - } - private String getTimeoutMessage(boolean scan) { long nowTimestamp = System.currentTimeMillis(); return (sent > 0 ? "Waiting server-side response timeout" : "Sending request timeout in client-side") @@ -361,4 +226,28 @@ private String getTimeoutMessage(boolean scan) { + timeout + " ms, request: " + request + ", channel: " + channel.getLocalAddress() + " -> " + channel.getRemoteAddress(); } + + private static class TimeoutCheckTask implements TimerTask { + + private DefaultFuture future; + + TimeoutCheckTask(DefaultFuture future) { + this.future = future; + } + + @Override + public void run(Timeout timeout) { + if (future == null || future.isDone()) { + return; + } + // create exception response. + Response timeoutResponse = new Response(future.getId()); + // set timeout status. + timeoutResponse.setStatus(future.isSent() ? Response.SERVER_TIMEOUT : Response.CLIENT_TIMEOUT); + timeoutResponse.setErrorMessage(future.getTimeoutMessage(true)); + // handle response. + DefaultFuture.received(future.getChannel(), timeoutResponse); + + } + } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/SimpleFuture.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/SimpleFuture.java deleted file mode 100644 index 95b95f4ce2f..00000000000 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/SimpleFuture.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.remoting.exchange.support; - -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.exchange.ResponseCallback; -import org.apache.dubbo.remoting.exchange.ResponseFuture; - -/** - * SimpleFuture - */ -public class SimpleFuture implements ResponseFuture { - - private final Object value; - - public SimpleFuture(Object value) { - this.value = value; - } - - @Override - public Object get() throws RemotingException { - return value; - } - - @Override - public Object get(int timeoutInMillis) throws RemotingException { - return value; - } - - @Override - public void setCallback(ResponseCallback callback) { - callback.done(value); - } - - @Override - public boolean isDone() { - return true; - } - -} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java index f9193de3e41..2529ac7e480 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java @@ -27,10 +27,10 @@ import org.apache.dubbo.remoting.exchange.ExchangeHandler; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; -import org.apache.dubbo.remoting.exchange.ResponseFuture; import org.apache.dubbo.remoting.exchange.support.DefaultFuture; import java.net.InetSocketAddress; +import java.util.concurrent.CompletableFuture; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; @@ -99,12 +99,12 @@ public void send(Object message, boolean sent) throws RemotingException { } @Override - public ResponseFuture request(Object request) throws RemotingException { + public CompletableFuture request(Object request) throws RemotingException { return request(request, channel.getUrl().getPositiveParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT)); } @Override - public ResponseFuture request(Object request, int timeout) throws RemotingException { + public CompletableFuture request(Object request, int timeout) throws RemotingException { if (closed) { throw new RemotingException(this.getLocalAddress(), null, "Failed to send request " + request + ", cause: The channel " + this + " is closed!"); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java index 8bd5665ad7a..72348e927d9 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java @@ -27,10 +27,10 @@ import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.remoting.exchange.ExchangeHandler; -import org.apache.dubbo.remoting.exchange.ResponseFuture; import java.net.InetSocketAddress; import java.util.Collections; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.utils.UrlUtils.getHeartbeat; @@ -65,7 +65,7 @@ public HeaderExchangeClient(Client client, boolean startTimer) { } @Override - public ResponseFuture request(Object request) throws RemotingException { + public CompletableFuture request(Object request) throws RemotingException { return channel.request(request); } @@ -80,7 +80,7 @@ public InetSocketAddress getRemoteAddress() { } @Override - public ResponseFuture request(Object request, int timeout) throws RemotingException { + public CompletableFuture request(Object request, int timeout) throws RemotingException { return channel.request(request, timeout); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java index 327eb7e3d22..220d5d78c83 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java @@ -34,7 +34,7 @@ import org.apache.dubbo.remoting.transport.ChannelHandlerDelegate; import java.net.InetSocketAddress; -import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; /** @@ -99,19 +99,12 @@ void handleRequest(final ExchangeChannel channel, Request req) throws RemotingEx // find handler by message class. Object msg = req.getData(); try { - // handle data. - CompletableFuture future = handler.reply(channel, msg); - if (future.isDone()) { - res.setStatus(Response.OK); - res.setResult(future.get()); - channel.send(res); - return; - } - future.whenComplete((result, t) -> { + CompletionStage future = handler.reply(channel, msg); + future.whenComplete((appResult, t) -> { try { if (t == null) { res.setStatus(Response.OK); - res.setResult(result); + res.setResult(appResult); } else { res.setStatus(Response.SERVICE_ERROR); res.setErrorMessage(StringUtils.toString(t)); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/Main.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/Main.java index 566bda10d8e..4478f86ecfd 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/Main.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/Main.java @@ -19,12 +19,12 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.Exchangers; -import org.apache.dubbo.remoting.exchange.ResponseFuture; import org.apache.dubbo.remoting.exchange.support.Replier; import org.apache.dubbo.remoting.exchange.support.ReplierDispatcher; import java.io.Serializable; import java.util.Random; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.Executors; @@ -94,7 +94,7 @@ private static void test(int port) throws Exception { System.out.println("=====test invoke====="); for (int i = 0; i < 100; i++) { - ResponseFuture future = client.request(new Main.Data()); + CompletableFuture future = client.request(new Main.Data()); System.out.println("invoke and get"); System.out.println("invoke result:" + future.get()); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/MockResult.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/MockResult.java index 78369527efc..c353621056a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/MockResult.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/MockResult.java @@ -19,7 +19,7 @@ import java.io.Serializable; /** - * RpcResult. + * AppResponse. */ public class MockResult implements Serializable { diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/DefaultFutureTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/DefaultFutureTest.java index 1ab41243dd4..2dd400545a4 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/DefaultFutureTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/DefaultFutureTest.java @@ -74,7 +74,7 @@ public void timeoutNotSend() throws Exception { try { f.get(); } catch (Exception e) { - Assertions.assertTrue(e instanceof TimeoutException, "catch exception is not timeout exception!"); + Assertions.assertTrue(e.getCause() instanceof TimeoutException, "catch exception is not timeout exception!"); System.out.println(e.getMessage()); } } @@ -108,7 +108,7 @@ public void timeoutSend() throws Exception { try { f.get(); } catch (Exception e) { - Assertions.assertTrue(e instanceof TimeoutException, "catch exception is not timeout exception!"); + Assertions.assertTrue(e.getCause() instanceof TimeoutException, "catch exception is not timeout exception!"); System.out.println(e.getMessage()); } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/HeaderExchangeHandlerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/HeaderExchangeHandlerTest.java index 1b58bf78a23..ca26a647f34 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/HeaderExchangeHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/HeaderExchangeHandlerTest.java @@ -178,7 +178,7 @@ public void send(Object message) throws RemotingException { HeaderExchangeHandler hexhandler = new HeaderExchangeHandler(new MockedExchangeHandler() { @Override - public CompletableFuture reply(ExchangeChannel channel, Object request) throws RemotingException { + public CompletableFuture reply(ExchangeChannel channel, Object request) throws RemotingException { Assertions.fail(); throw new RemotingException(channel, ""); } diff --git a/dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/ClientToServerTest.java b/dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/ClientToServerTest.java index 987139275d5..6414434f51d 100644 --- a/dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/ClientToServerTest.java +++ b/dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/ClientToServerTest.java @@ -19,7 +19,6 @@ import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeServer; -import org.apache.dubbo.remoting.exchange.ResponseFuture; import org.apache.dubbo.remoting.exchange.support.Replier; import org.junit.jupiter.api.AfterEach; @@ -27,6 +26,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.util.concurrent.CompletableFuture; + /** * ClientToServer */ @@ -64,7 +65,7 @@ protected void tearDown() { @Test public void testFuture() throws Exception { - ResponseFuture future = client.request(new World("world")); + CompletableFuture future = client.request(new World("world")); Hello result = (Hello) future.get(); Assertions.assertEquals("hello,world", result.getName()); } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java index 8a2cb256ef7..52bed1e0f5e 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java @@ -30,6 +30,7 @@ import org.apache.dubbo.remoting.exchange.ExchangeServer; import org.apache.dubbo.remoting.exchange.Exchangers; import org.apache.dubbo.remoting.transport.dispatcher.FakeChannelHandlers; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientToServerTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientToServerTest.java index 03466bed688..267f5694065 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientToServerTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientToServerTest.java @@ -19,14 +19,14 @@ import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeServer; -import org.apache.dubbo.remoting.exchange.ResponseFuture; import org.apache.dubbo.remoting.exchange.support.Replier; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.util.concurrent.CompletableFuture; + /** * ClientToServer */ @@ -64,7 +64,7 @@ protected void tearDown() throws Exception { @Test public void testFuture() throws Exception { - ResponseFuture future = client.request(new World("world")); + CompletableFuture future = client.request(new World("world")); Hello result = (Hello) future.get(); Assertions.assertEquals("hello,world", result.getName()); } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientToServerTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientToServerTest.java index 9d2311fa5ff..9b8db0027c2 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientToServerTest.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientToServerTest.java @@ -19,7 +19,6 @@ import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeServer; -import org.apache.dubbo.remoting.exchange.ResponseFuture; import org.apache.dubbo.remoting.exchange.support.Replier; import org.junit.jupiter.api.AfterEach; @@ -27,6 +26,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.util.concurrent.CompletableFuture; + /** * ClientToServer */ @@ -64,7 +65,7 @@ protected void tearDown() { @Test public void testFuture() throws Exception { - ResponseFuture future = client.request(new World("world")); + CompletableFuture future = client.request(new World("world")); Hello result = (Hello) future.get(); Assertions.assertEquals("hello,world", result.getName()); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AbstractResult.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AbstractResult.java index b898934c63c..2db743d5716 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AbstractResult.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AbstractResult.java @@ -16,59 +16,10 @@ */ package org.apache.dubbo.rpc; -import org.apache.dubbo.common.utils.StringUtils; - -import java.util.HashMap; -import java.util.Map; +import java.util.concurrent.CompletableFuture; /** * */ -public abstract class AbstractResult implements Result { - protected Map attachments = new HashMap(); - - protected Object result; - - protected Throwable exception; - - @Override - public Map getAttachments() { - return attachments; - } - - @Override - public void setAttachments(Map map) { - this.attachments = map == null ? new HashMap() : map; - } - - @Override - public void addAttachments(Map map) { - if (map == null) { - return; - } - if (this.attachments == null) { - this.attachments = new HashMap(); - } - this.attachments.putAll(map); - } - - @Override - public String getAttachment(String key) { - return attachments.get(key); - } - - @Override - public String getAttachment(String key, String defaultValue) { - String result = attachments.get(key); - if (StringUtils.isEmpty(result)) { - result = defaultValue; - } - return result; - } - - @Override - public void setAttachment(String key, String value) { - attachments.put(key, value); - } - +public abstract class AbstractResult extends CompletableFuture implements Result { } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AppResponse.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AppResponse.java new file mode 100644 index 00000000000..16e938095a5 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AppResponse.java @@ -0,0 +1,146 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.rpc; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; + +/** + * {@link AsyncRpcResult} is introduced in 3.0.0 to replace RpcResult, and RpcResult is replaced with {@link AppResponse}: + *
      + *
    • AsyncRpcResult is the object that is actually passed in the call chain
    • + *
    • AppResponse only simply represents the business result
    • + *
    + * + * The relationship between them can be described as follow, an abstraction of the definition of AsyncRpcResult: + *
    + *  {@code
    + *   Public class AsyncRpcResult implements CompletionStage {
    + *       ......
    + *  }
    + * 
    + * AsyncRpcResult is a future representing an unfinished RPC call, while AppResponse is the actual return type of this call. + * In theory, AppResponse does'n have to implement the {@link Result} interface, this is done mainly for compatibility purpose. + * + * @serial Do not change the class name and properties. + */ +public class AppResponse extends AbstractResult implements Serializable { + + private static final long serialVersionUID = -6925924956850004727L; + + private Object result; + + private Throwable exception; + + private Map attachments = new HashMap(); + + public AppResponse() { + } + + public AppResponse(Object result) { + this.result = result; + } + + public AppResponse(Throwable exception) { + this.exception = exception; + } + + @Override + public Object recreate() throws Throwable { + if (exception != null) { + throw exception; + } + return result; + } + + @Override + public Object getValue() { + return result; + } + + public void setValue(Object value) { + this.result = value; + } + + @Override + public Throwable getException() { + return exception; + } + + public void setException(Throwable e) { + this.exception = e; + } + + @Override + public boolean hasException() { + return exception != null; + } + + @Override + public Map getAttachments() { + return attachments; + } + + /** + * Append all items from the map into the attachment, if map is empty then nothing happens + * + * @param map contains all key-value pairs to append + */ + public void setAttachments(Map map) { + this.attachments = map == null ? new HashMap() : map; + } + + public void addAttachments(Map map) { + if (map == null) { + return; + } + if (this.attachments == null) { + this.attachments = new HashMap(); + } + this.attachments.putAll(map); + } + + @Override + public String getAttachment(String key) { + return attachments.get(key); + } + + @Override + public String getAttachment(String key, String defaultValue) { + String result = attachments.get(key); + if (result == null || result.length() == 0) { + result = defaultValue; + } + return result; + } + + public void setAttachment(String key, String value) { + attachments.put(key, value); + } + + @Override + public Result thenApplyWithContext(Function fn) { + throw new UnsupportedOperationException("AppResponse represents an concrete business response, there will be no status changes, you should get internal values directly."); + } + + @Override + public String toString() { + return "AppResponse [value=" + result + ", exception=" + exception + "]"; + } +} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncRpcResult.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncRpcResult.java index b631dffe180..9546e2a39ce 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncRpcResult.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncRpcResult.java @@ -25,176 +25,174 @@ import java.util.function.Function; /** - * NOTICE!! - * + * This class represents an unfinished RPC call, it will hold some context information for this call, for example RpcContext and Invocation, + * so that when the call finishes and the result returns, it can guarantee all the contexts being recovered as the same as when the call was made + * before any callback is invoked. *

    - * You should never rely on this class directly when using or extending Dubbo, the implementation of {@link AsyncRpcResult} - * is only a workaround for compatibility purpose. It may be changed or even get removed from the next major version. - * Please only use {@link Result} or {@link RpcResult}. - * - * Extending the {@link Filter} is one typical use case: - *

    - * {@code
    - * public class YourFilter implements Filter {
    - *     @Override
    - *     public Result onResponse(Result result, Invoker invoker, Invocation invocation) {
    - *         System.out.println("Filter get the return value: " + result.getValue());
    - *         // Don't do this
    - *         // AsyncRpcResult asyncRpcResult = ((AsyncRpcResult)result;
    - *         // System.out.println("Filter get the return value: " + asyncRpcResult.getValue());
    - *         return result;
    - *     }
    - *
    - *     @Override
    - *     public Result invoke(Invoker invoker, Invocation invocation) throws RpcException {
    - *         return invoker.invoke(invocation);
    - *     }
    - * }
    - * }
    - * 
    - *

    - * TODO RpcResult can be an instance of {@link java.util.concurrent.CompletionStage} instead of composing CompletionStage inside. + * TODO if it's reasonable or even right to keep a reference to Invocation? + *

    + * As {@link Result} implements CompletionStage, {@link AsyncRpcResult} allows you to easily build a async filter chain whose status will be + * driven entirely by the state of the underlying RPC call. + *

    + * AsyncRpcResult does not contain any concrete value (except the underlying value bring by CompletableFuture), consider it as a status transfer node. + * {@link #getValue()} and {@link #getException()} are all inherited from {@link Result} interface, implementing them are mainly + * for compatibility consideration. Because many legacy {@link Filter} implementation are most possibly to call getValue directly. */ public class AsyncRpcResult extends AbstractResult { private static final Logger logger = LoggerFactory.getLogger(AsyncRpcResult.class); /** - * RpcContext can be changed, because thread may have been used by other thread. It should be cloned before store. - * So we use Invocation instead, Invocation will create for every invoke, but invocation only support attachments of string type. + * RpcContext may already have been changed when callback happens, it happens when the same thread is used to execute another RPC call. + * So we should keep the reference of current RpcContext instance and restore it before callback being executed. */ private RpcContext storedContext; private RpcContext storedServerContext; - protected CompletableFuture valueFuture; - - protected CompletableFuture resultFuture; + private Invocation invocation; - public AsyncRpcResult(CompletableFuture future) { - this(future, true); + public AsyncRpcResult(Invocation invocation) { + this.invocation = invocation; + this.storedContext = RpcContext.getContext(); + this.storedServerContext = RpcContext.getServerContext(); } - public AsyncRpcResult(CompletableFuture future, boolean registerCallback) { - this(future, new CompletableFuture<>(), registerCallback); + public AsyncRpcResult(AsyncRpcResult asyncRpcResult) { + this.invocation = asyncRpcResult.getInvocation(); + this.storedContext = asyncRpcResult.getStoredContext(); + this.storedServerContext = asyncRpcResult.getStoredServerContext(); } /** - * @param future - * @param rFuture - * @param registerCallback + * Notice the return type of {@link #getValue} is the actual type of the RPC method, not {@link AppResponse} + * + * @return */ - public AsyncRpcResult(CompletableFuture future, final CompletableFuture rFuture, boolean registerCallback) { - if (rFuture == null) { - throw new IllegalArgumentException(); - } - resultFuture = rFuture; - if (registerCallback) { - /** - * We do not know whether future already completed or not, it's a future exposed or even created by end user. - * 1. future complete before whenComplete. whenComplete fn (resultFuture.complete) will be executed in thread subscribing, in our case, it's Dubbo thread. - * 2. future complete after whenComplete. whenComplete fn (resultFuture.complete) will be executed in thread calling complete, normally its User thread. - */ - future.whenComplete((v, t) -> { - RpcResult rpcResult; - if (t != null) { - if (t instanceof CompletionException) { - rpcResult = new RpcResult(t.getCause()); - } else { - rpcResult = new RpcResult(t); - } - } else { - rpcResult = new RpcResult(v); - } - // instead of resultFuture we must use rFuture here, resultFuture may being changed before complete when building filter chain, but rFuture was guaranteed never changed by closure. - rFuture.complete(rpcResult); - }); - } - this.valueFuture = future; - // employ copy of context avoid the other call may modify the context content - this.storedContext = RpcContext.getContext().copyOf(); - this.storedServerContext = RpcContext.getServerContext().copyOf(); - } - @Override public Object getValue() { - return getRpcResult().getValue(); + return getAppResponse().getValue(); } @Override - public Throwable getException() { - return getRpcResult().getException(); + public void setValue(Object value) { + AppResponse appResponse = new AppResponse(); + appResponse.setValue(value); + this.complete(appResponse); } @Override - public boolean hasException() { - return getRpcResult().hasException(); + public Throwable getException() { + return getAppResponse().getException(); } @Override - public Object getResult() { - return getRpcResult().getResult(); - } - - public CompletableFuture getValueFuture() { - return valueFuture; + public void setException(Throwable t) { + AppResponse appResponse = new AppResponse(); + appResponse.setException(t); + this.complete(appResponse); } - public CompletableFuture getResultFuture() { - return resultFuture; - } - - public void setResultFuture(CompletableFuture resultFuture) { - this.resultFuture = resultFuture; + @Override + public boolean hasException() { + return getAppResponse().hasException(); } - public Result getRpcResult() { + public Result getAppResponse() { try { - if (resultFuture.isDone()) { - return resultFuture.get(); + if (this.isDone()) { + return this.get(); } } catch (Exception e) { // This should never happen; logger.error("Got exception when trying to fetch the underlying result from AsyncRpcResult.", e); } - return new RpcResult(); + return new AppResponse(); } @Override public Object recreate() throws Throwable { - return valueFuture; + RpcInvocation rpcInvocation = (RpcInvocation) invocation; + if (InvokeMode.FUTURE == rpcInvocation.getInvokeMode()) { + AppResponse appResponse = new AppResponse(); + CompletableFuture future = new CompletableFuture<>(); + appResponse.setValue(future); + this.whenComplete((result, t) -> { + if (t != null) { + if (t instanceof CompletionException) { + t = t.getCause(); + } + future.completeExceptionally(t); + } else { + if (result.hasException()) { + future.completeExceptionally(result.getException()); + } else { + future.complete(result.getValue()); + } + } + }); + return appResponse.recreate(); + } else if (this.isDone()) { + return this.get().recreate(); + } + return (new AppResponse()).recreate(); + } + + public Result thenApplyWithContext(Function fn) { + CompletableFuture future = this.thenApply(fn.compose(beforeContext).andThen(afterContext)); + AsyncRpcResult nextAsyncRpcResult = new AsyncRpcResult(this); + nextAsyncRpcResult.subscribeTo(future); + return nextAsyncRpcResult; } - public void thenApplyWithContext(Function fn) { - this.resultFuture = resultFuture.thenApply(fn.compose(beforeContext).andThen(afterContext)); + public void subscribeTo(CompletableFuture future) { + future.whenComplete((obj, t) -> { + if (t != null) { + this.completeExceptionally(t); + } else { + this.complete((Result) obj); + } + }); } @Override public Map getAttachments() { - return getRpcResult().getAttachments(); + return getAppResponse().getAttachments(); } @Override public void setAttachments(Map map) { - getRpcResult().setAttachments(map); + getAppResponse().setAttachments(map); } @Override public void addAttachments(Map map) { - getRpcResult().addAttachments(map); + getAppResponse().addAttachments(map); } @Override public String getAttachment(String key) { - return getRpcResult().getAttachment(key); + return getAppResponse().getAttachment(key); } @Override public String getAttachment(String key, String defaultValue) { - return getRpcResult().getAttachment(key, defaultValue); + return getAppResponse().getAttachment(key, defaultValue); } @Override public void setAttachment(String key, String value) { - getRpcResult().setAttachment(key, value); + getAppResponse().setAttachment(key, value); + } + + public RpcContext getStoredContext() { + return storedContext; + } + + public RpcContext getStoredServerContext() { + return storedServerContext; + } + + public Invocation getInvocation() { + return invocation; } /** @@ -203,18 +201,51 @@ public void setAttachment(String key, String value) { private RpcContext tmpContext; private RpcContext tmpServerContext; - private Function beforeContext = (result) -> { + private Function beforeContext = (appResponse) -> { tmpContext = RpcContext.getContext(); tmpServerContext = RpcContext.getServerContext(); RpcContext.restoreContext(storedContext); RpcContext.restoreServerContext(storedServerContext); - return result; + return appResponse; }; - private Function afterContext = (result) -> { + private Function afterContext = (appResponse) -> { RpcContext.restoreContext(tmpContext); RpcContext.restoreServerContext(tmpServerContext); - return result; + return appResponse; }; + + /** + * Some utility methods used to quickly generate default AsyncRpcResult instance. + */ + public static AsyncRpcResult newDefaultAsyncResult(AppResponse appResponse, Invocation invocation) { + AsyncRpcResult asyncRpcResult = new AsyncRpcResult(invocation); + asyncRpcResult.complete(appResponse); + return asyncRpcResult; + } + + public static AsyncRpcResult newDefaultAsyncResult(Invocation invocation) { + return newDefaultAsyncResult(null, null, invocation); + } + + public static AsyncRpcResult newDefaultAsyncResult(Object value, Invocation invocation) { + return newDefaultAsyncResult(value, null, invocation); + } + + public static AsyncRpcResult newDefaultAsyncResult(Throwable t, Invocation invocation) { + return newDefaultAsyncResult(null, t, invocation); + } + + public static AsyncRpcResult newDefaultAsyncResult(Object value, Throwable t, Invocation invocation) { + AsyncRpcResult asyncRpcResult = new AsyncRpcResult(invocation); + AppResponse appResponse = new AppResponse(); + if (t != null) { + appResponse.setException(t); + } else { + appResponse.setValue(value); + } + asyncRpcResult.complete(appResponse); + return asyncRpcResult; + } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Filter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Filter.java index a17fd906d55..53ad128efa7 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Filter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Filter.java @@ -42,35 +42,29 @@ */ @SPI public interface Filter { - /** - * do invoke filter. - *

    - * - * // before filter - * Result result = invoker.invoke(invocation); - * // after filter - * return result; - * - * - * @param invoker service - * @param invocation invocation. - * @return invoke result. - * @throws RpcException - * @see org.apache.dubbo.rpc.Invoker#invoke(Invocation) + * Does not need to override/implement this method. */ Result invoke(Invoker invoker, Invocation invocation) throws RpcException; /** - * Return processing result + * Filter itself should only be response for passing invocation, all callbacks has been placed into {@link Listener} * - * @param result result - * @param invoker invoker - * @param invocation invocation - * @return Return {@link Result} + * @param appResponse + * @param invoker + * @param invocation + * @return */ - default Result onResponse(Result result, Invoker invoker, Invocation invocation) { - return result; + @Deprecated + default Result onResponse(Result appResponse, Invoker invoker, Invocation invocation) { + return appResponse; + } + + interface Listener { + + void onResponse(Result appResponse, Invoker invoker, Invocation invocation); + + void onError(Throwable t, Invoker invoker, Invocation invocation); } } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/FutureContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/FutureContext.java new file mode 100644 index 00000000000..8d5a1b62fa3 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/FutureContext.java @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.rpc; + +import org.apache.dubbo.common.threadlocal.InternalThreadLocal; + +import java.util.concurrent.CompletableFuture; + +/** + * Used for async call scenario. But if the method you are calling has a {@link CompletableFuture} signature + * you do not need to use this class since you will get a Future response directly. + *

    + * Remember to save the Future reference before making another call using the same thread, otherwise, + * the current Future will be override by the new one, which means you will lose the chance get the return value. + */ +public class FutureContext { + + public static InternalThreadLocal> futureTL = new InternalThreadLocal<>(); + + /** + * get future. + * + * @param + * @return future + */ + @SuppressWarnings("unchecked") + public static CompletableFuture getCompletableFuture() { + return (CompletableFuture) futureTL.get(); + } + + /** + * set future. + * + * @param future + */ + public static void setFuture(CompletableFuture future) { + futureTL.set(future); + } + +} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Invocation.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Invocation.java index 2b5f3dd9e95..058e0ad09c9 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Invocation.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Invocation.java @@ -59,6 +59,10 @@ public interface Invocation { */ Map getAttachments(); + void setAttachment(String key, String value); + + void setAttachmentIfAbsent(String key, String value); + /** * get attachment by key. * diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseCallback.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/InvokeMode.java similarity index 82% rename from dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseCallback.java rename to dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/InvokeMode.java index 893b262094b..a97a0be61f4 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseCallback.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/InvokeMode.java @@ -14,12 +14,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package org.apache.dubbo.rpc; -package com.alibaba.dubbo.remoting.exchange; +public enum InvokeMode { + + SYNC, ASYNC, FUTURE; -/** - * 2019-04-18 - */ -@Deprecated -public interface ResponseCallback extends org.apache.dubbo.remoting.exchange.ResponseCallback { } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/FutureAdapter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ListenableFilter.java similarity index 74% rename from dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/FutureAdapter.java rename to dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ListenableFilter.java index 07a69871af7..622ef1f0309 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/FutureAdapter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ListenableFilter.java @@ -14,16 +14,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -package com.alibaba.dubbo.rpc.protocol.dubbo; - -import org.apache.dubbo.remoting.exchange.ResponseFuture; +package org.apache.dubbo.rpc; /** - * 2019-04-18 + * */ -public class FutureAdapter extends org.apache.dubbo.rpc.protocol.dubbo.FutureAdapter { - public FutureAdapter(ResponseFuture future) { - super(future); +public abstract class ListenableFilter implements Filter { + + protected Listener listener = null; + + public Listener listener() { + return listener; } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Result.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Result.java index 58a258241ff..1f3a5138319 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Result.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Result.java @@ -18,16 +18,27 @@ import java.io.Serializable; import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.Future; +import java.util.function.Function; /** - * RPC invoke result. (API, Prototype, NonThreadSafe) + * (API, Prototype, NonThreadSafe) + * + * An RPC {@link Result}. + * + * Known implementations are: + * 1. {@link AsyncRpcResult}, it's a {@link CompletionStage} whose underlying value signifies the return value of an RPC call. + * 2. {@link AppResponse}, it inevitably inherits {@link CompletionStage} and {@link Future}, but you should never treat AppResponse as a type of Future, + * instead, it is a normal concrete type. * * @serial Don't change the class name and package name. * @see org.apache.dubbo.rpc.Invoker#invoke(Invocation) - * @see org.apache.dubbo.rpc.RpcResult + * @see AppResponse */ -public interface Result extends Serializable { +public interface Result extends CompletionStage, Future, Serializable { /** * Get invoke result. @@ -36,6 +47,8 @@ public interface Result extends Serializable { */ Object getValue(); + void setValue(Object value); + /** * Get exception. * @@ -43,6 +56,8 @@ public interface Result extends Serializable { */ Throwable getException(); + void setException(Throwable t); + /** * Has exception. * @@ -66,14 +81,6 @@ public interface Result extends Serializable { */ Object recreate() throws Throwable; - /** - * @see org.apache.dubbo.rpc.Result#getValue() - * @deprecated Replace to getValue() - */ - @Deprecated - Object getResult(); - - /** * get attachments. * @@ -111,4 +118,26 @@ public interface Result extends Serializable { void setAttachment(String key, String value); + /** + * Returns the specified {@code valueIfAbsent} when not complete, or + * returns the result value or throws an exception when complete. + * + * @see CompletableFuture#getNow(Object) + */ + Result getNow(Result valueIfAbsent); + + /** + * Add a callback which can be triggered when the RPC call finishes. + *

    + * Just as the method name implies, this method will guarantee the callback being triggered under the same context as when the call was started, + * see implementation in {@link AsyncRpcResult#thenApplyWithContext(Function)} + * + * @param fn + * @return + */ + Result thenApplyWithContext(Function fn); + + default CompletableFuture completionFuture() { + return toCompletableFuture(); + } } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java index fc658db052d..50221704099 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java @@ -75,7 +75,6 @@ protected RpcContext initialValue() { private final Map attachments = new HashMap(); private final Map values = new HashMap(); - private Future future; private List urls; @@ -144,32 +143,6 @@ public static void restoreContext(RpcContext oldContext) { LOCAL.set(oldContext); } - - public RpcContext copyOf() { - RpcContext copy = new RpcContext(); - copy.attachments.putAll(this.attachments); - copy.values.putAll(this.values); - copy.future = this.future; - copy.urls = this.urls; - copy.url = this.url; - copy.methodName = this.methodName; - copy.parameterTypes = this.parameterTypes; - copy.arguments = this.arguments; - copy.localAddress = this.localAddress; - copy.remoteAddress = this.remoteAddress; - copy.remoteApplicationName = this.remoteApplicationName; - copy.invokers = this.invokers; - copy.invoker = this.invoker; - copy.invocation = this.invocation; - - copy.request = this.request; - copy.response = this.response; - copy.asyncContext = this.asyncContext; - - return copy; - } - - /** * remove context. * @@ -251,7 +224,7 @@ public boolean isConsumerSide() { */ @SuppressWarnings("unchecked") public CompletableFuture getCompletableFuture() { - return (CompletableFuture) future; + return FutureContext.getCompletableFuture(); } /** @@ -262,7 +235,7 @@ public CompletableFuture getCompletableFuture() { */ @SuppressWarnings("unchecked") public Future getFuture() { - return (Future) future; + return FutureContext.getCompletableFuture(); } /** @@ -270,8 +243,8 @@ public Future getFuture() { * * @param future */ - public void setFuture(Future future) { - this.future = future; + public void setFuture(CompletableFuture future) { + FutureContext.setFuture(future); } public List getUrls() { diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.java index a03e3dc15a2..e422bef6cf1 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.java @@ -52,6 +52,10 @@ public class RpcInvocation implements Invocation, Serializable { private transient Invoker invoker; + private transient Class returnType; + + private transient InvokeMode invokeMode; + public RpcInvocation() { } @@ -94,6 +98,7 @@ public RpcInvocation(Method method, Object[] arguments) { public RpcInvocation(Method method, Object[] arguments, Map attachment) { this(method.getName(), method.getParameterTypes(), arguments, attachment, null); + this.returnType = method.getReturnType(); } public RpcInvocation(String methodName, Class[] parameterTypes, Object[] arguments) { @@ -212,6 +217,22 @@ public String getAttachment(String key, String defaultValue) { return value; } + public Class getReturnType() { + return returnType; + } + + public void setReturnType(Class returnType) { + this.returnType = returnType; + } + + public InvokeMode getInvokeMode() { + return invokeMode; + } + + public void setInvokeMode(InvokeMode invokeMode) { + this.invokeMode = invokeMode; + } + @Override public String toString() { return "RpcInvocation [methodName=" + methodName + ", parameterTypes=" diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcResult.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcResult.java deleted file mode 100644 index 8087210f29a..00000000000 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcResult.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc; - -import java.lang.reflect.Field; - -/** - * RPC Result. - * - * @serial Don't change the class name and properties. - */ -public class RpcResult extends AbstractResult { - - private static final long serialVersionUID = -6925924956850004727L; - - public RpcResult() { - } - - public RpcResult(Object result) { - this.result = result; - } - - public RpcResult(Throwable exception) { - this.exception = handleStackTraceNull(exception); - } - - @Override - public Object recreate() throws Throwable { - if (exception != null) { - throw exception; - } - return result; - } - - /** - * @see org.apache.dubbo.rpc.RpcResult#getValue() - * @deprecated Replace to getValue() - */ - @Override - @Deprecated - public Object getResult() { - return getValue(); - } - - /** - * @see org.apache.dubbo.rpc.RpcResult#setValue(Object) - * @deprecated Replace to setValue() - */ - @Deprecated - public void setResult(Object result) { - setValue(result); - } - - @Override - public Object getValue() { - return result; - } - - public void setValue(Object value) { - this.result = value; - } - - @Override - public Throwable getException() { - return exception; - } - - public void setException(Throwable e) { - this.exception = handleStackTraceNull(e); - } - - @Override - public boolean hasException() { - return exception != null; - } - - @Override - public String toString() { - return "RpcResult [result=" + result + ", exception=" + exception + "]"; - } - - /** - * we need to deal the exception whose stack trace is null. - *

    - * see https://github.com/apache/incubator-dubbo/pull/2956 - * and https://github.com/apache/incubator-dubbo/pull/3634 - * and https://github.com/apache/incubator-dubbo/issues/619 - * - * @param e exception - * @return exception after deal with stack trace - */ - private Throwable handleStackTraceNull(Throwable e) { - if (e != null) { - try { - // get Throwable class - Class clazz = e.getClass(); - while (!clazz.getName().equals(Throwable.class.getName())) { - clazz = clazz.getSuperclass(); - } - // get stackTrace value - Field stackTraceField = clazz.getDeclaredField("stackTrace"); - stackTraceField.setAccessible(true); - Object stackTrace = stackTraceField.get(e); - if (stackTrace == null) { - e.setStackTrace(new StackTraceElement[0]); - } - } catch (Throwable t) { - // ignore - } - } - - return e; - } -} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/SimpleAsyncRpcResult.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/SimpleAsyncRpcResult.java deleted file mode 100644 index 98e42d94a38..00000000000 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/SimpleAsyncRpcResult.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc; - -import java.util.concurrent.CompletableFuture; - -/** - * A sub class used for normal async invoke. - * - * NOTICE!! - * - *

    - * You should never rely on this class directly when using or extending Dubbo, the implementation of {@link SimpleAsyncRpcResult} - * is only a workaround for compatibility purpose. It may be changed or even get removed from the next major version. - * Please only use {@link Result} or {@link RpcResult}. - *

    - * - * Check {@link AsyncRpcResult} for more details. - * - * TODO AsyncRpcResult, AsyncNormalRpcResult should not be a parent-child hierarchy. - */ -public class SimpleAsyncRpcResult extends AsyncRpcResult { - public SimpleAsyncRpcResult(CompletableFuture future, boolean registerCallback) { - super(future, registerCallback); - } - - public SimpleAsyncRpcResult(CompletableFuture future, CompletableFuture rFuture, boolean registerCallback) { - super(future, rFuture, registerCallback); - } - - @Override - public Object recreate() throws Throwable { - // TODO should we check the status of valueFuture here? - return null; - } -} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java index 0e1df8f1d02..19090c1e0fb 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java @@ -18,9 +18,11 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; +import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.ListenableFilter; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcStatus; @@ -42,50 +44,75 @@ * @see Filter */ @Activate(group = CONSUMER, value = ACTIVES_KEY) -public class ActiveLimitFilter implements Filter { +public class ActiveLimitFilter extends ListenableFilter { + + private static final String ACTIVELIMIT_FILTER_START_TIME = "activelimit_filter_start_time"; + + public ActiveLimitFilter() { + super.listener = new ActiveLimitListener(); + } @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { URL url = invoker.getUrl(); String methodName = invocation.getMethodName(); int max = invoker.getUrl().getMethodParameter(methodName, ACTIVES_KEY, 0); - RpcStatus count = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName()); + RpcStatus rpcStatus = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName()); if (!RpcStatus.beginCount(url, methodName, max)) { long timeout = invoker.getUrl().getMethodParameter(invocation.getMethodName(), TIMEOUT_KEY, 0); long start = System.currentTimeMillis(); long remain = timeout; - synchronized (count) { + synchronized (rpcStatus) { while (!RpcStatus.beginCount(url, methodName, max)) { try { - count.wait(remain); + rpcStatus.wait(remain); } catch (InterruptedException e) { // ignore } long elapsed = System.currentTimeMillis() - start; remain = timeout - elapsed; if (remain <= 0) { - throw new RpcException("Waiting concurrent invoke timeout in client-side for service: " - + invoker.getInterface().getName() + ", method: " - + invocation.getMethodName() + ", elapsed: " + elapsed - + ", timeout: " + timeout + ". concurrent invokes: " + count.getActive() - + ". max concurrent invoke limit: " + max); + throw new RpcException("Waiting concurrent invoke timeout in client-side for service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", elapsed: " + elapsed + ", timeout: " + timeout + ". concurrent invokes: " + rpcStatus.getActive() + ". max concurrent invoke limit: " + max); } } } } - boolean isSuccess = true; - long begin = System.currentTimeMillis(); - try { - return invoker.invoke(invocation); - } catch (RuntimeException t) { - isSuccess = false; - throw t; - } finally { - RpcStatus.endCount(url, methodName, System.currentTimeMillis() - begin, isSuccess); + invocation.setAttachment(ACTIVELIMIT_FILTER_START_TIME, String.valueOf(System.currentTimeMillis())); + + return invoker.invoke(invocation); + } + + static class ActiveLimitListener implements Listener { + @Override + public void onResponse(Result appResponse, Invoker invoker, Invocation invocation) { + String methodName = invocation.getMethodName(); + URL url = invoker.getUrl(); + int max = invoker.getUrl().getMethodParameter(methodName, ACTIVES_KEY, 0); + + RpcStatus.endCount(url, methodName, getElapsed(invocation), true); + notifyFinish(RpcStatus.getStatus(url, methodName), max); + } + + @Override + public void onError(Throwable t, Invoker invoker, Invocation invocation) { + String methodName = invocation.getMethodName(); + URL url = invoker.getUrl(); + int max = invoker.getUrl().getMethodParameter(methodName, ACTIVES_KEY, 0); + + RpcStatus.endCount(url, methodName, getElapsed(invocation), false); + notifyFinish(RpcStatus.getStatus(url, methodName), max); + } + + private long getElapsed(Invocation invocation) { + String beginTime = invocation.getAttachment(ACTIVELIMIT_FILTER_START_TIME); + return StringUtils.isNotEmpty(beginTime) ? System.currentTimeMillis() - Long.parseLong(beginTime) : 0; + } + + private void notifyFinish(RpcStatus rpcStatus, int max) { if (max > 0) { - synchronized (count) { - count.notifyAll(); + synchronized (rpcStatus) { + rpcStatus.notifyAll(); } } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/CompatibleFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/CompatibleFilter.java index 5842b32c04d..54aea0d7378 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/CompatibleFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/CompatibleFilter.java @@ -20,17 +20,18 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CompatibleTypeUtils; import org.apache.dubbo.common.utils.PojoUtils; -import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.ListenableFilter; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.RpcResult; import java.lang.reflect.Method; import java.lang.reflect.Type; +import static org.apache.dubbo.remoting.Constants.SERIALIZATION_KEY; + /** * CompatibleFilter make the remote method's return value compatible to invoker's version of object. * To make return object compatible it does @@ -45,44 +46,54 @@ * @see Filter * */ -public class CompatibleFilter implements Filter { +public class CompatibleFilter extends ListenableFilter { private static Logger logger = LoggerFactory.getLogger(CompatibleFilter.class); + public CompatibleFilter() { + super.listener = new CompatibleListener(); + } + @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { - Result result = invoker.invoke(invocation); - if (!invocation.getMethodName().startsWith("$") && !result.hasException()) { - Object value = result.getValue(); - if (value != null) { - try { - Method method = invoker.getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes()); - Class type = method.getReturnType(); - Object newValue; - String serialization = invoker.getUrl().getParameter(Constants.SERIALIZATION_KEY); - if ("json".equals(serialization) - || "fastjson".equals(serialization)) { - // If the serialization key is json or fastjson - Type gtype = method.getGenericReturnType(); - newValue = PojoUtils.realize(value, type, gtype); - } else if (!type.isInstance(value)) { - //if local service interface's method's return type is not instance of return value - newValue = PojoUtils.isPojo(type) - ? PojoUtils.realize(value, type) - : CompatibleTypeUtils.compatibleTypeConvert(value, type); + return invoker.invoke(invocation); + } - } else { - newValue = value; - } - if (newValue != value) { - result = new RpcResult(newValue); + static class CompatibleListener implements Listener { + @Override + public void onResponse(Result appResponse, Invoker invoker, Invocation invocation) { + if (!invocation.getMethodName().startsWith("$") && !appResponse.hasException()) { + Object value = appResponse.getValue(); + if (value != null) { + try { + Method method = invoker.getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes()); + Class type = method.getReturnType(); + Object newValue; + String serialization = invoker.getUrl().getParameter(SERIALIZATION_KEY); + if ("json".equals(serialization) || "fastjson".equals(serialization)) { + // If the serialization key is json or fastjson + Type gtype = method.getGenericReturnType(); + newValue = PojoUtils.realize(value, type, gtype); + } else if (!type.isInstance(value)) { + //if local service interface's method's return type is not instance of return value + newValue = PojoUtils.isPojo(type) ? PojoUtils.realize(value, type) : CompatibleTypeUtils.compatibleTypeConvert(value, type); + + } else { + newValue = value; + } + if (newValue != value) { + appResponse.setValue(newValue); + } + } catch (Throwable t) { + logger.warn(t.getMessage(), t); } - } catch (Throwable t) { - logger.warn(t.getMessage(), t); } } } - return result; - } + @Override + public void onError(Throwable t, Invoker invoker, Invocation invocation) { + + } + } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ConsumerContextFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ConsumerContextFilter.java index f1696f4a077..43353f7e7dc 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ConsumerContextFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ConsumerContextFilter.java @@ -16,17 +16,18 @@ */ package org.apache.dubbo.rpc.filter; -import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.ListenableFilter; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; +import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; + /** * ConsumerContextFilter set current RpcContext with invoker,invocation, local host, remote host and port * for consumer invoker.It does it to make the requires info available to execution thread's RpcContext. @@ -34,8 +35,12 @@ * @see org.apache.dubbo.rpc.Filter * @see RpcContext */ -@Activate(group = CommonConstants.CONSUMER, order = -10000) -public class ConsumerContextFilter implements Filter { +@Activate(group = CONSUMER, order = -10000) +public class ConsumerContextFilter extends ListenableFilter { + + public ConsumerContextFilter() { + super.listener = new ConsumerContextListener(); + } @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { @@ -49,18 +54,22 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept ((RpcInvocation) invocation).setInvoker(invoker); } try { - // TODO should we clear server context? RpcContext.removeServerContext(); return invoker.invoke(invocation); } finally { - // TODO removeContext? but we need to save future for RpcContext.getFuture() API. If clear attachments here, attachments will not available when postProcessResult is invoked. - RpcContext.getContext().clearAttachments(); + RpcContext.removeContext(); } } - @Override - public Result onResponse(Result result, Invoker invoker, Invocation invocation) { - RpcContext.getServerContext().setAttachments(result.getAttachments()); - return result; + static class ConsumerContextListener implements Listener { + @Override + public void onResponse(Result appResponse, Invoker invoker, Invocation invocation) { + RpcContext.getServerContext().setAttachments(appResponse.getAttachments()); + } + + @Override + public void onError(Throwable t, Invoker invoker, Invocation invocation) { + + } } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java index 8939c3ace2a..49e2a602d21 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java @@ -17,9 +17,9 @@ package org.apache.dubbo.rpc.filter; import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.ListenableFilter; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; @@ -48,9 +48,13 @@ * @see RpcContext */ @Activate(group = PROVIDER, order = -10000) -public class ContextFilter implements Filter { +public class ContextFilter extends ListenableFilter { private static final String TAG_KEY = "dubbo.tag"; + public ContextFilter() { + super.listener = new ContextListener(); + } + @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { Map attachments = invocation.getAttachments(); @@ -97,10 +101,16 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept } } - @Override - public Result onResponse(Result result, Invoker invoker, Invocation invocation) { - // pass attachments to result - result.addAttachments(RpcContext.getServerContext().getAttachments()); - return result; + static class ContextListener implements Listener { + @Override + public void onResponse(Result appResponse, Invoker invoker, Invocation invocation) { + // pass attachments to result + appResponse.addAttachments(RpcContext.getServerContext().getAttachments()); + } + + @Override + public void onError(Throwable t, Invoker invoker, Invocation invocation) { + + } } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/EchoFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/EchoFilter.java index b50e9ffe16c..d51e6d4a2a3 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/EchoFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/EchoFilter.java @@ -18,12 +18,12 @@ import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; +import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.RpcResult; import static org.apache.dubbo.rpc.Constants.$ECHO; @@ -36,7 +36,7 @@ public class EchoFilter implements Filter { @Override public Result invoke(Invoker invoker, Invocation inv) throws RpcException { if (inv.getMethodName().equals($ECHO) && inv.getArguments() != null && inv.getArguments().length == 1) { - return new RpcResult(inv.getArguments()[0]); + return AsyncRpcResult.newDefaultAsyncResult(inv.getArguments()[0], inv); } return invoker.invoke(inv); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExceptionFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExceptionFilter.java index bc4018513fc..8f5411b179c 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExceptionFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExceptionFilter.java @@ -22,13 +22,12 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.ListenableFilter; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.service.GenericService; import java.lang.reflect.Method; @@ -45,85 +44,82 @@ * */ @Activate(group = CommonConstants.PROVIDER) -public class ExceptionFilter implements Filter { - - private final Logger logger; +public class ExceptionFilter extends ListenableFilter { public ExceptionFilter() { - this(LoggerFactory.getLogger(ExceptionFilter.class)); - } - - public ExceptionFilter(Logger logger) { - this.logger = logger; + super.listener = new ExceptionListener(); } @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { - try { - return invoker.invoke(invocation); - } catch (RuntimeException e) { - logger.error("Got unchecked and undeclared exception which called by " + RpcContext.getContext().getRemoteHost() - + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() - + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e); - throw e; - } + return invoker.invoke(invocation); } - @Override - public Result onResponse(Result result, Invoker invoker, Invocation invocation) { - if (result.hasException() && GenericService.class != invoker.getInterface()) { - try { - Throwable exception = result.getException(); - - // directly throw if it's checked exception - if (!(exception instanceof RuntimeException) && (exception instanceof Exception)) { - return result; - } - // directly throw if the exception appears in the signature + static class ExceptionListener implements Listener { + + private Logger logger = LoggerFactory.getLogger(ExceptionListener.class); + + @Override + public void onResponse(Result appResponse, Invoker invoker, Invocation invocation) { + if (appResponse.hasException() && GenericService.class != invoker.getInterface()) { try { - Method method = invoker.getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes()); - Class[] exceptionClassses = method.getExceptionTypes(); - for (Class exceptionClass : exceptionClassses) { - if (exception.getClass().equals(exceptionClass)) { - return result; + Throwable exception = appResponse.getException(); + + // directly throw if it's checked exception + if (!(exception instanceof RuntimeException) && (exception instanceof Exception)) { + return; + } + // directly throw if the exception appears in the signature + try { + Method method = invoker.getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes()); + Class[] exceptionClassses = method.getExceptionTypes(); + for (Class exceptionClass : exceptionClassses) { + if (exception.getClass().equals(exceptionClass)) { + return; + } } + } catch (NoSuchMethodException e) { + return; } - } catch (NoSuchMethodException e) { - return result; - } - // for the exception not found in method's signature, print ERROR message in server's log. - logger.error("Got unchecked and undeclared exception which called by " + RpcContext.getContext().getRemoteHost() - + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() - + ", exception: " + exception.getClass().getName() + ": " + exception.getMessage(), exception); + // for the exception not found in method's signature, print ERROR message in server's log. + logger.error("Got unchecked and undeclared exception which called by " + RpcContext.getContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + exception.getClass().getName() + ": " + exception.getMessage(), exception); - // directly throw if exception class and interface class are in the same jar file. - String serviceFile = ReflectUtils.getCodeBase(invoker.getInterface()); - String exceptionFile = ReflectUtils.getCodeBase(exception.getClass()); - if (serviceFile == null || exceptionFile == null || serviceFile.equals(exceptionFile)) { - return result; - } - // directly throw if it's JDK exception - String className = exception.getClass().getName(); - if (className.startsWith("java.") || className.startsWith("javax.")) { - return result; - } - // directly throw if it's dubbo exception - if (exception instanceof RpcException) { - return result; - } + // directly throw if exception class and interface class are in the same jar file. + String serviceFile = ReflectUtils.getCodeBase(invoker.getInterface()); + String exceptionFile = ReflectUtils.getCodeBase(exception.getClass()); + if (serviceFile == null || exceptionFile == null || serviceFile.equals(exceptionFile)) { + return; + } + // directly throw if it's JDK exception + String className = exception.getClass().getName(); + if (className.startsWith("java.") || className.startsWith("javax.")) { + return; + } + // directly throw if it's dubbo exception + if (exception instanceof RpcException) { + return; + } - // otherwise, wrap with RuntimeException and throw back to the client - return new RpcResult(new RuntimeException(StringUtils.toString(exception))); - } catch (Throwable e) { - logger.warn("Fail to ExceptionFilter when called by " + RpcContext.getContext().getRemoteHost() - + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() - + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e); - return result; + // otherwise, wrap with RuntimeException and throw back to the client + appResponse.setException(new RuntimeException(StringUtils.toString(exception))); + return; + } catch (Throwable e) { + logger.warn("Fail to ExceptionFilter when called by " + RpcContext.getContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e); + return; + } } } - return result; - } + @Override + public void onError(Throwable e, Invoker invoker, Invocation invocation) { + logger.error("Got unchecked and undeclared exception which called by " + RpcContext.getContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e); + } + + // For test purpose + public void setLogger(Logger logger) { + this.logger = logger; + } + } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java index f14dddfab68..e1af529b15f 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java @@ -19,9 +19,10 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.rpc.Filter; +import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.ListenableFilter; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcStatus; @@ -30,12 +31,20 @@ /** + * * The maximum parallel execution request count per method per service for the provider.If the max configured * executes is set to 10 and if invoke request where it is already 10 then it will throws exception. It * continue the same behaviour un till it is <10. + * */ @Activate(group = CommonConstants.PROVIDER, value = EXECUTES_KEY) -public class ExecuteLimitFilter implements Filter { +public class ExecuteLimitFilter extends ListenableFilter { + + private static final String EXECUTELIMIT_FILTER_START_TIME = "execugtelimit_filter_start_time"; + + public ExecuteLimitFilter() { + super.listener = new ExecuteLimitListener(); + } @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { @@ -48,20 +57,32 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept "\" /> limited."); } - long begin = System.currentTimeMillis(); - boolean isSuccess = true; + invocation.setAttachment(EXECUTELIMIT_FILTER_START_TIME, String.valueOf(System.currentTimeMillis())); try { return invoker.invoke(invocation); } catch (Throwable t) { - isSuccess = false; if (t instanceof RuntimeException) { throw (RuntimeException) t; } else { throw new RpcException("unexpected exception when ExecuteLimitFilter", t); } - } finally { - RpcStatus.endCount(url, methodName, System.currentTimeMillis() - begin, isSuccess); } } + static class ExecuteLimitListener implements Listener { + @Override + public void onResponse(Result appResponse, Invoker invoker, Invocation invocation) { + RpcStatus.endCount(invoker.getUrl(), invocation.getMethodName(), getElapsed(invocation), true); + } + + @Override + public void onError(Throwable t, Invoker invoker, Invocation invocation) { + RpcStatus.endCount(invoker.getUrl(), invocation.getMethodName(), getElapsed(invocation), false); + } + + private long getElapsed(Invocation invocation) { + String beginTime = invocation.getAttachment(EXECUTELIMIT_FILTER_START_TIME); + return StringUtils.isNotEmpty(beginTime) ? System.currentTimeMillis() - Long.parseLong(beginTime) : 0; + } + } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java index 07702dcb3e9..fd83e1f4271 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java @@ -28,14 +28,13 @@ import org.apache.dubbo.common.utils.PojoUtils; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.ListenableFilter; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.service.GenericException; import org.apache.dubbo.rpc.service.GenericService; import org.apache.dubbo.rpc.support.ProtocolUtils; @@ -44,20 +43,25 @@ import java.lang.reflect.Method; import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE; -import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_NATIVE_JAVA; +import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE_ASYNC; +import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_BEAN; +import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_NATIVE_JAVA; import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_PROTOBUF; -import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; /** * GenericInvokerFilter. */ @Activate(group = CommonConstants.PROVIDER, order = -20000) -public class GenericFilter implements Filter { +public class GenericFilter extends ListenableFilter { + + public GenericFilter() { + super.listener = new GenericListener(); + } @Override public Result invoke(Invoker invoker, Invocation inv) throws RpcException { - if (inv.getMethodName().equals($INVOKE) + if ((inv.getMethodName().equals($INVOKE) || inv.getMethodName().equals($INVOKE_ASYNC)) && inv.getArguments() != null && inv.getArguments().length == 3 && !GenericService.class.isAssignableFrom(invoker.getInterface())) { @@ -134,18 +138,38 @@ public Result invoke(Invoker invoker, Invocation inv) throws RpcException { args[0].getClass().getName()); } } - Result result = invoker.invoke(new RpcInvocation(method, args, inv.getAttachments())); - if (result.hasException() - && !(result.getException() instanceof GenericException)) { - return new RpcResult(new GenericException(result.getException())); + return invoker.invoke(new RpcInvocation(method, args, inv.getAttachments())); + } catch (NoSuchMethodException e) { + throw new RpcException(e.getMessage(), e); + } catch (ClassNotFoundException e) { + throw new RpcException(e.getMessage(), e); + } + } + return invoker.invoke(inv); + } + + static class GenericListener implements Listener { + + @Override + public void onResponse(Result appResponse, Invoker invoker, Invocation inv) { + if ((inv.getMethodName().equals($INVOKE) || inv.getMethodName().equals($INVOKE_ASYNC)) + && inv.getArguments() != null + && inv.getArguments().length == 3 + && !GenericService.class.isAssignableFrom(invoker.getInterface())) { + + String generic = inv.getAttachment(GENERIC_KEY); + if (StringUtils.isBlank(generic)) { + generic = RpcContext.getContext().getAttachment(GENERIC_KEY); + } + + if (appResponse.hasException() && !(appResponse.getException() instanceof GenericException)) { + appResponse.setException(new GenericException(appResponse.getException())); } if (ProtocolUtils.isJavaGenericSerialization(generic)) { try { UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(512); - ExtensionLoader.getExtensionLoader(Serialization.class) - .getExtension(GENERIC_SERIALIZATION_NATIVE_JAVA) - .serialize(null, os).writeObject(result.getValue()); - return new RpcResult(os.toByteArray()); + ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(GENERIC_SERIALIZATION_NATIVE_JAVA).serialize(null, os).writeObject(appResponse.getValue()); + appResponse.setValue(os.toByteArray()); } catch (IOException e) { throw new RpcException( "Generic serialization [" + @@ -153,29 +177,28 @@ public Result invoke(Invoker invoker, Invocation inv) throws RpcException { "] serialize result failed.", e); } } else if (ProtocolUtils.isBeanGenericSerialization(generic)) { - return new RpcResult(JavaBeanSerializeUtil.serialize(result.getValue(), JavaBeanAccessor.METHOD)); + appResponse.setValue(JavaBeanSerializeUtil.serialize(appResponse.getValue(), JavaBeanAccessor.METHOD)); } else if (ProtocolUtils.isProtobufGenericSerialization(generic)) { try { UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(512); ExtensionLoader.getExtensionLoader(Serialization.class) .getExtension(GENERIC_SERIALIZATION_PROTOBUF) - .serialize(null, os).writeObject(result.getValue()); - return new RpcResult(os.toString()); + .serialize(null, os).writeObject(appResponse.getValue()); + appResponse.setValue(os.toString()); } catch (IOException e) { throw new RpcException("Generic serialization [" + GENERIC_SERIALIZATION_PROTOBUF + "] serialize result failed.", e); } } else { - return new RpcResult(PojoUtils.generalize(result.getValue())); + appResponse.setValue(PojoUtils.generalize(appResponse.getValue())); } - } catch (NoSuchMethodException e) { - throw new RpcException(e.getMessage(), e); - } catch (ClassNotFoundException e) { - throw new RpcException(e.getMessage(), e); } } - return invoker.invoke(inv); - } + @Override + public void onError(Throwable t, Invoker invoker, Invocation invocation) { + + } + } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java index d422fb474e9..ed5de7e1571 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java @@ -25,40 +25,46 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.PojoUtils; import org.apache.dubbo.common.utils.ReflectUtils; -import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.ListenableFilter; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.service.GenericException; import org.apache.dubbo.rpc.support.ProtocolUtils; +import org.apache.dubbo.rpc.support.RpcUtils; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; +import java.lang.reflect.Type; import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE; +import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE_ASYNC; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; /** * GenericImplInvokerFilter */ @Activate(group = CommonConstants.CONSUMER, value = GENERIC_KEY, order = 20000) -public class GenericImplFilter implements Filter { +public class GenericImplFilter extends ListenableFilter { private static final Logger logger = LoggerFactory.getLogger(GenericImplFilter.class); private static final Class[] GENERIC_PARAMETER_TYPES = new Class[]{String.class, String[].class, Object[].class}; + public GenericImplFilter() { + super.listener = new GenericImplListener(); + } + @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { String generic = invoker.getUrl().getParameter(GENERIC_KEY); if (ProtocolUtils.isGeneric(generic) - && !$INVOKE.equals(invocation.getMethodName()) + && (!$INVOKE.equals(invocation.getMethodName()) && !$INVOKE_ASYNC.equals(invocation.getMethodName())) && invocation instanceof RpcInvocation) { - RpcInvocation invocation2 = (RpcInvocation) invocation; + RpcInvocation invocation2 = new RpcInvocation(invocation); String methodName = invocation2.getMethodName(); Class[] parameterTypes = invocation2.getParameterTypes(); Object[] arguments = invocation2.getArguments(); @@ -78,77 +84,15 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept args = PojoUtils.generalize(arguments); } - invocation2.setMethodName($INVOKE); + if (RpcUtils.isReturnTypeFuture(invocation)) { + invocation2.setMethodName($INVOKE_ASYNC); + } else { + invocation2.setMethodName($INVOKE); + } invocation2.setParameterTypes(GENERIC_PARAMETER_TYPES); invocation2.setArguments(new Object[]{methodName, types, args}); - Result result = invoker.invoke(invocation2); - - if (!result.hasException()) { - Object value = result.getValue(); - try { - Method method = invoker.getInterface().getMethod(methodName, parameterTypes); - if (ProtocolUtils.isBeanGenericSerialization(generic)) { - if (value == null) { - return new RpcResult(value); - } else if (value instanceof JavaBeanDescriptor) { - return new RpcResult(JavaBeanSerializeUtil.deserialize((JavaBeanDescriptor) value)); - } else { - throw new RpcException( - "The type of result value is " + - value.getClass().getName() + - " other than " + - JavaBeanDescriptor.class.getName() + - ", and the result is " + - value); - } - } else { - return new RpcResult(PojoUtils.realize(value, method.getReturnType(), method.getGenericReturnType())); - } - } catch (NoSuchMethodException e) { - throw new RpcException(e.getMessage(), e); - } - } else if (result.getException() instanceof GenericException) { - GenericException exception = (GenericException) result.getException(); - try { - String className = exception.getExceptionClass(); - Class clazz = ReflectUtils.forName(className); - Throwable targetException = null; - Throwable lastException = null; - try { - targetException = (Throwable) clazz.newInstance(); - } catch (Throwable e) { - lastException = e; - for (Constructor constructor : clazz.getConstructors()) { - try { - targetException = (Throwable) constructor.newInstance(new Object[constructor.getParameterTypes().length]); - break; - } catch (Throwable e1) { - lastException = e1; - } - } - } - if (targetException != null) { - try { - Field field = Throwable.class.getDeclaredField("detailMessage"); - if (!field.isAccessible()) { - field.setAccessible(true); - } - field.set(targetException, exception.getExceptionMessage()); - } catch (Throwable e) { - logger.warn(e.getMessage(), e); - } - result = new RpcResult(targetException); - } else if (lastException != null) { - throw lastException; - } - } catch (Throwable e) { - throw new RpcException("Can not deserialize exception " + exception.getExceptionClass() + ", message: " + exception.getExceptionMessage(), e); - } - } - return result; - } - - if (invocation.getMethodName().equals($INVOKE) + return invoker.invoke(invocation2); + } else if ((invocation.getMethodName().equals($INVOKE) || invocation.getMethodName().equals($INVOKE_ASYNC)) && invocation.getArguments() != null && invocation.getArguments().length == 3 && ProtocolUtils.isGeneric(generic)) { @@ -169,19 +113,89 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept } } - ((RpcInvocation) invocation).setAttachment(GENERIC_KEY, invoker.getUrl().getParameter(GENERIC_KEY)); + invocation.setAttachment( + GENERIC_KEY, invoker.getUrl().getParameter(GENERIC_KEY)); } return invoker.invoke(invocation); } private void error(String generic, String expected, String actual) throws RpcException { - throw new RpcException( - "Generic serialization [" + - generic + - "] only support message type " + - expected + - " and your message type is " + - actual); + throw new RpcException("Generic serialization [" + generic + "] only support message type " + expected + " and your message type is " + actual); + } + + static class GenericImplListener implements Listener { + @Override + public void onResponse(Result appResponse, Invoker invoker, Invocation invocation) { + String generic = invoker.getUrl().getParameter(GENERIC_KEY); + String methodName = invocation.getMethodName(); + Class[] parameterTypes = invocation.getParameterTypes(); + if (ProtocolUtils.isGeneric(generic) + && (!$INVOKE.equals(invocation.getMethodName()) && !$INVOKE_ASYNC.equals(invocation.getMethodName())) + && invocation instanceof RpcInvocation) { + if (!appResponse.hasException()) { + Object value = appResponse.getValue(); + try { + Method method = invoker.getInterface().getMethod(methodName, parameterTypes); + if (ProtocolUtils.isBeanGenericSerialization(generic)) { + if (value == null) { + appResponse.setValue(value); + } else if (value instanceof JavaBeanDescriptor) { + appResponse.setValue(JavaBeanSerializeUtil.deserialize((JavaBeanDescriptor) value)); + } else { + throw new RpcException("The type of result value is " + value.getClass().getName() + " other than " + JavaBeanDescriptor.class.getName() + ", and the result is " + value); + } + } else { + Type[] types = ReflectUtils.getReturnTypes(method); + appResponse.setValue(PojoUtils.realize(value, (Class) types[0], types[1])); + } + } catch (NoSuchMethodException e) { + throw new RpcException(e.getMessage(), e); + } + } else if (appResponse.getException() instanceof GenericException) { + GenericException exception = (GenericException) appResponse.getException(); + try { + String className = exception.getExceptionClass(); + Class clazz = ReflectUtils.forName(className); + Throwable targetException = null; + Throwable lastException = null; + try { + targetException = (Throwable) clazz.newInstance(); + } catch (Throwable e) { + lastException = e; + for (Constructor constructor : clazz.getConstructors()) { + try { + targetException = (Throwable) constructor.newInstance(new Object[constructor.getParameterTypes().length]); + break; + } catch (Throwable e1) { + lastException = e1; + } + } + } + if (targetException != null) { + try { + Field field = Throwable.class.getDeclaredField("detailMessage"); + if (!field.isAccessible()) { + field.setAccessible(true); + } + field.set(targetException, exception.getExceptionMessage()); + } catch (Throwable e) { + logger.warn(e.getMessage(), e); + } + appResponse.setException(targetException); + } else if (lastException != null) { + throw lastException; + } + } catch (Throwable e) { + throw new RpcException("Can not deserialize exception " + exception.getExceptionClass() + ", message: " + exception.getExceptionMessage(), e); + } + } + } + } + + @Override + public void onError(Throwable t, Invoker invoker, Invocation invocation) { + + } } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TimeoutFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TimeoutFilter.java index d0f7b572497..31b0dc977a8 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TimeoutFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TimeoutFilter.java @@ -20,12 +20,11 @@ import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.ListenableFilter; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.RpcInvocation; import java.util.Arrays; @@ -33,42 +32,40 @@ * Log any invocation timeout, but don't stop server from running */ @Activate(group = CommonConstants.PROVIDER) -public class TimeoutFilter implements Filter { +public class TimeoutFilter extends ListenableFilter { private static final Logger logger = LoggerFactory.getLogger(TimeoutFilter.class); private static final String TIMEOUT_FILTER_START_TIME = "timeout_filter_start_time"; + public TimeoutFilter() { + super.listener = new TimeoutListener(); + } + @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { - if (invocation.getAttachments() != null) { - long start = System.currentTimeMillis(); - invocation.getAttachments().put(TIMEOUT_FILTER_START_TIME, String.valueOf(start)); - } else { - if (invocation instanceof RpcInvocation) { - RpcInvocation invc = (RpcInvocation) invocation; - long start = System.currentTimeMillis(); - invc.setAttachment(TIMEOUT_FILTER_START_TIME, String.valueOf(start)); - } - } + invocation.setAttachment(TIMEOUT_FILTER_START_TIME, String.valueOf(System.currentTimeMillis())); return invoker.invoke(invocation); } - @Override - public Result onResponse(Result result, Invoker invoker, Invocation invocation) { - String startAttach = invocation.getAttachment(TIMEOUT_FILTER_START_TIME); - if (startAttach != null) { - long elapsed = System.currentTimeMillis() - Long.valueOf(startAttach); - if (invoker.getUrl() != null - && elapsed > invoker.getUrl().getMethodParameter(invocation.getMethodName(), - "timeout", Integer.MAX_VALUE)) { - if (logger.isWarnEnabled()) { - logger.warn("invoke time out. method: " + invocation.getMethodName() - + " arguments: " + Arrays.toString(invocation.getArguments()) + " , url is " - + invoker.getUrl() + ", invoke elapsed " + elapsed + " ms."); + static class TimeoutListener implements Listener { + + @Override + public void onResponse(Result appResponse, Invoker invoker, Invocation invocation) { + String startAttach = invocation.getAttachment(TIMEOUT_FILTER_START_TIME); + if (startAttach != null) { + long elapsed = System.currentTimeMillis() - Long.valueOf(startAttach); + if (invoker.getUrl() != null && elapsed > invoker.getUrl().getMethodParameter(invocation.getMethodName(), "timeout", Integer.MAX_VALUE)) { + if (logger.isWarnEnabled()) { + logger.warn("invoke time out. method: " + invocation.getMethodName() + " arguments: " + Arrays.toString(invocation.getArguments()) + " , url is " + invoker.getUrl() + ", invoke elapsed " + elapsed + " ms."); + } } } } - return result; + + @Override + public void onError(Throwable t, Invoker invoker, Invocation invocation) { + + } } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractInvoker.java index e218fa25f09..58cb4105f86 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractInvoker.java @@ -23,13 +23,13 @@ import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.NetUtils; +import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.support.RpcUtils; import java.lang.reflect.InvocationTargetException; @@ -38,8 +38,6 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; -import static org.apache.dubbo.rpc.Constants.ASYNC_KEY; - /** * AbstractInvoker. */ @@ -149,9 +147,8 @@ public Result invoke(Invocation inv) throws RpcException { */ invocation.addAttachments(contextAttachments); } - if (getUrl().getMethodParameter(invocation.getMethodName(), ASYNC_KEY, false)) { - invocation.setAttachment(ASYNC_KEY, Boolean.TRUE.toString()); - } + + invocation.setInvokeMode(RpcUtils.getInvokeMode(url, invocation)); RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation); try { @@ -159,21 +156,21 @@ public Result invoke(Invocation inv) throws RpcException { } catch (InvocationTargetException e) { // biz exception Throwable te = e.getTargetException(); if (te == null) { - return new RpcResult(e); + return AsyncRpcResult.newDefaultAsyncResult(null, e, invocation); } else { if (te instanceof RpcException) { ((RpcException) te).setCode(RpcException.BIZ_EXCEPTION); } - return new RpcResult(te); + return AsyncRpcResult.newDefaultAsyncResult(null, te, invocation); } } catch (RpcException e) { if (e.isBiz()) { - return new RpcResult(e); + return AsyncRpcResult.newDefaultAsyncResult(null, e, invocation); } else { throw e; } } catch (Throwable e) { - return new RpcResult(e); + return AsyncRpcResult.newDefaultAsyncResult(null, e, invocation); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java index 5c49e473ddb..ceeb92e1803 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java @@ -24,6 +24,7 @@ import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; +import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.support.ProtocolUtils; import java.util.ArrayList; @@ -84,4 +85,11 @@ public void destroy() { } } } + + @Override + public Invoker refer(Class type, URL url) throws RpcException { + return new AsyncToSyncInvoker<>(protocolBindingRefer(type, url)); + } + + protected abstract Invoker protocolBindingRefer(Class type, URL url) throws RpcException; } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java index 735b9fe4b7f..d45f9e3951f 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java @@ -95,13 +95,14 @@ public void unexport() { } @Override - public Invoker refer(final Class type, final URL url) throws RpcException { + protected Invoker protocolBindingRefer(final Class type, final URL url) throws RpcException { final Invoker target = proxyFactory.getInvoker(doRefer(type, url), type, url); Invoker invoker = new AbstractInvoker(type, url) { @Override protected Result doInvoke(Invocation invocation) throws Throwable { try { Result result = target.invoke(invocation); + // FIXME result is an AsyncRpcResult instance. Throwable e = result.getException(); if (e != null) { for (Class rpcException : rpcExceptions) { diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AsyncToSyncInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AsyncToSyncInvoker.java new file mode 100644 index 00000000000..5c06b4e4d1d --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AsyncToSyncInvoker.java @@ -0,0 +1,89 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.rpc.protocol; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.remoting.RemotingException; +import org.apache.dubbo.remoting.TimeoutException; +import org.apache.dubbo.rpc.Invocation; +import org.apache.dubbo.rpc.InvokeMode; +import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.Result; +import org.apache.dubbo.rpc.RpcException; +import org.apache.dubbo.rpc.RpcInvocation; + +import java.util.concurrent.ExecutionException; + +/** + * This class will work as a wrapper wrapping outside of each protocol invoker. + * @param + */ +public class AsyncToSyncInvoker implements Invoker { + + private Invoker invoker; + + public AsyncToSyncInvoker(Invoker invoker) { + this.invoker = invoker; + } + + @Override + public Class getInterface() { + return invoker.getInterface(); + } + + @Override + public Result invoke(Invocation invocation) throws RpcException { + Result asyncResult = invoker.invoke(invocation); + + try { + if (InvokeMode.SYNC == ((RpcInvocation)invocation).getInvokeMode()) { + asyncResult.get(); + } + } catch (InterruptedException e) { + throw new RpcException("Interrupted unexpectedly while waiting for remoting result to return! method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); + } catch (ExecutionException e) { + Throwable t = e.getCause(); + if (t instanceof TimeoutException) { + throw new RpcException(RpcException.TIMEOUT_EXCEPTION, "Invoke remote method timeout. method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); + } else if (t instanceof RemotingException) { + throw new RpcException(RpcException.NETWORK_EXCEPTION, "Failed to invoke remote method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); + } + } catch (Throwable e) { + throw new RpcException(e.getMessage(), e); + } + return asyncResult; + } + + @Override + public URL getUrl() { + return invoker.getUrl(); + } + + @Override + public boolean isAvailable() { + return invoker.isAvailable(); + } + + @Override + public void destroy() { + invoker.destroy(); + } + + public Invoker getInvoker() { + return invoker; + } +} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolFilterWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolFilterWrapper.java index f0039dbb7ab..9ee7d3e1f2b 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolFilterWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolFilterWrapper.java @@ -19,11 +19,11 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.ListenableFilter; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; @@ -75,14 +75,31 @@ public boolean isAvailable() { @Override public Result invoke(Invocation invocation) throws RpcException { - Result result = filter.invoke(next, invocation); - if (result instanceof AsyncRpcResult) { - AsyncRpcResult asyncResult = (AsyncRpcResult) result; - asyncResult.thenApplyWithContext(r -> filter.onResponse(r, invoker, invocation)); - return asyncResult; - } else { - return filter.onResponse(result, invoker, invocation); + Result asyncResult; + try { + asyncResult = filter.invoke(next, invocation); + } catch (Exception e) { + // onError callback + if (filter instanceof ListenableFilter) { + Filter.Listener listener = ((ListenableFilter) filter).listener(); + if (listener != null) { + listener.onError(e, invoker, invocation); + } + } + throw e; } + return asyncResult.thenApplyWithContext(r -> { + // onResponse callback + if (filter instanceof ListenableFilter) { + Filter.Listener listener = ((ListenableFilter) filter).listener(); + if (listener != null) { + listener.onResponse(r, invoker, invocation); + } + } else { + filter.onResponse(r, invoker, invocation); + } + return r; + }); } @Override diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyInvoker.java index 6a562d6f6fd..fe42fb2c6be 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyInvoker.java @@ -19,6 +19,7 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.AsyncContextImpl; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; @@ -26,11 +27,11 @@ import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.support.RpcUtils; import java.lang.reflect.InvocationTargetException; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; /** * InvokerWrapper @@ -78,30 +79,48 @@ public boolean isAvailable() { public void destroy() { } - // TODO Unified to AsyncResult? @Override public Result invoke(Invocation invocation) throws RpcException { - RpcContext rpcContext = RpcContext.getContext(); try { - Object obj = doInvoke(proxy, invocation.getMethodName(), invocation.getParameterTypes(), invocation.getArguments()); - if (RpcUtils.isReturnTypeFuture(invocation)) { - return new AsyncRpcResult((CompletableFuture) obj); - } else if (rpcContext.isAsyncStarted()) { // ignore obj in case of RpcContext.startAsync()? always rely on user to write back. - return new AsyncRpcResult(((AsyncContextImpl)(rpcContext.getAsyncContext())).getInternalFuture()); - } else { - return new RpcResult(obj); - } + Object value = doInvoke(proxy, invocation.getMethodName(), invocation.getParameterTypes(), invocation.getArguments()); + CompletableFuture future = wrapWithFuture(value, invocation); + AsyncRpcResult asyncRpcResult = new AsyncRpcResult(invocation); + future.whenComplete((obj, t) -> { + AppResponse result = new AppResponse(); + if (t != null) { + if (t instanceof CompletionException) { + result.setException(t.getCause()); + } else { + result.setException(t); + } + } else { + result.setValue(obj); + } + asyncRpcResult.complete(result); + }); + return asyncRpcResult; } catch (InvocationTargetException e) { - // TODO async throw exception before async thread write back, should stop asyncContext - if (rpcContext.isAsyncStarted() && !rpcContext.stopAsync()) { + if (RpcContext.getContext().isAsyncStarted() && !RpcContext.getContext().stopAsync()) { logger.error("Provider async started, but got an exception from the original method, cannot write the exception back to consumer because an async result may have returned the new thread.", e); } - return new RpcResult(e.getTargetException()); + return AsyncRpcResult.newDefaultAsyncResult(null, e.getTargetException(), invocation); } catch (Throwable e) { throw new RpcException("Failed to invoke remote proxy method " + invocation.getMethodName() + " to " + getUrl() + ", cause: " + e.getMessage(), e); } } + private CompletableFuture wrapWithFuture (Object value, Invocation invocation) { + if (RpcContext.getContext().isAsyncStarted()) { + return ((AsyncContextImpl)(RpcContext.getContext().getAsyncContext())).getInternalFuture(); + } else if (RpcUtils.isReturnTypeFuture(invocation)) { + if (value == null) { + return CompletableFuture.completedFuture(null); + } + return (CompletableFuture) value; + } + return CompletableFuture.completedFuture(value); + } + protected abstract Object doInvoke(T proxy, String methodName, Class[] parameterTypes, Object[] arguments) throws Throwable; @Override diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvokerInvocationHandler.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvokerInvocationHandler.java index a76f081122c..1d047cdccf4 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvokerInvocationHandler.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvokerInvocationHandler.java @@ -20,14 +20,10 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.support.RpcUtils; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; -import static org.apache.dubbo.rpc.Constants.ASYNC_KEY; -import static org.apache.dubbo.rpc.Constants.FUTURE_RETURNTYPE_KEY; - /** * InvokerHandler */ @@ -56,16 +52,6 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl return invoker.equals(args[0]); } - return invoker.invoke(createInvocation(method, args)).recreate(); + return invoker.invoke(new RpcInvocation(method, args)).recreate(); } - - private RpcInvocation createInvocation(Method method, Object[] args) { - RpcInvocation invocation = new RpcInvocation(method, args); - if (RpcUtils.hasFutureReturnType(method)) { - invocation.setAttachment(FUTURE_RETURNTYPE_KEY, "true"); - invocation.setAttachment(ASYNC_KEY, "true"); - } - return invocation; - } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/service/GenericService.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/service/GenericService.java index 07517d474a4..d93fa14930a 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/service/GenericService.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/service/GenericService.java @@ -16,6 +16,8 @@ */ package org.apache.dubbo.rpc.service; +import java.util.concurrent.CompletableFuture; + /** * Generic service interface * @@ -35,4 +37,12 @@ public interface GenericService { */ Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException; + default CompletableFuture $invokeAsync(String method, String[] parameterTypes, Object[] args) throws GenericException { + Object object = $invoke(method, parameterTypes, args); + if (object instanceof CompletableFuture) { + return (CompletableFuture) object; + } + return CompletableFuture.completedFuture(object); + } + } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java index 32fc5ae6324..e8f8209e69b 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java @@ -18,18 +18,18 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; +import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.PojoUtils; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.common.utils.ArrayUtils; +import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.RpcResult; import com.alibaba.fastjson.JSON; @@ -112,7 +112,7 @@ public Result invoke(Invocation invocation) throws RpcException { try { Type[] returnTypes = RpcUtils.getReturnTypes(invocation); Object value = parseMockValue(mock, returnTypes); - return new RpcResult(value); + return AsyncRpcResult.newDefaultAsyncResult(value, invocation); } catch (Exception ew) { throw new RpcException("mock return invoke error. method :" + invocation.getMethodName() + ", mock:" + mock + ", url: " + url, ew); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockProtocol.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockProtocol.java index 9237ab955c0..46089968172 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockProtocol.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockProtocol.java @@ -38,7 +38,7 @@ public Exporter export(Invoker invoker) throws RpcException { } @Override - public Invoker refer(Class type, URL url) throws RpcException { + public Invoker protocolBindingRefer(Class type, URL url) throws RpcException { return new MockInvoker<>(url, type); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java index 18e59ba4170..7bf4533100e 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java @@ -22,23 +22,22 @@ import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.Invocation; +import org.apache.dubbo.rpc.InvokeMode; import org.apache.dubbo.rpc.RpcInvocation; import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicLong; import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE; -import static org.apache.dubbo.rpc.Constants.AUTO_ATTACH_INVOCATIONID_KEY; -import static org.apache.dubbo.rpc.Constants.ID_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE_ASYNC; import static org.apache.dubbo.rpc.Constants.ASYNC_KEY; +import static org.apache.dubbo.rpc.Constants.AUTO_ATTACH_INVOCATIONID_KEY; import static org.apache.dubbo.rpc.Constants.FUTURE_GENERATED_KEY; -import static org.apache.dubbo.rpc.Constants.FUTURE_RETURNTYPE_KEY; +import static org.apache.dubbo.rpc.Constants.ID_KEY; import static org.apache.dubbo.rpc.Constants.RETURN_KEY; /** * RpcUtils @@ -71,7 +70,6 @@ public static Class getReturnType(Invocation invocation) { return null; } - // TODO why not get return type when initialize Invocation? public static Type[] getReturnTypes(Invocation invocation) { try { if (invocation != null && invocation.getInvoker() != null @@ -86,24 +84,7 @@ public static Type[] getReturnTypes(Invocation invocation) { if (method.getReturnType() == void.class) { return null; } - Class returnType = method.getReturnType(); - Type genericReturnType = method.getGenericReturnType(); - if (Future.class.isAssignableFrom(returnType)) { - if (genericReturnType instanceof ParameterizedType) { - Type actualArgType = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0]; - if (actualArgType instanceof ParameterizedType) { - returnType = (Class) ((ParameterizedType) actualArgType).getRawType(); - genericReturnType = actualArgType; - } else { - returnType = (Class) actualArgType; - genericReturnType = returnType; - } - } else { - returnType = null; - genericReturnType = null; - } - } - return new Type[]{returnType, genericReturnType}; + return ReflectUtils.getReturnTypes(method); } } } catch (Throwable t) { @@ -190,11 +171,22 @@ public static boolean isAsync(URL url, Invocation inv) { } public static boolean isReturnTypeFuture(Invocation inv) { - return Boolean.TRUE.toString().equals(inv.getAttachment(FUTURE_RETURNTYPE_KEY)); + Class clazz = getReturnType(inv); + return (clazz != null && CompletableFuture.class.isAssignableFrom(clazz)) || isGenericAsync(inv); + } + + public static InvokeMode getInvokeMode(URL url, Invocation inv) { + if (isReturnTypeFuture(inv)) { + return InvokeMode.FUTURE; + } else if (isAsync(url, inv)) { + return InvokeMode.ASYNC; + } else { + return InvokeMode.SYNC; + } } - public static boolean hasFutureReturnType(Method method) { - return CompletableFuture.class.isAssignableFrom(method.getReturnType()); + public static boolean isGenericAsync(Invocation inv) { + return $INVOKE_ASYNC.equals(inv.getMethodName()); } public static boolean isOneway(URL url, Invocation inv) { diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcResultTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/AppResponseTest.java similarity index 78% rename from dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcResultTest.java rename to dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/AppResponseTest.java index 9c983a544a5..2fcace07a9a 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcResultTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/AppResponseTest.java @@ -20,13 +20,13 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -public class RpcResultTest { +public class AppResponseTest { @Test - public void testRpcResultWithNormalException() { + public void testAppResponseWithNormalException() { NullPointerException npe = new NullPointerException(); - RpcResult rpcResult = new RpcResult(npe); + AppResponse appResponse = new AppResponse(npe); - StackTraceElement[] stackTrace = rpcResult.getException().getStackTrace(); + StackTraceElement[] stackTrace = appResponse.getException().getStackTrace(); Assertions.assertNotNull(stackTrace); Assertions.assertTrue(stackTrace.length > 1); } @@ -35,14 +35,14 @@ public void testRpcResultWithNormalException() { * please run this test in Run mode */ @Test - public void testRpcResultWithEmptyStackTraceException() { + public void testAppResponseWithEmptyStackTraceException() { Throwable throwable = buildEmptyStackTraceException(); if (throwable == null) { return; } - RpcResult rpcResult = new RpcResult(throwable); + AppResponse appResponse = new AppResponse(throwable); - StackTraceElement[] stackTrace = rpcResult.getException().getStackTrace(); + StackTraceElement[] stackTrace = appResponse.getException().getStackTrace(); Assertions.assertNotNull(stackTrace); Assertions.assertTrue(stackTrace.length == 0); } @@ -50,10 +50,10 @@ public void testRpcResultWithEmptyStackTraceException() { @Test public void testSetExceptionWithNormalException() { NullPointerException npe = new NullPointerException(); - RpcResult rpcResult = new RpcResult(); - rpcResult.setException(npe); + AppResponse appResponse = new AppResponse(); + appResponse.setException(npe); - StackTraceElement[] stackTrace = rpcResult.getException().getStackTrace(); + StackTraceElement[] stackTrace = appResponse.getException().getStackTrace(); Assertions.assertNotNull(stackTrace); Assertions.assertTrue(stackTrace.length > 1); } @@ -67,10 +67,10 @@ public void testSetExceptionWithEmptyStackTraceException() { if (throwable == null) { return; } - RpcResult rpcResult = new RpcResult(); - rpcResult.setException(throwable); + AppResponse appResponse = new AppResponse(); + appResponse.setException(throwable); - StackTraceElement[] stackTrace = rpcResult.getException().getStackTrace(); + StackTraceElement[] stackTrace = appResponse.getException().getStackTrace(); Assertions.assertNotNull(stackTrace); Assertions.assertTrue(stackTrace.length == 0); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ActiveLimitFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ActiveLimitFilterTest.java index 6d085f70617..9c749c983c5 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ActiveLimitFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ActiveLimitFilterTest.java @@ -17,9 +17,9 @@ package org.apache.dubbo.rpc.filter; import org.apache.dubbo.common.URL; -import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcStatus; import org.apache.dubbo.rpc.support.BlockMyInvoker; @@ -35,13 +35,14 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.fail; /** * ActiveLimitFilterTest.java */ public class ActiveLimitFilterTest { - Filter activeLimitFilter = new ActiveLimitFilter(); + ActiveLimitFilter activeLimitFilter = new ActiveLimitFilter(); @Test public void testInvokeNoActives() { @@ -97,7 +98,7 @@ public void run() { } @Test - public void testInvokeTimeOut() { + public void testInvokeTimeOut() throws Exception { int totalThread = 100; int maxActives = 10; long timeout = 1; @@ -120,9 +121,14 @@ public void run() { e.printStackTrace(); } try { - activeLimitFilter.invoke(invoker, invocation); + Result asyncResult = activeLimitFilter.invoke(invoker, invocation); + Result result = asyncResult.get(); + activeLimitFilter.listener().onResponse(result, invoker, invocation); } catch (RpcException expected) { count.incrementAndGet(); +// activeLimitFilter.listener().onError(expected, invoker, invocation); + } catch (Exception e) { + fail(); } } finally { latchBlocking.countDown(); @@ -142,7 +148,7 @@ public void run() { } @Test - public void testInvokeNotTimeOut() { + public void testInvokeNotTimeOut() throws Exception { int totalThread = 100; int maxActives = 10; long timeout = 1000; @@ -163,9 +169,14 @@ public void run() { e.printStackTrace(); } try { - activeLimitFilter.invoke(invoker, invocation); + Result asyncResult = activeLimitFilter.invoke(invoker, invocation); + Result result = asyncResult.get(); + activeLimitFilter.listener().onResponse(result, invoker, invocation); } catch (RpcException expected) { count.incrementAndGet(); + activeLimitFilter.listener().onError(expected, invoker, invocation); + } catch (Exception e) { + fail(); } } finally { latchBlocking.countDown(); @@ -208,6 +219,7 @@ public void testInvokeRuntimeExceptionWithActiveCountMatch() { try { activeLimitFilter.invoke(invoker, invocation); } catch (RuntimeException ex) { + activeLimitFilter.listener().onError(ex, invoker, invocation); int afterExceptionActiveCount = count.getActive(); assertEquals(beforeExceptionActiveCount, afterExceptionActiveCount, "After exception active count should be same"); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/CompatibleFilterFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/CompatibleFilterFilterTest.java index b91c92d1640..709401d4278 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/CompatibleFilterFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/CompatibleFilterFilterTest.java @@ -17,13 +17,14 @@ package org.apache.dubbo.rpc.filter; import org.apache.dubbo.common.URL; -import org.apache.dubbo.rpc.Filter; +import org.apache.dubbo.rpc.AppResponse; +import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.support.DemoService; import org.apache.dubbo.rpc.support.Type; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -37,7 +38,7 @@ * CompatibleFilterTest.java */ public class CompatibleFilterFilterTest { - private Filter compatibleFilter = new CompatibleFilter(); + private CompatibleFilter compatibleFilter = new CompatibleFilter(); private Invocation invocation; private Invoker invoker; @@ -56,7 +57,7 @@ public void testInvokerGeneric() { invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); given(invoker.getInterface()).willReturn(DemoService.class); - RpcResult result = new RpcResult(); + AppResponse result = new AppResponse(); result.setValue("High"); given(invoker.invoke(invocation)).willReturn(result); URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); @@ -76,7 +77,7 @@ public void testResulthasException() { invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); given(invoker.getInterface()).willReturn(DemoService.class); - RpcResult result = new RpcResult(); + AppResponse result = new AppResponse(); result.setException(new RuntimeException()); result.setValue("High"); given(invoker.invoke(invocation)).willReturn(result); @@ -88,7 +89,7 @@ public void testResulthasException() { } @Test - public void testInvokerJsonPojoSerialization() { + public void testInvokerJsonPojoSerialization() throws Exception { invocation = mock(Invocation.class); given(invocation.getMethodName()).willReturn("enumlength"); given(invocation.getParameterTypes()).willReturn(new Class[]{Type[].class}); @@ -97,18 +98,20 @@ public void testInvokerJsonPojoSerialization() { invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); given(invoker.getInterface()).willReturn(DemoService.class); - RpcResult result = new RpcResult(); + AppResponse result = new AppResponse(); result.setValue("High"); - given(invoker.invoke(invocation)).willReturn(result); + given(invoker.invoke(invocation)).willReturn(AsyncRpcResult.newDefaultAsyncResult(result, invocation)); URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1&serialization=json"); given(invoker.getUrl()).willReturn(url); - Result filterResult = compatibleFilter.invoke(invoker, invocation); - assertEquals(Type.High, filterResult.getValue()); + Result asyncResult = compatibleFilter.invoke(invoker, invocation); + AppResponse appResponse = (AppResponse) asyncResult.get(); + compatibleFilter.listener().onResponse(appResponse, invoker, invocation); + assertEquals(Type.High, appResponse.getValue()); } @Test - public void testInvokerNonJsonEnumSerialization() { + public void testInvokerNonJsonEnumSerialization() throws Exception { invocation = mock(Invocation.class); given(invocation.getMethodName()).willReturn("enumlength"); given(invocation.getParameterTypes()).willReturn(new Class[]{Type[].class}); @@ -117,14 +120,16 @@ public void testInvokerNonJsonEnumSerialization() { invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); given(invoker.getInterface()).willReturn(DemoService.class); - RpcResult result = new RpcResult(); + AppResponse result = new AppResponse(); result.setValue("High"); - given(invoker.invoke(invocation)).willReturn(result); + given(invoker.invoke(invocation)).willReturn(AsyncRpcResult.newDefaultAsyncResult(result, invocation)); URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); given(invoker.getUrl()).willReturn(url); - Result filterResult = compatibleFilter.invoke(invoker, invocation); - assertEquals(Type.High, filterResult.getValue()); + Result asyncResult = compatibleFilter.invoke(invoker, invocation); + AppResponse appResponse = (AppResponse) asyncResult.get(); + compatibleFilter.listener().onResponse(appResponse, invoker, invocation); + assertEquals(Type.High, appResponse.getValue()); } @Test @@ -137,7 +142,7 @@ public void testInvokerNonJsonNonPojoSerialization() { invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); given(invoker.getInterface()).willReturn(DemoService.class); - RpcResult result = new RpcResult(); + AppResponse result = new AppResponse(); result.setValue(new String[]{"High"}); given(invoker.invoke(invocation)).willReturn(result); URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); @@ -157,7 +162,7 @@ public void testInvokerNonJsonPojoSerialization() { invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); given(invoker.getInterface()).willReturn(DemoService.class); - RpcResult result = new RpcResult(); + AppResponse result = new AppResponse(); result.setValue("hello"); given(invoker.invoke(invocation)).willReturn(result); URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ConsumerContextFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ConsumerContextFilterTest.java index a906af47be2..93635528338 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ConsumerContextFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ConsumerContextFilterTest.java @@ -21,6 +21,7 @@ import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.support.DemoService; import org.apache.dubbo.rpc.support.MockInvocation; @@ -41,11 +42,13 @@ public void testSetContext() { URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); Invoker invoker = new MyInvoker(url); Invocation invocation = new MockInvocation(); - consumerContextFilter.invoke(invoker, invocation); - assertEquals(invoker, RpcContext.getContext().getInvoker()); - assertEquals(invocation, RpcContext.getContext().getInvocation()); - assertEquals(NetUtils.getLocalHost() + ":0", RpcContext.getContext().getLocalAddressString()); - assertEquals("test:11", RpcContext.getContext().getRemoteAddressString()); - + Result asyncResult = consumerContextFilter.invoke(invoker, invocation); + asyncResult.thenApplyWithContext(result -> { + assertEquals(invoker, RpcContext.getContext().getInvoker()); + assertEquals(invocation, RpcContext.getContext().getInvocation()); + assertEquals(NetUtils.getLocalHost() + ":0", RpcContext.getContext().getLocalAddressString()); + assertEquals("test:11", RpcContext.getContext().getRemoteAddressString()); + return result; + }); } } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ContextFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ContextFilterTest.java index c753c7e0e2e..506c10db5d5 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ContextFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ContextFilterTest.java @@ -17,12 +17,12 @@ package org.apache.dubbo.rpc.filter; import org.apache.dubbo.common.URL; +import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.support.DemoService; import org.apache.dubbo.rpc.support.MockInvocation; import org.apache.dubbo.rpc.support.MyInvoker; @@ -55,7 +55,7 @@ public void testSetContext() { invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); given(invoker.getInterface()).willReturn(DemoService.class); - RpcResult result = new RpcResult(); + AppResponse result = new AppResponse(); result.setValue("High"); given(invoker.invoke(invocation)).willReturn(result); URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/EchoFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/EchoFilterTest.java index 02f367b8a8e..3befdc77df9 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/EchoFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/EchoFilterTest.java @@ -17,11 +17,11 @@ package org.apache.dubbo.rpc.filter; import org.apache.dubbo.common.URL; +import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.support.DemoService; import org.junit.jupiter.api.Test; @@ -46,7 +46,7 @@ public void testEcho() { Invoker invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); given(invoker.getInterface()).willReturn(DemoService.class); - RpcResult result = new RpcResult(); + AppResponse result = new AppResponse(); result.setValue("High"); given(invoker.invoke(invocation)).willReturn(result); URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); @@ -68,7 +68,7 @@ public void testNonEcho() { Invoker invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); given(invoker.getInterface()).willReturn(DemoService.class); - RpcResult result = new RpcResult(); + AppResponse result = new AppResponse(); result.setValue("High"); given(invoker.invoke(invocation)).willReturn(result); URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExceptionFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExceptionFilterTest.java index f40f8776e45..bc9c1320372 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExceptionFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExceptionFilterTest.java @@ -17,13 +17,13 @@ package org.apache.dubbo.rpc.filter; import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.utils.StringUtils; +import org.apache.dubbo.rpc.AppResponse; +import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.support.DemoService; import org.apache.dubbo.rpc.support.LocalException; @@ -51,18 +51,20 @@ public void testRpcException() { RpcContext.getContext().setRemoteAddress("127.0.0.1", 1234); RpcException exception = new RpcException("TestRpcException"); - ExceptionFilter exceptionFilter = new ExceptionFilter(logger); + ExceptionFilter exceptionFilter = new ExceptionFilter(); RpcInvocation invocation = new RpcInvocation("sayHello", new Class[]{String.class}, new Object[]{"world"}); Invoker invoker = mock(Invoker.class); given(invoker.getInterface()).willReturn(DemoService.class); given(invoker.invoke(eq(invocation))).willThrow(exception); - try { exceptionFilter.invoke(invoker, invocation); } catch (RpcException e) { assertEquals("TestRpcException", e.getMessage()); + ((ExceptionFilter.ExceptionListener) exceptionFilter.listener()).setLogger(logger); + exceptionFilter.listener().onError(e, invoker, invocation); } + Mockito.verify(logger).error(eq("Got unchecked and undeclared exception which called by 127.0.0.1. service: " + DemoService.class.getName() + ", method: sayHello, exception: " + RpcException.class.getName() + ": TestRpcException"), eq(exception)); @@ -76,16 +78,16 @@ public void testJavaException() { ExceptionFilter exceptionFilter = new ExceptionFilter(); RpcInvocation invocation = new RpcInvocation("sayHello", new Class[]{String.class}, new Object[]{"world"}); - RpcResult rpcResult = new RpcResult(); - rpcResult.setException(new IllegalArgumentException("java")); + AppResponse appResponse = new AppResponse(); + appResponse.setException(new IllegalArgumentException("java")); Invoker invoker = mock(Invoker.class); - when(invoker.invoke(invocation)).thenReturn(rpcResult); + when(invoker.invoke(invocation)).thenReturn(appResponse); when(invoker.getInterface()).thenReturn(DemoService.class); Result newResult = exceptionFilter.invoke(invoker, invocation); - Assertions.assertEquals(rpcResult.getException(), newResult.getException()); + Assertions.assertEquals(appResponse.getException(), newResult.getException()); } @@ -96,42 +98,43 @@ public void testRuntimeException() { ExceptionFilter exceptionFilter = new ExceptionFilter(); RpcInvocation invocation = new RpcInvocation("sayHello", new Class[]{String.class}, new Object[]{"world"}); - RpcResult rpcResult = new RpcResult(); - rpcResult.setException(new LocalException("localException")); + AppResponse appResponse = new AppResponse(); + appResponse.setException(new LocalException("localException")); Invoker invoker = mock(Invoker.class); - when(invoker.invoke(invocation)).thenReturn(rpcResult); + when(invoker.invoke(invocation)).thenReturn(appResponse); when(invoker.getInterface()).thenReturn(DemoService.class); Result newResult = exceptionFilter.invoke(invoker, invocation); - Assertions.assertEquals(rpcResult.getException(), newResult.getException()); + Assertions.assertEquals(appResponse.getException(), newResult.getException()); } @SuppressWarnings("unchecked") @Test - public void testConvertToRunTimeException() { + public void testConvertToRunTimeException() throws Exception { ExceptionFilter exceptionFilter = new ExceptionFilter(); RpcInvocation invocation = new RpcInvocation("sayHello", new Class[]{String.class}, new Object[]{"world"}); - RpcResult rpcResult = new RpcResult(); - rpcResult.setException(new HessianException("hessian")); + AppResponse mockRpcResult = new AppResponse(); + mockRpcResult.setException(new HessianException("hessian")); + Result mockAsyncResult = AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation); + Invoker invoker = mock(Invoker.class); - when(invoker.invoke(invocation)).thenReturn(rpcResult); + when(invoker.invoke(invocation)).thenReturn(mockAsyncResult); when(invoker.getInterface()).thenReturn(DemoService.class); - Result newResult = exceptionFilter.invoke(invoker, invocation); - - newResult = exceptionFilter.onResponse(newResult, invoker, invocation); + Result asyncResult = exceptionFilter.invoke(invoker, invocation); - Assertions.assertFalse(newResult.getException() instanceof HessianException); + AppResponse appResponse = (AppResponse) asyncResult.get(); + exceptionFilter.listener().onResponse(appResponse, invoker, invocation); - Assertions.assertEquals(newResult.getException().getClass(), RuntimeException.class); - Assertions.assertEquals(newResult.getException().getMessage(), StringUtils.toString(rpcResult.getException())); + Assertions.assertFalse(appResponse.getException() instanceof HessianException); + Assertions.assertEquals(appResponse.getException().getClass(), RuntimeException.class); } } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilterTest.java index 2fab7894e32..4cbc280275d 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilterTest.java @@ -17,11 +17,11 @@ package org.apache.dubbo.rpc.filter; import org.apache.dubbo.common.URL; +import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.RpcStatus; import org.apache.dubbo.rpc.support.BlockMyInvoker; @@ -43,7 +43,7 @@ public class ExecuteLimitFilterTest { @Test public void testNoExecuteLimitInvoke() throws Exception { Invoker invoker = Mockito.mock(Invoker.class); - when(invoker.invoke(any(Invocation.class))).thenReturn(new RpcResult("result")); + when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result")); when(invoker.getUrl()).thenReturn(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1")); Invocation invocation = Mockito.mock(Invocation.class); @@ -56,7 +56,7 @@ public void testNoExecuteLimitInvoke() throws Exception { @Test public void testExecuteLimitInvoke() throws Exception { Invoker invoker = Mockito.mock(Invoker.class); - when(invoker.invoke(any(Invocation.class))).thenReturn(new RpcResult("result")); + when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result")); when(invoker.getUrl()).thenReturn(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&executes=10")); Invocation invocation = Mockito.mock(Invocation.class); @@ -82,6 +82,7 @@ public void testExecuteLimitInvokeWitException() throws Exception { executeLimitFilter.invoke(invoker, invocation); } catch (Exception e) { Assertions.assertTrue(e instanceof RpcException); + executeLimitFilter.listener().onError(e, invoker, invocation); } Assertions.assertEquals(1, RpcStatus.getStatus(url, invocation.getMethodName()).getFailed()); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.java index f7639f7f57f..46bc99ce9c4 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.java @@ -17,7 +17,13 @@ package org.apache.dubbo.rpc.filter; import org.apache.dubbo.common.URL; -import org.apache.dubbo.rpc.*; +import org.apache.dubbo.rpc.AppResponse; +import org.apache.dubbo.rpc.AsyncRpcResult; +import org.apache.dubbo.rpc.Invocation; +import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.Result; +import org.apache.dubbo.rpc.RpcException; +import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.service.GenericService; import org.apache.dubbo.rpc.support.DemoService; import org.apache.dubbo.rpc.support.Person; @@ -54,14 +60,16 @@ public void testInvokeWithDefault() throws Exception { URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + "accesslog=true&group=dubbo&version=1.1"); Invoker invoker = Mockito.mock(Invoker.class); - when(invoker.invoke(any(Invocation.class))).thenReturn(new RpcResult(new Person("person", 10))); + when(invoker.invoke(any(Invocation.class))).thenReturn(AsyncRpcResult.newDefaultAsyncResult(new Person("person", 10), invocation)); when(invoker.getUrl()).thenReturn(url); when(invoker.getInterface()).thenReturn(DemoService.class); - Result result = genericFilter.invoke(invoker, invocation); + Result asyncResult = genericFilter.invoke(invoker, invocation); - Assertions.assertEquals(HashMap.class, result.getValue().getClass()); - Assertions.assertEquals(10, ((HashMap) result.getValue()).get("age")); + AppResponse appResponse = (AppResponse) asyncResult.get(); + genericFilter.listener().onResponse(appResponse, invoker, invocation); + Assertions.assertEquals(HashMap.class, appResponse.getValue().getClass()); + Assertions.assertEquals(10, ((HashMap) appResponse.getValue()).get("age")); } @@ -81,7 +89,7 @@ public void testInvokeWithJavaException() throws Exception { URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + "accesslog=true&group=dubbo&version=1.1"); Invoker invoker = Mockito.mock(Invoker.class); - when(invoker.invoke(any(Invocation.class))).thenReturn(new RpcResult(new Person("person", 10))); + when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse(new Person("person", 10))); when(invoker.getUrl()).thenReturn(url); when(invoker.getInterface()).thenReturn(DemoService.class); @@ -104,7 +112,7 @@ public void testInvokeWithJavaException() throws Exception { URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + "accesslog=true&group=dubbo&version=1.1"); Invoker invoker = Mockito.mock(Invoker.class); - when(invoker.invoke(any(Invocation.class))).thenReturn(new RpcResult(new Person("person", 10))); + when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse(new Person("person", 10))); when(invoker.getUrl()).thenReturn(url); when(invoker.getInterface()).thenReturn(DemoService.class); @@ -128,7 +136,7 @@ public void testInvokeWithMethodArgumentSizeIsNot3() { URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + "accesslog=true&group=dubbo&version=1.1"); Invoker invoker = Mockito.mock(Invoker.class); - when(invoker.invoke(any(Invocation.class))).thenReturn(new RpcResult(new Person("person", 10))); + when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse(new Person("person", 10))); when(invoker.getUrl()).thenReturn(url); when(invoker.getInterface()).thenReturn(DemoService.class); diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java index 5adbdb728ab..73e0d82b6c0 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java @@ -17,11 +17,12 @@ package org.apache.dubbo.rpc.filter; import org.apache.dubbo.common.URL; +import org.apache.dubbo.rpc.AppResponse; +import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.service.GenericException; import org.apache.dubbo.rpc.service.GenericService; import org.apache.dubbo.rpc.support.DemoService; @@ -60,11 +61,14 @@ public void testInvoke() throws Exception { person.put("name", "dubbo"); person.put("age", 10); - when(invoker.invoke(any(Invocation.class))).thenReturn(new RpcResult(person)); + AppResponse mockRpcResult = new AppResponse(person); + when(invoker.invoke(any(Invocation.class))).thenReturn(AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation)); when(invoker.getUrl()).thenReturn(url); when(invoker.getInterface()).thenReturn(DemoService.class); - Result result = genericImplFilter.invoke(invoker, invocation); + Result asyncResult = genericImplFilter.invoke(invoker, invocation); + Result result = asyncResult.get(); + genericImplFilter.listener().onResponse(result, invoker, invocation); Assertions.assertEquals(Person.class, result.getValue().getClass()); Assertions.assertEquals(10, ((Person) result.getValue()).getAge()); @@ -80,12 +84,14 @@ public void testInvokeWithException() throws Exception { "accesslog=true&group=dubbo&version=1.1&generic=true"); Invoker invoker = Mockito.mock(Invoker.class); - when(invoker.invoke(any(Invocation.class))).thenReturn( - new RpcResult(new GenericException(new RuntimeException("failed")))); + AppResponse mockRpcResult = new AppResponse(new GenericException(new RuntimeException("failed"))); + when(invoker.invoke(any(Invocation.class))).thenReturn(AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation)); when(invoker.getUrl()).thenReturn(url); when(invoker.getInterface()).thenReturn(DemoService.class); - Result result = genericImplFilter.invoke(invoker, invocation); + Result asyncResult = genericImplFilter.invoke(invoker, invocation); + Result result = asyncResult.get(); + genericImplFilter.listener().onResponse(result, invoker, invocation); Assertions.assertEquals(RuntimeException.class, result.getException().getClass()); } @@ -105,7 +111,7 @@ public void testInvokeWithException() throws Exception { URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + "accesslog=true&group=dubbo&version=1.1&generic=true"); Invoker invoker = Mockito.mock(Invoker.class); - when(invoker.invoke(any(Invocation.class))).thenReturn(new RpcResult(new Person("person", 10))); + when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse(new Person("person", 10))); when(invoker.getUrl()).thenReturn(url); genericImplFilter.invoke(invoker, invocation); diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TimeoutFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TimeoutFilterTest.java index f99a0f35480..be853653335 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TimeoutFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TimeoutFilterTest.java @@ -17,10 +17,10 @@ package org.apache.dubbo.rpc.filter; import org.apache.dubbo.common.URL; +import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.support.BlockMyInvoker; import org.junit.jupiter.api.Assertions; @@ -39,7 +39,7 @@ public void testInvokeWithoutTimeout() throws Exception { int timeout = 3000; Invoker invoker = Mockito.mock(Invoker.class); - when(invoker.invoke(any(Invocation.class))).thenReturn(new RpcResult("result")); + when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result")); when(invoker.getUrl()).thenReturn(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&timeout=" + timeout)); Invocation invocation = Mockito.mock(Invocation.class); @@ -60,7 +60,7 @@ public void testInvokeWithTimeout() throws Exception { when(invocation.getMethodName()).thenReturn("testInvokeWithTimeout"); Result result = timeoutFilter.invoke(invoker, invocation); - Assertions.assertEquals("alibaba", result.getValue()); + Assertions.assertEquals("Dubbo", result.getValue()); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TokenFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TokenFilterTest.java index 275ddabcdc6..839416fa9c9 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TokenFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TokenFilterTest.java @@ -17,11 +17,11 @@ package org.apache.dubbo.rpc.filter; import org.apache.dubbo.common.URL; +import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.RpcResult; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -46,7 +46,7 @@ public void testInvokeWithToken() throws Exception { Invoker invoker = Mockito.mock(Invoker.class); URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&token=" + token); when(invoker.getUrl()).thenReturn(url); - when(invoker.invoke(any(Invocation.class))).thenReturn(new RpcResult("result")); + when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result")); Map attachments = new HashMap(); attachments.put(TOKEN_KEY, token); @@ -65,7 +65,7 @@ public void testInvokeWithWrongToken() throws Exception { Invoker invoker = Mockito.mock(Invoker.class); URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&token=" + token); when(invoker.getUrl()).thenReturn(url); - when(invoker.invoke(any(Invocation.class))).thenReturn(new RpcResult("result")); + when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result")); Map attachments = new HashMap(); attachments.put(TOKEN_KEY, "wrongToken"); @@ -84,7 +84,7 @@ public void testInvokeWithoutToken() throws Exception { Invoker invoker = Mockito.mock(Invoker.class); URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&token=" + token); when(invoker.getUrl()).thenReturn(url); - when(invoker.invoke(any(Invocation.class))).thenReturn(new RpcResult("result")); + when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result")); Invocation invocation = Mockito.mock(Invocation.class); diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/BlockMyInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/BlockMyInvoker.java index 28baacbf611..7fec8d49fdb 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/BlockMyInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/BlockMyInvoker.java @@ -17,10 +17,11 @@ package org.apache.dubbo.rpc.support; import org.apache.dubbo.common.URL; +import org.apache.dubbo.rpc.AppResponse; +import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.RpcResult; public class BlockMyInvoker extends MyInvoker { @@ -38,19 +39,18 @@ public BlockMyInvoker(URL url, boolean hasException, long blockTime) { @Override public Result invoke(Invocation invocation) throws RpcException { - RpcResult result = new RpcResult(); + AppResponse result = new AppResponse(); if (hasException == false) { try { Thread.sleep(blockTime); } catch (InterruptedException e) { } - result.setValue("alibaba"); - return result; + result.setValue("Dubbo"); } else { result.setException(new RuntimeException("mocked exception")); - return result; } + return AsyncRpcResult.newDefaultAsyncResult(result, invocation); } public long getBlockTime() { diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java index 44e330724c8..f28022dca38 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java @@ -57,6 +57,16 @@ public Map getAttachments() { return attachments; } + @Override + public void setAttachment(String key, String value) { + + } + + @Override + public void setAttachmentIfAbsent(String key, String value) { + + } + public Invoker getInvoker() { return null; } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java index eb944c9bc1a..57f1f1e6cc5 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java @@ -17,11 +17,12 @@ package org.apache.dubbo.rpc.support; import org.apache.dubbo.common.URL; +import org.apache.dubbo.rpc.AppResponse; +import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.RpcResult; /** * MockInvoker.java @@ -58,15 +59,14 @@ public boolean isAvailable() { } public Result invoke(Invocation invocation) throws RpcException { - RpcResult result = new RpcResult(); + AppResponse result = new AppResponse(); if (hasException == false) { result.setValue("alibaba"); - return result; } else { result.setException(new RuntimeException("mocked exception")); - return result; } + return AsyncRpcResult.newDefaultAsyncResult(result, invocation); } @Override diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java index 7e26606bd99..0ebe357f780 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java @@ -30,6 +30,7 @@ import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.RpcInvocation; +import org.apache.dubbo.rpc.protocol.AsyncToSyncInvoker; import java.io.IOException; import java.util.HashMap; @@ -155,7 +156,7 @@ private static Object referOrDestroyCallbackService(Channel channel, URL url, Cl if (!isInstancesOverLimit(channel, referurl, clazz.getName(), instid, true)) { @SuppressWarnings("rawtypes") Invoker invoker = new ChannelWrappedInvoker(clazz, channel, referurl, String.valueOf(instid)); - proxy = PROXY_FACTORY.getProxy(invoker); + proxy = PROXY_FACTORY.getProxy(new AsyncToSyncInvoker<>(invoker)); channel.setAttribute(proxyCacheKey, proxy); channel.setAttribute(invokerCacheKey, invoker); increaseInstanceCount(channel, countkey); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java index 54d74d3ef6c..101851240c0 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java @@ -24,25 +24,27 @@ import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.remoting.exchange.support.header.HeaderExchangeClient; import org.apache.dubbo.remoting.transport.ClientDelegate; +import org.apache.dubbo.rpc.AppResponse; +import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.protocol.AbstractInvoker; +import org.apache.dubbo.rpc.support.RpcUtils; import java.net.InetSocketAddress; +import java.util.concurrent.CompletableFuture; -import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.remoting.Constants.SENT_KEY; -import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CALLBACK_SERVICE_KEY; -import static org.apache.dubbo.rpc.Constants.ASYNC_KEY; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; +import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CALLBACK_SERVICE_KEY; /** + * Server push uses this Invoker to continuously push data to client. * Wrap the existing invoker on the channel. */ class ChannelWrappedInvoker extends AbstractInvoker { @@ -66,15 +68,20 @@ protected Result doInvoke(Invocation invocation) throws Throwable { inv.setAttachment(CALLBACK_SERVICE_KEY, serviceKey); try { - if (getUrl().getMethodParameter(invocation.getMethodName(), ASYNC_KEY, false)) { // may have concurrency issue + if (RpcUtils.isOneway(getUrl(), inv)) { // may have concurrency issue currentClient.send(inv, getUrl().getMethodParameter(invocation.getMethodName(), SENT_KEY, false)); - return new RpcResult(); - } - int timeout = getUrl().getMethodParameter(invocation.getMethodName(), TIMEOUT_KEY, DEFAULT_TIMEOUT); - if (timeout > 0) { - return (Result) currentClient.request(inv, timeout).get(); + return AsyncRpcResult.newDefaultAsyncResult(invocation); } else { - return (Result) currentClient.request(inv).get(); + CompletableFuture responseFuture = currentClient.request(inv); + AsyncRpcResult asyncRpcResult = new AsyncRpcResult(inv); + responseFuture.whenComplete((appResponse, t) -> { + if (t != null) { + asyncRpcResult.completeExceptionally(t); + } else { + asyncRpcResult.complete((AppResponse) appResponse); + } + }); + return asyncRpcResult; } } catch (RpcException e) { throw e; diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java index 0edfdb8f3a3..9515a1ba51d 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java @@ -28,8 +28,8 @@ import org.apache.dubbo.remoting.Decodeable; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.transport.CodecSupport; +import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invocation; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.support.RpcUtils; import java.io.IOException; @@ -38,7 +38,7 @@ import java.lang.reflect.Type; import java.util.Map; -public class DecodeableRpcResult extends RpcResult implements Codec, Decodeable { +public class DecodeableRpcResult extends AppResponse implements Codec, Decodeable { private static final Logger log = LoggerFactory.getLogger(DecodeableRpcResult.class); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCountCodec.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCountCodec.java index fab4dd82b9c..1b1cd1414fd 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCountCodec.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCountCodec.java @@ -23,8 +23,8 @@ import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.exchange.support.MultiMessage; +import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.RpcResult; import java.io.IOException; @@ -76,7 +76,7 @@ private void logMessageLength(Object result, int bytes) { } } else if (result instanceof Response) { try { - ((RpcResult) ((Response) result).getResult()).setAttachment(OUTPUT_KEY, String.valueOf(bytes)); + ((AppResponse) ((Response) result).getResult()).setAttachment(OUTPUT_KEY, String.valueOf(bytes)); } catch (Throwable e) { /* ignore */ } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java index cc0b9e7e225..f40b664e160 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java @@ -23,7 +23,7 @@ import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.TimeoutException; import org.apache.dubbo.remoting.exchange.ExchangeClient; -import org.apache.dubbo.remoting.exchange.ResponseFuture; +import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -31,12 +31,11 @@ import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.RpcResult; -import org.apache.dubbo.rpc.SimpleAsyncRpcResult; import org.apache.dubbo.rpc.protocol.AbstractInvoker; import org.apache.dubbo.rpc.support.RpcUtils; import java.util.Set; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.locks.ReentrantLock; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; @@ -88,32 +87,25 @@ protected Result doInvoke(final Invocation invocation) throws Throwable { currentClient = clients[index.getAndIncrement() % clients.length]; } try { - boolean isAsync = RpcUtils.isAsync(getUrl(), invocation); - boolean isAsyncFuture = RpcUtils.isReturnTypeFuture(inv); boolean isOneway = RpcUtils.isOneway(getUrl(), invocation); int timeout = getUrl().getMethodParameter(methodName, TIMEOUT_KEY, DEFAULT_TIMEOUT); if (isOneway) { boolean isSent = getUrl().getMethodParameter(methodName, Constants.SENT_KEY, false); currentClient.send(inv, isSent); RpcContext.getContext().setFuture(null); - return new RpcResult(); - } else if (isAsync) { - ResponseFuture future = currentClient.request(inv, timeout); - // For compatibility - FutureAdapter futureAdapter = new FutureAdapter<>(future); - RpcContext.getContext().setFuture(futureAdapter); - - Result result; - if (isAsyncFuture) { - // register resultCallback, sometimes we need the async result being processed by the filter chain. - result = new AsyncRpcResult(futureAdapter, futureAdapter.getResultFuture(), false); - } else { - result = new SimpleAsyncRpcResult(futureAdapter, futureAdapter.getResultFuture(), false); - } - return result; + return AsyncRpcResult.newDefaultAsyncResult(invocation); } else { - RpcContext.getContext().setFuture(null); - return (Result) currentClient.request(inv, timeout).get(); + AsyncRpcResult asyncRpcResult = new AsyncRpcResult(inv); + CompletableFuture responseFuture = currentClient.request(inv, timeout); + responseFuture.whenComplete((obj, t) -> { + if (t != null) { + asyncRpcResult.completeExceptionally(t); + } else { + asyncRpcResult.complete((AppResponse) obj); + } + }); + RpcContext.getContext().setFuture(new FutureAdapter(asyncRpcResult)); + return asyncRpcResult; } } catch (TimeoutException e) { throw new RpcException(RpcException.TIMEOUT_EXCEPTION, "Invoke remote method timeout. method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java index f1a627d8c7a..7f9281cc5da 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java @@ -36,7 +36,6 @@ import org.apache.dubbo.remoting.exchange.ExchangeServer; import org.apache.dubbo.remoting.exchange.Exchangers; import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerAdapter; -import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -57,6 +56,7 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import java.util.function.Function; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; @@ -148,16 +148,9 @@ public CompletableFuture reply(ExchangeChannel channel, Object message) return null; } } - RpcContext rpcContext = RpcContext.getContext(); - rpcContext.setRemoteAddress(channel.getRemoteAddress()); + RpcContext.getContext().setRemoteAddress(channel.getRemoteAddress()); Result result = invoker.invoke(inv); - - if (result instanceof AsyncRpcResult) { - return ((AsyncRpcResult) result).getResultFuture().thenApply(r -> (Object) r); - - } else { - return CompletableFuture.completedFuture(result); - } + return result.completionFuture().thenApply(Function.identity()); } @Override @@ -407,7 +400,7 @@ private void optimizeSerialization(URL url) throws RpcException { } @Override - public Invoker refer(Class serviceType, URL url) throws RpcException { + public Invoker protocolBindingRefer(Class serviceType, URL url) throws RpcException { optimizeSerialization(url); // create rpc invoker. diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/FutureAdapter.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/FutureAdapter.java index 28645410d42..03954d1b345 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/FutureAdapter.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/FutureAdapter.java @@ -16,12 +16,11 @@ */ package org.apache.dubbo.rpc.protocol.dubbo; -import org.apache.dubbo.remoting.exchange.ResponseCallback; -import org.apache.dubbo.remoting.exchange.ResponseFuture; -import org.apache.dubbo.rpc.Result; +import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.RpcException; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; @@ -31,45 +30,35 @@ */ public class FutureAdapter extends CompletableFuture { - private final ResponseFuture future; - private CompletableFuture resultFuture; + private CompletableFuture appResponseFuture; - public FutureAdapter(ResponseFuture future) { - this.future = future; - this.resultFuture = new CompletableFuture<>(); - future.setCallback(new ResponseCallback() { - @Override - public void done(Object response) { - Result result = (Result) response; - FutureAdapter.this.resultFuture.complete(result); - V value = null; - try { - value = (V) result.recreate(); - } catch (Throwable t) { - FutureAdapter.this.completeExceptionally(t); + public FutureAdapter(CompletableFuture future) { + this.appResponseFuture = future; + future.whenComplete((appResponse, t) -> { + if (t != null) { + if (t instanceof CompletionException) { + t = t.getCause(); + } + this.completeExceptionally(t); + } else { + if (appResponse.hasException()) { + this.completeExceptionally(appResponse.getException()); + } else { + this.complete((V) appResponse.getValue()); } - FutureAdapter.this.complete(value); - } - - @Override - public void caught(Throwable exception) { - FutureAdapter.this.completeExceptionally(exception); } }); } - public ResponseFuture getFuture() { - return future; - } - + // TODO figure out the meaning of cancel in DefaultFuture. @Override public boolean cancel(boolean mayInterruptIfRunning) { - return false; + return appResponseFuture.cancel(mayInterruptIfRunning); } @Override public boolean isCancelled() { - return false; + return appResponseFuture.isCancelled(); } @Override @@ -101,15 +90,4 @@ public V get(long timeout, TimeUnit unit) throws InterruptedException, Execution } } - /** - * FIXME - * This method has no need open to the the end user. - * Mostly user use RpcContext.getFuture() to refer the instance of this class, so the user will get a CompletableFuture, this method will rarely be noticed. - * - * @return - */ - public CompletableFuture getResultFuture() { - return resultFuture; - } - } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java index eadbf20681a..a495775d111 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java @@ -26,9 +26,9 @@ import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.remoting.exchange.ExchangeHandler; import org.apache.dubbo.remoting.exchange.Exchangers; -import org.apache.dubbo.remoting.exchange.ResponseFuture; import java.net.InetSocketAddress; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; @@ -87,7 +87,7 @@ private void initClient() throws RemotingException { } @Override - public ResponseFuture request(Object request) throws RemotingException { + public CompletableFuture request(Object request) throws RemotingException { warning(); initClient(); return client.request(request); @@ -108,7 +108,7 @@ public InetSocketAddress getRemoteAddress() { } @Override - public ResponseFuture request(Object request, int timeout) throws RemotingException { + public CompletableFuture request(Object request, int timeout) throws RemotingException { warning(); initClient(); return client.request(request, timeout); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java index fd32951b320..c7074aa9dbe 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java @@ -24,9 +24,9 @@ import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.remoting.exchange.ExchangeHandler; -import org.apache.dubbo.remoting.exchange.ResponseFuture; import java.net.InetSocketAddress; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; import static org.apache.dubbo.remoting.Constants.RECONNECT_KEY; @@ -56,7 +56,7 @@ public void reset(URL url) { } @Override - public ResponseFuture request(Object request) throws RemotingException { + public CompletableFuture request(Object request) throws RemotingException { return client.request(request); } @@ -76,7 +76,7 @@ public ChannelHandler getChannelHandler() { } @Override - public ResponseFuture request(Object request, int timeout) throws RemotingException { + public CompletableFuture request(Object request, int timeout) throws RemotingException { return client.request(request, timeout); } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java index a64dc2b66e7..7b1c17c7517 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java @@ -20,10 +20,9 @@ import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.rpc.AsyncRpcResult; -import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.ListenableFilter; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.ApplicationModel; @@ -39,10 +38,14 @@ * EventFilter */ @Activate(group = CommonConstants.CONSUMER) -public class FutureFilter implements Filter { +public class FutureFilter extends ListenableFilter { protected static final Logger logger = LoggerFactory.getLogger(FutureFilter.class); + public FutureFilter() { + super.listener = new FutureListener(); + } + @Override public Result invoke(final Invoker invoker, final Invocation invocation) throws RpcException { fireInvokeCallback(invoker, invocation); @@ -51,37 +54,6 @@ public Result invoke(final Invoker invoker, final Invocation invocation) thro return invoker.invoke(invocation); } - @Override - public Result onResponse(Result result, Invoker invoker, Invocation invocation) { - if (result instanceof AsyncRpcResult) { - AsyncRpcResult asyncResult = (AsyncRpcResult) result; - asyncResult.thenApplyWithContext(r -> { - asyncCallback(invoker, invocation, r); - return r; - }); - return asyncResult; - } else { - syncCallback(invoker, invocation, result); - return result; - } - } - - private void syncCallback(final Invoker invoker, final Invocation invocation, final Result result) { - if (result.hasException()) { - fireThrowCallback(invoker, invocation, result.getException()); - } else { - fireReturnCallback(invoker, invocation, result.getValue()); - } - } - - private void asyncCallback(final Invoker invoker, final Invocation invocation, Result result) { - if (result.hasException()) { - fireThrowCallback(invoker, invocation, result.getException()); - } else { - fireReturnCallback(invoker, invocation, result.getValue()); - } - } - private void fireInvokeCallback(final Invoker invoker, final Invocation invocation) { final ConsumerMethodModel.AsyncMethodInfo asyncMethodInfo = getAsyncMethodInfo(invoker, invocation); if (asyncMethodInfo == null) { @@ -226,4 +198,20 @@ private ConsumerMethodModel.AsyncMethodInfo getAsyncMethodInfo(Invoker invoke return asyncMethodInfo; } + + class FutureListener implements Listener { + @Override + public void onResponse(Result result, Invoker invoker, Invocation invocation) { + if (result.hasException()) { + fireThrowCallback(invoker, invocation, result.getException()); + } else { + fireReturnCallback(invoker, invocation, result.getValue()); + } + } + + @Override + public void onError(Throwable t, Invoker invoker, Invocation invocation) { + + } + } } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/telnet/InvokeTelnetHandler.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/telnet/InvokeTelnetHandler.java index 56fe5b8e564..3998026b70b 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/telnet/InvokeTelnetHandler.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/telnet/InvokeTelnetHandler.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.dubbo.telnet; -import com.alibaba.fastjson.JSON; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ReflectUtils; @@ -24,11 +23,13 @@ import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.telnet.TelnetHandler; import org.apache.dubbo.remoting.telnet.support.Help; -import org.apache.dubbo.rpc.RpcResult; +import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ProviderMethodModel; import org.apache.dubbo.rpc.model.ProviderModel; +import com.alibaba.fastjson.JSON; + import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; @@ -124,7 +125,7 @@ public String telnet(Channel channel, String message) { Object[] array = realize(list.toArray(), invokeMethod.getParameterTypes(), invokeMethod.getGenericParameterTypes()); long start = System.currentTimeMillis(); - RpcResult result = new RpcResult(); + AppResponse result = new AppResponse(); try { Object o = invokeMethod.invoke(selectedProvider.getServiceInstance(), array); result.setValue(o); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java index 804f05856b7..7c6a34c40bf 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java @@ -24,6 +24,7 @@ import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.ProxyFactory; +import org.apache.dubbo.rpc.protocol.AsyncToSyncInvoker; import org.apache.dubbo.rpc.protocol.dubbo.support.ProtocolUtils; import org.junit.jupiter.api.AfterAll; @@ -63,7 +64,7 @@ public void test_Normal_available() { URL url = URL.valueOf("dubbo://127.0.0.1:20883/org.apache.dubbo.rpc.protocol.dubbo.IDemoService"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); - DubboInvoker invoker = (DubboInvoker) protocol.refer(IDemoService.class, url); + DubboInvoker invoker = (DubboInvoker) protocol.protocolBindingRefer(IDemoService.class, url); Assertions.assertEquals(true, invoker.isAvailable()); invoker.destroy(); Assertions.assertEquals(false, invoker.isAvailable()); @@ -74,7 +75,7 @@ public void test_Normal_ChannelReadOnly() throws Exception { URL url = URL.valueOf("dubbo://127.0.0.1:20883/org.apache.dubbo.rpc.protocol.dubbo.IDemoService"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); - DubboInvoker invoker = (DubboInvoker) protocol.refer(IDemoService.class, url); + DubboInvoker invoker = (DubboInvoker) protocol.protocolBindingRefer(IDemoService.class, url); Assertions.assertEquals(true, invoker.isAvailable()); getClients(invoker)[0].setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); @@ -92,7 +93,7 @@ public void test_normal_channel_close_wait_gracefully() throws Exception { Exporter exporter = ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); Exporter exporter0 = ProtocolUtils.export(new DemoServiceImpl0(), IDemoService.class, url); - DubboInvoker invoker = (DubboInvoker) protocol.refer(IDemoService.class, url); + DubboInvoker invoker = (DubboInvoker) protocol.protocolBindingRefer(IDemoService.class, url); long start = System.currentTimeMillis(); @@ -114,7 +115,7 @@ public void test_NoInvokers() throws Exception { URL url = URL.valueOf("dubbo://127.0.0.1:20883/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?connections=1"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); - DubboInvoker invoker = (DubboInvoker) protocol.refer(IDemoService.class, url); + DubboInvoker invoker = (DubboInvoker) protocol.protocolBindingRefer(IDemoService.class, url); ExchangeClient[] clients = getClients(invoker); clients[0].close(); @@ -127,11 +128,10 @@ public void test_Lazy_ChannelReadOnly() throws Exception { URL url = URL.valueOf("dubbo://127.0.0.1:20883/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?lazy=true&connections=1&timeout=10000"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); - DubboInvoker invoker = (DubboInvoker) protocol.refer(IDemoService.class, url); + AsyncToSyncInvoker invoker = (AsyncToSyncInvoker) protocol.refer(IDemoService.class, url); Assertions.assertEquals(true, invoker.isAvailable()); - try { - getClients(invoker)[0].setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); + getClients((DubboInvoker) invoker.getInvoker())[0].setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); fail(); } catch (IllegalStateException e) { @@ -141,7 +141,7 @@ public void test_Lazy_ChannelReadOnly() throws Exception { Assertions.assertEquals("ok", service.get()); Assertions.assertEquals(true, invoker.isAvailable()); - getClients(invoker)[0].setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); + getClients((DubboInvoker) invoker.getInvoker())[0].setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); Assertions.assertEquals(false, invoker.isAvailable()); } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/FutureFilterTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/FutureFilterTest.java index 2429b4b9580..500a95eeacb 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/FutureFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/FutureFilterTest.java @@ -17,12 +17,12 @@ package org.apache.dubbo.rpc.protocol.dubbo; import org.apache.dubbo.common.URL; +import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.protocol.dubbo.filter.FutureFilter; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoService; @@ -57,7 +57,7 @@ public void testSyncCallback() { Invoker invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); given(invoker.getInterface()).willReturn(DemoService.class); - RpcResult result = new RpcResult(); + AppResponse result = new AppResponse(); result.setValue("High"); given(invoker.invoke(invocation)).willReturn(result); URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); @@ -74,7 +74,7 @@ public void testSyncCallbackHasException() throws RpcException, Throwable { Invoker invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); given(invoker.getInterface()).willReturn(DemoService.class); - RpcResult result = new RpcResult(); + AppResponse result = new AppResponse(); result.setException(new RuntimeException()); given(invoker.invoke(invocation)).willReturn(result); URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1&" + ON_THROW_METHOD_KEY + "=echo"); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ImplicitCallBackTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ImplicitCallBackTest.java index fd5979b7469..0a3a9d161b5 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ImplicitCallBackTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ImplicitCallBackTest.java @@ -236,7 +236,7 @@ public void test_Sync_NoFuture() throws Exception { Person ret = demoProxy.get(requestId); Assertions.assertEquals(requestId, ret.getId()); Future pFuture = RpcContext.getContext().getFuture(); - Assertions.assertEquals(null, pFuture); + Assertions.assertEquals(ret, pFuture.get()); destroyService(); } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java index 1f01e658c45..ca5a306df43 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java @@ -25,7 +25,9 @@ import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.ProxyFactory; +import org.apache.dubbo.rpc.protocol.AsyncToSyncInvoker; import org.apache.dubbo.rpc.protocol.dubbo.support.ProtocolUtils; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -273,8 +275,7 @@ private ExchangeClient getInvokerClient(Invoker invoker) { } private List getInvokerClientList(Invoker invoker) { - @SuppressWarnings("rawtypes") - DubboInvoker dInvoker = (DubboInvoker) invoker; + @SuppressWarnings("rawtypes") DubboInvoker dInvoker = (DubboInvoker) ((AsyncToSyncInvoker) invoker).getInvoker(); try { Field clientField = DubboInvoker.class.getDeclaredField("clients"); clientField.setAccessible(true); diff --git a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java b/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java index abbfe82dac6..7d621913928 100644 --- a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java +++ b/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java @@ -47,8 +47,8 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; +import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java b/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java index cc273aafbe3..3e681b27117 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java @@ -93,7 +93,7 @@ public Exporter export(Invoker invoker) throws RpcException { } @Override - public Invoker refer(Class serviceType, URL url) throws RpcException { + public Invoker protocolBindingRefer(Class serviceType, URL url) throws RpcException { return new InjvmInvoker(serviceType, url, url.getServiceKey(), exporterMap); } diff --git a/dubbo-rpc/dubbo-rpc-memcached/src/main/java/org/apache/dubbo/rpc/protocol/memcached/MemcachedProtocol.java b/dubbo-rpc/dubbo-rpc-memcached/src/main/java/org/apache/dubbo/rpc/protocol/memcached/MemcachedProtocol.java index 2633e961d85..b056a795ee9 100644 --- a/dubbo-rpc/dubbo-rpc-memcached/src/main/java/org/apache/dubbo/rpc/protocol/memcached/MemcachedProtocol.java +++ b/dubbo-rpc/dubbo-rpc-memcached/src/main/java/org/apache/dubbo/rpc/protocol/memcached/MemcachedProtocol.java @@ -18,12 +18,12 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RemotingConstants; +import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.protocol.AbstractInvoker; import org.apache.dubbo.rpc.protocol.AbstractProtocol; @@ -56,7 +56,7 @@ public Exporter export(final Invoker invoker) throws RpcException { } @Override - public Invoker refer(final Class type, final URL url) throws RpcException { + public Invoker protocolBindingRefer(final Class type, final URL url) throws RpcException { try { String address = url.getAddress(); String backup = url.getParameter(RemotingConstants.BACKUP_KEY); @@ -73,26 +73,26 @@ public Invoker refer(final Class type, final URL url) throws RpcExcept @Override protected Result doInvoke(Invocation invocation) throws Throwable { try { + Object value = null; if (get.equals(invocation.getMethodName())) { if (invocation.getArguments().length != 1) { throw new IllegalArgumentException("The memcached get method arguments mismatch, must only one arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url); } - return new RpcResult(memcachedClient.get(String.valueOf(invocation.getArguments()[0]))); + value = memcachedClient.get(String.valueOf(invocation.getArguments()[0])); } else if (set.equals(invocation.getMethodName())) { if (invocation.getArguments().length != 2) { throw new IllegalArgumentException("The memcached set method arguments mismatch, must be two arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url); } memcachedClient.set(String.valueOf(invocation.getArguments()[0]), expiry, invocation.getArguments()[1]); - return new RpcResult(); } else if (delete.equals(invocation.getMethodName())) { if (invocation.getArguments().length != 1) { throw new IllegalArgumentException("The memcached delete method arguments mismatch, must only one arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url); } memcachedClient.delete(String.valueOf(invocation.getArguments()[0])); - return new RpcResult(); } else { throw new UnsupportedOperationException("Unsupported method " + invocation.getMethodName() + " in memcached service."); } + return AsyncRpcResult.newDefaultAsyncResult(value, invocation); } catch (Throwable t) { RpcException re = new RpcException("Failed to invoke memcached service method. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url + ", cause: " + t.getMessage(), t); if (t instanceof TimeoutException || t instanceof SocketTimeoutException) { diff --git a/dubbo-rpc/dubbo-rpc-native-thrift/pom.xml b/dubbo-rpc/dubbo-rpc-native-thrift/pom.xml index 524cd1a706b..bcc3cf9ec8a 100644 --- a/dubbo-rpc/dubbo-rpc-native-thrift/pom.xml +++ b/dubbo-rpc/dubbo-rpc-native-thrift/pom.xml @@ -28,7 +28,7 @@ false - + org.apache.dubbo diff --git a/dubbo-rpc/dubbo-rpc-native-thrift/src/main/java/org/apache/dubbo/rpc/protocol/nativethrift/ThriftProtocol.java b/dubbo-rpc/dubbo-rpc-native-thrift/src/main/java/org/apache/dubbo/rpc/protocol/nativethrift/ThriftProtocol.java index c869c60337b..028d3cf42e2 100644 --- a/dubbo-rpc/dubbo-rpc-native-thrift/src/main/java/org/apache/dubbo/rpc/protocol/nativethrift/ThriftProtocol.java +++ b/dubbo-rpc/dubbo-rpc-native-thrift/src/main/java/org/apache/dubbo/rpc/protocol/nativethrift/ThriftProtocol.java @@ -20,6 +20,7 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.protocol.AbstractProxyProtocol; + import org.apache.thrift.TException; import org.apache.thrift.TMultiplexedProcessor; import org.apache.thrift.TProcessor; diff --git a/dubbo-rpc/dubbo-rpc-redis/src/main/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocol.java b/dubbo-rpc/dubbo-rpc-redis/src/main/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocol.java index 2601a09b48f..b5081887c2c 100644 --- a/dubbo-rpc/dubbo-rpc-redis/src/main/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocol.java +++ b/dubbo-rpc/dubbo-rpc-redis/src/main/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocol.java @@ -23,12 +23,12 @@ import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Constants; +import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.protocol.AbstractInvoker; import org.apache.dubbo.rpc.protocol.AbstractProtocol; @@ -71,7 +71,7 @@ private Serialization getSerialization(URL url) { } @Override - public Invoker refer(final Class type, final URL url) throws RpcException { + protected Invoker protocolBindingRefer(final Class type, final URL url) throws RpcException { try { GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setTestOnBorrow(url.getParameter("test.on.borrow", true)); @@ -122,10 +122,10 @@ protected Result doInvoke(Invocation invocation) throws Throwable { } byte[] value = jedis.get(String.valueOf(invocation.getArguments()[0]).getBytes()); if (value == null) { - return new RpcResult(); + return AsyncRpcResult.newDefaultAsyncResult(invocation); } ObjectInput oin = getSerialization(url).deserialize(url, new ByteArrayInputStream(value)); - return new RpcResult(oin.readObject()); + return AsyncRpcResult.newDefaultAsyncResult(oin.readObject(), invocation); } else if (set.equals(invocation.getMethodName())) { if (invocation.getArguments().length != 2) { throw new IllegalArgumentException("The redis set method arguments mismatch, must be two arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url); @@ -138,13 +138,13 @@ protected Result doInvoke(Invocation invocation) throws Throwable { if (expiry > 1000) { jedis.expire(key, expiry / 1000); } - return new RpcResult(); + return AsyncRpcResult.newDefaultAsyncResult(invocation); } else if (delete.equals(invocation.getMethodName())) { if (invocation.getArguments().length != 1) { throw new IllegalArgumentException("The redis delete method arguments mismatch, must only one arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url); } jedis.del(String.valueOf(invocation.getArguments()[0]).getBytes()); - return new RpcResult(); + return AsyncRpcResult.newDefaultAsyncResult(invocation); } else { throw new UnsupportedOperationException("Unsupported method " + invocation.getMethodName() + " in redis service."); } diff --git a/dubbo-rpc/dubbo-rpc-rest/pom.xml b/dubbo-rpc/dubbo-rpc-rest/pom.xml index c1d9e4e727b..b162030fd8d 100644 --- a/dubbo-rpc/dubbo-rpc-rest/pom.xml +++ b/dubbo-rpc/dubbo-rpc-rest/pom.xml @@ -91,22 +91,22 @@ io.swagger swagger-annotations - - - javax.ws.rs - jsr311-api - - + + + javax.ws.rs + jsr311-api + + io.swagger swagger-jaxrs - - - javax.ws.rs - jsr311-api - - + + + javax.ws.rs + jsr311-api + + diff --git a/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocol.java b/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocol.java index cbf16872840..d570b2f01f4 100644 --- a/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocol.java +++ b/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocol.java @@ -21,6 +21,7 @@ import org.apache.dubbo.rpc.protocol.AbstractProxyProtocol; import org.apache.dubbo.rpc.service.GenericService; import org.apache.dubbo.rpc.support.ProtocolUtils; + import org.springframework.remoting.RemoteAccessException; import org.springframework.remoting.rmi.RmiProxyFactoryBean; import org.springframework.remoting.rmi.RmiServiceExporter; @@ -30,11 +31,11 @@ import java.net.SocketTimeoutException; import java.rmi.RemoteException; +import static org.apache.dubbo.common.Version.isRelease263OrHigher; +import static org.apache.dubbo.common.Version.isRelease270OrHigher; import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY; import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; -import static org.apache.dubbo.common.Version.isRelease263OrHigher; -import static org.apache.dubbo.common.Version.isRelease270OrHigher; /** * RmiProtocol. diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java index e37fab6a68b..14c2947017a 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java @@ -25,9 +25,9 @@ import org.apache.dubbo.remoting.buffer.ChannelBufferInputStream; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; +import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.protocol.thrift.io.RandomAccessByteArrayOutputStream; import org.apache.thrift.TApplicationException; @@ -287,7 +287,7 @@ private Object decode(TProtocol protocol) throw new IOException(e.getMessage(), e); } - RpcResult result = new RpcResult(); + AppResponse result = new AppResponse(); result.setException(new RpcException(exception.getMessage())); @@ -378,15 +378,15 @@ private Object decode(TProtocol protocol) response.setId(id); - RpcResult rpcResult = new RpcResult(); + AppResponse appResponse = new AppResponse(); if (realResult instanceof Throwable) { - rpcResult.setException((Throwable) realResult); + appResponse.setException((Throwable) realResult); } else { - rpcResult.setValue(realResult); + appResponse.setValue(realResult); } - response.setResult(rpcResult); + response.setResult(appResponse); return response; @@ -539,7 +539,7 @@ private void encodeRequest(Channel channel, ChannelBuffer buffer, Request reques private void encodeResponse(Channel channel, ChannelBuffer buffer, Response response) throws IOException { - RpcResult result = (RpcResult) response.getResult(); + AppResponse result = (AppResponse) response.getResult(); RequestData rd = CACHED_REQUEST.get(response.getId()); @@ -613,7 +613,7 @@ private void encodeResponse(Channel channel, ChannelBuffer buffer, Response resp } } else { - Object realResult = result.getResult(); + Object realResult = result.getValue(); // result field id is 0 String fieldName = resultObj.fieldForId(0).getFieldName(); String setMethodName = ThriftUtils.generateSetMethodName(fieldName); diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java index 7d29f5813af..3b0e3d9352f 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java @@ -22,6 +22,7 @@ import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.TimeoutException; import org.apache.dubbo.remoting.exchange.ExchangeClient; +import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; @@ -29,8 +30,10 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.protocol.AbstractInvoker; +import org.apache.dubbo.rpc.protocol.dubbo.FutureAdapter; import java.util.Set; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.locks.ReentrantLock; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; @@ -91,10 +94,11 @@ protected Result doInvoke(Invocation invocation) throws Throwable { try { int timeout = getUrl().getMethodParameter(methodName, TIMEOUT_KEY, DEFAULT_TIMEOUT); - RpcContext.getContext().setFuture(null); - - return (Result) currentClient.request(inv, timeout).get(); - + AsyncRpcResult asyncRpcResult = new AsyncRpcResult(invocation); + CompletableFuture responseFuture = currentClient.request(inv, timeout); + asyncRpcResult.subscribeTo(responseFuture); + RpcContext.getContext().setFuture(new FutureAdapter(asyncRpcResult)); + return asyncRpcResult; } catch (TimeoutException e) { throw new RpcException(RpcException.TIMEOUT_EXCEPTION, e.getMessage(), e); } catch (RemotingException e) { diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java index 0da5ee8be6f..d6a88cbe4e4 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java @@ -32,6 +32,7 @@ import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.protocol.AbstractProtocol; @@ -42,10 +43,11 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import java.util.function.Function; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; -import static org.apache.dubbo.rpc.Constants.IS_SERVER_KEY; import static org.apache.dubbo.common.constants.RpcConstants.CONNECTIONS_KEY; +import static org.apache.dubbo.rpc.Constants.IS_SERVER_KEY; /** * @since 2.7.0, use https://github.com/dubbo/dubbo-rpc-native-thrift instead @@ -88,8 +90,8 @@ public CompletableFuture reply(ExchangeChannel channel, Object msg) thro RpcContext.getContext().setRemoteAddress(channel.getRemoteAddress()); - return CompletableFuture.completedFuture(exporter.getInvoker().invoke(inv)); - + Result result = exporter.getInvoker().invoke(inv); + return result.completionFuture().thenApply(Function.identity()); } throw new RemotingException(channel, @@ -162,7 +164,7 @@ public void destroy() { } // ~ end of method destroy @Override - public Invoker refer(Class type, URL url) throws RpcException { + protected Invoker protocolBindingRefer(Class type, URL url) throws RpcException { ThriftInvoker invoker = new ThriftInvoker(type, url, getClients(url), invokers); diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodecTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodecTest.java index 93421c4bcfb..8cdbae7f99e 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodecTest.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodecTest.java @@ -23,9 +23,9 @@ import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.exchange.support.DefaultFuture; +import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.RpcResult; import org.apache.dubbo.rpc.gen.thrift.Demo; import org.apache.dubbo.rpc.protocol.thrift.io.RandomAccessByteArrayOutputStream; @@ -189,13 +189,13 @@ public void testDecodeReplyResponse() throws Exception { Assertions.assertEquals(request.getId(), response.getId()); - Assertions.assertTrue(response.getResult() instanceof RpcResult); + Assertions.assertTrue(response.getResult() instanceof AppResponse); - RpcResult result = (RpcResult) response.getResult(); + AppResponse result = (AppResponse) response.getResult(); - Assertions.assertTrue(result.getResult() instanceof String); + Assertions.assertTrue(result.getValue() instanceof String); - Assertions.assertEquals(methodResult.success, result.getResult()); + Assertions.assertEquals(methodResult.success, result.getValue()); } @@ -259,9 +259,9 @@ public void testDecodeExceptionResponse() throws Exception { Response response = (Response) obj; - Assertions.assertTrue(response.getResult() instanceof RpcResult); + Assertions.assertTrue(response.getResult() instanceof AppResponse); - RpcResult result = (RpcResult) response.getResult(); + AppResponse result = (AppResponse) response.getResult(); Assertions.assertTrue(result.hasException()); @@ -278,11 +278,11 @@ public void testEncodeReplyResponse() throws Exception { Request request = createRequest(); - RpcResult rpcResult = new RpcResult(); - rpcResult.setResult("Hello, World!"); + AppResponse appResponse = new AppResponse(); + appResponse.setValue("Hello, World!"); Response response = new Response(); - response.setResult(rpcResult); + response.setResult(appResponse); response.setId(request.getId()); ChannelBuffer bos = ChannelBuffers.dynamicBuffer(1024); @@ -324,7 +324,7 @@ public void testEncodeReplyResponse() throws Exception { result.read(protocol); protocol.readMessageEnd(); - Assertions.assertEquals(rpcResult.getValue(), result.getSuccess()); + Assertions.assertEquals(appResponse.getValue(), result.getSuccess()); } @Test @@ -336,12 +336,12 @@ public void testEncodeExceptionResponse() throws Exception { Request request = createRequest(); - RpcResult rpcResult = new RpcResult(); + AppResponse appResponse = new AppResponse(); String exceptionMessage = "failed"; - rpcResult.setException(new RuntimeException(exceptionMessage)); + appResponse.setException(new RuntimeException(exceptionMessage)); Response response = new Response(); - response.setResult(rpcResult); + response.setResult(appResponse); response.setId(request.getId()); ChannelBuffer bos = ChannelBuffers.dynamicBuffer(1024); diff --git a/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java b/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java index c62bd8c85b8..68927d7bd1f 100644 --- a/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java +++ b/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java @@ -16,16 +16,6 @@ */ package org.apache.dubbo.xml.rpc.protocol.xmlrpc; -import java.io.IOException; -import java.net.SocketTimeoutException; -import java.util.ArrayList; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.http.HttpBinder; import org.apache.dubbo.remoting.http.HttpHandler; @@ -33,6 +23,7 @@ import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.protocol.AbstractProxyProtocol; + import org.apache.xmlrpc.XmlRpcException; import org.apache.xmlrpc.XmlRpcRequest; import org.apache.xmlrpc.server.PropertyHandlerMapping; @@ -41,6 +32,15 @@ import org.apache.xmlrpc.webserver.XmlRpcServletServer; import org.springframework.remoting.RemoteAccessException; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.net.SocketTimeoutException; +import java.util.ArrayList; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + public class XmlRpcProtocol extends AbstractProxyProtocol { public static final String ACCESS_CONTROL_ALLOW_ORIGIN_HEADER = "Access-Control-Allow-Origin"; From 5285952a2ab80780133b4f9b1a9bb308ac9978a0 Mon Sep 17 00:00:00 2001 From: cvictory Date: Thu, 23 May 2019 11:20:11 +0800 Subject: [PATCH 079/115] check curator event with empty data value (#4126) fixes #3866 --- .../zookeeper/curator/CuratorZookeeperClient.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java index e3a06e59980..b14cd11b83f 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java @@ -17,6 +17,8 @@ package org.apache.dubbo.remoting.zookeeper.curator; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.zookeeper.ChildListener; import org.apache.dubbo.remoting.zookeeper.DataListener; @@ -49,6 +51,8 @@ public class CuratorZookeeperClient extends AbstractZookeeperClient { + protected static final Logger logger = LoggerFactory.getLogger(CuratorZookeeperClient.class); + static final Charset CHARSET = Charset.forName("UTF-8"); private final CuratorFramework client; private Map treeCacheMap = new ConcurrentHashMap<>(); @@ -288,6 +292,9 @@ public void process(WatchedEvent event) throws Exception { @Override public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception { if (dataListener != null) { + if (logger.isInfoEnabled()) { + logger.info("listen the zookeeper changed. The changed data:" + event.getData()); + } TreeCacheEvent.Type type = event.getType(); EventType eventType = null; String content = null; @@ -296,12 +303,12 @@ public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exc case NODE_ADDED: eventType = EventType.NodeCreated; path = event.getData().getPath(); - content = new String(event.getData().getData(), CHARSET); + content = event.getData().getData() == null ? "" : new String(event.getData().getData(), CHARSET); break; case NODE_UPDATED: eventType = EventType.NodeDataChanged; path = event.getData().getPath(); - content = new String(event.getData().getData(), CHARSET); + content = event.getData().getData() == null ? "" : new String(event.getData().getData(), CHARSET); break; case NODE_REMOVED: path = event.getData().getPath(); From 1a66206e5ed3086fc52fab57263b4afe4b6ad8d5 Mon Sep 17 00:00:00 2001 From: "ken.lj" Date: Thu, 23 May 2019 15:30:45 +0800 Subject: [PATCH 080/115] Performance tuning for TimeoutTask in DefaultFuture (#4129) Performance tuning for TimeoutTask in DefaultFuture, manually merge #4085 and #4087 --- .../exchange/support/DefaultFuture.java | 29 ++++++++++--------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture.java index 1dab931a9c4..7f0e3a7227c 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture.java @@ -50,20 +50,19 @@ public class DefaultFuture extends CompletableFuture { private static final Map FUTURES = new ConcurrentHashMap<>(); - private static final Map PENDING_TASKS = new ConcurrentHashMap<>(); - public static final Timer TIME_OUT_TIMER = new HashedWheelTimer( new NamedThreadFactory("dubbo-future-timeout", true), 30, TimeUnit.MILLISECONDS); // invoke id. - private final long id; + private final Long id; private final Channel channel; private final Request request; private final int timeout; private final long start = System.currentTimeMillis(); private volatile long sent; + private Timeout timeoutCheckTask; private DefaultFuture(Channel channel, Request request, int timeout) { this.channel = channel; @@ -79,9 +78,8 @@ private DefaultFuture(Channel channel, Request request, int timeout) { * check time out of the future */ private static void timeoutCheck(DefaultFuture future) { - TimeoutCheckTask task = new TimeoutCheckTask(future); - Timeout t = TIME_OUT_TIMER.newTimeout(task, future.getTimeout(), TimeUnit.MILLISECONDS); - PENDING_TASKS.put(future.getId(), t); + TimeoutCheckTask task = new TimeoutCheckTask(future.getId()); + future.timeoutCheckTask = TIME_OUT_TIMER.newTimeout(task, future.getTimeout(), TimeUnit.MILLISECONDS); } /** @@ -140,15 +138,19 @@ public static void closeChannel(Channel channel) { } public static void received(Channel channel, Response response) { + received(channel, response, false); + } + + public static void received(Channel channel, Response response, boolean timeout) { try { DefaultFuture future = FUTURES.remove(response.getId()); if (future != null) { - future.doReceived(response); - Timeout t = PENDING_TASKS.remove(future.getId()); - if (t != null) { + Timeout t = future.timeoutCheckTask; + if (!timeout) { // decrease Time t.cancel(); } + future.doReceived(response); } else { logger.warn("The timeout response finally returned at " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date())) @@ -229,14 +231,15 @@ private String getTimeoutMessage(boolean scan) { private static class TimeoutCheckTask implements TimerTask { - private DefaultFuture future; + private final Long requestID; - TimeoutCheckTask(DefaultFuture future) { - this.future = future; + TimeoutCheckTask(Long requestID) { + this.requestID = requestID; } @Override public void run(Timeout timeout) { + DefaultFuture future = DefaultFuture.getFuture(requestID); if (future == null || future.isDone()) { return; } @@ -246,7 +249,7 @@ public void run(Timeout timeout) { timeoutResponse.setStatus(future.isSent() ? Response.SERVER_TIMEOUT : Response.CLIENT_TIMEOUT); timeoutResponse.setErrorMessage(future.getTimeoutMessage(true)); // handle response. - DefaultFuture.received(future.getChannel(), timeoutResponse); + DefaultFuture.received(future.getChannel(), timeoutResponse, true); } } From 13e876e40caa0ba658c8204cb2ca9b6321ad8bfa Mon Sep 17 00:00:00 2001 From: violin Date: Thu, 23 May 2019 16:09:04 +0800 Subject: [PATCH 081/115] fix client retry create proxy lead to OOM (#4109) --- .../src/main/java/org/apache/dubbo/config/ReferenceConfig.java | 1 + 1 file changed, 1 insertion(+) diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java index 3b8eb93add7..bb23381277a 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java @@ -356,6 +356,7 @@ private T createProxy(Map map) { logger.info("Using injvm service " + interfaceClass.getName()); } } else { + urls.clear(); // reference retry init will add url to urls, lead to OOM if (url != null && url.length() > 0) { // user specified URL, could be peer-to-peer address, or register center's address. String[] us = SEMICOLON_SPLIT_PATTERN.split(url); if (us != null && us.length > 0) { From 779fc27255b30c07164b2db6978c71e7fea0b82f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?y=C3=AC=20j=C3=AD?= Date: Thu, 23 May 2019 17:40:30 +0800 Subject: [PATCH 082/115] [Dubbo-4115] When the network is reconnected, the listener should not to be empty. (#4116) --- .../apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java index d0ec61969da..8f5001754fa 100644 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java +++ b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java @@ -278,7 +278,14 @@ public void unwatch() { } try { - this.listener = null; + /** + * issue : https://github.com/apache/incubator-dubbo/issues/4115 + * + * When the network is reconnected, the listener is empty + * and the data cannot be received. + */ + // this.listener = null; + if (watchRequest != null) { WatchCancelRequest watchCancelRequest = WatchCancelRequest.newBuilder().setWatchId(watchId).build(); From 8321c8f8a3a0fafd66d4a2ffc58deacbfdf34c55 Mon Sep 17 00:00:00 2001 From: uglycow Date: Thu, 23 May 2019 18:36:53 +0800 Subject: [PATCH 083/115] fix for #4111 do not ignore empty value when we construct servicename (#4112) --- .../dubbo/registry/nacos/NacosRegistry.java | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java index ff53d64421e..6639962fa88 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java @@ -278,19 +278,19 @@ private void filterServiceNames(List serviceNames, URL url) { final String targetServiceInterface = url.getServiceInterface(); - final String targetVersion = url.getParameter(VERSION_KEY); + final String targetVersion = url.getParameter(VERSION_KEY,""); - final String targetGroup = url.getParameter(GROUP_KEY); + final String targetGroup = url.getParameter(GROUP_KEY,""); filterData(serviceNames, serviceName -> { // split service name to segments // (required) segments[0] = category // (required) segments[1] = serviceInterface - // (required) segments[2] = version + // (optional) segments[2] = version // (optional) segments[3] = group String[] segments = StringUtils.split(serviceName, SERVICE_NAME_SEPARATOR); int length = segments.length; - if (length < 3) { // must present 3 segments or more + if (length != 4) { // must present 4 segments return false; } @@ -311,8 +311,7 @@ private void filterServiceNames(List serviceNames, URL url) { return false; } - String group = length > 3 ? segments[SERVICE_GROUP_INDEX] : null; - // no match service group + String group = segments[SERVICE_GROUP_INDEX]; return group == null || WILDCARD.equals(targetGroup) || StringUtils.equals(targetGroup, group); }); @@ -420,16 +419,17 @@ private String getServiceName(URL url) { private String getServiceName(URL url, String category) { StringBuilder serviceNameBuilder = new StringBuilder(category); - appendIfPresent(serviceNameBuilder, url, INTERFACE_KEY); - appendIfPresent(serviceNameBuilder, url, VERSION_KEY); - appendIfPresent(serviceNameBuilder, url, GROUP_KEY); + append(serviceNameBuilder, url, INTERFACE_KEY); + append(serviceNameBuilder, url, VERSION_KEY); + append(serviceNameBuilder, url, GROUP_KEY); return serviceNameBuilder.toString(); } - private void appendIfPresent(StringBuilder target, URL url, String parameterName) { + private void append(StringBuilder target, URL url, String parameterName) { + target.append(SERVICE_NAME_SEPARATOR); String parameterValue = url.getParameter(parameterName); if (!StringUtils.isBlank(parameterValue)) { - target.append(SERVICE_NAME_SEPARATOR).append(parameterValue); + target.append(parameterValue); } } From ccb990f54228f9a3315c92e09376eef6ba30cc5a Mon Sep 17 00:00:00 2001 From: "ken.lj" Date: Fri, 24 May 2019 10:57:32 +0800 Subject: [PATCH 084/115] add miss-deleted snippet from #2956 (#4137) --- .../java/org/apache/dubbo/rpc/AppResponse.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AppResponse.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AppResponse.java index 16e938095a5..6657b79b407 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AppResponse.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AppResponse.java @@ -17,6 +17,7 @@ package org.apache.dubbo.rpc; import java.io.Serializable; +import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import java.util.function.Function; @@ -64,6 +65,23 @@ public AppResponse(Throwable exception) { @Override public Object recreate() throws Throwable { if (exception != null) { + // fix issue#619 + try { + // get Throwable class + Class clazz = exception.getClass(); + while (!clazz.getName().equals(Throwable.class.getName())) { + clazz = clazz.getSuperclass(); + } + // get stackTrace value + Field stackTraceField = clazz.getDeclaredField("stackTrace"); + stackTraceField.setAccessible(true); + Object stackTrace = stackTraceField.get(exception); + if (stackTrace == null) { + exception.setStackTrace(new StackTraceElement[0]); + } + } catch (Exception e) { + // ignore + } throw exception; } return result; From 5ba55c03600a9aeeab63c69e2371102a34198510 Mon Sep 17 00:00:00 2001 From: "ken.lj" Date: Fri, 24 May 2019 14:44:12 +0800 Subject: [PATCH 085/115] unify config config items: qos.enable to qos-enable. (#4095) unify config config items: qos.enable to qos-enable. (#4095) --- .../common/constants/ConfigConstants.java | 6 +-- .../dubbo/config/ApplicationConfig.java | 39 +++++++++++++++++-- 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ConfigConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ConfigConstants.java index 44ba466e580..9f36406ae9c 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ConfigConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ConfigConstants.java @@ -40,9 +40,9 @@ public interface ConfigConstants { String DUBBO_PROTOCOL = "dubbo"; - String QOS_ENABLE = "qos.enable"; + String QOS_ENABLE = "qos-enable"; - String QOS_PORT = "qos.port"; + String QOS_PORT = "qos-port"; - String ACCEPT_FOREIGN_IP = "qos.accept.foreign.ip"; + String ACCEPT_FOREIGN_IP = "qos-accept-foreign-ip"; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java index 2b50e50ed72..851be9bcd80 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java @@ -29,6 +29,9 @@ import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DUMP_DIRECTORY; import static org.apache.dubbo.common.constants.ConfigConstants.ACCEPT_FOREIGN_IP; +import static org.apache.dubbo.common.constants.ConfigConstants.QOS_ENABLE; +import static org.apache.dubbo.common.constants.ConfigConstants.QOS_PORT; +import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.config.Constants.ARCHITECTURE; import static org.apache.dubbo.config.Constants.DEVELOPMENT_ENVIRONMENT; import static org.apache.dubbo.config.Constants.ENVIRONMENT; @@ -36,9 +39,6 @@ import static org.apache.dubbo.config.Constants.ORGANIZATION; import static org.apache.dubbo.config.Constants.OWNER; import static org.apache.dubbo.config.Constants.PRODUCTION_ENVIRONMENT; -import static org.apache.dubbo.common.constants.ConfigConstants.QOS_ENABLE; -import static org.apache.dubbo.common.constants.ConfigConstants.QOS_PORT; -import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.config.Constants.TEST_ENVIRONMENT; @@ -317,6 +317,39 @@ public void setQosAcceptForeignIp(Boolean qosAcceptForeignIp) { this.qosAcceptForeignIp = qosAcceptForeignIp; } + @Deprecated + @Parameter(key = "qos.enable", excluded = true) + public Boolean getQosEnableDeprecated() { + return getQosEnable(); + } + + @Deprecated + public void setQosEnableDeprecated(Boolean qosEnable) { + setQosEnable(qosEnable); + } + + @Deprecated + @Parameter(key = "qos.port", excluded = true) + public Integer getQosPortDeprecated() { + return getQosPort(); + } + + @Deprecated + public void setQosPortDeprecated(Integer qosPort) { + this.setQosPort(qosPort); + } + + @Deprecated + @Parameter(key = "qos.accept.foreign.ip", excluded = true) + public Boolean getQosAcceptForeignIpDeprecated() { + return this.getQosAcceptForeignIp(); + } + + @Deprecated + public void setQosAcceptForeignIpDeprecated(Boolean qosAcceptForeignIp) { + this.setQosAcceptForeignIp(qosAcceptForeignIp); + } + public Map getParameters() { return parameters; } From 92cafe962d8fd3df034c16629954425f4640f343 Mon Sep 17 00:00:00 2001 From: "ken.lj" Date: Fri, 24 May 2019 14:49:25 +0800 Subject: [PATCH 086/115] register callback once for the full filter chain. (#4127) --- .../org/apache/dubbo/rpc/AsyncRpcResult.java | 18 +---- .../rpc/protocol/ProtocolFilterWrapper.java | 73 +++++++++++++++---- .../internal/org.apache.dubbo.rpc.Filter | 3 +- 3 files changed, 65 insertions(+), 29 deletions(-) diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncRpcResult.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncRpcResult.java index 9546e2a39ce..fc262475e88 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncRpcResult.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncRpcResult.java @@ -137,20 +137,10 @@ public Object recreate() throws Throwable { } public Result thenApplyWithContext(Function fn) { - CompletableFuture future = this.thenApply(fn.compose(beforeContext).andThen(afterContext)); - AsyncRpcResult nextAsyncRpcResult = new AsyncRpcResult(this); - nextAsyncRpcResult.subscribeTo(future); - return nextAsyncRpcResult; - } - - public void subscribeTo(CompletableFuture future) { - future.whenComplete((obj, t) -> { - if (t != null) { - this.completeExceptionally(t); - } else { - this.complete((Result) obj); - } - }); + this.thenApply(fn.compose(beforeContext).andThen(afterContext)); + // You may need to return a new Result instance representing the next async stage, + // like thenApply will return a new CompletableFuture. + return this; } @Override diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolFilterWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolFilterWrapper.java index 9ee7d3e1f2b..f54d07688b8 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolFilterWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolFilterWrapper.java @@ -31,7 +31,6 @@ import java.util.List; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; - import static org.apache.dubbo.rpc.Constants.REFERENCE_FILTER_KEY; import static org.apache.dubbo.rpc.Constants.SERVICE_FILTER_KEY; @@ -49,9 +48,12 @@ public ProtocolFilterWrapper(Protocol protocol) { this.protocol = protocol; } + + private static Invoker buildInvokerChain(final Invoker invoker, String key, String group) { Invoker last = invoker; List filters = ExtensionLoader.getExtensionLoader(Filter.class).getActivateExtension(invoker.getUrl(), key, group); + if (!filters.isEmpty()) { for (int i = filters.size() - 1; i >= 0; i--) { final Filter filter = filters.get(i); @@ -88,18 +90,7 @@ public Result invoke(Invocation invocation) throws RpcException { } throw e; } - return asyncResult.thenApplyWithContext(r -> { - // onResponse callback - if (filter instanceof ListenableFilter) { - Filter.Listener listener = ((ListenableFilter) filter).listener(); - if (listener != null) { - listener.onResponse(r, invoker, invocation); - } - } else { - filter.onResponse(r, invoker, invocation); - } - return r; - }); + return asyncResult; } @Override @@ -114,7 +105,8 @@ public String toString() { }; } } - return last; + + return new CallbackRegistrationInvoker<>(last, filters); } @Override @@ -143,4 +135,57 @@ public void destroy() { protocol.destroy(); } + static class CallbackRegistrationInvoker implements Invoker { + + private final Invoker filterInvoker; + private final List filters; + + public CallbackRegistrationInvoker(Invoker filterInvoker, List filters) { + this.filterInvoker = filterInvoker; + this.filters = filters; + } + + @Override + public Result invoke(Invocation invocation) throws RpcException { + Result asyncResult = filterInvoker.invoke(invocation); + + asyncResult.thenApplyWithContext(r -> { + for (int i = filters.size() - 1; i >= 0; i--) { + Filter filter = filters.get(i); + // onResponse callback + if (filter instanceof ListenableFilter) { + Filter.Listener listener = ((ListenableFilter) filter).listener(); + if (listener != null) { + listener.onResponse(r, filterInvoker, invocation); + } + } else { + filter.onResponse(r, filterInvoker, invocation); + } + } + return r; + }); + + return asyncResult; + } + + @Override + public Class getInterface() { + return filterInvoker.getInterface(); + } + + @Override + public URL getUrl() { + return filterInvoker.getUrl(); + } + + @Override + public boolean isAvailable() { + return filterInvoker.isAvailable(); + } + + @Override + public void destroy() { + filterInvoker.destroy(); + } + } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter b/dubbo-rpc/dubbo-rpc-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter index 376f966e7ba..24065214f46 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter +++ b/dubbo-rpc/dubbo-rpc-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter @@ -11,4 +11,5 @@ exception=org.apache.dubbo.rpc.filter.ExceptionFilter executelimit=org.apache.dubbo.rpc.filter.ExecuteLimitFilter deprecated=org.apache.dubbo.rpc.filter.DeprecatedFilter compatible=org.apache.dubbo.rpc.filter.CompatibleFilter -timeout=org.apache.dubbo.rpc.filter.TimeoutFilter \ No newline at end of file +timeout=org.apache.dubbo.rpc.filter.TimeoutFilter +callback-registration=org.apache.dubbo.rpc.filter.CallbackRegistrationFilter \ No newline at end of file From 543a52abc0a86efad59f0f97f32de282321a4ab5 Mon Sep 17 00:00:00 2001 From: cvictory Date: Fri, 24 May 2019 14:54:37 +0800 Subject: [PATCH 087/115] Multiple registry (#4066) fixes #3932, #3599, #3084 --- dubbo-all/pom.xml | 8 + .../dubbo-registry-multiple/pom.xml | 60 ++++ .../registry/multiple/MultipleRegistry.java | 314 ++++++++++++++++++ .../multiple/MultipleRegistryFactory.java | 33 ++ .../org.apache.dubbo.registry.RegistryFactory | 1 + .../multiple/MultipleRegistry2S2RTest.java | 206 ++++++++++++ .../multiple/MultipleRegistryTestUtil.java | 138 ++++++++ dubbo-registry/pom.xml | 1 + 8 files changed, 761 insertions(+) create mode 100644 dubbo-registry/dubbo-registry-multiple/pom.xml create mode 100644 dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleRegistry.java create mode 100644 dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleRegistryFactory.java create mode 100644 dubbo-registry/dubbo-registry-multiple/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory create mode 100644 dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleRegistry2S2RTest.java create mode 100644 dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleRegistryTestUtil.java diff --git a/dubbo-all/pom.xml b/dubbo-all/pom.xml index be5a2e3fd77..d8c8949c13e 100644 --- a/dubbo-all/pom.xml +++ b/dubbo-all/pom.xml @@ -282,6 +282,13 @@ compile true + + org.apache.dubbo + dubbo-registry-multiple + ${project.version} + compile + true + org.apache.dubbo dubbo-monitor-api @@ -596,6 +603,7 @@ org.apache.dubbo:dubbo-registry-etcd3 org.apache.dubbo:dubbo-registry-nacos org.apache.dubbo:dubbo-registry-sofa + org.apache.dubbo:dubbo-registry-multiple org.apache.dubbo:dubbo-monitor-api org.apache.dubbo:dubbo-monitor-default org.apache.dubbo:dubbo-config-api diff --git a/dubbo-registry/dubbo-registry-multiple/pom.xml b/dubbo-registry/dubbo-registry-multiple/pom.xml new file mode 100644 index 00000000000..e62e2fe21b4 --- /dev/null +++ b/dubbo-registry/dubbo-registry-multiple/pom.xml @@ -0,0 +1,60 @@ + + + 4.0.0 + + org.apache.dubbo + dubbo-registry + ${revision} + + dubbo-registry-multiple + jar + ${project.artifactId} + The multiple registry module of dubbo project + + false + + + + org.apache.dubbo + dubbo-registry-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-registry-redis + ${project.parent.version} + test + + + org.apache.curator + curator-test + test + + + com.github.kstyrc + embedded-redis + test + + + diff --git a/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleRegistry.java b/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleRegistry.java new file mode 100644 index 00000000000..ea5948151dd --- /dev/null +++ b/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleRegistry.java @@ -0,0 +1,314 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.registry.multiple; + + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.constants.CommonConstants; +import org.apache.dubbo.common.extension.ExtensionLoader; +import org.apache.dubbo.common.utils.CollectionUtils; +import org.apache.dubbo.registry.NotifyListener; +import org.apache.dubbo.registry.Registry; +import org.apache.dubbo.registry.RegistryFactory; +import org.apache.dubbo.registry.support.AbstractRegistry; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; + +/** + * MultipleRegistry + */ +public class MultipleRegistry extends AbstractRegistry { + + public static final String REGISTRY_FOR_SERVICE = "service-registry"; + public static final String REGISTRY_FOR_REFERENCE = "reference-registry"; + + protected RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getAdaptiveExtension(); + private final Map serviceRegistries = new ConcurrentHashMap<>(4); + private final Map referenceRegistries = new ConcurrentHashMap(4); + private final Map multipleNotifyListenerMap = new ConcurrentHashMap(32); + protected List origServiceRegistryURLs; + protected List origReferenceRegistryURLs; + protected List effectServiceRegistryURLs; + protected List effectReferenceRegistryURLs; + private URL registryUrl; + private String applicationName; + + + public MultipleRegistry(URL url) { + super(url); + this.registryUrl = url; + this.applicationName = url.getParameter(CommonConstants.APPLICATION_KEY); + init(); + checkApplicationName(this.applicationName); + // This urls contain parameter and it donot inherit from the parameter of url in MultipleRegistry + origServiceRegistryURLs = url.getParameter(REGISTRY_FOR_SERVICE, new ArrayList()); + origReferenceRegistryURLs = url.getParameter(REGISTRY_FOR_REFERENCE, new ArrayList()); + effectServiceRegistryURLs = this.filterServiceRegistry(origServiceRegistryURLs); + effectReferenceRegistryURLs = this.filterReferenceRegistry(origReferenceRegistryURLs); + + boolean defaultRegistry = url.getParameter(CommonConstants.DEFAULT_KEY, true); + if (defaultRegistry && effectServiceRegistryURLs.isEmpty() && effectReferenceRegistryURLs.isEmpty()) { + throw new IllegalArgumentException("Illegal registry url. You need to configure parameter " + + REGISTRY_FOR_SERVICE + " or " + REGISTRY_FOR_REFERENCE); + } + Set allURLs = new HashSet(effectServiceRegistryURLs); + allURLs.addAll(effectReferenceRegistryURLs); + Map tmpMap = new HashMap(4); + for (String tmpUrl : allURLs) { + tmpMap.put(tmpUrl, registryFactory.getRegistry(URL.valueOf(tmpUrl))); + } + for (String serviceRegistyURL : effectServiceRegistryURLs) { + serviceRegistries.put(serviceRegistyURL, tmpMap.get(serviceRegistyURL)); + } + for (String referenceReigstyURL : effectReferenceRegistryURLs) { + referenceRegistries.put(referenceReigstyURL, tmpMap.get(referenceReigstyURL)); + } + } + + + @Override + public URL getUrl() { + return registryUrl; + } + + @Override + public boolean isAvailable() { + boolean available = serviceRegistries.isEmpty() ? true : false; + for (Registry serviceRegistry : serviceRegistries.values()) { + if (serviceRegistry.isAvailable()) { + available = true; + } + } + if (!available) { + return false; + } + + available = referenceRegistries.isEmpty() ? true : false; + for (Registry referenceRegistry : referenceRegistries.values()) { + if (referenceRegistry.isAvailable()) { + available = true; + } + } + if (!available) { + return false; + } + return true; + } + + @Override + public void destroy() { + Set registries = new HashSet(serviceRegistries.values()); + registries.addAll(referenceRegistries.values()); + for (Registry registry : registries) { + registry.destroy(); + } + } + + @Override + public void register(URL url) { + super.register(url); + for (Registry registry : serviceRegistries.values()) { + registry.register(url); + } + } + + @Override + public void unregister(URL url) { + super.unregister(url); + for (Registry registry : serviceRegistries.values()) { + registry.unregister(url); + } + } + + @Override + public void subscribe(URL url, NotifyListener listener) { + MultipleNotifyListenerWrapper multipleNotifyListenerWrapper = new MultipleNotifyListenerWrapper(listener); + multipleNotifyListenerMap.put(listener, multipleNotifyListenerWrapper); + for (Registry registry : referenceRegistries.values()) { + SingleNotifyListener singleNotifyListener = new SingleNotifyListener(multipleNotifyListenerWrapper, registry); + multipleNotifyListenerWrapper.putRegistryMap(registry.getUrl(), singleNotifyListener); + registry.subscribe(url, singleNotifyListener); + } + super.subscribe(url, multipleNotifyListenerWrapper); + } + + @Override + public void unsubscribe(URL url, NotifyListener listener) { + MultipleNotifyListenerWrapper notifyListener = multipleNotifyListenerMap.remove(listener); + for (Registry registry : referenceRegistries.values()) { + SingleNotifyListener singleNotifyListener = notifyListener.registryMap.get(registry.getUrl()); + registry.unsubscribe(url, singleNotifyListener); + } + + if (notifyListener != null) { + super.unsubscribe(url, notifyListener); + notifyListener.destroy(); + } + } + + @Override + public List lookup(URL url) { + List urls = new ArrayList(); + for (Registry registry : referenceRegistries.values()) { + List tmpUrls = registry.lookup(url); + if (!CollectionUtils.isEmpty(tmpUrls)) { + urls.addAll(tmpUrls); + } + } + return urls; + } + + protected void init() { + } + + protected List filterServiceRegistry(List serviceRegistryURLs) { + return serviceRegistryURLs; + } + + protected List filterReferenceRegistry(List referenceRegistryURLs) { + return referenceRegistryURLs; + } + + + protected void checkApplicationName(String applicationName) { + } + + protected String getApplicationName() { + return applicationName; + } + + public Map getServiceRegistries() { + return serviceRegistries; + } + + public Map getReferenceRegistries() { + return referenceRegistries; + } + + public List getOrigServiceRegistryURLs() { + return origServiceRegistryURLs; + } + + public List getOrigReferenceRegistryURLs() { + return origReferenceRegistryURLs; + } + + public List getEffectServiceRegistryURLs() { + return effectServiceRegistryURLs; + } + + public List getEffectReferenceRegistryURLs() { + return effectReferenceRegistryURLs; + } + + static protected class MultipleNotifyListenerWrapper implements NotifyListener { + + Map registryMap = new ConcurrentHashMap(4); + NotifyListener sourceNotifyListener; + + public MultipleNotifyListenerWrapper(NotifyListener sourceNotifyListener) { + this.sourceNotifyListener = sourceNotifyListener; + } + + public void putRegistryMap(URL registryURL, SingleNotifyListener singleNotifyListener) { + this.registryMap.put(registryURL, singleNotifyListener); + } + + public void destroy() { + for (SingleNotifyListener singleNotifyListener : registryMap.values()) { + if (singleNotifyListener != null) { + singleNotifyListener.destroy(); + } + } + registryMap.clear(); + sourceNotifyListener = null; + } + + public synchronized void notifySourceListener() { + List notifyURLs = new ArrayList(); + URL emptyURL = null; + for (SingleNotifyListener singleNotifyListener : registryMap.values()) { + List tmpUrls = singleNotifyListener.getUrlList(); + if (CollectionUtils.isEmpty(tmpUrls)) { + continue; + } + // empty protocol + if (tmpUrls.size() == 1 + && tmpUrls.get(0) != null + && EMPTY_PROTOCOL.equals(tmpUrls.get(0).getProtocol())) { + // if only one empty + if (emptyURL == null) { + emptyURL = tmpUrls.get(0); + } + continue; + } + notifyURLs.addAll(tmpUrls); + } + // if no notify URL, add empty protocol URL + if (emptyURL != null && notifyURLs.isEmpty()) { + notifyURLs.add(emptyURL); + } + this.notify(notifyURLs); + } + + @Override + public void notify(List urls) { + sourceNotifyListener.notify(urls); + } + + public Map getRegistryMap() { + return registryMap; + } + } + + static protected class SingleNotifyListener implements NotifyListener { + + MultipleNotifyListenerWrapper multipleNotifyListenerWrapper; + Registry registry; + volatile List urlList; + + public SingleNotifyListener(MultipleNotifyListenerWrapper multipleNotifyListenerWrapper, Registry registry) { + this.registry = registry; + this.multipleNotifyListenerWrapper = multipleNotifyListenerWrapper; + } + + @Override + public synchronized void notify(List urls) { + this.urlList = urls; + if (multipleNotifyListenerWrapper != null) { + this.multipleNotifyListenerWrapper.notifySourceListener(); + } + } + + public void destroy() { + this.multipleNotifyListenerWrapper = null; + this.registry = null; + } + + public List getUrlList() { + return urlList; + } + } +} diff --git a/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleRegistryFactory.java b/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleRegistryFactory.java new file mode 100644 index 00000000000..69d695b235f --- /dev/null +++ b/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleRegistryFactory.java @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.registry.multiple; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.registry.Registry; +import org.apache.dubbo.registry.support.AbstractRegistryFactory; + +/** + * MultipleRegistryFactory + */ +public class MultipleRegistryFactory extends AbstractRegistryFactory { + + @Override + protected Registry createRegistry(URL url) { + return new MultipleRegistry(url); + } + +} diff --git a/dubbo-registry/dubbo-registry-multiple/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory b/dubbo-registry/dubbo-registry-multiple/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory new file mode 100644 index 00000000000..defb7a27a06 --- /dev/null +++ b/dubbo-registry/dubbo-registry-multiple/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory @@ -0,0 +1 @@ +multiple=org.apache.dubbo.registry.multiple.MultipleRegistryFactory diff --git a/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleRegistry2S2RTest.java b/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleRegistry2S2RTest.java new file mode 100644 index 00000000000..cfc15b2df95 --- /dev/null +++ b/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleRegistry2S2RTest.java @@ -0,0 +1,206 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.registry.multiple; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.utils.NetUtils; +import org.apache.dubbo.registry.NotifyListener; +import org.apache.dubbo.registry.Registry; +import org.apache.dubbo.registry.redis.RedisRegistry; +import org.apache.dubbo.registry.zookeeper.ZookeeperRegistry; +import org.apache.dubbo.remoting.zookeeper.ZookeeperClient; +import org.apache.dubbo.remoting.zookeeper.curator.CuratorZookeeperClient; + +import org.apache.curator.test.TestingServer; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import redis.embedded.RedisServer; + +import java.util.ArrayList; +import java.util.List; + +/** + * 2019-04-30 + */ +public class MultipleRegistry2S2RTest { + + private static final String SERVICE_NAME = "org.apache.dubbo.registry.MultipleService2S2R"; + private static final String SERVICE2_NAME = "org.apache.dubbo.registry.MultipleService2S2R2"; + + private static TestingServer zkServer; + private static RedisServer redisServer; + static int zkServerPort; + static int redisServerPort; + + private static String zookeeperRegistryURLStr; + private static String redisRegistryURLStr; + + private static MultipleRegistry multipleRegistry; + // for test content + private static ZookeeperClient zookeeperClient; + + private static ZookeeperRegistry zookeeperRegistry; + private static RedisRegistry redisRegistry; + + + @BeforeAll + public static void setUp() throws Exception { + zkServerPort = NetUtils.getAvailablePort(); + zkServer = new TestingServer(zkServerPort, true); + zookeeperRegistryURLStr = "zookeeper://127.0.0.1:" + zkServerPort; + + redisServerPort = NetUtils.getAvailablePort(); + redisServer = new RedisServer(redisServerPort); + redisServer.start(); + redisRegistryURLStr = "redis://127.0.0.1:" + redisServerPort; + + + URL url = URL.valueOf("multiple://127.0.0.1?application=vic&" + + MultipleRegistry.REGISTRY_FOR_SERVICE + "=" + zookeeperRegistryURLStr + "," + redisRegistryURLStr + "&" + + MultipleRegistry.REGISTRY_FOR_REFERENCE + "=" + zookeeperRegistryURLStr + "," + redisRegistryURLStr); + multipleRegistry = (MultipleRegistry) new MultipleRegistryFactory().createRegistry(url); + + // for test validation + zookeeperClient = new CuratorZookeeperClient(URL.valueOf(zookeeperRegistryURLStr)); + zookeeperRegistry = MultipleRegistryTestUtil.getZookeeperRegistry(multipleRegistry.getServiceRegistries().values()); + redisRegistry = MultipleRegistryTestUtil.getRedisRegistry(multipleRegistry.getServiceRegistries().values()); + } + + @AfterAll + public static void tearDown() throws Exception { + zkServer.stop(); + redisServer.stop(); + } + + @Test + public void testParamConfig() { + + Assertions.assertTrue(multipleRegistry.origReferenceRegistryURLs.size() == 2); + Assertions.assertTrue(multipleRegistry.origReferenceRegistryURLs.contains(zookeeperRegistryURLStr)); + Assertions.assertTrue(multipleRegistry.origReferenceRegistryURLs.contains(redisRegistryURLStr)); + + Assertions.assertTrue(multipleRegistry.origServiceRegistryURLs.size() == 2); + Assertions.assertTrue(multipleRegistry.origServiceRegistryURLs.contains(zookeeperRegistryURLStr)); + Assertions.assertTrue(multipleRegistry.origServiceRegistryURLs.contains(redisRegistryURLStr)); + + Assertions.assertTrue(multipleRegistry.effectReferenceRegistryURLs.size() == 2); + Assertions.assertTrue(multipleRegistry.effectReferenceRegistryURLs.contains(zookeeperRegistryURLStr)); + Assertions.assertTrue(multipleRegistry.effectReferenceRegistryURLs.contains(redisRegistryURLStr)); + + Assertions.assertTrue(multipleRegistry.effectServiceRegistryURLs.size() == 2); + Assertions.assertTrue(multipleRegistry.effectServiceRegistryURLs.contains(zookeeperRegistryURLStr)); + Assertions.assertTrue(multipleRegistry.effectServiceRegistryURLs.contains(redisRegistryURLStr)); + + Assertions.assertTrue(multipleRegistry.getServiceRegistries().containsKey(zookeeperRegistryURLStr)); + Assertions.assertTrue(multipleRegistry.getServiceRegistries().containsKey(redisRegistryURLStr)); + Assertions.assertTrue(multipleRegistry.getServiceRegistries().values().size() == 2); +// java.util.Iterator registryIterable = multipleRegistry.getServiceRegistries().values().iterator(); +// Registry firstRegistry = registryIterable.next(); +// Registry secondRegistry = registryIterable.next(); + Assertions.assertNotNull(MultipleRegistryTestUtil.getZookeeperRegistry(multipleRegistry.getServiceRegistries().values())); + Assertions.assertNotNull(MultipleRegistryTestUtil.getRedisRegistry(multipleRegistry.getServiceRegistries().values())); + Assertions.assertNotNull(MultipleRegistryTestUtil.getZookeeperRegistry(multipleRegistry.getReferenceRegistries().values())); + Assertions.assertNotNull(MultipleRegistryTestUtil.getRedisRegistry(multipleRegistry.getReferenceRegistries().values())); + + Assertions.assertEquals(MultipleRegistryTestUtil.getZookeeperRegistry(multipleRegistry.getServiceRegistries().values()), + MultipleRegistryTestUtil.getZookeeperRegistry(multipleRegistry.getReferenceRegistries().values())); + + Assertions.assertEquals(MultipleRegistryTestUtil.getRedisRegistry(multipleRegistry.getServiceRegistries().values()), + MultipleRegistryTestUtil.getRedisRegistry(multipleRegistry.getReferenceRegistries().values())); + + Assertions.assertEquals(multipleRegistry.getApplicationName(), "vic"); + + Assertions.assertTrue(multipleRegistry.isAvailable()); + } + + @Test + public void testRegistryAndUnRegistry() throws InterruptedException { + URL serviceUrl = URL.valueOf("http2://multiple/" + SERVICE_NAME + "?notify=false&methods=test1,test2&category=providers"); +// URL serviceUrl2 = URL.valueOf("http2://multiple2/" + SERVICE_NAME + "?notify=false&methods=test1,test2&category=providers"); + multipleRegistry.register(serviceUrl); + + String path = "/dubbo/" + SERVICE_NAME + "/providers"; + List providerList = zookeeperClient.getChildren(path); + Assertions.assertTrue(!providerList.isEmpty()); + System.out.println(providerList.get(0)); + + Assertions.assertNotNull(MultipleRegistryTestUtil.getRedisHashContent(redisServerPort, path, serviceUrl.toFullString())); + + final List list = new ArrayList(); + multipleRegistry.subscribe(serviceUrl, new NotifyListener() { + @Override + public void notify(List urls) { + System.out.println("invoke notify: " + urls); + list.clear(); + list.addAll(urls); + } + }); + Thread.sleep(1500); + Assertions.assertTrue(list.size() == 2); + + multipleRegistry.unregister(serviceUrl); + Thread.sleep(1500); + Assertions.assertTrue(list.size() == 1); + List urls = MultipleRegistryTestUtil.getProviderURLsFromNotifyURLS(list); + Assertions.assertTrue(list.size() == 1); + Assertions.assertTrue("empty".equals(list.get(0).getProtocol())); + } + + @Test + public void testSubscription() throws InterruptedException { + URL serviceUrl = URL.valueOf("http2://multiple/" + SERVICE2_NAME + "?notify=false&methods=test1,test2&category=providers"); +// URL serviceUrl2 = URL.valueOf("http2://multiple2/" + SERVICE_NAME + "?notify=false&methods=test1,test2&category=providers"); + multipleRegistry.register(serviceUrl); + + String path = "/dubbo/" + SERVICE2_NAME + "/providers"; + List providerList = zookeeperClient.getChildren(path); + Assertions.assertTrue(!providerList.isEmpty()); + System.out.println(providerList.get(0)); + + Assertions.assertNotNull(MultipleRegistryTestUtil.getRedisHashContent(redisServerPort, path, serviceUrl.toFullString())); + + final List list = new ArrayList(); + multipleRegistry.subscribe(serviceUrl, new NotifyListener() { + @Override + public void notify(List urls) { + System.out.println("invoke notify: " + urls); + list.clear(); + list.addAll(urls); + } + }); + Thread.sleep(1500); + Assertions.assertTrue(list.size() == 2); + + List serviceRegistries = new ArrayList(multipleRegistry.getServiceRegistries().values()); + serviceRegistries.get(0).unregister(serviceUrl); + Thread.sleep(1500); + Assertions.assertTrue(list.size() == 1); + List urls = MultipleRegistryTestUtil.getProviderURLsFromNotifyURLS(list); + Assertions.assertTrue(list.size() == 1); + Assertions.assertTrue(!"empty".equals(list.get(0).getProtocol())); + + serviceRegistries.get(1).unregister(serviceUrl); + Thread.sleep(1500); + Assertions.assertTrue(list.size() == 1); + urls = MultipleRegistryTestUtil.getProviderURLsFromNotifyURLS(list); + Assertions.assertTrue(list.size() == 1); + Assertions.assertTrue("empty".equals(list.get(0).getProtocol())); + } + +} diff --git a/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleRegistryTestUtil.java b/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleRegistryTestUtil.java new file mode 100644 index 00000000000..2c70a83355a --- /dev/null +++ b/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleRegistryTestUtil.java @@ -0,0 +1,138 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.registry.multiple; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.utils.StringUtils; +import org.apache.dubbo.common.utils.UrlUtils; +import org.apache.dubbo.registry.Registry; +import org.apache.dubbo.registry.redis.RedisRegistry; +import org.apache.dubbo.registry.zookeeper.ZookeeperRegistry; +import org.apache.dubbo.rpc.RpcException; + +import redis.clients.jedis.Jedis; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +import static org.apache.dubbo.common.constants.RegistryConstants.APP_DYNAMIC_CONFIGURATORS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.COMPATIBLE_CONFIG_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_CONFIGURATORS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; +import static org.apache.dubbo.common.constants.RegistryConstants.ROUTE_PROTOCOL; + +/** + * 2019-05-13 + */ +public class MultipleRegistryTestUtil { + public static ZookeeperRegistry getZookeeperRegistry(Collection registryCollection) { + for (Registry registry : registryCollection) { + if (registry instanceof ZookeeperRegistry) { + return (ZookeeperRegistry) registry; + } + } + return null; + } + + public static RedisRegistry getRedisRegistry(Collection registryCollection) { + for (Registry registry : registryCollection) { + if (registry instanceof RedisRegistry) { + return (RedisRegistry) registry; + } + } + return null; + } + + public static String getRedisContent(int port, String key) { + Jedis jedis = null; + try { + jedis = new Jedis("127.0.0.1", port); + return jedis.get(key); + } catch (Throwable e) { + throw new RpcException("Failed to put to redis . cause: " + e.getMessage(), e); + } finally { + if (jedis != null) { + jedis.close(); + } + } + } + + public static String getRedisHashContent(int port, String key, String field) { + Jedis jedis = null; + try { + jedis = new Jedis("127.0.0.1", port); + return jedis.hget(key, field); + } catch (Throwable e) { + throw new RpcException("Failed to put to redis . cause: " + e.getMessage(), e); + } finally { + if (jedis != null) { + jedis.close(); + } + } + } + + /** + * copy from @org.apache.dubbo.registry.integration.RegistryDirectory#notify(java.util.List) + * + * @param urls + * @return + */ + public static List getProviderURLsFromNotifyURLS(List urls) { + Map> categoryUrls = urls.stream() + .filter(Objects::nonNull) + .filter(MultipleRegistryTestUtil::isValidCategory) + .filter(MultipleRegistryTestUtil::isNotCompatibleFor26x) + .collect(Collectors.groupingBy(url -> { + if (UrlUtils.isConfigurator(url)) { + return CONFIGURATORS_CATEGORY; + } else if (UrlUtils.isRoute(url)) { + return ROUTERS_CATEGORY; + } else if (UrlUtils.isProvider(url)) { + return PROVIDERS_CATEGORY; + } + return ""; + })); + + // providers + List providerURLs = categoryUrls.getOrDefault(PROVIDERS_CATEGORY, Collections.emptyList()); + return providerURLs; + + } + + private static boolean isValidCategory(URL url) { + String category = url.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY); + if ((ROUTERS_CATEGORY.equals(category) || ROUTE_PROTOCOL.equals(url.getProtocol())) || + PROVIDERS_CATEGORY.equals(category) || + CONFIGURATORS_CATEGORY.equals(category) || DYNAMIC_CONFIGURATORS_CATEGORY.equals(category) || + APP_DYNAMIC_CONFIGURATORS_CATEGORY.equals(category)) { + return true; + } + return false; + } + + private static boolean isNotCompatibleFor26x(URL url) { + return StringUtils.isEmpty(url.getParameter(COMPATIBLE_CONFIG_KEY)); + } +} diff --git a/dubbo-registry/pom.xml b/dubbo-registry/pom.xml index 962148b354a..32db5d495ad 100644 --- a/dubbo-registry/pom.xml +++ b/dubbo-registry/pom.xml @@ -37,6 +37,7 @@ dubbo-registry-consul dubbo-registry-etcd3 dubbo-registry-nacos + dubbo-registry-multiple dubbo-registry-sofa From 4c01c5ee1a8a7bc4c034d819f411b289b1507ea9 Mon Sep 17 00:00:00 2001 From: "ken.lj" Date: Fri, 24 May 2019 15:06:33 +0800 Subject: [PATCH 088/115] delete useless SPI declare (#4148) --- .../META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter b/dubbo-rpc/dubbo-rpc-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter index 24065214f46..376f966e7ba 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter +++ b/dubbo-rpc/dubbo-rpc-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter @@ -11,5 +11,4 @@ exception=org.apache.dubbo.rpc.filter.ExceptionFilter executelimit=org.apache.dubbo.rpc.filter.ExecuteLimitFilter deprecated=org.apache.dubbo.rpc.filter.DeprecatedFilter compatible=org.apache.dubbo.rpc.filter.CompatibleFilter -timeout=org.apache.dubbo.rpc.filter.TimeoutFilter -callback-registration=org.apache.dubbo.rpc.filter.CallbackRegistrationFilter \ No newline at end of file +timeout=org.apache.dubbo.rpc.filter.TimeoutFilter \ No newline at end of file From c14605e15600e6817e12db07826ca896420f65d3 Mon Sep 17 00:00:00 2001 From: cvictory Date: Fri, 24 May 2019 23:50:47 +0800 Subject: [PATCH 089/115] bugfix follow #4127 (#4155) --- .../main/java/org/apache/dubbo/rpc/AsyncRpcResult.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncRpcResult.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncRpcResult.java index fc262475e88..658797d0b6d 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncRpcResult.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncRpcResult.java @@ -143,6 +143,16 @@ public Result thenApplyWithContext(Function fn) { return this; } + public void subscribeTo(CompletableFuture future) { + future.whenComplete((obj, t) -> { + if (t != null) { + this.completeExceptionally(t); + } else { + this.complete((Result) obj); + } + }); + } + @Override public Map getAttachments() { return getAppResponse().getAttachments(); From a8ca64c8aae3e4b1d26de833f59f61080b3276e4 Mon Sep 17 00:00:00 2001 From: Xin Wang Date: Sat, 25 May 2019 00:06:55 +0800 Subject: [PATCH 090/115] Remove incubator (#4161) --- .../dubbo-issue-report-template.md | 4 +- CHANGES.md | 200 +++++++++--------- CONTRIBUTING.md | 18 +- NOTICE | 2 +- PULL_REQUEST_TEMPLATE.md | 6 +- README.md | 70 +++--- dubbo-bom/pom.xml | 10 +- .../common/utils/CompatibleTypeUtils.java | 4 +- .../ReferenceAnnotationBeanPostProcessor.java | 4 +- .../ServiceAnnotationBeanPostProcessor.java | 2 +- .../DubboConfigConfigurationRegistrar.java | 2 +- .../spring/status/SpringStatusChecker.java | 2 +- dubbo-demo/README.md | 2 +- dubbo-dependencies-bom/pom.xml | 10 +- dubbo-distribution/pom.xml | 2 +- .../zookeeper/ZookeeperRegistryTest.java | 2 +- .../remoting/etcd/jetcd/JEtcdClient.java | 2 +- .../dubbo/rpc/protocol/http/HttpProtocol.java | 2 +- dubbo-rpc/dubbo-rpc-xml/pom.xml | 2 +- pom.xml | 10 +- 20 files changed, 178 insertions(+), 178 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/dubbo-issue-report-template.md b/.github/ISSUE_TEMPLATE/dubbo-issue-report-template.md index 13587d07ebc..ac82ec81b96 100644 --- a/.github/ISSUE_TEMPLATE/dubbo-issue-report-template.md +++ b/.github/ISSUE_TEMPLATE/dubbo-issue-report-template.md @@ -4,8 +4,8 @@ about: If you would like to report a issue to Dubbo, please use this template. --- -- [ ] I have searched the [issues](https://github.com/apache/incubator-dubbo/issues) of this repository and believe that this is not a duplicate. -- [ ] I have checked the [FAQ](https://github.com/apache/incubator-dubbo/blob/master/FAQ.md) of this repository and believe that this is not a duplicate. +- [ ] I have searched the [issues](https://github.com/apache/dubbo/issues) of this repository and believe that this is not a duplicate. +- [ ] I have checked the [FAQ](https://github.com/apache/dubbo/blob/master/FAQ.md) of this repository and believe that this is not a duplicate. ### Environment diff --git a/CHANGES.md b/CHANGES.md index e49e66636c8..6296565891f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -8,84 +8,84 @@ ### New Features -- service register support on nacos [#3582](https://github.com/apache/incubator-dubbo/issues/3582) -- support consul as registry center, config center and metadata center [#983](https://github.com/apache/incubator-dubbo/issues/983) -- service registry support/config center support on etcd [#808](https://github.com/apache/incubator-dubbo/issues/808) -- metrics support in dubbo 2.7.1 [#3598](https://github.com/apache/incubator-dubbo/issues/3598) -- @Argument @Method support [#2405](https://github.com/apache/incubator-dubbo/issues/2045) +- service register support on nacos [#3582](https://github.com/apache/dubbo/issues/3582) +- support consul as registry center, config center and metadata center [#983](https://github.com/apache/dubbo/issues/983) +- service registry support/config center support on etcd [#808](https://github.com/apache/dubbo/issues/808) +- metrics support in dubbo 2.7.1 [#3598](https://github.com/apache/dubbo/issues/3598) +- @Argument @Method support [#2405](https://github.com/apache/dubbo/issues/2045) ### Enhancement -- [Enhancement] @EnableDubboConfigBinding annotates @Repeatable [#1770](https://github.com/apache/incubator-dubbo/issues/1770) -- [Enhancement] Change the default behavior of @EnableDubboConfig.multiple() [#3193](https://github.com/apache/incubator-dubbo/issues/3193) -- Should make annotation easier to use in multiple items circumstance [#3039](https://github.com/apache/incubator-dubbo/issues/3039) -- NoSuchMethodError are thrown when add custom Filter using dubbo2.6.5 and JDK1.6 and upgrade to dubbo2.7.0 [#3570](https://github.com/apache/incubator-dubbo/issues/3570) -- introduce dubbo-dependencies-zookeeper [#3607](https://github.com/apache/incubator-dubbo/pull/3607) -- Zookeeper ConfigCenter reuse the client abstraction and connection session [#3288](https://github.com/apache/incubator-dubbo/issues/3288) -- [Survey] Is it necessary to continue to maintain zkclient in dubbo project? [#3569](https://github.com/apache/incubator-dubbo/issues/3569) -- Start to use IdleStateHandler in Netty4 [#3341](https://github.com/apache/incubator-dubbo/pull/3341) -- Support multiple shared links [#2457](https://github.com/apache/incubator-dubbo/pull/2457) -- Optimize heartbeat [#3299](https://github.com/apache/incubator-dubbo/pull/3299) -- AccessLogFilter simple date format reduce instance creation [#3026](https://github.com/apache/incubator-dubbo/issues/3026) -- Support wildcard ip for tag router rule. [#3289](https://github.com/apache/incubator-dubbo/issues/3289) -- ScriptRouter should cache CompiledScript [#390](https://github.com/apache/incubator-dubbo/issues/390) -- Optimize compareTo in Router to guarantee consistent behaviour. [#3302](https://github.com/apache/incubator-dubbo/issues/3302) -- RMI protocol doesn't support generic invocation [#2779](https://github.com/apache/incubator-dubbo/issues/2779) -- a more elegant way to enhance HashedWheelTimer [#3567](https://github.com/apache/incubator-dubbo/pull/3567) -- obtain local address incorrectly sometimes in dubbo [#538](https://github.com/apache/incubator-dubbo/issues/538) -- implement pull request #3412 on master branch [#3418](https://github.com/apache/incubator-dubbo/pull/3418) -- enhancement for event of response (follow up for pull request #3043) [#3244](https://github.com/apache/incubator-dubbo/issues/3244) -- bump up hessian-lite version #3423 [#3513](https://github.com/apache/incubator-dubbo/pull/3513) -- [Dubbo-3610]make snakeyaml transitive, should we do this? [#3659](https://github.com/apache/incubator-dubbo/pull/3659) +- [Enhancement] @EnableDubboConfigBinding annotates @Repeatable [#1770](https://github.com/apache/dubbo/issues/1770) +- [Enhancement] Change the default behavior of @EnableDubboConfig.multiple() [#3193](https://github.com/apache/dubbo/issues/3193) +- Should make annotation easier to use in multiple items circumstance [#3039](https://github.com/apache/dubbo/issues/3039) +- NoSuchMethodError are thrown when add custom Filter using dubbo2.6.5 and JDK1.6 and upgrade to dubbo2.7.0 [#3570](https://github.com/apache/dubbo/issues/3570) +- introduce dubbo-dependencies-zookeeper [#3607](https://github.com/apache/dubbo/pull/3607) +- Zookeeper ConfigCenter reuse the client abstraction and connection session [#3288](https://github.com/apache/dubbo/issues/3288) +- [Survey] Is it necessary to continue to maintain zkclient in dubbo project? [#3569](https://github.com/apache/dubbo/issues/3569) +- Start to use IdleStateHandler in Netty4 [#3341](https://github.com/apache/dubbo/pull/3341) +- Support multiple shared links [#2457](https://github.com/apache/dubbo/pull/2457) +- Optimize heartbeat [#3299](https://github.com/apache/dubbo/pull/3299) +- AccessLogFilter simple date format reduce instance creation [#3026](https://github.com/apache/dubbo/issues/3026) +- Support wildcard ip for tag router rule. [#3289](https://github.com/apache/dubbo/issues/3289) +- ScriptRouter should cache CompiledScript [#390](https://github.com/apache/dubbo/issues/390) +- Optimize compareTo in Router to guarantee consistent behaviour. [#3302](https://github.com/apache/dubbo/issues/3302) +- RMI protocol doesn't support generic invocation [#2779](https://github.com/apache/dubbo/issues/2779) +- a more elegant way to enhance HashedWheelTimer [#3567](https://github.com/apache/dubbo/pull/3567) +- obtain local address incorrectly sometimes in dubbo [#538](https://github.com/apache/dubbo/issues/538) +- implement pull request #3412 on master branch [#3418](https://github.com/apache/dubbo/pull/3418) +- enhancement for event of response (follow up for pull request #3043) [#3244](https://github.com/apache/dubbo/issues/3244) +- bump up hessian-lite version #3423 [#3513](https://github.com/apache/dubbo/pull/3513) +- [Dubbo-3610]make snakeyaml transitive, should we do this? [#3659](https://github.com/apache/dubbo/pull/3659) ### Bugfixes -- cannot register REST service in 2.7 due to the changes in RestProtoco#getContextPath [#3445](https://github.com/apache/incubator-dubbo/issues/3445) -- Conflict between curator client and dubbo [#3574](https://github.com/apache/incubator-dubbo/issues/3574) -- is there a problem in NettyBackedChannelBuffer.setBytes(...)? [#2619](https://github.com/apache/incubator-dubbo/issues/2619) -- [Dubbo - client always reconnect offline provider] Dubbo client bug [#3158](https://github.com/apache/incubator-dubbo/issues/3158) -- fix heartbeat internal [#3579](https://github.com/apache/incubator-dubbo/pull/3579) -- logic issue in RedisRegistry leads to services cannot be discovered. [#3291](https://github.com/apache/incubator-dubbo/pull/3291) -- Multicast demo fails with message "Can't assign requested address" [#2423](https://github.com/apache/incubator-dubbo/issues/2423) -- Fix thrift protocol, use path to locate exporter. [#3331](https://github.com/apache/incubator-dubbo/pull/3331) -- cannot use override to modify provider's configuration when hessian protocol is used [#900](https://github.com/apache/incubator-dubbo/issues/900) -- Condition is not properly used ? [#1917](https://github.com/apache/incubator-dubbo/issues/1917) -- connectionMonitor in RestProtocol seems not work [#3237](https://github.com/apache/incubator-dubbo/issues/3237) -- fail to parse config text with white space [#3367](https://github.com/apache/incubator-dubbo/issues/3367) -- @Reference check=false doesn't take effect [#195](https://github.com/apache/incubator-dubbo/issues/195) -- [Issue] SpringStatusChecker execute errors on non-XML Spring configuration [#3615](https://github.com/apache/incubator-dubbo/issues/3615) -- monitor's cluster config is set to failsafe and set to failsafe only [#274](https://github.com/apache/incubator-dubbo/issues/274) -- A question for ReferenceConfigCache. [#1293](https://github.com/apache/incubator-dubbo/issues/1293) -- referenceconfig#destroy never invoke unregister [#3294](https://github.com/apache/incubator-dubbo/issues/3294) -- Fix when qos is disable,log will print every time [#3397](https://github.com/apache/incubator-dubbo/pull/3397) -- service group is not supported in generic direct invocation [#3555](https://github.com/apache/incubator-dubbo/issues/3555) -- setOnreturn doesn't take effect in async generic invocation [#208](https://github.com/apache/incubator-dubbo/issues/208) -- Fix timeout filter not work in async way [#3174](https://github.com/apache/incubator-dubbo/pull/3174) -- java.lang.NumberFormatException: For input string: "" [#3069](https://github.com/apache/incubator-dubbo/issues/3069) -- NPE occurred when the configuration was deleted [#3533](https://github.com/apache/incubator-dubbo/issues/3533) -- NPE when package of interface is empty [#3556](https://github.com/apache/incubator-dubbo/issues/3556) -- NPE when exporting rest service using a given path. [#3477](https://github.com/apache/incubator-dubbo/issues/3477) -- NullPointerException happened when using SpringContainer.getContext() [#3476](https://github.com/apache/incubator-dubbo/issues/3476) -- Why does not tomcat throw an exception when `server.start` failed with a socket binding error. [#3236](https://github.com/apache/incubator-dubbo/issues/3236) -- No such extension org.apache.dubbo.metadata.store.MetadataReportFactory by name redis [#3514](https://github.com/apache/incubator-dubbo/issues/3514) -- dubbo 2.7.1-SNAPSHOT NoClassDefFoundError when use springboot [#3426](https://github.com/apache/incubator-dubbo/issues/3426) -- NPE occurs when use @Reference in junit in spring boot application [#3429](https://github.com/apache/incubator-dubbo/issues/3429) -- When refer the same service with more than one @References(with different configs) on consumer side, only one take effect [#1306](https://github.com/apache/incubator-dubbo/issues/1306) -- consumer always catch java.lang.reflect.UndeclaredThrowableException for the exception thrown from provider [#3386](https://github.com/apache/incubator-dubbo/issues/3386) -- dubbo2.7.0 com.alibaba.com.caucho.hessian.io.HessianProtocolException: 'com.alibaba.dubbo.common.URL' could not be instantiated [#3342](https://github.com/apache/incubator-dubbo/issues/3342) -- Close Resources Properly [#3473](https://github.com/apache/incubator-dubbo/issues/3473) -- SPI entires dup by 3 times. [#2842](https://github.com/apache/incubator-dubbo/issues/2842) -- provider gets wrong interface name from attachment when use generic invocation in 2.6.3 [#2981](https://github.com/apache/incubator-dubbo/issues/2981) -- HashedWheelTimer's queue gets full [#3449](https://github.com/apache/incubator-dubbo/issues/3449) -- Modify MetadataReportRetry ThreadName [#3550](https://github.com/apache/incubator-dubbo/pull/3550) -- Keep interface key in the URL in simplify mode when it's different from path. [#3478](https://github.com/apache/incubator-dubbo/issues/3478) -- nc is not stable in dubbo's bootstrap script [#936](https://github.com/apache/incubator-dubbo/issues/936) +- cannot register REST service in 2.7 due to the changes in RestProtoco#getContextPath [#3445](https://github.com/apache/dubbo/issues/3445) +- Conflict between curator client and dubbo [#3574](https://github.com/apache/dubbo/issues/3574) +- is there a problem in NettyBackedChannelBuffer.setBytes(...)? [#2619](https://github.com/apache/dubbo/issues/2619) +- [Dubbo - client always reconnect offline provider] Dubbo client bug [#3158](https://github.com/apache/dubbo/issues/3158) +- fix heartbeat internal [#3579](https://github.com/apache/dubbo/pull/3579) +- logic issue in RedisRegistry leads to services cannot be discovered. [#3291](https://github.com/apache/dubbo/pull/3291) +- Multicast demo fails with message "Can't assign requested address" [#2423](https://github.com/apache/dubbo/issues/2423) +- Fix thrift protocol, use path to locate exporter. [#3331](https://github.com/apache/dubbo/pull/3331) +- cannot use override to modify provider's configuration when hessian protocol is used [#900](https://github.com/apache/dubbo/issues/900) +- Condition is not properly used ? [#1917](https://github.com/apache/dubbo/issues/1917) +- connectionMonitor in RestProtocol seems not work [#3237](https://github.com/apache/dubbo/issues/3237) +- fail to parse config text with white space [#3367](https://github.com/apache/dubbo/issues/3367) +- @Reference check=false doesn't take effect [#195](https://github.com/apache/dubbo/issues/195) +- [Issue] SpringStatusChecker execute errors on non-XML Spring configuration [#3615](https://github.com/apache/dubbo/issues/3615) +- monitor's cluster config is set to failsafe and set to failsafe only [#274](https://github.com/apache/dubbo/issues/274) +- A question for ReferenceConfigCache. [#1293](https://github.com/apache/dubbo/issues/1293) +- referenceconfig#destroy never invoke unregister [#3294](https://github.com/apache/dubbo/issues/3294) +- Fix when qos is disable,log will print every time [#3397](https://github.com/apache/dubbo/pull/3397) +- service group is not supported in generic direct invocation [#3555](https://github.com/apache/dubbo/issues/3555) +- setOnreturn doesn't take effect in async generic invocation [#208](https://github.com/apache/dubbo/issues/208) +- Fix timeout filter not work in async way [#3174](https://github.com/apache/dubbo/pull/3174) +- java.lang.NumberFormatException: For input string: "" [#3069](https://github.com/apache/dubbo/issues/3069) +- NPE occurred when the configuration was deleted [#3533](https://github.com/apache/dubbo/issues/3533) +- NPE when package of interface is empty [#3556](https://github.com/apache/dubbo/issues/3556) +- NPE when exporting rest service using a given path. [#3477](https://github.com/apache/dubbo/issues/3477) +- NullPointerException happened when using SpringContainer.getContext() [#3476](https://github.com/apache/dubbo/issues/3476) +- Why does not tomcat throw an exception when `server.start` failed with a socket binding error. [#3236](https://github.com/apache/dubbo/issues/3236) +- No such extension org.apache.dubbo.metadata.store.MetadataReportFactory by name redis [#3514](https://github.com/apache/dubbo/issues/3514) +- dubbo 2.7.1-SNAPSHOT NoClassDefFoundError when use springboot [#3426](https://github.com/apache/dubbo/issues/3426) +- NPE occurs when use @Reference in junit in spring boot application [#3429](https://github.com/apache/dubbo/issues/3429) +- When refer the same service with more than one @References(with different configs) on consumer side, only one take effect [#1306](https://github.com/apache/dubbo/issues/1306) +- consumer always catch java.lang.reflect.UndeclaredThrowableException for the exception thrown from provider [#3386](https://github.com/apache/dubbo/issues/3386) +- dubbo2.7.0 com.alibaba.com.caucho.hessian.io.HessianProtocolException: 'com.alibaba.dubbo.common.URL' could not be instantiated [#3342](https://github.com/apache/dubbo/issues/3342) +- Close Resources Properly [#3473](https://github.com/apache/dubbo/issues/3473) +- SPI entires dup by 3 times. [#2842](https://github.com/apache/dubbo/issues/2842) +- provider gets wrong interface name from attachment when use generic invocation in 2.6.3 [#2981](https://github.com/apache/dubbo/issues/2981) +- HashedWheelTimer's queue gets full [#3449](https://github.com/apache/dubbo/issues/3449) +- Modify MetadataReportRetry ThreadName [#3550](https://github.com/apache/dubbo/pull/3550) +- Keep interface key in the URL in simplify mode when it's different from path. [#3478](https://github.com/apache/dubbo/issues/3478) +- nc is not stable in dubbo's bootstrap script [#936](https://github.com/apache/dubbo/issues/936) ## 2.7.0 Requirements: **Java 8+** required -Please check [here](https://github.com/apache/incubator-dubbo/blob/2.7.0-release/CHANGES.md#upgrading-and-compatibility-notifications) for notes and possible compatibility issues for upgrading from 2.6.x or lower to 2.7.0. +Please check [here](https://github.com/apache/dubbo/blob/2.7.0-release/CHANGES.md#upgrading-and-compatibility-notifications) for notes and possible compatibility issues for upgrading from 2.6.x or lower to 2.7.0. ### New Features @@ -101,7 +101,7 @@ Please check [here](https://github.com/apache/incubator-dubbo/blob/2.7.0-release - Simplified registry URL. With lower Registry memory use and less notification pressure from Service Directory, separates Configuration notification from Service Discovery. -- Metadata Center. A totally new concept since 2.7.0, used to store service metadata including static configuration, service definition, method signature, etc.. By default, Zookeeper and Redis are supported as the backend storage. Will work as the basis of service testing, mock and other service governance features going to be supported in [Dubbo-Admin](https://github.com/apache/incubator-dubbo-admin). +- Metadata Center. A totally new concept since 2.7.0, used to store service metadata including static configuration, service definition, method signature, etc.. By default, Zookeeper and Redis are supported as the backend storage. Will work as the basis of service testing, mock and other service governance features going to be supported in [Dubbo-Admin](https://github.com/apache/dubbo-admin). - Asynchronous Programming Model (only works for Dubbo protocol now) - Built-in support for the method with CompletableFuture signature. @@ -176,57 +176,57 @@ BugFix: Enhancements / Features: -- Reactor the generation rule for @Service Bean name [#2235](https://github.com/apache/incubator-dubbo/issues/2235) -- Introduce a new Spring ApplicationEvent for ServiceBean exporting [#2251](https://github.com/apache/incubator-dubbo/issues/2251) -- [Enhancement] the algorithm of load issue on Windows. [#1641](https://github.com/apache/incubator-dubbo/issues/1641) -- add javadoc to dubbo-all module good first issue. [#2600](https://github.com/apache/incubator-dubbo/issues/2600) -- [Enhancement] Reactor the generation rule for @Service Bean name type/enhancement [#2235](https://github.com/apache/incubator-dubbo/issues/2235) -- Optimize LeastActiveLoadBalance and add weight test case. [#2540](https://github.com/apache/incubator-dubbo/issues/2540) -- Smooth Round Robin selection. [#2578](https://github.com/apache/incubator-dubbo/issues/2578) [#2647](https://github.com/apache/incubator-dubbo/pull/2647) -- [Enhancement] Resolve the placeholders for sub-properties. [#2297](https://github.com/apache/incubator-dubbo/issues/2297) -- Add ability to turn off SPI auto injection, special support for generic Object type injection. [#2681](https://github.com/apache/incubator-dubbo/pull/2681) +- Reactor the generation rule for @Service Bean name [#2235](https://github.com/apache/dubbo/issues/2235) +- Introduce a new Spring ApplicationEvent for ServiceBean exporting [#2251](https://github.com/apache/dubbo/issues/2251) +- [Enhancement] the algorithm of load issue on Windows. [#1641](https://github.com/apache/dubbo/issues/1641) +- add javadoc to dubbo-all module good first issue. [#2600](https://github.com/apache/dubbo/issues/2600) +- [Enhancement] Reactor the generation rule for @Service Bean name type/enhancement [#2235](https://github.com/apache/dubbo/issues/2235) +- Optimize LeastActiveLoadBalance and add weight test case. [#2540](https://github.com/apache/dubbo/issues/2540) +- Smooth Round Robin selection. [#2578](https://github.com/apache/dubbo/issues/2578) [#2647](https://github.com/apache/dubbo/pull/2647) +- [Enhancement] Resolve the placeholders for sub-properties. [#2297](https://github.com/apache/dubbo/issues/2297) +- Add ability to turn off SPI auto injection, special support for generic Object type injection. [#2681](https://github.com/apache/dubbo/pull/2681) Bugfixes: -- @Service(register=false) is not work. [#2063](https://github.com/apache/incubator-dubbo/issues/2063) -- Our customized serialization id exceeds the maximum limit, now it cannot work on 2.6.2 anymore. [#1903](https://github.com/apache/incubator-dubbo/issues/1903) -- Consumer throws RpcException after RegistryDirectory notify in high QPS. [#2016](https://github.com/apache/incubator-dubbo/issues/2016) -- Annotation @Reference can't support to export a service with a sync one and an async one . [#2194](https://github.com/apache/incubator-dubbo/issues/2194) -- `org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor#generateReferenceBeanCacheKey` has a bug. [#2522](https://github.com/apache/incubator-dubbo/issues/2522) -- 2.6.x Spring Event & Bugfix. [#2256](https://github.com/apache/incubator-dubbo/issues/2256) -- Fix incorrect descriptions for dubbo-serialization module. [#2665](https://github.com/apache/incubator-dubbo/issues/2665) -- A empty directory dubbo-config/dubbo-config-spring/src/test/resources/work after package source tgz. [#2560](https://github.com/apache/incubator-dubbo/issues/2560) -- Fixed 2.6.x branch a minor issue with doConnect not using getConnectTimeout() in NettyClient. (*No issue*). [#2622](https://github.com/apache/incubator-dubbo/pull/2622) -- Bean name of @service annotated class does not resolve placeholder. [#1755](https://github.com/apache/incubator-dubbo/issues/1755) +- @Service(register=false) is not work. [#2063](https://github.com/apache/dubbo/issues/2063) +- Our customized serialization id exceeds the maximum limit, now it cannot work on 2.6.2 anymore. [#1903](https://github.com/apache/dubbo/issues/1903) +- Consumer throws RpcException after RegistryDirectory notify in high QPS. [#2016](https://github.com/apache/dubbo/issues/2016) +- Annotation @Reference can't support to export a service with a sync one and an async one . [#2194](https://github.com/apache/dubbo/issues/2194) +- `org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor#generateReferenceBeanCacheKey` has a bug. [#2522](https://github.com/apache/dubbo/issues/2522) +- 2.6.x Spring Event & Bugfix. [#2256](https://github.com/apache/dubbo/issues/2256) +- Fix incorrect descriptions for dubbo-serialization module. [#2665](https://github.com/apache/dubbo/issues/2665) +- A empty directory dubbo-config/dubbo-config-spring/src/test/resources/work after package source tgz. [#2560](https://github.com/apache/dubbo/issues/2560) +- Fixed 2.6.x branch a minor issue with doConnect not using getConnectTimeout() in NettyClient. (*No issue*). [#2622](https://github.com/apache/dubbo/pull/2622) +- Bean name of @service annotated class does not resolve placeholder. [#1755](https://github.com/apache/dubbo/issues/1755) -Issues and Pull Requests, check [milestone-2.6.5](https://github.com/apache/incubator-dubbo/milestone/21). +Issues and Pull Requests, check [milestone-2.6.5](https://github.com/apache/dubbo/milestone/21). ## 2.6.4 Enhancements / Features -- Support access Redis with password, [#2146](https://github.com/apache/incubator-dubbo/pull/2146) -- Support char array for GenericService, [#2137](https://github.com/apache/incubator-dubbo/pull/2137) -- Direct return when the server goes down abnormally, [#2451](https://github.com/apache/incubator-dubbo/pull/2451) -- Add log for trouble-shooting when qos start failed, [#2455](https://github.com/apache/incubator-dubbo/pull/2455) -- PojoUtil support subclasses of java.util.Date, [#2502](https://github.com/apache/incubator-dubbo/pull/2502) -- Add ip and application name for MonitorService, [#2166](https://github.com/apache/incubator-dubbo/pull/2166) -- New ASCII logo, [#2402](https://github.com/apache/incubator-dubbo/pull/2402) +- Support access Redis with password, [#2146](https://github.com/apache/dubbo/pull/2146) +- Support char array for GenericService, [#2137](https://github.com/apache/dubbo/pull/2137) +- Direct return when the server goes down abnormally, [#2451](https://github.com/apache/dubbo/pull/2451) +- Add log for trouble-shooting when qos start failed, [#2455](https://github.com/apache/dubbo/pull/2455) +- PojoUtil support subclasses of java.util.Date, [#2502](https://github.com/apache/dubbo/pull/2502) +- Add ip and application name for MonitorService, [#2166](https://github.com/apache/dubbo/pull/2166) +- New ASCII logo, [#2402](https://github.com/apache/dubbo/pull/2402) Bugfixes -- Change consumer retries default value from 0 to 2, [#2303](https://github.com/apache/incubator-dubbo/pull/2303) -- Fix the problem that attachment is lost when retry, [#2024](https://github.com/apache/incubator-dubbo/pull/2024) -- Fix NPE when telnet get a null parameter, [#2453](https://github.com/apache/incubator-dubbo/pull/2453) +- Change consumer retries default value from 0 to 2, [#2303](https://github.com/apache/dubbo/pull/2303) +- Fix the problem that attachment is lost when retry, [#2024](https://github.com/apache/dubbo/pull/2024) +- Fix NPE when telnet get a null parameter, [#2453](https://github.com/apache/dubbo/pull/2453) UT stability -- Improve the stability by changing different port, setting timeout to 3000ms, [#2501](https://github.com/apache/incubator-dubbo/pull/2501) +- Improve the stability by changing different port, setting timeout to 3000ms, [#2501](https://github.com/apache/dubbo/pull/2501) -Issues and Pull Requests, check [milestone-2.6.4](https://github.com/apache/incubator-dubbo/milestone/19). +Issues and Pull Requests, check [milestone-2.6.4](https://github.com/apache/dubbo/milestone/19). ## 2.6.3 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e5ed3a9ee9b..c92e4a115b5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -9,15 +9,15 @@ Before we accept a non-trivial patch or pull request we will need you to sign th #### Mailing list -The mailing list is the recommended way for discussing almost anything that related to Dubbo. Please refer to this [guide](https://github.com/apache/incubator-dubbo/wiki/Mailing-list-subscription-guide) for detailed documentation on how to subscribe. +The mailing list is the recommended way for discussing almost anything that related to Dubbo. Please refer to this [guide](https://github.com/apache/dubbo/wiki/Mailing-list-subscription-guide) for detailed documentation on how to subscribe. -- [dev@dubbo.incubator.apache.org](mailto:dev-subscribe@dubbo.incubator.apache.org): the develop mailing list, you can ask question here if you have encountered any problem when using or developing Dubbo. -- [commits@dubbo.incubator.apache.org](mailto:commits-subscribe@dubbo.incubator.apache.org): all the commits will be sent to this mailing list. You can subscribe to it if you are interested in Dubbo's development. -- [notifications@dubbo.incubator.apache.org](mailto:notifications-subscribe@dubbo.incubator.apache.org): all the Github [issue](https://github.com/apache/incubator-dubbo/issues) updates and [pull request](https://github.com/apache/incubator-dubbo/pulls) updates will be sent to this mailing list. +- [dev@dubbo.apache.org](mailto:dev-subscribe@dubbo.apache.org): the develop mailing list, you can ask question here if you have encountered any problem when using or developing Dubbo. +- [commits@dubbo.apache.org](mailto:commits-subscribe@dubbo.apache.org): all the commits will be sent to this mailing list. You can subscribe to it if you are interested in Dubbo's development. +- [notifications@dubbo.apache.org](mailto:notifications-subscribe@dubbo.apache.org): all the Github [issue](https://github.com/apache/dubbo/issues) updates and [pull request](https://github.com/apache/dubbo/pulls) updates will be sent to this mailing list. ### Reporting issue -Please follow the [template](https://github.com/apache/incubator-dubbo/issues/new?template=dubbo-issue-report-template.md) for reporting any issues. +Please follow the [template](https://github.com/apache/dubbo/issues/new?template=dubbo-issue-report-template.md) for reporting any issues. ### Code Conventions Our code style is almost in line with the standard java conventions (Popular IDE's default setting satisfy this), with the following additional restricts: @@ -46,23 +46,23 @@ This is a rough outline of what a contributor's workflow looks like: * Make commits of logical units. * Make sure commit messages are in the proper format (see below). * Push changes in a topic branch to your forked repository. -* Follow the checklist in the [pull request template](https://github.com/apache/incubator-dubbo/blob/master/PULL_REQUEST_TEMPLATE.md) +* Follow the checklist in the [pull request template](https://github.com/apache/dubbo/blob/master/PULL_REQUEST_TEMPLATE.md) * Before you sending out the pull request, please sync your forked repository with remote repository, this will make your pull request simple and clear. See guide below: ``` -git remote add upstream git@github.com:apache/incubator-dubbo.git +git remote add upstream git@github.com:apache/dubbo.git git fetch upstream git rebase upstream/master git checkout -b your_awesome_patch ... add some work git push origin your_awesome_patch ``` -* Submit a pull request to apache/incubator-dubbo and wait for the reply. +* Submit a pull request to apache/dubbo and wait for the reply. Thanks for contributing! ### Code style -We provide a template file [dubbo_codestyle_for_idea.xml](https://github.com/apache/incubator-dubbo/tree/master/codestyle/dubbo_codestyle_for_idea.xml) for IntelliJ idea, you can import it to you IDE. +We provide a template file [dubbo_codestyle_for_idea.xml](https://github.com/apache/dubbo/tree/master/codestyle/dubbo_codestyle_for_idea.xml) for IntelliJ idea, you can import it to you IDE. If you use Eclipse you can config manually by referencing the same file. **NOTICE** diff --git a/NOTICE b/NOTICE index e3151c76035..743868e3d16 100644 --- a/NOTICE +++ b/NOTICE @@ -1,4 +1,4 @@ -Apache Dubbo (incubating) +Apache Dubbo Copyright 2018-2019 The Apache Software Foundation This product includes software developed at diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md index 17bc2b3ac33..20c5854a2fd 100644 --- a/PULL_REQUEST_TEMPLATE.md +++ b/PULL_REQUEST_TEMPLATE.md @@ -12,9 +12,9 @@ XXXXX Follow this checklist to help us incorporate your contribution quickly and easily: -- [x] Make sure there is a [GITHUB_issue](https://github.com/apache/incubator-dubbo/issues) field for the change (usually before you start working on it). Trivial changes like typos do not require a GITHUB issue. Your pull request should address just this issue, without pulling in other changes - one PR resolves one issue. +- [x] Make sure there is a [GITHUB_issue](https://github.com/apache/dubbo/issues) field for the change (usually before you start working on it). Trivial changes like typos do not require a GITHUB issue. Your pull request should address just this issue, without pulling in other changes - one PR resolves one issue. - [ ] Format the pull request title like `[Dubbo-XXX] Fix UnknownException when host config not exist #XXX`. Each commit in the pull request should have a meaningful subject line and body. - [ ] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. -- [ ] Write necessary unit-test to verify your logic correction, more mock a little better when cross module dependency exist. If the new feature or significant change is committed, please remember to add sample in [dubbo samples](https://github.com/apache/incubator-dubbo-samples) project. +- [ ] Write necessary unit-test to verify your logic correction, more mock a little better when cross module dependency exist. If the new feature or significant change is committed, please remember to add sample in [dubbo samples](https://github.com/apache/dubbo-samples) project. - [ ] Run `mvn clean install -DskipTests=false` & `mvn clean test-compile failsafe:integration-test` to make sure unit-test and integration-test pass. -- [ ] If this contribution is large, please follow the [Software Donation Guide](https://github.com/apache/incubator-dubbo/wiki/Software-donation-guide). +- [ ] If this contribution is large, please follow the [Software Donation Guide](https://github.com/apache/dubbo/wiki/Software-donation-guide). diff --git a/README.md b/README.md index 3010a784558..751ad1e1764 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,18 @@ # Apache Dubbo Project -[![Build Status](https://travis-ci.org/apache/incubator-dubbo.svg?branch=master)](https://travis-ci.org/apache/incubator-dubbo) -[![codecov](https://codecov.io/gh/apache/incubator-dubbo/branch/master/graph/badge.svg)](https://codecov.io/gh/apache/incubator-dubbo) +[![Build Status](https://travis-ci.org/apache/dubbo.svg?branch=master)](https://travis-ci.org/apache/dubbo) +[![codecov](https://codecov.io/gh/apache/dubbo/branch/master/graph/badge.svg)](https://codecov.io/gh/apache/dubbo) ![maven](https://img.shields.io/maven-central/v/org.apache.dubbo/dubbo.svg) ![license](https://img.shields.io/github/license/alibaba/dubbo.svg) -[![Average time to resolve an issue](http://isitmaintained.com/badge/resolution/apache/incubator-dubbo.svg)](http://isitmaintained.com/project/apache/incubator-dubbo "Average time to resolve an issue") -[![Percentage of issues still open](http://isitmaintained.com/badge/open/apache/incubator-dubbo.svg)](http://isitmaintained.com/project/apache/incubator-dubbo "Percentage of issues still open") -[![Tweet](https://img.shields.io/twitter/url/http/shields.io.svg?style=social)](https://twitter.com/intent/tweet?text=Apache%20Dubbo%20(incubating)%20is%20a%20high-performance%2C%20java%20based%2C%20open%20source%20RPC%20framework.&url=http://dubbo.incubator.apache.org/&via=ApacheDubbo&hashtags=rpc,java,dubbo,micro-service) +[![Average time to resolve an issue](http://isitmaintained.com/badge/resolution/apache/dubbo.svg)](http://isitmaintained.com/project/apache/dubbo "Average time to resolve an issue") +[![Percentage of issues still open](http://isitmaintained.com/badge/open/apache/dubbo.svg)](http://isitmaintained.com/project/apache/dubbo "Percentage of issues still open") +[![Tweet](https://img.shields.io/twitter/url/http/shields.io.svg?style=social)](https://twitter.com/intent/tweet?text=Apache%20Dubbo%20is%20a%20high-performance%2C%20java%20based%2C%20open%20source%20RPC%20framework.&url=http://dubbo.apache.org/&via=ApacheDubbo&hashtags=rpc,java,dubbo,micro-service) [![](https://img.shields.io/twitter/follow/ApacheDubbo.svg?label=Follow&style=social&logoWidth=0)](https://twitter.com/intent/follow?screen_name=ApacheDubbo) [![Gitter](https://badges.gitter.im/alibaba/dubbo.svg)](https://gitter.im/alibaba/dubbo?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) -Apache Dubbo is a high-performance, Java based open source RPC framework. Please visit [official site](http://dubbo.apache.org) for quick start and documentations, as well as [Wiki](https://github.com/apache/incubator-dubbo/wiki) for news, FAQ, and release notes. +Apache Dubbo is a high-performance, Java based open source RPC framework. Please visit [official site](http://dubbo.apache.org) for quick start and documentations, as well as [Wiki](https://github.com/apache/dubbo/wiki) for news, FAQ, and release notes. -We are now collecting dubbo user info in order to help us to improve Dubbo better, pls. kindly help us by providing yours on [issue#1012: Wanted: who's using dubbo](https://github.com/apache/incubator-dubbo/issues/1012), thanks :) +We are now collecting dubbo user info in order to help us to improve Dubbo better, pls. kindly help us by providing yours on [issue#1012: Wanted: who's using dubbo](https://github.com/apache/dubbo/issues/1012), thanks :) ## Architecture @@ -29,14 +29,14 @@ We are now collecting dubbo user info in order to help us to improve Dubbo bette ## Getting started -The following code snippet comes from [Dubbo Samples](https://github.com/apache/incubator-dubbo-samples/tree/master/dubbo-samples-api). You may clone the sample project and step into `dubbo-samples-api` sub directory before read on. +The following code snippet comes from [Dubbo Samples](https://github.com/apache/dubbo-samples/tree/master/dubbo-samples-api). You may clone the sample project and step into `dubbo-samples-api` sub directory before read on. ```bash -# git clone https://github.com/apache/incubator-dubbo-samples.git -# cd incubator-dubbo-samples/dubbo-samples-api +# git clone https://github.com/apache/dubbo-samples.git +# cd dubbo-samples/dubbo-samples-api ``` -There's a [README](https://github.com/apache/incubator-dubbo-samples/tree/master/dubbo-samples-api/README.md) file under `dubbo-samples-api` directory. Read it and try this sample out by following the instructions. +There's a [README](https://github.com/apache/dubbo-samples/tree/master/dubbo-samples-api/README.md) file under `dubbo-samples-api` directory. Read it and try this sample out by following the instructions. ### Maven dependency @@ -70,7 +70,7 @@ public interface GreetingService { } ``` -*See [api/GreetingService.java](https://github.com/apache/incubator-dubbo-samples/blob/master/dubbo-samples-api/src/main/java/org/apache/dubbo/samples/api/GreetingsService.java) on GitHub.* +*See [api/GreetingService.java](https://github.com/apache/dubbo-samples/blob/master/dubbo-samples-api/src/main/java/org/apache/dubbo/samples/api/GreetingsService.java) on GitHub.* ### Implement service interface for the provider @@ -87,7 +87,7 @@ public class GreetingServiceImpl implements GreetingService { } ``` -*See [provider/GreetingServiceImpl.java](https://github.com/apache/incubator-dubbo-samples/blob/master/dubbo-samples-api/src/main/java/org/apache/dubbo/samples/server/GreetingsServiceImpl.java) on GitHub.* +*See [provider/GreetingServiceImpl.java](https://github.com/apache/dubbo-samples/blob/master/dubbo-samples-api/src/main/java/org/apache/dubbo/samples/server/GreetingsServiceImpl.java) on GitHub.* ### Start service provider @@ -115,7 +115,7 @@ public class Application { } ``` -*See [provider/Application.java](https://github.com/apache/incubator-dubbo-samples/blob/master/dubbo-samples-api/src/main/java/org/apache/dubbo/samples/server/Application.java) on GitHub.* +*See [provider/Application.java](https://github.com/apache/dubbo-samples/blob/master/dubbo-samples-api/src/main/java/org/apache/dubbo/samples/server/Application.java) on GitHub.* ### Build and run the provider @@ -155,7 +155,7 @@ public class Application { The consumer will print out `Hello world` on the screen. -*See [consumer/Application.java](https://github.com/apache/incubator-dubbo-samples/blob/master/dubbo-samples-api/src/main/java/org/apache/dubbo/samples/client/Application.java) on GitHub.* +*See [consumer/Application.java](https://github.com/apache/dubbo-samples/blob/master/dubbo-samples-api/src/main/java/org/apache/dubbo/samples/client/Application.java) on GitHub.* ### Next steps @@ -175,35 +175,35 @@ If you want to try out the cutting-edge features, you can built with the followi ## Contact * Mailing list: - * dev list: for dev/user discussion. [subscribe](mailto:dev-subscribe@dubbo.apache.org), [unsubscribe](mailto:dev-unsubscribe@dubbo.apache.org), [archive](https://lists.apache.org/list.html?dev@dubbo.apache.org), [guide](https://github.com/apache/incubator-dubbo/wiki/Mailing-list-subscription-guide) + * dev list: for dev/user discussion. [subscribe](mailto:dev-subscribe@dubbo.apache.org), [unsubscribe](mailto:dev-unsubscribe@dubbo.apache.org), [archive](https://lists.apache.org/list.html?dev@dubbo.apache.org), [guide](https://github.com/apache/dubbo/wiki/Mailing-list-subscription-guide) -* Bugs: [Issues](https://github.com/apache/incubator-dubbo/issues/new?template=dubbo-issue-report-template.md) +* Bugs: [Issues](https://github.com/apache/dubbo/issues/new?template=dubbo-issue-report-template.md) * Gitter: [Gitter channel](https://gitter.im/alibaba/dubbo) * Twitter: [@ApacheDubbo](https://twitter.com/ApacheDubbo) ## Contributing -See [CONTRIBUTING](https://github.com/apache/incubator-dubbo/blob/master/CONTRIBUTING.md) for details on submitting patches and the contribution workflow. +See [CONTRIBUTING](https://github.com/apache/dubbo/blob/master/CONTRIBUTING.md) for details on submitting patches and the contribution workflow. ### How can I contribute? -* Take a look at issues with tag called [`Good first issue`](https://github.com/apache/incubator-dubbo/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) or [`Help wanted`](https://github.com/apache/incubator-dubbo/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22). -* Join the discussion on mailing list, subscription [guide](https://github.com/apache/incubator-dubbo/wiki/Mailing-list-subscription-guide). -* Answer questions on [issues](https://github.com/apache/incubator-dubbo/issues). -* Fix bugs reported on [issues](https://github.com/apache/incubator-dubbo/issues), and send us pull request. -* Review the existing [pull request](https://github.com/apache/incubator-dubbo/pulls). -* Improve the [website](https://github.com/apache/incubator-dubbo-website), typically we need +* Take a look at issues with tag called [`Good first issue`](https://github.com/apache/dubbo/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) or [`Help wanted`](https://github.com/apache/dubbo/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22). +* Join the discussion on mailing list, subscription [guide](https://github.com/apache/dubbo/wiki/Mailing-list-subscription-guide). +* Answer questions on [issues](https://github.com/apache/dubbo/issues). +* Fix bugs reported on [issues](https://github.com/apache/dubbo/issues), and send us pull request. +* Review the existing [pull request](https://github.com/apache/dubbo/pulls). +* Improve the [website](https://github.com/apache/dubbo-website), typically we need * blog post * translation on documentation * use cases about how Dubbo is being used in enterprise system. -* Improve the [dubbo-admin/dubbo-monitor](https://github.com/apache/incubator-dubbo-admin). +* Improve the [dubbo-admin/dubbo-monitor](https://github.com/apache/dubbo-admin). * Contribute to the projects listed in [ecosystem](https://github.com/dubbo). * Any form of contribution that is not mentioned above. * If you would like to contribute, please send an email to dev@dubbo.apache.org to let us know! ## Reporting bugs -Please follow the [template](https://github.com/apache/incubator-dubbo/issues/new?template=dubbo-issue-report-template.md) for reporting any issues. +Please follow the [template](https://github.com/apache/dubbo/issues/new?template=dubbo-issue-report-template.md) for reporting any issues. ## Reporting a security vulnerability @@ -212,19 +212,19 @@ Please report security vulnerability to [us](mailto:security@dubbo.apache.org) p ## Dubbo ecosystem * [Dubbo Ecosystem Entry](https://github.com/dubbo) - A GitHub group `dubbo` to gather all Dubbo relevant projects not appropriate in [apache](https://github.com/apache) group yet -* [Dubbo Website](https://github.com/apache/incubator-dubbo-website) - Apache Dubbo official website -* [Dubbo Samples](https://github.com/apache/incubator-dubbo-samples) - samples for Apache Dubbo -* [Dubbo Spring Boot](https://github.com/apache/incubator-dubbo-spring-boot-project) - Spring Boot Project for Dubbo -* [Dubbo Admin](https://github.com/apache/incubator-dubbo-admin) - The reference implementation for Dubbo admin +* [Dubbo Website](https://github.com/apache/dubbo-website) - Apache Dubbo official website +* [Dubbo Samples](https://github.com/apache/dubbo-samples) - samples for Apache Dubbo +* [Dubbo Spring Boot](https://github.com/apache/dubbo-spring-boot-project) - Spring Boot Project for Dubbo +* [Dubbo Admin](https://github.com/apache/dubbo-admin) - The reference implementation for Dubbo admin #### Language -* [Node.js](https://github.com/dubbo/dubbo2.js) -* [Python](https://github.com/dubbo/dubbo-client-py) -* [PHP](https://github.com/dubbo/dubbo-php-framework) +* [Node.js](https://github.com/apache/dubbo-js) +* [Python](https://github.com/apache/dubbo-client-py) +* [PHP](https://github.com/apache/dubbo-php-framework) * [Go](https://github.com/dubbo/dubbo-go) -* [Erlang](https://github.com/apache/incubator-dubbo-erlang) +* [Erlang](https://github.com/apache/dubbo-erlang) ## License -Apache Dubbo is under the Apache 2.0 license. See the [LICENSE](https://github.com/apache/incubator-dubbo/blob/master/LICENSE) file for details. +Apache Dubbo is under the Apache 2.0 license. See the [LICENSE](https://github.com/apache/dubbo/blob/master/LICENSE) file for details. diff --git a/dubbo-bom/pom.xml b/dubbo-bom/pom.xml index 15908715496..8b69673ec9f 100644 --- a/dubbo-bom/pom.xml +++ b/dubbo-bom/pom.xml @@ -30,7 +30,7 @@ dubbo-bom Dubbo dependencies BOM - https://github.com/apache/incubator-dubbo + https://github.com/apache/dubbo 2011 @@ -41,9 +41,9 @@ - https://github.com/apache/incubator-dubbo - scm:git:https://github.com/apache/incubator-dubbo.git - scm:git:https://github.com/apache/incubator-dubbo.git + https://github.com/apache/dubbo + scm:git:https://github.com/apache/dubbo.git + scm:git:https://github.com/apache/dubbo.git HEAD @@ -82,7 +82,7 @@ Github Issues - https://github.com/apache/incubator-dubbo/issues + https://github.com/apache/dubbo/issues diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CompatibleTypeUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CompatibleTypeUtils.java index efc570fe925..26cb834efa7 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CompatibleTypeUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CompatibleTypeUtils.java @@ -103,7 +103,7 @@ public static Object compatibleTypeConvert(Object value, Class type) { } else if (char[].class.equals(type)) { // Process string to char array for generic invoke // See - // - https://github.com/apache/incubator-dubbo/issues/2003 + // - https://github.com/apache/dubbo/issues/2003 int len = string.length(); char[] chars = new char[len]; string.getChars(0, len, chars, 0); @@ -173,4 +173,4 @@ public static Object compatibleTypeConvert(Object value, Class type) { } return value; } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java index 7c3a6b9b87d..e0ba649ce34 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java @@ -156,7 +156,7 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl Object result; try { if (bean == null) { // If the bean is not initialized, invoke init() - // issue: https://github.com/apache/incubator-dubbo/issues/3429 + // issue: https://github.com/apache/dubbo/issues/3429 init(); } result = method.invoke(bean, args); @@ -258,4 +258,4 @@ public void destroy() throws Exception { this.injectedFieldReferenceBeanCache.clear(); this.injectedMethodReferenceBeanCache.clear(); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java index 305e3724132..e167c074710 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java @@ -320,7 +320,7 @@ private Class resolveServiceInterfaceClass(Class annotatedServiceBeanClass if (interfaceClass == null) { // Find all interfaces from the annotated class - // To resolve an issue : https://github.com/apache/incubator-dubbo/issues/3251 + // To resolve an issue : https://github.com/apache/dubbo/issues/3251 Class[] allInterfaces = ClassUtils.getAllInterfacesForClass(annotatedServiceBeanClass); if (allInterfaces.length > 0) { diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfigurationRegistrar.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfigurationRegistrar.java index d01dd398ee0..c1bec4ae4c7 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfigurationRegistrar.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfigurationRegistrar.java @@ -47,7 +47,7 @@ public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, B // Single Config Bindings registerBeans(registry, DubboConfigConfiguration.Single.class); - if (multiple) { // Since 2.6.6 https://github.com/apache/incubator-dubbo/issues/3193 + if (multiple) { // Since 2.6.6 https://github.com/apache/dubbo/issues/3193 registerBeans(registry, DubboConfigConfiguration.Multiple.class); } } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/status/SpringStatusChecker.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/status/SpringStatusChecker.java index 63517c6e52a..30f7347595e 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/status/SpringStatusChecker.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/status/SpringStatusChecker.java @@ -42,7 +42,7 @@ public Status check() { ApplicationContext context = null; for (ApplicationContext c : SpringExtensionFactory.getContexts()) { // [Issue] SpringStatusChecker execute errors on non-XML Spring configuration - // issue : https://github.com/apache/incubator-dubbo/issues/3615 + // issue : https://github.com/apache/dubbo/issues/3615 if(c instanceof GenericWebApplicationContext) { // ignore GenericXmlApplicationContext continue; } diff --git a/dubbo-demo/README.md b/dubbo-demo/README.md index 4cb99b72a95..04653c76409 100644 --- a/dubbo-demo/README.md +++ b/dubbo-demo/README.md @@ -1,6 +1,6 @@ # Dubbo Demo -This directory contains basic usages of Dubbo to help Dubbo developers for debugging and smoke test purpose. If you are looking for Dubbo samples for study purpose, you should look into [here](https://github.com/apache/incubator-dubbo-samples) where you will find comprehensive usages for how to use Dubbo in different scenarios with the different features. +This directory contains basic usages of Dubbo to help Dubbo developers for debugging and smoke test purpose. If you are looking for Dubbo samples for study purpose, you should look into [here](https://github.com/apache/dubbo-samples) where you will find comprehensive usages for how to use Dubbo in different scenarios with the different features. ## How To Build diff --git a/dubbo-dependencies-bom/pom.xml b/dubbo-dependencies-bom/pom.xml index ef42a6e4517..3573df1ed36 100644 --- a/dubbo-dependencies-bom/pom.xml +++ b/dubbo-dependencies-bom/pom.xml @@ -32,7 +32,7 @@ dubbo-dependencies-bom Dubbo dependencies BOM - https://github.com/apache/incubator-dubbo + https://github.com/apache/dubbo 2011 @@ -43,9 +43,9 @@ - https://github.com/apache/incubator-dubbo - scm:git:https://github.com/apache/incubator-dubbo.git - scm:git:https://github.com/apache/incubator-dubbo.git + https://github.com/apache/dubbo + scm:git:https://github.com/apache/dubbo.git + scm:git:https://github.com/apache/dubbo.git HEAD @@ -84,7 +84,7 @@ Github Issues - https://github.com/apache/incubator-dubbo/issues + https://github.com/apache/dubbo/issues diff --git a/dubbo-distribution/pom.xml b/dubbo-distribution/pom.xml index 1ab955cc3e9..41cef658d21 100644 --- a/dubbo-distribution/pom.xml +++ b/dubbo-distribution/pom.xml @@ -46,7 +46,7 @@ release - apache-dubbo-incubating-${project.version} + apache-dubbo-${project.version} maven-assembly-plugin diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistryTest.java b/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistryTest.java index c2dd23129d6..b645408bd5b 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistryTest.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistryTest.java @@ -127,7 +127,7 @@ public void testLookup() { @Test /* This UT is unstable, consider remove it later. - @see https://github.com/apache/incubator-dubbo/issues/1787 + @see https://github.com/apache/dubbo/issues/1787 */ public void testStatusChecker() { RegistryStatusChecker registryStatusChecker = new RegistryStatusChecker(); diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java index 8f5001754fa..4c055b48f38 100644 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java +++ b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java @@ -279,7 +279,7 @@ public void unwatch() { try { /** - * issue : https://github.com/apache/incubator-dubbo/issues/4115 + * issue : https://github.com/apache/dubbo/issues/4115 * * When the network is reconnected, the listener is empty * and the data cannot be received. diff --git a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java b/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java index 7d621913928..5b548ae0722 100644 --- a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java +++ b/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java @@ -135,7 +135,7 @@ public RemoteInvocation createRemoteInvocation(MethodInvocation methodInvocation /* The customized 'com.alibaba.dubbo.rpc.protocol.http.HttpRemoteInvocation' was firstly introduced in v2.6.3. The main purpose is to support transformation of attachments in HttpProtocol, see - https://github.com/apache/incubator-dubbo/pull/1827. To guarantee interoperability with lower + https://github.com/apache/dubbo/pull/1827. To guarantee interoperability with lower versions, we need to check if the provider is v2.6.3 or higher before sending customized HttpRemoteInvocation. */ diff --git a/dubbo-rpc/dubbo-rpc-xml/pom.xml b/dubbo-rpc/dubbo-rpc-xml/pom.xml index 8caed152b82..9afede914ba 100644 --- a/dubbo-rpc/dubbo-rpc-xml/pom.xml +++ b/dubbo-rpc/dubbo-rpc-xml/pom.xml @@ -35,7 +35,7 @@ UTF-8 false - https://github.com/apache/incubator-dubbo + https://github.com/apache/dubbo diff --git a/pom.xml b/pom.xml index e9a1661e033..6ceb8fb295c 100644 --- a/pom.xml +++ b/pom.xml @@ -31,7 +31,7 @@ ${project.artifactId} The parent project of dubbo - https://github.com/apache/incubator-dubbo + https://github.com/apache/dubbo 2011 @@ -42,9 +42,9 @@ - https://github.com/apache/incubator-dubbo - scm:git:https://github.com/apache/incubator-dubbo.git - scm:git:https://github.com/apache/incubator-dubbo.git + https://github.com/apache/dubbo + scm:git:https://github.com/apache/dubbo.git + scm:git:https://github.com/apache/dubbo.git HEAD @@ -83,7 +83,7 @@ Github Issues - https://github.com/apache/incubator-dubbo/issues + https://github.com/apache/dubbo/issues From cf1a09d3c381607585def4a7bb213496efea655b Mon Sep 17 00:00:00 2001 From: Huang YunKun Date: Sat, 25 May 2019 15:22:57 +0800 Subject: [PATCH 091/115] [CI] add snapshot deploy check (#4157) --- pom.xml | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/pom.xml b/pom.xml index 6ceb8fb295c..16afc2714ff 100644 --- a/pom.xml +++ b/pom.xml @@ -120,6 +120,7 @@ 3.0.0 0.8.2 1.1.0 + 3.0.0-M2 0.12 true @@ -196,6 +197,35 @@ + + snapshot-ci-deploy + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${maven_enforce_version} + + + enforce-no-releases + + enforce + + + + + No Releases Allowed! + false + + + true + + + + + + + javadoc-lint From 9168543d855f287720fcd257f68ee0acccb95170 Mon Sep 17 00:00:00 2001 From: wavesZh <30332053+wavesZh@users.noreply.github.com> Date: Sun, 26 May 2019 20:29:31 +0800 Subject: [PATCH 092/115] change logger name (#4150) --- .../dubbo/remoting/transport/netty4/NettyClientHandler.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClientHandler.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClientHandler.java index c7077086dbb..8827a0bb5b7 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClientHandler.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClientHandler.java @@ -35,7 +35,7 @@ */ @io.netty.channel.ChannelHandler.Sharable public class NettyClientHandler extends ChannelDuplexHandler { - private static final Logger logger = LoggerFactory.getLogger(NettyClient.class); + private static final Logger logger = LoggerFactory.getLogger(NettyClientHandler.class); private final URL url; From 9559c4ef8a629f73c8bed620006c9d5a3b924cbc Mon Sep 17 00:00:00 2001 From: Mercy Ma Date: Mon, 27 May 2019 10:31:43 +0800 Subject: [PATCH 093/115] Unify the bean name convention of ServiceBean and ReferenceBean (#4135) fixes #4071, #3709 --- .../annotation/AnnotationBeanNameBuilder.java | 142 ------------------ .../ReferenceAnnotationBeanPostProcessor.java | 10 +- .../ServiceAnnotationBeanPostProcessor.java | 14 +- .../annotation/ServiceBeanNameBuilder.java | 112 ++++++++++++++ ...t.java => ServiceBeanNameBuilderTest.java} | 29 ++-- dubbo-registry/dubbo-registry-nacos/pom.xml | 43 ------ .../DemoServiceConsumerBootstrap.java | 4 - .../dubbo/demo/service/DemoService.java | 8 +- .../test/resources/provider-config.properties | 3 - 9 files changed, 135 insertions(+), 230 deletions(-) delete mode 100644 dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationBeanNameBuilder.java create mode 100644 dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilder.java rename dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/{AnnotationBeanNameBuilderTest.java => ServiceBeanNameBuilderTest.java} (67%) diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationBeanNameBuilder.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationBeanNameBuilder.java deleted file mode 100644 index 6e18e2a3471..00000000000 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationBeanNameBuilder.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.config.spring.beans.factory.annotation; - -import org.apache.dubbo.common.constants.CommonConstants; -import org.apache.dubbo.config.annotation.Reference; -import org.apache.dubbo.config.annotation.Service; -import org.apache.dubbo.registry.Registry; - -import org.springframework.core.env.Environment; - -import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_PROTOCOL; -import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY; -import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; -import static org.apache.dubbo.config.spring.util.AnnotationUtils.resolveInterfaceName; -import static org.springframework.util.StringUtils.arrayToCommaDelimitedString; -import static org.springframework.util.StringUtils.hasText; - -/** - * The Bean Name Builder for the annotations {@link Service} and {@link Reference} - *

    - * The naming rule is consistent with the the implementation {@link Registry} that is based on the service-name aware - * infrastructure, e.g Spring Cloud, Cloud Native and so on. - *

    - * The pattern of bean name : ${category}:${protocol}:${serviceInterface}:${version}:${group}. - *

    - * ${version} and ${group} are optional. - * - * @since 2.6.6 - */ -class AnnotationBeanNameBuilder { - - private static final String SEPARATOR = ":"; - - // Required properties - - private final String category; - - private final String protocol; - - private final String interfaceClassName; - - // Optional properties - - private String version; - - private String group; - - private Environment environment; - - private AnnotationBeanNameBuilder(String category, String protocol, String interfaceClassName) { - this.category = category; - this.protocol = protocol; - this.interfaceClassName = interfaceClassName; - } - - private AnnotationBeanNameBuilder(Service service, Class interfaceClass) { - this(PROVIDERS_CATEGORY, resolveProtocol(service.protocol()), resolveInterfaceName(service, interfaceClass)); - this.group(service.group()); - this.version(service.version()); - } - - private AnnotationBeanNameBuilder(Reference reference, Class interfaceClass) { - this(CONSUMERS_CATEGORY, resolveProtocol(reference.protocol()), resolveInterfaceName(reference, interfaceClass)); - this.group(reference.group()); - this.version(reference.version()); - } - - public static AnnotationBeanNameBuilder create(Service service, Class interfaceClass) { - return new AnnotationBeanNameBuilder(service, interfaceClass); - } - - public static AnnotationBeanNameBuilder create(Reference reference, Class interfaceClass) { - return new AnnotationBeanNameBuilder(reference, interfaceClass); - } - - private static void append(StringBuilder builder, String value) { - if (hasText(value)) { - builder.append(SEPARATOR).append(value); - } - } - - public AnnotationBeanNameBuilder group(String group) { - this.group = group; - return this; - } - - public AnnotationBeanNameBuilder version(String version) { - this.version = version; - return this; - } - - public AnnotationBeanNameBuilder environment(Environment environment) { - this.environment = environment; - return this; - } - - /** - * Resolve the protocol - * - * @param protocols one or more protocols - * @return if protocols == null, it will return - * {@link CommonConstants#DEFAULT_PROTOCOL "dubbo"} as the default protocol - * @see CommonConstants#DEFAULT_PROTOCOL - */ - private static String resolveProtocol(String... protocols) { - String protocol = arrayToCommaDelimitedString(protocols); - return hasText(protocol) ? protocol : DEFAULT_PROTOCOL; - } - - /** - * Build bean name while resolve the placeholders if possible. - * - * @return pattern : ${category}:${protocol}:${serviceInterface}:${version}:${group} - */ - public String build() { - // Append the required properties - StringBuilder beanNameBuilder = new StringBuilder(category); - append(beanNameBuilder, protocol); - append(beanNameBuilder, interfaceClassName); - // Append the optional properties - append(beanNameBuilder, version); - append(beanNameBuilder, group); - String beanName = beanNameBuilder.toString(); - // Resolve placeholders - return environment != null ? environment.resolvePlaceholders(beanName) : beanName; - } -} diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java index e0ba649ce34..f7cc7b797e6 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java @@ -41,6 +41,8 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import static org.apache.dubbo.config.spring.beans.factory.annotation.ServiceBeanNameBuilder.create; + /** * {@link org.springframework.beans.factory.config.BeanPostProcessor} implementation * that Consumer service {@link Reference} annotated fields @@ -178,16 +180,14 @@ protected String buildInjectedObjectCacheKey(Reference reference, Object bean, S return buildReferencedBeanName(reference, injectedType) + "#source=" + (injectedElement.getMember()) + - "#attributes=" + AnnotationUtils.getAttributes(reference,getEnvironment(),true); + "#attributes=" + AnnotationUtils.getAttributes(reference, getEnvironment(), true); } private String buildReferencedBeanName(Reference reference, Class injectedType) { - AnnotationBeanNameBuilder builder = AnnotationBeanNameBuilder.create(reference, injectedType); - - builder.environment(getEnvironment()); + ServiceBeanNameBuilder serviceBeanNameBuilder = create(reference, injectedType, getEnvironment()); - return getEnvironment().resolvePlaceholders(builder.build()); + return serviceBeanNameBuilder.build(); } private ReferenceBean buildReferenceBeanIfAbsent(String referencedBeanName, Reference reference, diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java index e167c074710..2dec2d32b0a 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java @@ -60,6 +60,7 @@ import java.util.Map; import java.util.Set; +import static org.apache.dubbo.config.spring.beans.factory.annotation.ServiceBeanNameBuilder.create; import static org.apache.dubbo.config.spring.util.ObjectUtils.of; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; import static org.springframework.context.annotation.AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR; @@ -259,7 +260,7 @@ private void registerServiceBean(BeanDefinitionHolder beanDefinitionHolder, Bean buildServiceBeanDefinition(service, interfaceClass, annotatedServiceBeanName); // ServiceBean Bean name - String beanName = generateServiceBeanName(service, interfaceClass, annotatedServiceBeanName); + String beanName = generateServiceBeanName(service, interfaceClass); if (scanner.checkCandidate(beanName, serviceBeanDefinition)) { // check duplicated candidate bean registry.registerBeanDefinition(beanName, serviceBeanDefinition); @@ -285,19 +286,14 @@ private void registerServiceBean(BeanDefinitionHolder beanDefinitionHolder, Bean * Generates the bean name of {@link ServiceBean} * * @param service - * @param interfaceClass the class of interface annotated {@link Service} - * @param annotatedServiceBeanName the bean name of annotated {@link Service} + * @param interfaceClass the class of interface annotated {@link Service} * @return ServiceBean@interfaceClassName#annotatedServiceBeanName * @since 2.5.9 */ - private String generateServiceBeanName(Service service, Class interfaceClass, String annotatedServiceBeanName) { - - AnnotationBeanNameBuilder builder = AnnotationBeanNameBuilder.create(service, interfaceClass); - - builder.environment(environment); + private String generateServiceBeanName(Service service, Class interfaceClass) { + ServiceBeanNameBuilder builder = create(service, interfaceClass, environment); return builder.build(); - } private Class resolveServiceInterfaceClass(Class annotatedServiceBeanClass, Service service) { diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilder.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilder.java new file mode 100644 index 00000000000..5d272515ab3 --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilder.java @@ -0,0 +1,112 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.config.spring.beans.factory.annotation; + +import org.apache.dubbo.config.annotation.Reference; +import org.apache.dubbo.config.annotation.Service; +import org.apache.dubbo.config.spring.ReferenceBean; +import org.apache.dubbo.config.spring.ServiceBean; + +import org.springframework.core.env.Environment; +import org.springframework.util.StringUtils; + +import static org.apache.dubbo.config.spring.util.AnnotationUtils.resolveInterfaceName; + +/** + * Dubbo {@link Service @Service} Bean Builder + * + * @see Service + * @see Reference + * @see ServiceBean + * @see ReferenceBean + * @since 2.6.5 + */ +public class ServiceBeanNameBuilder { + + private static final String SEPARATOR = ":"; + + private final String interfaceClassName; + + private final Environment environment; + + // Optional + private String version; + + private String group; + + private ServiceBeanNameBuilder(String interfaceClassName, Environment environment) { + this.interfaceClassName = interfaceClassName; + this.environment = environment; + } + + private ServiceBeanNameBuilder(Class interfaceClass, Environment environment) { + this(interfaceClass.getName(), environment); + } + + private ServiceBeanNameBuilder(Service service, Class interfaceClass, Environment environment) { + this(resolveInterfaceName(service, interfaceClass), environment); + this.group(service.group()); + this.version(service.version()); + } + + private ServiceBeanNameBuilder(Reference reference, Class interfaceClass, Environment environment) { + this(resolveInterfaceName(reference, interfaceClass), environment); + this.group(reference.group()); + this.version(reference.version()); + } + + public static ServiceBeanNameBuilder create(Class interfaceClass, Environment environment) { + return new ServiceBeanNameBuilder(interfaceClass, environment); + } + + public static ServiceBeanNameBuilder create(Service service, Class interfaceClass, Environment environment) { + return new ServiceBeanNameBuilder(service, interfaceClass, environment); + } + + public static ServiceBeanNameBuilder create(Reference reference, Class interfaceClass, Environment environment) { + return new ServiceBeanNameBuilder(reference, interfaceClass, environment); + } + + private static void append(StringBuilder builder, String value) { + if (StringUtils.hasText(value)) { + builder.append(value).append(SEPARATOR); + } + } + + public ServiceBeanNameBuilder group(String group) { + this.group = group; + return this; + } + + public ServiceBeanNameBuilder version(String version) { + this.version = version; + return this; + } + + public String build() { + StringBuilder beanNameBuilder = new StringBuilder("ServiceBean").append(SEPARATOR); + // Required + append(beanNameBuilder, interfaceClassName); + // Optional + append(beanNameBuilder, version); + append(beanNameBuilder, group); + // Build and remove last ":" + String rawBeanName = beanNameBuilder.substring(0, beanNameBuilder.length() - 1); + // Resolve placeholders + return environment.resolvePlaceholders(rawBeanName); + } +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationBeanNameBuilderTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilderTest.java similarity index 67% rename from dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationBeanNameBuilderTest.java rename to dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilderTest.java index 2e79109ab33..747fc1e2693 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationBeanNameBuilderTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilderTest.java @@ -27,18 +27,18 @@ import org.springframework.mock.env.MockEnvironment; import org.springframework.util.ReflectionUtils; -import static org.apache.dubbo.config.spring.beans.factory.annotation.AnnotationBeanNameBuilderTest.GROUP; -import static org.apache.dubbo.config.spring.beans.factory.annotation.AnnotationBeanNameBuilderTest.VERSION; +import static org.apache.dubbo.config.spring.beans.factory.annotation.ServiceBeanNameBuilderTest.GROUP; +import static org.apache.dubbo.config.spring.beans.factory.annotation.ServiceBeanNameBuilderTest.VERSION; /** - * {@link AnnotationBeanNameBuilder} Test + * {@link ServiceBeanNameBuilder} Test * - * @see AnnotationBeanNameBuilder + * @see ServiceBeanNameBuilder * @since 2.6.6 */ @Service(interfaceClass = DemoService.class, group = GROUP, version = VERSION, application = "application", module = "module", registry = {"1", "2", "3"}) -public class AnnotationBeanNameBuilderTest { +public class ServiceBeanNameBuilderTest { @Reference(interfaceClass = DemoService.class, group = "DUBBO", version = "${dubbo.version}", application = "application", module = "module", registry = {"1", "2", "3"}) @@ -58,25 +58,20 @@ public void prepare() { @Test public void testServiceAnnotation() { - Service service = AnnotationUtils.getAnnotation(AnnotationBeanNameBuilderTest.class, Service.class); - AnnotationBeanNameBuilder builder = AnnotationBeanNameBuilder.create(service, INTERFACE_CLASS); - Assert.assertEquals("providers:dubbo:org.apache.dubbo.config.spring.api.DemoService:1.0.0:DUBBO", + Service service = AnnotationUtils.getAnnotation(ServiceBeanNameBuilderTest.class, Service.class); + ServiceBeanNameBuilder builder = ServiceBeanNameBuilder.create(service, INTERFACE_CLASS, environment); + Assert.assertEquals("ServiceBean:org.apache.dubbo.config.spring.api.DemoService:1.0.0:DUBBO", builder.build()); - builder.environment(environment); - Assert.assertEquals("providers:dubbo:org.apache.dubbo.config.spring.api.DemoService:1.0.0:DUBBO", + Assert.assertEquals("ServiceBean:org.apache.dubbo.config.spring.api.DemoService:1.0.0:DUBBO", builder.build()); } @Test public void testReferenceAnnotation() { - Reference reference = AnnotationUtils.getAnnotation(ReflectionUtils.findField(AnnotationBeanNameBuilderTest.class, "INTERFACE_CLASS"), Reference.class); - AnnotationBeanNameBuilder builder = AnnotationBeanNameBuilder.create(reference, INTERFACE_CLASS); - Assert.assertEquals("consumers:dubbo:org.apache.dubbo.config.spring.api.DemoService:${dubbo.version}:DUBBO", - builder.build()); - - builder.environment(environment); - Assert.assertEquals("consumers:dubbo:org.apache.dubbo.config.spring.api.DemoService:1.0.0:DUBBO", + Reference reference = AnnotationUtils.getAnnotation(ReflectionUtils.findField(ServiceBeanNameBuilderTest.class, "INTERFACE_CLASS"), Reference.class); + ServiceBeanNameBuilder builder = ServiceBeanNameBuilder.create(reference, INTERFACE_CLASS, environment); + Assert.assertEquals("ServiceBean:org.apache.dubbo.config.spring.api.DemoService:1.0.0:DUBBO", builder.build()); } diff --git a/dubbo-registry/dubbo-registry-nacos/pom.xml b/dubbo-registry/dubbo-registry-nacos/pom.xml index b8c952d267b..675901e2ec3 100644 --- a/dubbo-registry/dubbo-registry-nacos/pom.xml +++ b/dubbo-registry/dubbo-registry-nacos/pom.xml @@ -92,49 +92,6 @@ - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - test - - - - org.jboss.resteasy - resteasy-jaxrs - test - - - - org.jboss.resteasy - resteasy-client - test - - - - org.jboss.resteasy - resteasy-netty4 - test - - - - javax.validation - validation-api - test - - - - org.jboss.resteasy - resteasy-jackson-provider - test - - - - org.jboss.resteasy - resteasy-jaxb-provider - test - - org.springframework spring-test diff --git a/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/demo/consumer/DemoServiceConsumerBootstrap.java b/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/demo/consumer/DemoServiceConsumerBootstrap.java index b411d4a80f0..f11bdb5df3f 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/demo/consumer/DemoServiceConsumerBootstrap.java +++ b/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/demo/consumer/DemoServiceConsumerBootstrap.java @@ -37,14 +37,10 @@ public class DemoServiceConsumerBootstrap { @Reference(version = "${demo.service.version}") private DemoService demoService; - @Reference(version = "${demo.service.version}", protocol = "rest") - private DemoService restDemoService; - @PostConstruct public void init() throws InterruptedException { for (int j = 0; j < 10; j++) { System.out.println(demoService.sayName("小马哥(mercyblitz)")); - System.out.println(restDemoService.sayName("小马哥(mercyblitz)")); } Thread.sleep(TimeUnit.SECONDS.toMillis(5)); } diff --git a/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/demo/service/DemoService.java b/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/demo/service/DemoService.java index 0c808779311..77ac1b60e21 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/demo/service/DemoService.java +++ b/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/demo/service/DemoService.java @@ -16,19 +16,13 @@ */ package org.apache.dubbo.demo.service; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.QueryParam; - /** * DemoService * * @since 2.6.5 */ -@Path("/demo-service") public interface DemoService { - @GET - String sayName(@QueryParam("name") String name); + String sayName(String name); } \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-nacos/src/test/resources/provider-config.properties b/dubbo-registry/dubbo-registry-nacos/src/test/resources/provider-config.properties index e2dd335b0ed..7e2046b5c40 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/test/resources/provider-config.properties +++ b/dubbo-registry/dubbo-registry-nacos/src/test/resources/provider-config.properties @@ -6,9 +6,6 @@ dubbo.registry.address=127.0.0.1:8848 ## Exports multiple protocols ### Dubbo Protocol using random port dubbo.protocols.dubbo.port=-1 -### REST protocol -dubbo.protocols.rest.port=9090 -dubbo.protocols.rest.server=netty # Provider @Service info demo.service.version=1.0.0 demo.service.name=demoService \ No newline at end of file From 18eb69e96475c05be9bb8b5d7a0c7bcdafa97405 Mon Sep 17 00:00:00 2001 From: "ken.lj" Date: Mon, 27 May 2019 16:42:10 +0800 Subject: [PATCH 094/115] Solve compile problem in java11 (#4172) --- .../rpc/cluster/router/condition/ConditionRouterTest.java | 5 +++++ dubbo-registry/dubbo-registry-nacos/pom.xml | 6 ++++++ 2 files changed, 11 insertions(+) diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java index bf378f0c214..76ffad19cae 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java @@ -98,6 +98,9 @@ public void testRoute_matchFilter() { invokers.add(invoker2); invokers.add(invoker3); + System.err.println("The localhost address: " + invoker2.getUrl().getAddress()); + System.err.println(invoker3.getUrl().getAddress()); + Router router1 = new ConditionRouterFactory().getRouter(getRouteUrl( "host = " + NetUtils.getLocalHost() + " => " + " host = 10.20.3.3").addParameter(FORCE_KEY, String.valueOf(true))); @@ -117,6 +120,8 @@ public void testRoute_matchFilter() { "host = " + NetUtils.getLocalHost() + " => " + " serialization = fastjson").addParameter( FORCE_KEY, String.valueOf(true))); + + List> filteredInvokers1 = router1.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation()); List> filteredInvokers2 = router2.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation()); List> filteredInvokers3 = router3.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation()); diff --git a/dubbo-registry/dubbo-registry-nacos/pom.xml b/dubbo-registry/dubbo-registry-nacos/pom.xml index 675901e2ec3..de374651b51 100644 --- a/dubbo-registry/dubbo-registry-nacos/pom.xml +++ b/dubbo-registry/dubbo-registry-nacos/pom.xml @@ -98,5 +98,11 @@ test + + javax.annotation + javax.annotation-api + 1.3.1 + + From 3dd261a4362332533dbc5fcac12151c8e334c362 Mon Sep 17 00:00:00 2001 From: Huxing Zhang Date: Mon, 27 May 2019 17:32:36 +0800 Subject: [PATCH 095/115] [Dubbo-4147] restore the metadata store key change (#4170) --- .../dubbo/metadata/identifier/MetadataIdentifier.java | 4 ++-- .../dubbo/metadata/identifier/MetadataIdentifierTest.java | 6 ++---- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/identifier/MetadataIdentifier.java b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/identifier/MetadataIdentifier.java index 3b20bc7a373..f9b7e4c35f3 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/identifier/MetadataIdentifier.java +++ b/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/identifier/MetadataIdentifier.java @@ -61,9 +61,9 @@ public MetadataIdentifier(URL url) { public String getUniqueKey(KeyTypeEnum keyType) { if (keyType == KeyTypeEnum.PATH) { - return getFilePathKey() + PATH_SEPARATOR + DEFAULT_PATH_TAG; + return getFilePathKey(); } - return getIdentifierKey() + META_DATA_STORE_TAG; + return getIdentifierKey(); } public String getIdentifierKey() { diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/identifier/MetadataIdentifierTest.java b/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/identifier/MetadataIdentifierTest.java index cdb089b83eb..2467571ec29 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/identifier/MetadataIdentifierTest.java +++ b/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/identifier/MetadataIdentifierTest.java @@ -35,17 +35,15 @@ public void testGetUniqueKey() { String group = null; String application = "vic.zk.md"; MetadataIdentifier providerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE, application); - System.out.println(providerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.PATH)); Assertions.assertEquals(providerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.PATH), "metadata" + PATH_SEPARATOR + interfaceName + PATH_SEPARATOR + (version == null ? "" : (version + PATH_SEPARATOR)) + (group == null ? "" : (group + PATH_SEPARATOR)) + PROVIDER_SIDE - + PATH_SEPARATOR + application + PATH_SEPARATOR + "metadata"); - System.out.println(providerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY)); + + PATH_SEPARATOR + application); Assertions.assertEquals(providerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY), interfaceName + MetadataIdentifier.SEPARATOR + (version == null ? "" : version + MetadataIdentifier.SEPARATOR) + (group == null ? "" : group + MetadataIdentifier.SEPARATOR) - + PROVIDER_SIDE + MetadataIdentifier.SEPARATOR + application + META_DATA_STORE_TAG); + + PROVIDER_SIDE + MetadataIdentifier.SEPARATOR + application); } } From 28bea9c1871f65ce98a47bff9b7dd7afa710e338 Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Tue, 28 May 2019 13:48:50 +0800 Subject: [PATCH 096/115] [DUBBO-3137]: get rid of ConfigConstants, RpcConstatns, RemotingConstants (#4138) * [DUBBO-3137]: get rid of ConfigConstants, RpcConstatns, RemotingConstants * fix compilation error * fix compilation issue * let compatible constants to reference all constants * use static imports --- .../router/condition/ConditionRouter.java | 2 +- .../rpc/cluster/support/ClusterUtils.java | 2 +- .../cluster/directory/MockDirInvocation.java | 2 +- .../rpc/cluster/support/ClusterUtilsTest.java | 4 +- .../java/org/apache/dubbo/common/URL.java | 8 +- .../common/config/ConfigurationUtils.java | 4 +- .../common/constants/CommonConstants.java | 10 ++ ...ConfigConstants.java => QosConstants.java} | 22 +--- .../common/constants/RemotingConstants.java | 7 -- .../dubbo/common/constants/RpcConstants.java | 103 ------------------ .../apache/dubbo/common/utils/NetUtils.java | 2 +- .../apache/dubbo/common/utils/UrlUtils.java | 23 +--- .../common/config/ConfigurationUtilsTest.java | 2 +- .../com/alibaba/dubbo/common/Constants.java | 21 +++- .../alibaba/dubbo/common/utils/UrlUtils.java | 4 +- .../dubbo/config/ApplicationConfigTest.java | 4 +- .../dubbo/config/RegistryConfigTest.java | 2 +- .../apache/dubbo/filter/LegacyInvocation.java | 2 +- .../apache/dubbo/service/MockInvocation.java | 2 +- .../dubbo/config/AbstractInterfaceConfig.java | 10 +- .../dubbo/config/ApplicationConfig.java | 8 +- .../apache/dubbo/config/ProtocolConfig.java | 6 +- .../apache/dubbo/config/ReferenceConfig.java | 2 +- .../apache/dubbo/config/RegistryConfig.java | 6 +- .../apache/dubbo/config/ServiceConfig.java | 2 +- .../dubbo/config/annotation/Reference.java | 3 +- .../dubbo/config/annotation/Service.java | 5 +- .../config/AbstractInterfaceConfigTest.java | 4 +- .../dubbo/config/ApplicationConfigTest.java | 4 +- .../dubbo/config/RegistryConfigTest.java | 2 +- .../dubbo/config/ServiceConfigTest.java | 2 +- .../config/spring/SimpleRegistryExporter.java | 4 +- .../store/redis/RedisMetadataReport.java | 2 +- .../apache/dubbo/monitor/MonitorService.java | 6 +- .../dubbo/monitor/support/MonitorFilter.java | 4 +- .../monitor/dubbo/DubboMonitorFactory.java | 2 +- .../dubbo/monitor/dubbo/DubboMonitorTest.java | 2 +- .../dubbo/monitor/dubbo/StatisticsTest.java | 2 +- .../qos/protocol/QosProtocolWrapper.java | 6 +- .../qos/protocol/QosProtocolWrapperTest.java | 6 +- .../integration/RegistryDirectory.java | 2 +- .../integration/RegistryProtocol.java | 12 +- .../registry/dubbo/DubboRegistryFactory.java | 2 +- .../registry/dubbo/RegistryDirectoryTest.java | 2 +- .../dubbo/SimpleRegistryExporter.java | 4 +- .../registry/redis/RedisRegistryTest.java | 2 +- .../org/apache/dubbo/remoting/Constants.java | 5 + .../support/header/HeaderExchangeClient.java | 4 +- .../support/header/HeaderExchangeServer.java | 14 +-- .../support/header/HeartbeatHandler.java | 4 +- .../apache/dubbo/remoting/utils/UrlUtils.java | 36 ++++++ .../remoting/PerformanceClientFixedTest.java | 2 +- .../dubbo/remoting/PerformanceClientTest.java | 2 +- .../support/header/HeartBeatTaskTest.java | 2 +- .../support/header/HeartbeatHandlerTest.java | 11 +- .../transport/netty/ClientReconnectTest.java | 4 +- .../netty/NettyClientToServerTest.java | 8 +- .../transport/netty4/NettyClient.java | 2 +- .../transport/netty4/NettyServer.java | 2 +- .../transport/netty4/ClientReconnectTest.java | 4 +- .../netty4/NettyClientToServerTest.java | 8 +- .../java/org/apache/dubbo/rpc/Constants.java | 18 +++ .../org/apache/dubbo/rpc/RpcConstants.java | 6 +- .../dubbo/rpc/filter/ContextFilter.java | 2 +- .../dubbo/rpc/filter/GenericFilter.java | 4 +- .../dubbo/rpc/filter/GenericImplFilter.java | 4 +- .../dubbo/rpc/model/ConsumerMethodModel.java | 2 +- .../apache/dubbo/rpc/support/RpcUtils.java | 4 +- .../dubbo/rpc/filter/GenericFilterTest.java | 2 +- .../rpc/filter/GenericImplFilterTest.java | 2 +- .../dubbo/rpc/support/MockInvocation.java | 2 +- .../protocol/dubbo/CallbackServiceCodec.java | 4 +- .../dubbo/DecodeableRpcInvocation.java | 2 +- .../dubbo/rpc/protocol/dubbo/DubboCodec.java | 2 +- .../rpc/protocol/dubbo/DubboCountCodec.java | 4 +- .../rpc/protocol/dubbo/DubboProtocol.java | 6 +- .../protocol/dubbo/filter/FutureFilter.java | 2 +- .../dubbo/DubboInvokerAvilableTest.java | 2 +- .../protocol/dubbo/ExplicitCallbackTest.java | 4 +- .../ReferenceCountExchangeClientTest.java | 4 +- .../dubbo/rpc/protocol/http/HttpProtocol.java | 2 +- .../dubbo/rpc/protocol/rest/RestProtocol.java | 2 +- .../dubbo/rpc/protocol/rmi/RmiProtocol.java | 2 +- .../rpc/protocol/thrift/ThriftProtocol.java | 2 +- 84 files changed, 234 insertions(+), 296 deletions(-) rename dubbo-common/src/main/java/org/apache/dubbo/common/constants/{ConfigConstants.java => QosConstants.java} (67%) delete mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/constants/RpcConstants.java create mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/utils/UrlUtils.java diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java index 5fe82025460..87e9b25a001 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouter.java @@ -47,7 +47,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.HOST_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.HOST_KEY; /** * ConditionRouter diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java index ffea52f0cc7..7a2894b7b12 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java @@ -38,7 +38,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.remoting.Constants.DUBBO_VERSION_KEY; import static org.apache.dubbo.rpc.Constants.INVOKER_LISTENER_KEY; import static org.apache.dubbo.rpc.Constants.REFERENCE_FILTER_KEY; diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java index 5245a2cb69d..cc99a875982 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java @@ -26,7 +26,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.remoting.Constants.DUBBO_VERSION_KEY; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ClusterUtilsTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ClusterUtilsTest.java index 5cdc25f30b9..871e075bbe6 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ClusterUtilsTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ClusterUtilsTest.java @@ -32,8 +32,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; -import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL; +import static org.apache.dubbo.remoting.Constants.DUBBO_VERSION_KEY; public class ClusterUtilsTest { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java b/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java index b67b917b1de..106bebc70c2 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java @@ -40,8 +40,8 @@ import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; -import static org.apache.dubbo.common.constants.ConfigConstants.HOST_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.PORT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.HOST_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PORT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; @@ -52,8 +52,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.PASSWORD_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.USERNAME_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PASSWORD_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.USERNAME_KEY; /** * URL - Uniform Resource Locator (Immutable, ThreadSafe) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java index 29699acea5b..a70f7a7e069 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java @@ -27,8 +27,8 @@ import java.util.Properties; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_SERVER_SHUTDOWN_TIMEOUT; -import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_SECONDS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_SECONDS_KEY; /** * Utilities for manipulating configurations from different sources diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java index 702b8412419..d005ae931ae 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java @@ -159,4 +159,14 @@ public interface CommonConstants { int MAX_PROXY_COUNT = 65535; String MONITOR_KEY = "monitor"; + String CLUSTER_KEY = "cluster"; + String USERNAME_KEY = "username"; + String PASSWORD_KEY = "password"; + String HOST_KEY = "host"; + String PORT_KEY = "port"; + String DUBBO_IP_TO_BIND = "DUBBO_IP_TO_BIND"; + @Deprecated + String SHUTDOWN_WAIT_SECONDS_KEY = "dubbo.service.shutdown.wait.seconds"; + String SHUTDOWN_WAIT_KEY = "dubbo.service.shutdown.wait"; + String DUBBO_PROTOCOL = "dubbo"; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ConfigConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/QosConstants.java similarity index 67% rename from dubbo-common/src/main/java/org/apache/dubbo/common/constants/ConfigConstants.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/constants/QosConstants.java index 9f36406ae9c..6815daedb48 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ConfigConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/QosConstants.java @@ -18,27 +18,9 @@ package org.apache.dubbo.common.constants; /** - * ConfigConstants + * QosConstants */ -public interface ConfigConstants { - String CLUSTER_KEY = "cluster"; - - String USERNAME_KEY = "username"; - - String PASSWORD_KEY = "password"; - - String HOST_KEY = "host"; - - String PORT_KEY = "port"; - - String DUBBO_IP_TO_BIND = "DUBBO_IP_TO_BIND"; - - @Deprecated - String SHUTDOWN_WAIT_SECONDS_KEY = "dubbo.service.shutdown.wait.seconds"; - - String SHUTDOWN_WAIT_KEY = "dubbo.service.shutdown.wait"; - - String DUBBO_PROTOCOL = "dubbo"; +public interface QosConstants { String QOS_ENABLE = "qos-enable"; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RemotingConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RemotingConstants.java index aa4aeb66134..cbdb0bffe16 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RemotingConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RemotingConstants.java @@ -22,12 +22,5 @@ */ public interface RemotingConstants { - String HEARTBEAT_KEY = "heartbeat"; - - int DEFAULT_HEARTBEAT = 60 * 1000; - String BACKUP_KEY = "backup"; - - String HEARTBEAT_TIMEOUT_KEY = "heartbeat.timeout"; - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RpcConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RpcConstants.java deleted file mode 100644 index b40a9c1d58c..00000000000 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RpcConstants.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.dubbo.common.constants; - -/** - * RpcConstants - */ -public interface RpcConstants { - - String INPUT_KEY = "input"; - - String OUTPUT_KEY = "output"; - - /** - * The limit of callback service instances for one interface on every client - */ - String CALLBACK_INSTANCES_LIMIT_KEY = "callbacks"; - - /** - * The default limit number for callback service instances - * - * @see #CALLBACK_INSTANCES_LIMIT_KEY - */ - int DEFAULT_CALLBACK_INSTANCES = 1; - - String DUBBO_VERSION_KEY = "dubbo"; - - String $INVOKE = "$invoke"; - - String $INVOKE_ASYNC = "$invokeAsync"; - - String $ECHO = "$echo"; - - String RETURN_PREFIX = "return "; - - String THROW_PREFIX = "throw"; - - String FAIL_PREFIX = "fail:"; - - String FORCE_PREFIX = "force:"; - - String MERGER_KEY = "merger"; - - String IS_SERVER_KEY = "isserver"; - - String FORCE_USE_TAG = "dubbo.force.tag"; - - String GENERIC_SERIALIZATION_NATIVE_JAVA = "nativejava"; - - String GENERIC_SERIALIZATION_DEFAULT = "true"; - - String GENERIC_SERIALIZATION_BEAN = "bean"; - - String GENERIC_SERIALIZATION_PROTOBUF = "protobuf-json"; - - String TPS_LIMIT_RATE_KEY = "tps"; - - String TPS_LIMIT_INTERVAL_KEY = "tps.interval"; - - long DEFAULT_TPS_LIMIT_INTERVAL = 60 * 1000; - - String AUTO_ATTACH_INVOCATIONID_KEY = "invocationid.autoattach"; - - String STUB_EVENT_KEY = "dubbo.stub.event"; - - boolean DEFAULT_STUB_EVENT = false; - - String STUB_EVENT_METHODS_KEY = "dubbo.stub.event.methods"; - - String PROXY_KEY = "proxy"; - - String EXECUTES_KEY = "executes"; - - String REFERENCE_FILTER_KEY = "reference.filter"; - - String INVOKER_LISTENER_KEY = "invoker.listener"; - - String SERVICE_FILTER_KEY = "service.filter"; - - String EXPORTER_LISTENER_KEY = "exporter.listener"; - - String ACCESS_LOG_KEY = "accesslog"; - - String ACTIVES_KEY = "actives"; - - String CONNECTIONS_KEY = "connections"; - -} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java index 916fdcd185b..6fd1a4e27e7 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java @@ -39,7 +39,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_VALUE; -import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_IP_TO_BIND; +import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_IP_TO_BIND; /** * IP and Port Helper for RPC diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java index 6cac0e0630e..56e73cb75ac 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java @@ -38,11 +38,11 @@ import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.REMOVE_VALUE_PREFIX; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; -import static org.apache.dubbo.common.constants.ConfigConstants.HOST_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.PASSWORD_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.PORT_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.USERNAME_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL; +import static org.apache.dubbo.common.constants.CommonConstants.HOST_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PASSWORD_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PORT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.USERNAME_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; @@ -484,19 +484,6 @@ public static boolean isProvider(URL url) { PROVIDERS_CATEGORY.equals(url.getParameter(CATEGORY_KEY, PROVIDERS_CATEGORY)); } - public static int getHeartbeat(URL url) { - return url.getParameter(RemotingConstants.HEARTBEAT_KEY, RemotingConstants.DEFAULT_HEARTBEAT); - } - - public static int getIdleTimeout(URL url) { - int heartBeat = getHeartbeat(url); - int idleTimeout = url.getParameter(RemotingConstants.HEARTBEAT_TIMEOUT_KEY, heartBeat * 3); - if (idleTimeout < heartBeat * 2) { - throw new IllegalStateException("idleTimeout < heartbeatInterval * 2"); - } - return idleTimeout; - } - /** * Check if the given value matches the given pattern. The pattern supports wildcard "*". * diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/config/ConfigurationUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/config/ConfigurationUtilsTest.java index d741e6d88dc..1c8a549d8ad 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/config/ConfigurationUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/config/ConfigurationUtilsTest.java @@ -21,7 +21,7 @@ import java.util.Map; -import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; /** * diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java index 1b0042bd7eb..7b489a3e2c7 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java @@ -18,13 +18,26 @@ package com.alibaba.dubbo.common; import org.apache.dubbo.common.constants.CommonConstants; -import org.apache.dubbo.common.constants.ConfigConstants; import org.apache.dubbo.common.constants.FilterConstants; +import org.apache.dubbo.common.constants.QosConstants; import org.apache.dubbo.common.constants.RegistryConstants; import org.apache.dubbo.common.constants.RemotingConstants; -import org.apache.dubbo.common.constants.RpcConstants; @Deprecated -public class Constants implements CommonConstants, ConfigConstants, FilterConstants, RegistryConstants, - RemotingConstants, RpcConstants, org.apache.dubbo.rpc.cluster.Constants, org.apache.dubbo.monitor.Constants { +public class Constants implements CommonConstants, + QosConstants, + FilterConstants, + RegistryConstants, + RemotingConstants, + org.apache.dubbo.config.Constants, + org.apache.dubbo.remoting.Constants, + org.apache.dubbo.rpc.cluster.Constants, + org.apache.dubbo.monitor.Constants, + org.apache.dubbo.rpc.Constants, + org.apache.dubbo.rpc.protocol.dubbo.Constants, + org.apache.dubbo.common.serialize.Constants, + org.apache.dubbo.configcenter.Constants, + org.apache.dubbo.metadata.support.Constants, + org.apache.dubbo.rpc.protocol.rest.Constants, + org.apache.dubbo.registry.Constants { } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/utils/UrlUtils.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/utils/UrlUtils.java index c8417610b52..0fa26ef6e14 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/utils/UrlUtils.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/utils/UrlUtils.java @@ -101,10 +101,10 @@ public static boolean isProvider(URL url) { } public static int getHeartbeat(URL url) { - return org.apache.dubbo.common.utils.UrlUtils.getHeartbeat(url.getOriginalURL()); + return org.apache.dubbo.remoting.utils.UrlUtils.getHeartbeat(url.getOriginalURL()); } public static int getIdleTimeout(URL url) { - return org.apache.dubbo.common.utils.UrlUtils.getIdleTimeout(url.getOriginalURL()); + return org.apache.dubbo.remoting.utils.UrlUtils.getIdleTimeout(url.getOriginalURL()); } } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java index 40fb9370f21..2a2d5b14a64 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java @@ -29,8 +29,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DUMP_DIRECTORY; -import static org.apache.dubbo.common.constants.ConfigConstants.ACCEPT_FOREIGN_IP; -import static org.apache.dubbo.common.constants.ConfigConstants.QOS_ENABLE; +import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP; +import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java index 746eee97c92..30452f334ff 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java @@ -24,7 +24,7 @@ import java.util.HashMap; import java.util.Map; -import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvocation.java b/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvocation.java index 509d316dc27..a98f22e6ef5 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvocation.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvocation.java @@ -23,7 +23,7 @@ import java.util.HashMap; import java.util.Map; -import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.remoting.Constants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java b/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java index c088917e51d..08347466760 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java @@ -26,7 +26,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.remoting.Constants.DUBBO_VERSION_KEY; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java index 90577cd786d..b72560897cd 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java @@ -64,22 +64,22 @@ import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.CLUSTER_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY; import static org.apache.dubbo.config.Constants.DUBBO_IP_TO_REGISTRY; -import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; +import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL; import static org.apache.dubbo.config.Constants.LAYER_KEY; import static org.apache.dubbo.config.Constants.LISTENER_KEY; import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY; import static org.apache.dubbo.config.Constants.REGISTRIES_SUFFIX; -import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_SECONDS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_SECONDS_KEY; import static org.apache.dubbo.monitor.Constants.LOGSTAT_PROTOCOL; import static org.apache.dubbo.registry.Constants.REGISTER_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; import static org.apache.dubbo.registry.Constants.SUBSCRIBE_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.remoting.Constants.DUBBO_VERSION_KEY; import static org.apache.dubbo.rpc.Constants.INVOKER_LISTENER_KEY; import static org.apache.dubbo.rpc.Constants.LOCAL_KEY; import static org.apache.dubbo.rpc.Constants.PROXY_KEY; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java index 851be9bcd80..83fc6db2e9a 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java @@ -28,10 +28,10 @@ import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DUMP_DIRECTORY; -import static org.apache.dubbo.common.constants.ConfigConstants.ACCEPT_FOREIGN_IP; -import static org.apache.dubbo.common.constants.ConfigConstants.QOS_ENABLE; -import static org.apache.dubbo.common.constants.ConfigConstants.QOS_PORT; -import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; +import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP; +import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE; +import static org.apache.dubbo.common.constants.QosConstants.QOS_PORT; import static org.apache.dubbo.config.Constants.ARCHITECTURE; import static org.apache.dubbo.config.Constants.DEVELOPMENT_ENVIRONMENT; import static org.apache.dubbo.config.Constants.ENVIRONMENT; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java index 265db331161..c3dcf0c4f91 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ProtocolConfig.java @@ -33,11 +33,11 @@ import java.util.Map; import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; -import static org.apache.dubbo.common.constants.ConfigConstants.HOST_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL; +import static org.apache.dubbo.common.constants.CommonConstants.HOST_KEY; import static org.apache.dubbo.config.Constants.PROTOCOLS_SUFFIX; import static org.apache.dubbo.remoting.Constants.TELNET; -import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.remoting.Constants.DUBBO_VERSION_KEY; /** * ProtocolConfig diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java index bb23381277a..a3c020ceec9 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java @@ -65,7 +65,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SEMICOLON_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.CLUSTER_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY; import static org.apache.dubbo.config.Constants.DUBBO_IP_TO_REGISTRY; import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java index 94d0f2cbe9e..83f56b1fd48 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java @@ -24,10 +24,10 @@ import static org.apache.dubbo.common.constants.CommonConstants.FILE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.PASSWORD_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PASSWORD_KEY; import static org.apache.dubbo.config.Constants.REGISTRIES_SUFFIX; -import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.USERNAME_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.USERNAME_KEY; import static org.apache.dubbo.config.Constants.ZOOKEEPER_PROTOCOL; import static org.apache.dubbo.registry.Constants.EXTRA_KEYS_KEY; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index f95e15e0e55..caee14d07b6 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -71,7 +71,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_IP_TO_BIND; +import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_IP_TO_BIND; import static org.apache.dubbo.config.Constants.DUBBO_IP_TO_REGISTRY; import static org.apache.dubbo.config.Constants.DUBBO_PORT_TO_BIND; import static org.apache.dubbo.config.Constants.DUBBO_PORT_TO_REGISTRY; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java index 3956b9f4955..f5d09d343e6 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Reference.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config.annotation; -import org.apache.dubbo.common.constants.RpcConstants; import org.apache.dubbo.rpc.ExporterListener; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.cluster.Constants; @@ -136,7 +135,7 @@ /** * The callback instance limit peer connection * - * @see RpcConstants#DEFAULT_CALLBACK_INSTANCES + * @see org.apache.dubbo.rpc.Constants#DEFAULT_CALLBACK_INSTANCES */ int callbacks() default 0; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Service.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Service.java index f743386f139..8b13373b963 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Service.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/annotation/Service.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config.annotation; -import org.apache.dubbo.common.constants.RpcConstants; import org.apache.dubbo.rpc.ExporterListener; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.cluster.Constants; @@ -146,9 +145,9 @@ /** * The callback instance limit peer connection * - * @see RpcConstants#DEFAULT_CALLBACK_INSTANCES + * @see org.apache.dubbo.rpc.Constants#DEFAULT_CALLBACK_INSTANCES */ - int callbacks() default RpcConstants.DEFAULT_CALLBACK_INSTANCES; + int callbacks() default org.apache.dubbo.rpc.Constants.DEFAULT_CALLBACK_INSTANCES; /** * Callback method name when connected, default value is empty string diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractInterfaceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractInterfaceConfigTest.java index 355c39e5161..c218892b0cf 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractInterfaceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractInterfaceConfigTest.java @@ -46,8 +46,8 @@ import java.util.List; import java.util.Properties; -import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_SECONDS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_SECONDS_KEY; public class AbstractInterfaceConfigTest { private static File dubboProperties; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java index 64f09ae2661..87fb6211836 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java @@ -26,8 +26,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DUMP_DIRECTORY; -import static org.apache.dubbo.common.constants.ConfigConstants.ACCEPT_FOREIGN_IP; -import static org.apache.dubbo.common.constants.ConfigConstants.QOS_ENABLE; +import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP; +import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java index 9b3e0e75d63..51d91fc601d 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java @@ -24,7 +24,7 @@ import java.util.Map; import static org.apache.dubbo.config.Constants.SHUTDOWN_TIMEOUT_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java index 147648b67fb..ee2fea931d6 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java @@ -49,7 +49,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY; import static org.apache.dubbo.config.Constants.SHUTDOWN_TIMEOUT_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.remoting.Constants.BIND_IP_KEY; import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java index 38f57abc330..85cc968ce5c 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java @@ -29,8 +29,8 @@ import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_STICKY_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; -import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_INSTANCES_LIMIT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL; +import static org.apache.dubbo.rpc.Constants.CALLBACK_INSTANCES_LIMIT_KEY; /** * SimpleRegistryExporter diff --git a/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java b/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java index a9245eb28d8..85e95acbc07 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java +++ b/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java @@ -36,7 +36,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.CLUSTER_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY; import static org.apache.dubbo.metadata.identifier.MetadataIdentifier.META_DATA_STORE_TAG; /** diff --git a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MonitorService.java b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MonitorService.java index 7e606a53b94..1622fff771c 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MonitorService.java +++ b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MonitorService.java @@ -21,8 +21,8 @@ import java.util.List; -import static org.apache.dubbo.common.constants.RpcConstants.INPUT_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.OUTPUT_KEY; +import static org.apache.dubbo.rpc.Constants.INPUT_KEY; +import static org.apache.dubbo.rpc.Constants.OUTPUT_KEY; /** * MonitorService. (SPI, Prototype, ThreadSafe) */ @@ -89,4 +89,4 @@ public interface MonitorService { List lookup(URL query); -} \ No newline at end of file +} diff --git a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java index 8c1f19a2892..2216e273066 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java +++ b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java @@ -46,8 +46,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.monitor.Constants.COUNT_PROTOCOL; import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.INPUT_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.OUTPUT_KEY; +import static org.apache.dubbo.rpc.Constants.INPUT_KEY; +import static org.apache.dubbo.rpc.Constants.OUTPUT_KEY; /** * MonitorFilter. (SPI, Singleton, ThreadSafe) */ diff --git a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java index 0884d10ea28..591296fa447 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java +++ b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java @@ -27,7 +27,7 @@ import org.apache.dubbo.rpc.ProxyFactory; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; +import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL; import static org.apache.dubbo.remoting.Constants.CHECK_KEY; import static org.apache.dubbo.rpc.Constants.REFERENCE_FILTER_KEY; diff --git a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/DubboMonitorTest.java b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/DubboMonitorTest.java index 71354e159ce..c6d910ab6f0 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/DubboMonitorTest.java +++ b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/DubboMonitorTest.java @@ -38,7 +38,7 @@ import java.util.Arrays; import java.util.List; -import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; +import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; diff --git a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/StatisticsTest.java b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/StatisticsTest.java index fb91790e064..d98f9cd514c 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/StatisticsTest.java +++ b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/StatisticsTest.java @@ -23,7 +23,7 @@ import org.hamcrest.MatcherAssert; import org.junit.jupiter.api.Test; -import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; +import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/protocol/QosProtocolWrapper.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/protocol/QosProtocolWrapper.java index 361c5ee92b2..fd824ba1b74 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/protocol/QosProtocolWrapper.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/protocol/QosProtocolWrapper.java @@ -28,9 +28,9 @@ import java.util.concurrent.atomic.AtomicBoolean; -import static org.apache.dubbo.common.constants.ConfigConstants.ACCEPT_FOREIGN_IP; -import static org.apache.dubbo.common.constants.ConfigConstants.QOS_ENABLE; -import static org.apache.dubbo.common.constants.ConfigConstants.QOS_PORT; +import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP; +import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE; +import static org.apache.dubbo.common.constants.QosConstants.QOS_PORT; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/protocol/QosProtocolWrapperTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/protocol/QosProtocolWrapperTest.java index ad310f6d156..12023b62781 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/protocol/QosProtocolWrapperTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/protocol/QosProtocolWrapperTest.java @@ -27,9 +27,9 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import static org.apache.dubbo.common.constants.ConfigConstants.ACCEPT_FOREIGN_IP; -import static org.apache.dubbo.common.constants.ConfigConstants.QOS_ENABLE; -import static org.apache.dubbo.common.constants.ConfigConstants.QOS_PORT; +import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP; +import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE; +import static org.apache.dubbo.common.constants.QosConstants.QOS_PORT; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java index 6dd235a885c..f74931b3291 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java @@ -66,7 +66,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; +import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL; import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.APP_DYNAMIC_CONFIGURATORS_CATEGORY; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java index f55fad4558b..96b060ff44a 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java @@ -67,11 +67,11 @@ import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.ACCEPT_FOREIGN_IP; -import static org.apache.dubbo.common.constants.ConfigConstants.CLUSTER_KEY; +import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP; +import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY; import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.QOS_ENABLE; -import static org.apache.dubbo.common.constants.ConfigConstants.QOS_PORT; +import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE; +import static org.apache.dubbo.common.constants.QosConstants.QOS_PORT; import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY; import static org.apache.dubbo.common.constants.FilterConstants.VALIDATION_KEY; @@ -97,8 +97,8 @@ import static org.apache.dubbo.remoting.Constants.CODEC_KEY; import static org.apache.dubbo.remoting.Constants.EXCHANGER_KEY; import static org.apache.dubbo.remoting.Constants.SERIALIZATION_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.CONNECTIONS_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY; +import static org.apache.dubbo.remoting.Constants.DUBBO_VERSION_KEY; import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY; import static org.apache.dubbo.rpc.Constants.INTERFACES; import static org.apache.dubbo.rpc.Constants.MOCK_KEY; diff --git a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java index 82a80a74ee2..9ddbc283c46 100644 --- a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java +++ b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java @@ -48,7 +48,7 @@ import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; import static org.apache.dubbo.remoting.Constants.CONNECT_TIMEOUT_KEY; import static org.apache.dubbo.remoting.Constants.RECONNECT_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_INSTANCES_LIMIT_KEY; +import static org.apache.dubbo.rpc.Constants.CALLBACK_INSTANCES_LIMIT_KEY; /** * DubboRegistryFactory diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java index 6a2b4e6a2e8..5b9123ff587 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java @@ -68,7 +68,7 @@ import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.ROUTE_PROTOCOL; -import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE; +import static org.apache.dubbo.rpc.Constants.$INVOKE; import static org.apache.dubbo.rpc.Constants.MOCK_KEY; import static org.junit.jupiter.api.Assertions.fail; diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java index 785cf528858..c2b7c67604c 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java @@ -29,8 +29,8 @@ import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_STICKY_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; -import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_INSTANCES_LIMIT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL; +import static org.apache.dubbo.rpc.Constants.CALLBACK_INSTANCES_LIMIT_KEY; /** * SimpleRegistryExporter diff --git a/dubbo-registry/dubbo-registry-redis/src/test/java/org/apache/dubbo/registry/redis/RedisRegistryTest.java b/dubbo-registry/dubbo-registry-redis/src/test/java/org/apache/dubbo/registry/redis/RedisRegistryTest.java index 0cc1c3126a3..1664ec1ba14 100644 --- a/dubbo-registry/dubbo-registry-redis/src/test/java/org/apache/dubbo/registry/redis/RedisRegistryTest.java +++ b/dubbo-registry/dubbo-registry-redis/src/test/java/org/apache/dubbo/registry/redis/RedisRegistryTest.java @@ -121,4 +121,4 @@ public void testAvailableWithBackup() { assertThat(registry.isAvailable(), is(true)); } -} \ No newline at end of file +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Constants.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Constants.java index 592b0d5217d..61a7e798642 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Constants.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Constants.java @@ -129,4 +129,9 @@ public interface Constants { String DEFAULT_PROMPT = "dubbo>"; String TELNET = "telnet"; + String HEARTBEAT_KEY = "heartbeat"; + int DEFAULT_HEARTBEAT = 60 * 1000; + String HEARTBEAT_TIMEOUT_KEY = "heartbeat.timeout"; + String CONNECTIONS_KEY = "connections"; + String DUBBO_VERSION_KEY = "dubbo"; } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java index 72348e927d9..5a010faf52e 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java @@ -33,8 +33,8 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; -import static org.apache.dubbo.common.utils.UrlUtils.getHeartbeat; -import static org.apache.dubbo.common.utils.UrlUtils.getIdleTimeout; +import static org.apache.dubbo.remoting.utils.UrlUtils.getHeartbeat; +import static org.apache.dubbo.remoting.utils.UrlUtils.getIdleTimeout; import static org.apache.dubbo.remoting.Constants.HEARTBEAT_CHECK_TICK; import static org.apache.dubbo.remoting.Constants.LEAST_HEARTBEAT_DURATION; import static org.apache.dubbo.remoting.Constants.TICKS_PER_WHEEL; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java index 0546a7ddccf..c0524ab196a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java @@ -24,7 +24,6 @@ import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.NamedThreadFactory; -import org.apache.dubbo.common.utils.UrlUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Constants; @@ -41,10 +40,11 @@ import java.util.concurrent.atomic.AtomicBoolean; import static java.util.Collections.unmodifiableCollection; - import static org.apache.dubbo.remoting.Constants.HEARTBEAT_CHECK_TICK; import static org.apache.dubbo.remoting.Constants.LEAST_HEARTBEAT_DURATION; import static org.apache.dubbo.remoting.Constants.TICKS_PER_WHEEL; +import static org.apache.dubbo.remoting.utils.UrlUtils.getHeartbeat; +import static org.apache.dubbo.remoting.utils.UrlUtils.getIdleTimeout; /** * ExchangeServerImpl @@ -209,10 +209,10 @@ public ChannelHandler getChannelHandler() { public void reset(URL url) { server.reset(url); try { - int currHeartbeat = UrlUtils.getHeartbeat(getUrl()); - int currIdleTimeout = UrlUtils.getIdleTimeout(getUrl()); - int heartbeat = UrlUtils.getHeartbeat(url); - int idleTimeout = UrlUtils.getIdleTimeout(url); + int currHeartbeat = getHeartbeat(getUrl()); + int currIdleTimeout = getIdleTimeout(getUrl()); + int heartbeat = getHeartbeat(url); + int idleTimeout = getIdleTimeout(url); if (currHeartbeat != heartbeat || currIdleTimeout != idleTimeout) { cancelCloseTask(); startIdleCheckTask(url); @@ -260,7 +260,7 @@ private long calculateLeastDuration(int time) { private void startIdleCheckTask(URL url) { if (!server.canHandleIdle()) { AbstractTimerTask.ChannelProvider cp = () -> unmodifiableCollection(HeaderExchangeServer.this.getChannels()); - int idleTimeout = UrlUtils.getIdleTimeout(url); + int idleTimeout = getIdleTimeout(url); long idleTimeoutTick = calculateLeastDuration(idleTimeout); CloseTimerTask closeTimerTask = new CloseTimerTask(cp, idleTimeoutTick, idleTimeout); this.closeTimerTask = closeTimerTask; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandler.java index 87d912187ea..c8ba14a4ae1 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandler.java @@ -17,11 +17,11 @@ package org.apache.dubbo.remoting.exchange.support.header; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; @@ -69,7 +69,7 @@ public void received(Channel channel, Object message) throws RemotingException { res.setEvent(Response.HEARTBEAT_EVENT); channel.send(res); if (logger.isInfoEnabled()) { - int heartbeat = channel.getUrl().getParameter(RemotingConstants.HEARTBEAT_KEY, 0); + int heartbeat = channel.getUrl().getParameter(Constants.HEARTBEAT_KEY, 0); if (logger.isDebugEnabled()) { logger.debug("Received heartbeat from remote channel " + channel.getRemoteAddress() + ", cause: The channel has no data-transmission exceeds a heartbeat period" diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/utils/UrlUtils.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/utils/UrlUtils.java new file mode 100644 index 00000000000..49f5a621fb4 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/utils/UrlUtils.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.remoting.utils; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.remoting.Constants; + +public class UrlUtils { + public static int getIdleTimeout(URL url) { + int heartBeat = getHeartbeat(url); + int idleTimeout = url.getParameter(Constants.HEARTBEAT_TIMEOUT_KEY, heartBeat * 3); + if (idleTimeout < heartBeat * 2) { + throw new IllegalStateException("idleTimeout < heartbeatInterval * 2"); + } + return idleTimeout; + } + + public static int getHeartbeat(URL url) { + return url.getParameter(Constants.HEARTBEAT_KEY, Constants.DEFAULT_HEARTBEAT); + } +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java index e5b87e19026..93ccc76e515 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java @@ -28,7 +28,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.CONNECTIONS_KEY; +import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY; public class PerformanceClientFixedTest { diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java index 4178358c1c4..f4dfbc2a3e0 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java @@ -34,7 +34,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.CONNECTIONS_KEY; +import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY; /** * PerformanceClientTest diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.java index aaf8f7a0f6c..3249d46f168 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.java @@ -29,7 +29,7 @@ import java.util.List; import java.util.concurrent.TimeUnit; -import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.remoting.Constants.DUBBO_VERSION_KEY; import static org.apache.dubbo.remoting.Constants.HEARTBEAT_CHECK_TICK; public class HeartBeatTaskTest { diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java index 52bed1e0f5e..27c8f718b23 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java @@ -18,7 +18,6 @@ package org.apache.dubbo.remoting.exchange.support.header; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.Channel; @@ -63,16 +62,16 @@ public void after() throws Exception { @Test public void testServerHeartbeat() throws Exception { URL serverURL = URL.valueOf("header://localhost:55555?transporter=netty3"); - serverURL = serverURL.addParameter(RemotingConstants.HEARTBEAT_KEY, 1000); + serverURL = serverURL.addParameter(Constants.HEARTBEAT_KEY, 1000); TestHeartbeatHandler handler = new TestHeartbeatHandler(); server = Exchangers.bind(serverURL, handler); System.out.println("Server bind successfully"); FakeChannelHandlers.setTestingChannelHandlers(); - serverURL = serverURL.removeParameter(RemotingConstants.HEARTBEAT_KEY); + serverURL = serverURL.removeParameter(Constants.HEARTBEAT_KEY); // Let the client not reply to the heartbeat, and turn off automatic reconnect to simulate the client dropped. - serverURL = serverURL.addParameter(RemotingConstants.HEARTBEAT_KEY, 600 * 1000); + serverURL = serverURL.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000); serverURL = serverURL.addParameter(Constants.RECONNECT_KEY, false); client = Exchangers.connect(serverURL); @@ -84,7 +83,7 @@ public void testServerHeartbeat() throws Exception { @Test public void testHeartbeat() throws Exception { URL serverURL = URL.valueOf("header://localhost:55555?transporter=netty3"); - serverURL = serverURL.addParameter(RemotingConstants.HEARTBEAT_KEY, 1000); + serverURL = serverURL.addParameter(Constants.HEARTBEAT_KEY, 1000); TestHeartbeatHandler handler = new TestHeartbeatHandler(); server = Exchangers.bind(serverURL, handler); System.out.println("Server bind successfully"); @@ -106,7 +105,7 @@ public void testClientHeartbeat() throws Exception { System.out.println("Server bind successfully"); FakeChannelHandlers.resetChannelHandlers(); - serverURL = serverURL.addParameter(RemotingConstants.HEARTBEAT_KEY, 1000); + serverURL = serverURL.addParameter(Constants.HEARTBEAT_KEY, 1000); client = Exchangers.connect(serverURL); Thread.sleep(10000); Assertions.assertTrue(handler.connectCount > 0); diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientReconnectTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientReconnectTest.java index 52452126bf5..939cd10b7c0 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientReconnectTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientReconnectTest.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.remoting.transport.netty; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.DubboAppender; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Client; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.Server; import org.apache.dubbo.remoting.exchange.Exchangers; @@ -70,7 +70,7 @@ public void testReconnect() throws RemotingException, InterruptedException { public Client startClient(int port, int heartbeat) throws RemotingException { - final String url = "exchange://127.0.0.1:" + port + "/client.reconnect.test?check=false&client=netty3&" + RemotingConstants.HEARTBEAT_KEY + "=" + heartbeat; + final String url = "exchange://127.0.0.1:" + port + "/client.reconnect.test?check=false&client=netty3&" + Constants.HEARTBEAT_KEY + "=" + heartbeat; return Exchangers.connect(url); } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientToServerTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientToServerTest.java index 060efbe9d1f..4bc62df0b06 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientToServerTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientToServerTest.java @@ -17,7 +17,7 @@ package org.apache.dubbo.remoting.transport.netty; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeServer; @@ -32,15 +32,15 @@ public class NettyClientToServerTest extends ClientToServerTest { protected ExchangeServer newServer(int port, Replier receiver) throws RemotingException { // add heartbeat cycle to avoid unstable ut. URL url = URL.valueOf("exchange://localhost:" + port + "?server=netty3"); - url = url.addParameter(RemotingConstants.HEARTBEAT_KEY, 600 * 1000); + url = url.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000); return Exchangers.bind(url, receiver); } protected ExchangeChannel newClient(int port) throws RemotingException { // add heartbeat cycle to avoid unstable ut. URL url = URL.valueOf("exchange://localhost:" + port + "?client=netty3&timeout=3000"); - url = url.addParameter(RemotingConstants.HEARTBEAT_KEY, 600 * 1000); + url = url.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000); return Exchangers.connect(url); } -} \ No newline at end of file +} diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java index 62574a4da82..13e0c4ef831 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java @@ -22,11 +22,11 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.common.utils.UrlUtils; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.transport.AbstractClient; +import org.apache.dubbo.remoting.utils.UrlUtils; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.PooledByteBufAllocator; diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java index 616fd18a080..515dc002288 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java @@ -21,7 +21,6 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ExecutorUtil; import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.common.utils.UrlUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Constants; @@ -29,6 +28,7 @@ import org.apache.dubbo.remoting.Server; import org.apache.dubbo.remoting.transport.AbstractServer; import org.apache.dubbo.remoting.transport.dispatcher.ChannelHandlers; +import org.apache.dubbo.remoting.utils.UrlUtils; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.PooledByteBufAllocator; diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientReconnectTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientReconnectTest.java index 1768183c3ee..51c4907b361 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientReconnectTest.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientReconnectTest.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.remoting.transport.netty4; -import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.utils.DubboAppender; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Client; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.Server; import org.apache.dubbo.remoting.exchange.Exchangers; @@ -72,7 +72,7 @@ public void testReconnect() throws RemotingException, InterruptedException { public Client startClient(int port, int heartbeat) throws RemotingException { - final String url = "exchange://127.0.0.1:" + port + "/client.reconnect.test?client=netty4&check=false&" + RemotingConstants.HEARTBEAT_KEY + "=" + heartbeat; + final String url = "exchange://127.0.0.1:" + port + "/client.reconnect.test?client=netty4&check=false&" + Constants.HEARTBEAT_KEY + "=" + heartbeat; return Exchangers.connect(url); } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyClientToServerTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyClientToServerTest.java index 04eaef883cc..3147ae89d07 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyClientToServerTest.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyClientToServerTest.java @@ -17,7 +17,7 @@ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; +import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeServer; @@ -32,15 +32,15 @@ public class NettyClientToServerTest extends ClientToServerTest { protected ExchangeServer newServer(int port, Replier receiver) throws RemotingException { // add heartbeat cycle to avoid unstable ut. URL url = URL.valueOf("exchange://localhost:" + port + "?server=netty4"); - url = url.addParameter(RemotingConstants.HEARTBEAT_KEY, 600 * 1000); + url = url.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000); return Exchangers.bind(url, receiver); } protected ExchangeChannel newClient(int port) throws RemotingException { // add heartbeat cycle to avoid unstable ut. URL url = URL.valueOf("exchange://localhost:" + port + "?client=netty4&timeout=3000"); - url = url.addParameter(RemotingConstants.HEARTBEAT_KEY, 600 * 1000); + url = url.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000); return Exchangers.connect(url); } -} \ No newline at end of file +} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Constants.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Constants.java index 67a2f03c2aa..5085887e872 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Constants.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Constants.java @@ -107,4 +107,22 @@ public interface Constants { * To decide whether to make connection when the client is created */ String LAZY_CONNECT_KEY = "lazy"; + String $INVOKE = "$invoke"; + String $INVOKE_ASYNC = "$invokeAsync"; + + String INPUT_KEY = "input"; + String OUTPUT_KEY = "output"; + /** + * The limit of callback service instances for one interface on every client + */ + String CALLBACK_INSTANCES_LIMIT_KEY = "callbacks"; + + /** + * The default limit number for callback service instances + * + * @see #CALLBACK_INSTANCES_LIMIT_KEY + */ + int DEFAULT_CALLBACK_INSTANCES = 1; + + } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcConstants.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcConstants.java index 57dacca0225..2c7186f6d99 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcConstants.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcConstants.java @@ -17,8 +17,8 @@ package org.apache.dubbo.rpc; import org.apache.dubbo.common.constants.CommonConstants; -import org.apache.dubbo.common.constants.ConfigConstants; import org.apache.dubbo.common.constants.FilterConstants; +import org.apache.dubbo.common.constants.QosConstants; import org.apache.dubbo.common.constants.RegistryConstants; import org.apache.dubbo.common.constants.RemotingConstants; @@ -28,8 +28,8 @@ * @deprecated Replace to org.apache.dubbo.common.Constants */ @Deprecated -public final class RpcConstants implements CommonConstants, ConfigConstants, FilterConstants, - RegistryConstants, RemotingConstants, org.apache.dubbo.common.constants.RpcConstants { +public final class RpcConstants implements CommonConstants, QosConstants, FilterConstants, + RegistryConstants, RemotingConstants { private RpcConstants() { } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java index 49e2a602d21..eb6cebed618 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java @@ -36,7 +36,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.rpc.Constants.ASYNC_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.remoting.Constants.DUBBO_VERSION_KEY; import static org.apache.dubbo.rpc.Constants.FORCE_USE_TAG; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java index fd83e1f4271..ed6e1239714 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java @@ -42,8 +42,8 @@ import java.io.IOException; import java.lang.reflect.Method; -import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE; -import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE_ASYNC; +import static org.apache.dubbo.rpc.Constants.$INVOKE; +import static org.apache.dubbo.rpc.Constants.$INVOKE_ASYNC; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_BEAN; import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_NATIVE_JAVA; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java index ed5de7e1571..0fd0d826df2 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java @@ -40,8 +40,8 @@ import java.lang.reflect.Method; import java.lang.reflect.Type; -import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE; -import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE_ASYNC; +import static org.apache.dubbo.rpc.Constants.$INVOKE; +import static org.apache.dubbo.rpc.Constants.$INVOKE_ASYNC; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; /** diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ConsumerMethodModel.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ConsumerMethodModel.java index 2d5352d3040..0798a500295 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ConsumerMethodModel.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ConsumerMethodModel.java @@ -20,7 +20,7 @@ import java.lang.reflect.Method; import java.util.Map; -import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE; +import static org.apache.dubbo.rpc.Constants.$INVOKE; public class ConsumerMethodModel { private final Method method; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java index 7bf4533100e..955cb31f986 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java @@ -32,8 +32,8 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicLong; -import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE; -import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE_ASYNC; +import static org.apache.dubbo.rpc.Constants.$INVOKE; +import static org.apache.dubbo.rpc.Constants.$INVOKE_ASYNC; import static org.apache.dubbo.rpc.Constants.ASYNC_KEY; import static org.apache.dubbo.rpc.Constants.AUTO_ATTACH_INVOCATIONID_KEY; import static org.apache.dubbo.rpc.Constants.FUTURE_GENERATED_KEY; diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.java index 46bc99ce9c4..b571bd1de3b 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.java @@ -38,7 +38,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; -import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE; +import static org.apache.dubbo.rpc.Constants.$INVOKE; import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_NATIVE_JAVA; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java index 73e0d82b6c0..7145aa08abb 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java @@ -39,7 +39,7 @@ import static org.mockito.Mockito.any; import static org.mockito.Mockito.when; -import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE; +import static org.apache.dubbo.rpc.Constants.$INVOKE; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; public class GenericImplFilterTest { diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java index f28022dca38..e479445ba6d 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java @@ -26,7 +26,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.remoting.Constants.DUBBO_VERSION_KEY; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java index 0ebe357f780..c82599c3a14 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java @@ -42,8 +42,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CALLBACK_SERVICE_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_INSTANCES_LIMIT_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_CALLBACK_INSTANCES; +import static org.apache.dubbo.rpc.Constants.CALLBACK_INSTANCES_LIMIT_KEY; +import static org.apache.dubbo.rpc.Constants.DEFAULT_CALLBACK_INSTANCES; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CALLBACK_SERVICE_PROXY_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.IS_CALLBACK_SERVICE; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CHANNEL_CALLBACK_KEY; diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java index 7aa5198e597..69a0629c4ed 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java @@ -40,7 +40,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.CallbackServiceCodec.decodeInvocationArgument; -import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.remoting.Constants.DUBBO_VERSION_KEY; public class DecodeableRpcInvocation extends RpcInvocation implements Codec, Decodeable { diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java index 1e12bb9736c..dd3e8477486 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java @@ -43,7 +43,7 @@ import static org.apache.dubbo.rpc.protocol.dubbo.CallbackServiceCodec.encodeInvocationArgument; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.DECODE_IN_IO_THREAD_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.DEFAULT_DECODE_IN_IO_THREAD; -import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.remoting.Constants.DUBBO_VERSION_KEY; /** * Dubbo codec. diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCountCodec.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCountCodec.java index 1b1cd1414fd..f282c9dbe00 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCountCodec.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCountCodec.java @@ -28,8 +28,8 @@ import java.io.IOException; -import static org.apache.dubbo.common.constants.RpcConstants.INPUT_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.OUTPUT_KEY; +import static org.apache.dubbo.rpc.Constants.INPUT_KEY; +import static org.apache.dubbo.rpc.Constants.OUTPUT_KEY; public final class DubboCountCodec implements Codec2 { diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java index 7f9281cc5da..3cc20237f32 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java @@ -65,8 +65,8 @@ import static org.apache.dubbo.rpc.Constants.LAZY_CONNECT_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.ON_CONNECT_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.ON_DISCONNECT_KEY; -import static org.apache.dubbo.common.constants.RemotingConstants.DEFAULT_HEARTBEAT; -import static org.apache.dubbo.common.constants.RemotingConstants.HEARTBEAT_KEY; +import static org.apache.dubbo.remoting.Constants.DEFAULT_HEARTBEAT; +import static org.apache.dubbo.remoting.Constants.HEARTBEAT_KEY; import static org.apache.dubbo.remoting.Constants.CHANNEL_READONLYEVENT_SENT_KEY; import static org.apache.dubbo.remoting.Constants.CLIENT_KEY; import static org.apache.dubbo.remoting.Constants.CODEC_KEY; @@ -74,7 +74,7 @@ import static org.apache.dubbo.remoting.Constants.SERVER_KEY; import static org.apache.dubbo.rpc.Constants.DEFAULT_REMOTING_SERVER; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CALLBACK_SERVICE_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.CONNECTIONS_KEY; +import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY; import static org.apache.dubbo.rpc.Constants.DEFAULT_STUB_EVENT; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.IS_CALLBACK_SERVICE; import static org.apache.dubbo.rpc.Constants.IS_SERVER_KEY; diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java index 7b1c17c7517..dcf732e2e56 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java @@ -32,7 +32,7 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import static org.apache.dubbo.common.constants.RpcConstants.$INVOKE; +import static org.apache.dubbo.rpc.Constants.$INVOKE; /** * EventFilter diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java index 7c6a34c40bf..1d8c212b99f 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java @@ -36,7 +36,7 @@ import java.lang.reflect.Field; -import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; import static org.junit.jupiter.api.Assertions.fail; /** diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ExplicitCallbackTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ExplicitCallbackTest.java index cf3635bff03..7490eeec1f1 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ExplicitCallbackTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ExplicitCallbackTest.java @@ -35,7 +35,7 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; -import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_INSTANCES_LIMIT_KEY; +import static org.apache.dubbo.rpc.Constants.CALLBACK_INSTANCES_LIMIT_KEY; public class ExplicitCallbackTest { @@ -354,4 +354,4 @@ public void unxxx2(IDemoCallback callback) { callbacks.remove(callback); } } -} \ No newline at end of file +} diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java index ca5a306df43..52972801778 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java @@ -42,7 +42,7 @@ import java.util.Objects; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.SHARE_CONNECTIONS_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.CONNECTIONS_KEY; +import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY; public class ReferenceCountExchangeClientTest { @@ -317,4 +317,4 @@ public String hello() { return "hello"; } } -} \ No newline at end of file +} diff --git a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java b/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java index 5b548ae0722..dddd724cf86 100644 --- a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java +++ b/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java @@ -50,7 +50,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.remoting.Constants.DUBBO_VERSION_KEY; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; /** diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java index ec34f95b185..c433b00ad83 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java @@ -54,7 +54,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.CONNECTIONS_KEY; +import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY; import static org.apache.dubbo.remoting.Constants.CONNECT_TIMEOUT_KEY; import static org.apache.dubbo.remoting.Constants.DEFAULT_CONNECT_TIMEOUT; import static org.apache.dubbo.remoting.Constants.SERVER_KEY; diff --git a/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocol.java b/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocol.java index d570b2f01f4..d988938507d 100644 --- a/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocol.java +++ b/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocol.java @@ -34,7 +34,7 @@ import static org.apache.dubbo.common.Version.isRelease263OrHigher; import static org.apache.dubbo.common.Version.isRelease270OrHigher; import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.remoting.Constants.DUBBO_VERSION_KEY; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; /** diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java index d6a88cbe4e4..da8bec6a652 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java @@ -46,7 +46,7 @@ import java.util.function.Function; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; -import static org.apache.dubbo.common.constants.RpcConstants.CONNECTIONS_KEY; +import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY; import static org.apache.dubbo.rpc.Constants.IS_SERVER_KEY; /** From 61ab3209b230cb2171945cdf8326a49d942cabd7 Mon Sep 17 00:00:00 2001 From: Taosheng Wei Date: Wed, 29 May 2019 10:05:30 +0800 Subject: [PATCH 097/115] Delete dead code (#4189) --- .../java/org/apache/dubbo/common/config/Configuration.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/Configuration.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/Configuration.java index 7937b9d82c0..6fa15bde11a 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/Configuration.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/Configuration.java @@ -105,10 +105,6 @@ default T convert(Class cls, String key, T defaultValue) { return cls.cast(value); } - if (String.class.equals(cls)) { - return cls.cast(value); - } - if (Boolean.class.equals(cls) || Boolean.TYPE.equals(cls)) { obj = Boolean.valueOf(value); } else if (Number.class.isAssignableFrom(cls) || cls.isPrimitive()) { From 21cfe1163d4fa07c3cb22b8d12ea149f6c87a701 Mon Sep 17 00:00:00 2001 From: Huxing Zhang Date: Wed, 29 May 2019 10:20:42 +0800 Subject: [PATCH 098/115] Create security.md (#4165) Add security.md --- SECURITY.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 SECURITY.md diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 00000000000..5f6760944b6 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,31 @@ +# Security Policy + +## Supported Versions + +Below is a table that shows versions that accept security fix. + +| Version | Supported | +| ------- | ------------------ | +| 2.7.x | :white_check_mark: | +| 2.6.x | :white_check_mark: | +| 2.5.x | :x: | + + +## Reporting a Vulnerability + +The Apache Software Foundation takes a rigorous standpoint in annihilating the security issues in its software projects. Apache Dubbo is highly sensitive and forthcoming to issues pertaining to its features and functionality. + +If you have apprehensions regarding Dubbo's security or you discover vulnerability or potential threat, don’t hesitate to get in touch with the Apache Dubbo Security Team by dropping a mail at security@dubbo.apache.org. In the mail, specify the description of the issue or potential threat. You are also urged to recommend the way to reproduce and replicate the issue. The Dubbo community will get back to you after assessing and analysing the findings. + +PLEASE PAY ATTENTION to report the security issue on the security email before disclosing it on public domain. + +## VULNERABILITY HANDLING + +An overview of the vulnerability handling process is: + +* The reporter reports the vulnerability privately to Apache. +* The appropriate project's security team works privately with the reporter to resolve the vulnerability. +* A new release of the Apache product concerned is made that includes the fix. +* The vulnerability is publically announced. + +A more detailed description of the process can be found [here](https://www.apache.org/security/committers.html). From 4b97a0ba8b5edcedb37a320e00cd5bc36f304f90 Mon Sep 17 00:00:00 2001 From: uglycow Date: Wed, 29 May 2019 10:27:03 +0800 Subject: [PATCH 099/115] fix for #4175: ServiceConfigurationListener should override ProviderConfigurationListener (#4179) --- .../org/apache/dubbo/registry/integration/RegistryProtocol.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java index 96b060ff44a..b9ad1b3ce5b 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java @@ -557,9 +557,9 @@ public synchronized void doOverrideIfNecessary() { URL currentUrl = exporter.getInvoker().getUrl(); //Merged with this configuration URL newUrl = getConfigedInvokerUrl(configurators, originUrl); + newUrl = getConfigedInvokerUrl(providerConfigurationListener.getConfigurators(), newUrl); newUrl = getConfigedInvokerUrl(serviceConfigurationListeners.get(originUrl.getServiceKey()) .getConfigurators(), newUrl); - newUrl = getConfigedInvokerUrl(providerConfigurationListener.getConfigurators(), newUrl); if (!currentUrl.equals(newUrl)) { RegistryProtocol.this.reExport(originInvoker, newUrl); logger.info("exported provider url changed, origin url: " + originUrl + From 177f71b9f52c8a5896d91089bc0260a66d9611bd Mon Sep 17 00:00:00 2001 From: jimin Date: Fri, 31 May 2019 12:56:51 +0800 Subject: [PATCH 100/115] optimize code style (#4188) --- .../apache/dubbo/common/utils/ClassUtils.java | 26 +++++++++---------- .../registry/support/AbstractRegistry.java | 2 ++ .../support/AbstractRegistryFactory.java | 1 + .../registry/support/FailbackRegistry.java | 6 +++++ .../apache/dubbo/config/ServiceConfig.java | 12 ++++----- .../org/apache/dubbo/rpc/AppResponse.java | 5 ++++ .../org/apache/dubbo/rpc/AsyncRpcResult.java | 1 + .../org/apache/dubbo/rpc/RpcInvocation.java | 2 ++ .../apache/dubbo/rpc/support/MockInvoker.java | 20 +++++++------- .../rpc/protocol/rmi/RmiRemoteInvocation.java | 6 ++--- .../rpc/protocol/xmlrpc/XmlRpcProtocol.java | 17 +++++++++--- .../xmlrpc/XmlRpcProxyFactoryBean.java | 5 ++++ 12 files changed, 67 insertions(+), 36 deletions(-) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassUtils.java index 51e4ee516b0..10b6b9abc57 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassUtils.java @@ -37,32 +37,32 @@ public class ClassUtils { * Map with primitive type name as key and corresponding primitive type as * value, for example: "int" -> "int.class". */ - private static final Map> primitiveTypeNameMap = new HashMap>(16); + private static final Map> PRIMITIVE_TYPE_NAME_MAP = new HashMap>(16); /** * Map with primitive wrapper type as key and corresponding primitive type * as value, for example: Integer.class -> int.class. */ - private static final Map, Class> primitiveWrapperTypeMap = new HashMap, Class>(8); + private static final Map, Class> PRIMITIVE_WRAPPER_TYPE_MAP = new HashMap, Class>(8); private static final char PACKAGE_SEPARATOR_CHAR = '.'; static { - primitiveWrapperTypeMap.put(Boolean.class, boolean.class); - primitiveWrapperTypeMap.put(Byte.class, byte.class); - primitiveWrapperTypeMap.put(Character.class, char.class); - primitiveWrapperTypeMap.put(Double.class, double.class); - primitiveWrapperTypeMap.put(Float.class, float.class); - primitiveWrapperTypeMap.put(Integer.class, int.class); - primitiveWrapperTypeMap.put(Long.class, long.class); - primitiveWrapperTypeMap.put(Short.class, short.class); + PRIMITIVE_WRAPPER_TYPE_MAP.put(Boolean.class, boolean.class); + PRIMITIVE_WRAPPER_TYPE_MAP.put(Byte.class, byte.class); + PRIMITIVE_WRAPPER_TYPE_MAP.put(Character.class, char.class); + PRIMITIVE_WRAPPER_TYPE_MAP.put(Double.class, double.class); + PRIMITIVE_WRAPPER_TYPE_MAP.put(Float.class, float.class); + PRIMITIVE_WRAPPER_TYPE_MAP.put(Integer.class, int.class); + PRIMITIVE_WRAPPER_TYPE_MAP.put(Long.class, long.class); + PRIMITIVE_WRAPPER_TYPE_MAP.put(Short.class, short.class); Set> primitiveTypeNames = new HashSet<>(16); - primitiveTypeNames.addAll(primitiveWrapperTypeMap.values()); + primitiveTypeNames.addAll(PRIMITIVE_WRAPPER_TYPE_MAP.values()); primitiveTypeNames.addAll(Arrays .asList(boolean[].class, byte[].class, char[].class, double[].class, float[].class, int[].class, long[].class, short[].class)); for (Class primitiveTypeName : primitiveTypeNames) { - primitiveTypeNameMap.put(primitiveTypeName.getName(), primitiveTypeName); + PRIMITIVE_TYPE_NAME_MAP.put(primitiveTypeName.getName(), primitiveTypeName); } } @@ -202,7 +202,7 @@ public static Class resolvePrimitiveClassName(String name) { // SHOULD sit in a package, so a length check is worthwhile. if (name != null && name.length() <= 8) { // Could be a primitive - likely. - result = (Class) primitiveTypeNameMap.get(name); + result = (Class) PRIMITIVE_TYPE_NAME_MAP.get(name); } return result; } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistry.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistry.java index ef1bb3d9e75..0e271ed1252 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistry.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistry.java @@ -134,10 +134,12 @@ public boolean isAvailable() { return false; } + @Override public void notify(URL url, NotifyListener listener, List urls) { super.notify(url, listener, urls); } + @Override public void setUrl(URL url) { super.setUrl(url); } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistryFactory.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistryFactory.java index 9b0b698e63d..d611fa6ec75 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistryFactory.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistryFactory.java @@ -28,6 +28,7 @@ public abstract class AbstractRegistryFactory extends org.apache.dubbo.registry. protected abstract com.alibaba.dubbo.registry.Registry createRegistry(com.alibaba.dubbo.common.URL url); + @Override protected Registry createRegistry(URL url) { return createRegistry(new com.alibaba.dubbo.common.URL(url)); } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/FailbackRegistry.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/FailbackRegistry.java index 0156ddb4624..2a4bd8e9c5a 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/FailbackRegistry.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/FailbackRegistry.java @@ -55,18 +55,22 @@ public void removeFailedNotifiedTask(URL url, NotifyListener listener) { failbackRegistry.removeFailedNotifiedTask(url.getOriginalURL(), new NotifyListener.ReverseCompatibleNotifyListener(listener)); } + @Override public void register(URL url) { failbackRegistry.register(url.getOriginalURL()); } + @Override public void unregister(URL url) { failbackRegistry.unregister(url.getOriginalURL()); } + @Override public void subscribe(URL url, NotifyListener listener) { failbackRegistry.subscribe(url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener)); } + @Override public void unsubscribe(URL url, NotifyListener listener) { failbackRegistry.unsubscribe(url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener)); } @@ -85,10 +89,12 @@ protected void recover() throws Exception { failbackRegistry.recover(); } + @Override public List lookup(URL url) { return failbackRegistry.lookup(url.getOriginalURL()).stream().map(e -> new URL(e)).collect(Collectors.toList()); } + @Override public URL getUrl() { return new URL(failbackRegistry.getUrl()); } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index caee14d07b6..257d2a15ee0 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -122,7 +122,7 @@ public class ServiceConfig extends AbstractServiceConfig { * A {@link ProxyFactory} implementation that will generate a exported service proxy,the JavassistProxyFactory is its * default implementation */ - private static final ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + private static final ProxyFactory PROXY_FACTORY = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); /** * A random port cache, the different protocols who has no port specified have different random port @@ -132,7 +132,7 @@ public class ServiceConfig extends AbstractServiceConfig { /** * A delayed exposure service timer */ - private static final ScheduledExecutorService delayExportExecutor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("DubboServiceDelayExporter", true)); + private static final ScheduledExecutorService DELAY_EXPORT_EXECUTOR = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("DubboServiceDelayExporter", true)); /** * The urls of the services exported @@ -373,7 +373,7 @@ public synchronized void export() { } if (shouldDelay()) { - delayExportExecutor.schedule(this::doExport, getDelay(), TimeUnit.MILLISECONDS); + DELAY_EXPORT_EXECUTOR.schedule(this::doExport, getDelay(), TimeUnit.MILLISECONDS); } else { doExport(); } @@ -601,14 +601,14 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r registryURL = registryURL.addParameter(PROXY_KEY, proxy); } - Invoker invoker = proxyFactory.getInvoker(ref, (Class) interfaceClass, registryURL.addParameterAndEncoded(EXPORT_KEY, url.toFullString())); + Invoker invoker = PROXY_FACTORY.getInvoker(ref, (Class) interfaceClass, registryURL.addParameterAndEncoded(EXPORT_KEY, url.toFullString())); DelegateProviderMetaDataInvoker wrapperInvoker = new DelegateProviderMetaDataInvoker(invoker, this); Exporter exporter = protocol.export(wrapperInvoker); exporters.add(exporter); } } else { - Invoker invoker = proxyFactory.getInvoker(ref, (Class) interfaceClass, url); + Invoker invoker = PROXY_FACTORY.getInvoker(ref, (Class) interfaceClass, url); DelegateProviderMetaDataInvoker wrapperInvoker = new DelegateProviderMetaDataInvoker(invoker, this); Exporter exporter = protocol.export(wrapperInvoker); @@ -638,7 +638,7 @@ private void exportLocal(URL url) { .setPort(0) .build(); Exporter exporter = protocol.export( - proxyFactory.getInvoker(ref, (Class) interfaceClass, local)); + PROXY_FACTORY.getInvoker(ref, (Class) interfaceClass, local)); exporters.add(exporter); logger.info("Export dubbo service " + interfaceClass.getName() + " to local registry url : " + local); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AppResponse.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AppResponse.java index 6657b79b407..a02b16a300d 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AppResponse.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AppResponse.java @@ -92,6 +92,7 @@ public Object getValue() { return result; } + @Override public void setValue(Object value) { this.result = value; } @@ -101,6 +102,7 @@ public Throwable getException() { return exception; } + @Override public void setException(Throwable e) { this.exception = e; } @@ -120,10 +122,12 @@ public Map getAttachments() { * * @param map contains all key-value pairs to append */ + @Override public void setAttachments(Map map) { this.attachments = map == null ? new HashMap() : map; } + @Override public void addAttachments(Map map) { if (map == null) { return; @@ -148,6 +152,7 @@ public String getAttachment(String key, String defaultValue) { return result; } + @Override public void setAttachment(String key, String value) { attachments.put(key, value); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncRpcResult.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncRpcResult.java index 658797d0b6d..815bec562e0 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncRpcResult.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncRpcResult.java @@ -136,6 +136,7 @@ public Object recreate() throws Throwable { return (new AppResponse()).recreate(); } + @Override public Result thenApplyWithContext(Function fn) { this.thenApply(fn.compose(beforeContext).andThen(afterContext)); // You may need to return a new Result instance representing the next async stage, diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.java index e422bef6cf1..06b7cb6a0dd 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.java @@ -162,6 +162,7 @@ public void setAttachments(Map attachments) { this.attachments = attachments == null ? new HashMap() : attachments; } + @Override public void setAttachment(String key, String value) { if (attachments == null) { attachments = new HashMap(); @@ -169,6 +170,7 @@ public void setAttachment(String key, String value) { attachments.put(key, value); } + @Override public void setAttachmentIfAbsent(String key, String value) { if (attachments == null) { attachments = new HashMap(); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java index e8f8209e69b..90f4d69b97d 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java @@ -47,9 +47,9 @@ import static org.apache.dubbo.rpc.Constants.RETURN_KEY; final public class MockInvoker implements Invoker { - private final static ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - private final static Map> mocks = new ConcurrentHashMap>(); - private final static Map throwables = new ConcurrentHashMap(); + private final static ProxyFactory PROXY_FACTORY = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + private final static Map> MOCK_MAP = new ConcurrentHashMap>(); + private final static Map THROWABLE_MAP = new ConcurrentHashMap(); private final URL url; private final Class type; @@ -136,7 +136,7 @@ public Result invoke(Invocation invocation) throws RpcException { } public static Throwable getThrowable(String throwstr) { - Throwable throwable = throwables.get(throwstr); + Throwable throwable = THROWABLE_MAP.get(throwstr); if (throwable != null) { return throwable; } @@ -147,8 +147,8 @@ public static Throwable getThrowable(String throwstr) { Constructor constructor; constructor = ReflectUtils.findConstructor(bizException, String.class); t = (Throwable) constructor.newInstance(new Object[]{"mocked exception for service degradation."}); - if (throwables.size() < 1000) { - throwables.put(throwstr, t); + if (THROWABLE_MAP.size() < 1000) { + THROWABLE_MAP.put(throwstr, t); } return t; } catch (Exception e) { @@ -158,16 +158,16 @@ public static Throwable getThrowable(String throwstr) { @SuppressWarnings("unchecked") private Invoker getInvoker(String mockService) { - Invoker invoker = (Invoker) mocks.get(mockService); + Invoker invoker = (Invoker) MOCK_MAP.get(mockService); if (invoker != null) { return invoker; } Class serviceType = (Class) ReflectUtils.forName(url.getServiceInterface()); T mockObject = (T) getMockObject(mockService, serviceType); - invoker = proxyFactory.getInvoker(mockObject, serviceType, url); - if (mocks.size() < 10000) { - mocks.put(mockService, invoker); + invoker = PROXY_FACTORY.getInvoker(mockObject, serviceType, url); + if (MOCK_MAP.size() < 10000) { + MOCK_MAP.put(mockService, invoker); } return invoker; } diff --git a/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiRemoteInvocation.java b/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiRemoteInvocation.java index cdb25183f6d..a8ead53e96e 100644 --- a/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiRemoteInvocation.java +++ b/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiRemoteInvocation.java @@ -30,14 +30,14 @@ public class RmiRemoteInvocation extends RemoteInvocation { private static final long serialVersionUID = 1L; - private static final String dubboAttachmentsAttrName = "dubbo.attachments"; + private static final String DUBBO_ATTACHMENTS_ATTR_NAME = "dubbo.attachments"; /** * executed on consumer side */ public RmiRemoteInvocation(MethodInvocation methodInvocation) { super(methodInvocation); - addAttribute(dubboAttachmentsAttrName, new HashMap<>(RpcContext.getContext().getAttachments())); + addAttribute(DUBBO_ATTACHMENTS_ATTR_NAME, new HashMap<>(RpcContext.getContext().getAttachments())); } /** @@ -50,7 +50,7 @@ public RmiRemoteInvocation(MethodInvocation methodInvocation) { public Object invoke(Object targetObject) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { RpcContext context = RpcContext.getContext(); - context.setAttachments((Map) getAttribute(dubboAttachmentsAttrName)); + context.setAttachments((Map) getAttribute(DUBBO_ATTACHMENTS_ATTR_NAME)); String generic = (String) getAttribute(GENERIC_KEY); if (StringUtils.isNotEmpty(generic)) { context.setAttachment(GENERIC_KEY, generic); diff --git a/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java b/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java index 68927d7bd1f..1a8240e8f3e 100644 --- a/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java +++ b/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java @@ -61,6 +61,7 @@ public void setHttpBinder(HttpBinder httpBinder) { this.httpBinder = httpBinder; } + @Override public int getDefaultPort() { return 80; } @@ -73,6 +74,7 @@ public InternalHandler(boolean cors) { this.cors = cors; } + @Override public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String uri = request.getRequestURI(); @@ -99,15 +101,16 @@ public void handle(HttpServletRequest request, HttpServletResponse response) } + @Override protected Runnable doExport(T impl, Class type, URL url) throws RpcException { - final URL http_url = url.setProtocol("http"); - String addr = http_url.getIp() + ":" + http_url.getPort(); + final URL httpUrl = url.setProtocol("http"); + String addr = httpUrl.getIp() + ":" + httpUrl.getPort(); HttpServer server = serverMap.get(addr); if (server == null) { - server = httpBinder.bind(http_url, new InternalHandler(http_url.getParameter("cors", false))); + server = httpBinder.bind(httpUrl, new InternalHandler(httpUrl.getParameter("cors", false))); serverMap.put(addr, server); } - final String path = http_url.getAbsolutePath(); + final String path = httpUrl.getAbsolutePath(); XmlRpcServletServer xmlRpcServer = new XmlRpcServletServer(); @@ -115,8 +118,10 @@ protected Runnable doExport(T impl, Class type, URL url) throws RpcExcept try { propertyHandlerMapping.setRequestProcessorFactoryFactory(new RequestProcessorFactoryFactory(){ + @Override public RequestProcessorFactory getRequestProcessorFactory(Class pClass) throws XmlRpcException{ return new RequestProcessorFactory(){ + @Override public Object getRequestProcessor(XmlRpcRequest pRequest) throws XmlRpcException{ return impl; } @@ -137,12 +142,14 @@ public Object getRequestProcessor(XmlRpcRequest pRequest) throws XmlRpcException skeletonMap.put(path, xmlRpcServer); return new Runnable() { + @Override public void run() { skeletonMap.remove(path); } }; } + @Override @SuppressWarnings("unchecked") protected T doRefer(final Class serviceType, URL url) throws RpcException { XmlRpcProxyFactoryBean xmlRpcProxyFactoryBean = new XmlRpcProxyFactoryBean(); @@ -152,6 +159,7 @@ protected T doRefer(final Class serviceType, URL url) throws RpcException return (T) xmlRpcProxyFactoryBean.getObject(); } + @Override protected int getErrorCode(Throwable e) { if (e instanceof RemoteAccessException) { e = e.getCause(); @@ -169,6 +177,7 @@ protected int getErrorCode(Throwable e) { return super.getErrorCode(e); } + @Override public void destroy() { super.destroy(); for (String key : new ArrayList<>(serverMap.keySet())) { diff --git a/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProxyFactoryBean.java b/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProxyFactoryBean.java index c720b22f507..d1dfe6e2a9b 100644 --- a/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProxyFactoryBean.java +++ b/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProxyFactoryBean.java @@ -74,6 +74,7 @@ public void afterPropertiesSet() { /** * {@inheritDoc} */ + @Override public Object invoke(MethodInvocation invocation) throws Throwable { @@ -105,6 +106,7 @@ public Object invoke(MethodInvocation invocation) /** * {@inheritDoc} */ + @Override public Object getObject() { return proxyObject; } @@ -112,6 +114,7 @@ public Object getObject() { /** * {@inheritDoc} */ + @Override public Class getObjectType() { return getServiceInterface(); } @@ -119,6 +122,7 @@ public Class getObjectType() { /** * {@inheritDoc} */ + @Override public boolean isSingleton() { return true; } @@ -126,6 +130,7 @@ public boolean isSingleton() { /** * {@inheritDoc} */ + @Override public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } From 7f7a28987853aa511ba18ab3647c34187e88230f Mon Sep 17 00:00:00 2001 From: Kyle Date: Fri, 31 May 2019 12:57:50 +0800 Subject: [PATCH 101/115] Standardized code (#4211) --- .../org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java | 1 + 1 file changed, 1 insertion(+) diff --git a/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java b/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java index 1a8240e8f3e..acda3dea481 100644 --- a/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java +++ b/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java @@ -151,6 +151,7 @@ public void run() { @Override @SuppressWarnings("unchecked") + @Override protected T doRefer(final Class serviceType, URL url) throws RpcException { XmlRpcProxyFactoryBean xmlRpcProxyFactoryBean = new XmlRpcProxyFactoryBean(); xmlRpcProxyFactoryBean.setServiceUrl(url.setProtocol("http").toIdentityString()); From 85dd59cd7323160169634ca86708fc3cd9dbea1e Mon Sep 17 00:00:00 2001 From: wanghbxxxx Date: Fri, 31 May 2019 19:28:40 +0800 Subject: [PATCH 102/115] Remove duplicate @Override (#4228) --- .../apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java b/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java index acda3dea481..0ee9156584e 100644 --- a/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java +++ b/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java @@ -151,7 +151,6 @@ public void run() { @Override @SuppressWarnings("unchecked") - @Override protected T doRefer(final Class serviceType, URL url) throws RpcException { XmlRpcProxyFactoryBean xmlRpcProxyFactoryBean = new XmlRpcProxyFactoryBean(); xmlRpcProxyFactoryBean.setServiceUrl(url.setProtocol("http").toIdentityString()); @@ -195,4 +194,4 @@ public void destroy() { } } } -} \ No newline at end of file +} From 492f7601ce31a475674f54dccfb5d6eff2e3210f Mon Sep 17 00:00:00 2001 From: Xin Wang Date: Fri, 31 May 2019 21:51:13 +0800 Subject: [PATCH 103/115] Reverse url of python (#4162) reverse url of python --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 751ad1e1764..6c8ae12fde5 100644 --- a/README.md +++ b/README.md @@ -220,7 +220,7 @@ Please report security vulnerability to [us](mailto:security@dubbo.apache.org) p #### Language * [Node.js](https://github.com/apache/dubbo-js) -* [Python](https://github.com/apache/dubbo-client-py) +* [Python](https://github.com/dubbo/py-client-for-apache-dubbo) * [PHP](https://github.com/apache/dubbo-php-framework) * [Go](https://github.com/dubbo/dubbo-go) * [Erlang](https://github.com/apache/dubbo-erlang) From 847990662db849f5abf0c154e7a4b474be501691 Mon Sep 17 00:00:00 2001 From: "tao.zhang" Date: Sat, 1 Jun 2019 09:32:04 +0800 Subject: [PATCH 104/115] Improve java doc for dubbo-remoting-netty4 (#4180) * add some comments for dubbo-remoting-netty4 * update from upstream/master * adjust format --- .../apache/dubbo/common/utils/UrlUtils.java | 1 + .../org/apache/dubbo/remoting/Constants.java | 6 ++- .../apache/dubbo/remoting/utils/UrlUtils.java | 1 + .../transport/netty4/NettyChannel.java | 48 +++++++++++++++---- .../transport/netty4/NettyClient.java | 35 +++++++++++--- .../transport/netty4/NettyClientHandler.java | 1 + .../transport/netty4/NettyServer.java | 26 +++++++--- .../transport/netty4/NettyServerHandler.java | 10 ++-- .../transport/netty4/NettyTransporter.java | 3 ++ 9 files changed, 105 insertions(+), 26 deletions(-) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java index 56e73cb75ac..73c03f04eff 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java @@ -484,6 +484,7 @@ public static boolean isProvider(URL url) { PROVIDERS_CATEGORY.equals(url.getParameter(CATEGORY_KEY, PROVIDERS_CATEGORY)); } + /** * Check if the given value matches the given pattern. The pattern supports wildcard "*". * diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Constants.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Constants.java index 61a7e798642..8fd636183e2 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Constants.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Constants.java @@ -36,10 +36,12 @@ public interface Constants { String IDLE_TIMEOUT_KEY = "idle.timeout"; int DEFAULT_IDLE_TIMEOUT = 600 * 1000; - + /** + * max size of channel. default value is zero that means unlimited. + */ String ACCEPTS_KEY = "accepts"; - int DEFAULT_ACCEPTS = 0; + int DEFAULT_ACCEPTS = 0; String CONNECT_QUEUE_CAPACITY = "connect.queue.capacity"; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/utils/UrlUtils.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/utils/UrlUtils.java index 49f5a621fb4..9b38c7b0020 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/utils/UrlUtils.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/utils/UrlUtils.java @@ -23,6 +23,7 @@ public class UrlUtils { public static int getIdleTimeout(URL url) { int heartBeat = getHeartbeat(url); + // idleTimeout should be at least more than twice heartBeat because possible retries of client. int idleTimeout = url.getParameter(Constants.HEARTBEAT_TIMEOUT_KEY, heartBeat * 3); if (idleTimeout < heartBeat * 2) { throw new IllegalStateException("idleTimeout < heartbeatInterval * 2"); diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java index b4202e1a219..f8bbcf682e5 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java @@ -35,18 +35,29 @@ import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; /** - * NettyChannel. + * NettyChannel maintains the cache of channel. */ final class NettyChannel extends AbstractChannel { private static final Logger logger = LoggerFactory.getLogger(NettyChannel.class); - + /** + * the cache for netty channel and dubbo channel + */ private static final ConcurrentMap CHANNEL_MAP = new ConcurrentHashMap(); - + /** + * netty channel + */ private final Channel channel; private final Map attributes = new ConcurrentHashMap(); - + /** + * The constructor of NettyChannel. + * It is private so NettyChannel usually create by {@link NettyChannel#getOrAddChannel(Channel, URL, ChannelHandler)} + * + * @param channel netty channel + * @param url + * @param handler dubbo handler that contain netty handler + */ private NettyChannel(Channel channel, URL url, ChannelHandler handler) { super(url, handler); if (channel == null) { @@ -54,7 +65,15 @@ private NettyChannel(Channel channel, URL url, ChannelHandler handler) { } this.channel = channel; } - + /** + * Get dubbo channel by netty channel through channel cache. + * Put netty channel into it if dubbo channel don't exist in the cache. + * + * @param ch netty channel + * @param url + * @param handler dubbo handler that contain netty's handler + * @return + */ static NettyChannel getOrAddChannel(Channel ch, URL url, ChannelHandler handler) { if (ch == null) { return null; @@ -71,7 +90,11 @@ static NettyChannel getOrAddChannel(Channel ch, URL url, ChannelHandler handler) } return ret; } - + /** + * Remove the inactive channel. + * + * @param ch netty channel + */ static void removeChannelIfDisconnected(Channel ch) { if (ch != null && !ch.isActive()) { CHANNEL_MAP.remove(ch); @@ -93,8 +116,16 @@ public boolean isConnected() { return !isClosed() && channel.isActive(); } + /** + * Send message by netty and whether to wait the completion of the send. + * + * @param message message that need send. + * @param sent whether to ack async-sent + * @throws RemotingException throw RemotingException if wait until timeout or any exception thrown by method body that surrounded by try-catch. + */ @Override public void send(Object message, boolean sent) throws RemotingException { + // whether the channel is closed super.send(message, sent); boolean success = true; @@ -102,6 +133,7 @@ public void send(Object message, boolean sent) throws RemotingException { try { ChannelFuture future = channel.writeAndFlush(message); if (sent) { + // wait timeout ms timeout = getUrl().getPositiveParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT); success = future.await(timeout); } @@ -112,7 +144,6 @@ public void send(Object message, boolean sent) throws RemotingException { } catch (Throwable e) { throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress() + ", cause: " + e.getMessage(), e); } - if (!success) { throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress() + "in timeout(" + timeout + "ms) limit"); @@ -158,7 +189,8 @@ public Object getAttribute(String key) { @Override public void setAttribute(String key, Object value) { - if (value == null) { // The null value unallowed in the ConcurrentHashMap. + // The null value is unallowed in the ConcurrentHashMap. + if (value == null) { attributes.remove(key); } else { attributes.put(key, value); diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java index 13e0c4ef831..3c32a9cb459 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java @@ -50,7 +50,9 @@ public class NettyClient extends AbstractClient { private static final Logger logger = LoggerFactory.getLogger(NettyClient.class); - + /** + * netty client bootstrap + */ private static final NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup(Constants.DEFAULT_IO_THREADS, new DefaultThreadFactory("NettyClientWorker", true)); private static final String SOCKS_PROXY_HOST = "socksProxyHost"; @@ -61,12 +63,28 @@ public class NettyClient extends AbstractClient { private Bootstrap bootstrap; - private volatile Channel channel; // volatile, please copy reference to use - + /** + * current channel. Each successful invocation of {@link NettyClient#doConnect()} will + * replace this with new channel and close old channel. + * volatile, please copy reference to use. + */ + private volatile Channel channel; + + /** + * The constructor of NettyClient. + * It wil init and start netty. + */ public NettyClient(final URL url, final ChannelHandler handler) throws RemotingException { - super(url, wrapChannelHandler(url, handler)); + // you can customize name and type of client thread pool by THREAD_NAME_KEY and THREADPOOL_KEY in CommonConstants. + // the handler will be warped: MultiMessageHandler->HeartbeatHandler->handler + super(url, wrapChannelHandler(url, handler)); } + /** + * Init bootstrap + * + * @throws Throwable + */ @Override protected void doOpen() throws Throwable { final NettyClientHandler nettyClientHandler = new NettyClientHandler(getUrl(), this); @@ -116,7 +134,8 @@ protected void doConnect() throws Throwable { Channel newChannel = future.channel(); try { // Close old channel - Channel oldChannel = NettyClient.this.channel; // copy reference + // copy reference + Channel oldChannel = NettyClient.this.channel; if (oldChannel != null) { try { if (logger.isInfoEnabled()) { @@ -152,6 +171,7 @@ protected void doConnect() throws Throwable { + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion()); } } finally { + // just add new valid channel to NettyChannel's cache if (!isConnected()) { //future.cancel(true); } @@ -169,8 +189,9 @@ protected void doDisConnect() throws Throwable { @Override protected void doClose() throws Throwable { - //can't shutdown nioEventLoopGroup - //nioEventLoopGroup.shutdownGracefully(); + // can't shutdown nioEventLoopGroup because the method will be invoked when closing one channel but not a client, + // but when and how to close the nioEventLoopGroup ? + // nioEventLoopGroup.shutdownGracefully(); } @Override diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClientHandler.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClientHandler.java index 8827a0bb5b7..8ff2d98413c 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClientHandler.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClientHandler.java @@ -113,6 +113,7 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { + // send heartbeat when read idle. if (evt instanceof IdleStateEvent) { try { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java index 515dc002288..0cdd9f769e9 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java @@ -51,25 +51,39 @@ import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY; /** - * NettyServer + * NettyServer. */ public class NettyServer extends AbstractServer implements Server { private static final Logger logger = LoggerFactory.getLogger(NettyServer.class); - - private Map channels; // - + /** + * the cache for alive worker channel. + * + */ + private Map channels; + /** + * netty server bootstrap. + */ private ServerBootstrap bootstrap; - - private io.netty.channel.Channel channel; + /** + * the boss channel that receive connections and dispatch these to worker channel. + */ + private io.netty.channel.Channel channel; private EventLoopGroup bossGroup; private EventLoopGroup workerGroup; public NettyServer(URL url, ChannelHandler handler) throws RemotingException { + // you can customize name and type of client thread pool by THREAD_NAME_KEY and THREADPOOL_KEY in CommonConstants. + // the handler will be warped: MultiMessageHandler->HeartbeatHandler->handler super(url, ChannelHandlers.wrap(handler, ExecutorUtil.setThreadName(url, SERVER_THREAD_POOL_NAME))); } + /** + * Init and start netty server + * + * @throws Throwable + */ @Override protected void doOpen() throws Throwable { bootstrap = new ServerBootstrap(); diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServerHandler.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServerHandler.java index ea5b3249839..e62ab720f10 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServerHandler.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServerHandler.java @@ -33,13 +33,16 @@ import java.util.concurrent.ConcurrentHashMap; /** - * NettyServerHandler + * NettyServerHandler. */ @io.netty.channel.ChannelHandler.Sharable public class NettyServerHandler extends ChannelDuplexHandler { private static final Logger logger = LoggerFactory.getLogger(NettyServerHandler.class); - - private final Map channels = new ConcurrentHashMap(); // + /** + * the cache for alive worker channel. + * + */ + private final Map channels = new ConcurrentHashMap(); private final URL url; @@ -108,6 +111,7 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { + // server will close channel when server don't receive any heartbeat from client util timeout. if (evt instanceof IdleStateEvent) { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); try { diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporter.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporter.java index 5e1ec3e9fc5..fce2df12179 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporter.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporter.java @@ -23,6 +23,9 @@ import org.apache.dubbo.remoting.Server; import org.apache.dubbo.remoting.Transporter; +/** + * Default extension of {@link Transporter} using netty4.x. + */ public class NettyTransporter implements Transporter { public static final String NAME = "netty"; From 8f783fad911edea9b0a7a50ffad94f26f7499af7 Mon Sep 17 00:00:00 2001 From: jimin Date: Sun, 2 Jun 2019 01:16:53 +0800 Subject: [PATCH 105/115] optimize junit Assert usage (#4214) --- .../apache/dubbo/rpc/cluster/StickyTest.java | 4 +- .../rpc/cluster/merger/ResultMergerTest.java | 12 ++-- .../router/condition/ConditionRouterTest.java | 22 +++---- .../support/AbstractClusterInvokerTest.java | 20 +++---- .../wrapper/MockClusterInvokerTest.java | 22 +++---- .../java/org/apache/dubbo/common/URLTest.java | 12 ++-- .../beanutil/JavaBeanSerializeUtilTest.java | 14 ++--- .../dubbo/common/bytecode/MixinTest.java | 7 ++- .../dubbo/common/bytecode/WrapperTest.java | 8 +-- .../compiler/support/ClassUtilsTest.java | 2 +- .../common/extension/ExtensionLoaderTest.java | 18 +++--- .../support/ActivateComparatorTest.java | 1 - .../apache/dubbo/common/json/JSONTest.java | 6 +- .../threadlocal/InternalThreadLocalTest.java | 29 ++++----- .../NamedInternalThreadFactoryTest.java | 2 +- .../eager/EagerThreadPoolExecutorTest.java | 8 +-- .../common/utils/CompatibleTypeUtilsTest.java | 2 +- .../dubbo/common/utils/MethodUtilsTest.java | 4 +- .../dubbo/common/utils/PojoUtilsTest.java | 6 +- .../apache/dubbo/config/MethodConfigTest.java | 3 +- .../dubbo/config/ReferenceConfigTest.java | 10 ++-- .../AnnotationPropertyValuesAdapterTest.java | 10 ++-- .../annotation/ReferenceBeanBuilderTest.java | 2 +- .../dubbo/cache/filter/CacheFilterTest.java | 4 +- .../support/jvalidation/JValidationTest.java | 1 - .../identifier/MetadataIdentifierTest.java | 1 - .../support/AbstractMetadataReportTest.java | 8 +-- .../monitor/support/MonitorFilterTest.java | 4 +- .../qos/command/util/CommandHelperTest.java | 1 - .../registry/PerformanceRegistryTest.java | 1 - .../support/AbstractRegistryTest.java | 2 +- .../support/FailbackRegistryTest.java | 2 +- .../registry/dubbo/RegistryDirectoryTest.java | 60 ++++++++++--------- .../registry/dubbo/RegistryProtocolTest.java | 11 ++-- .../dubbo/registry/etcd/EtcdRegistryTest.java | 30 +++++----- .../multiple/MultipleRegistry2S2RTest.java | 30 +++++----- .../remoting/codec/ExchangeCodecTest.java | 28 ++++----- .../handler/ConnectChannelHandlerTest.java | 2 +- .../handler/HeaderExchangeHandlerTest.java | 2 +- .../remoting/transport/AbstractCodecTest.java | 5 +- .../remoting/etcd/jetcd/JEtcdClientTest.java | 4 +- .../support/header/HeartbeatHandlerTest.java | 4 +- .../transport/netty/ClientReconnectTest.java | 8 +-- .../transport/netty4/ClientReconnectTest.java | 8 +-- .../curator/CuratorZookeeperClientTest.java | 1 - .../CuratorZookeeperTransporterTest.java | 1 - .../org/apache/dubbo/rpc/AppResponseTest.java | 4 +- .../org/apache/dubbo/rpc/RpcContextTest.java | 8 +-- .../dubbo/rpc/filter/tps/StatItemTest.java | 4 +- .../dubbo/rpc/support/RpcUtilsTest.java | 6 +- .../dubbo/DubboInvokerAvilableTest.java | 18 +++--- .../protocol/dubbo/ImplicitCallBackTest.java | 14 ++--- .../ReferenceCountExchangeClientTest.java | 8 +-- .../telnet/CurrentTelnetHandlerTest.java | 1 - .../dubbo/rpc/validation/ValidationTest.java | 2 +- .../rpc/protocol/http/HttpProtocolTest.java | 2 +- .../DubboSwaggerApiListingResourceTest.java | 2 - .../rpc/protocol/rmi/RmiProtocolTest.java | 5 +- .../rpc/protocol/thrift/ThriftCodecTest.java | 2 +- .../base/AbstractSerializationTest.java | 8 +-- .../hessian2/Hessian2PersonOkTest.java | 1 - .../ProtostuffSerializationTest.java | 1 - .../SerializableClassRegistryTest.java | 1 - 63 files changed, 260 insertions(+), 269 deletions(-) diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/StickyTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/StickyTest.java index cb2656f33b9..34148202af1 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/StickyTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/StickyTest.java @@ -104,7 +104,7 @@ public void testMethodsSticky() { for (int i = 0; i < 100; i++) {//Two different methods should always use the same invoker every time. int count1 = testSticky("method1", true); int count2 = testSticky("method2", true); - Assertions.assertTrue(count1 == count2); + Assertions.assertEquals(count1, count2); } } @@ -129,7 +129,7 @@ public int testSticky(String methodName, boolean check) { int count = 0; for (int i = 0; i < runs; i++) { - Assertions.assertEquals(null, clusterinvoker.invoke(invocation)); + Assertions.assertNull(clusterinvoker.invoke(invocation)); if (invoker1 == clusterinvoker.getSelectedInvoker()) { count++; } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/ResultMergerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/ResultMergerTest.java index 788d1af160f..f27b958299e 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/ResultMergerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/ResultMergerTest.java @@ -81,7 +81,7 @@ public void testArrayMerger() { result = MergerFactory.getMerger(Integer[].class).merge(intArray1, intArray2, intArray3, null); Assertions.assertTrue(result.getClass().isArray()); Assertions.assertEquals(7, Array.getLength(result)); - Assertions.assertTrue(Integer.class == result.getClass().getComponentType()); + Assertions.assertSame(Integer.class, result.getClass().getComponentType()); for (int i = 0; i < 7; i++) { Assertions.assertEquals(i + 1, Array.get(result, i)); } @@ -170,7 +170,7 @@ public void testDoubleArrayMerger() { Assertions.assertEquals(4, result.length); double[] mergedResult = {1.2d, 3.5d, 2d, 34d}; for (int i = 0; i < mergedResult.length; i++) { - Assertions.assertTrue(mergedResult[i] == result[i]); + Assertions.assertEquals(mergedResult[i], result[i], 0.0); } result = MergerFactory.getMerger(double[].class).merge(null); @@ -191,7 +191,7 @@ public void testFloatArrayMerger() { Assertions.assertEquals(4, result.length); double[] mergedResult = {1.2f, 3.5f, 2f, 34f}; for (int i = 0; i < mergedResult.length; i++) { - Assertions.assertTrue(mergedResult[i] == result[i]); + Assertions.assertEquals(mergedResult[i], result[i], 0.0); } result = MergerFactory.getMerger(float[].class).merge(null); @@ -212,7 +212,7 @@ public void testIntArrayMerger() { Assertions.assertEquals(4, result.length); double[] mergedResult = {1, 2, 2, 34}; for (int i = 0; i < mergedResult.length; i++) { - Assertions.assertTrue(mergedResult[i] == result[i]); + Assertions.assertEquals(mergedResult[i], result[i], 0.0); } result = MergerFactory.getMerger(int[].class).merge(null); @@ -296,7 +296,7 @@ public void testLongArrayMerger() { Assertions.assertEquals(4, result.length); double[] mergedResult = {1l, 2l, 2l, 34l}; for (int i = 0; i < mergedResult.length; i++) { - Assertions.assertTrue(mergedResult[i] == result[i]); + Assertions.assertEquals(mergedResult[i], result[i], 0.0); } result = MergerFactory.getMerger(long[].class).merge(null); @@ -352,7 +352,7 @@ public void testShortArrayMerger() { Assertions.assertEquals(4, result.length); double[] mergedResult = {1, 2, 2, 34}; for (int i = 0; i < mergedResult.length; i++) { - Assertions.assertTrue(mergedResult[i] == result[i]); + Assertions.assertEquals(mergedResult[i], result[i], 0.0); } result = MergerFactory.getMerger(short[].class).merge(null); diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java index 76ffad19cae..a88a7591610 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java @@ -58,31 +58,31 @@ public void testRoute_matchWhen() { Router router = new ConditionRouterFactory().getRouter(getRouteUrl(" => host = 1.2.3.4")); boolean matchWhen = ((ConditionRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation); - Assertions.assertEquals(true, matchWhen); + Assertions.assertTrue(matchWhen); router = new ConditionRouterFactory().getRouter(getRouteUrl("host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4")); matchWhen = ((ConditionRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation); - Assertions.assertEquals(true, matchWhen); + Assertions.assertTrue(matchWhen); router = new ConditionRouterFactory().getRouter(getRouteUrl("host = 2.2.2.2,1.1.1.1,3.3.3.3 & host !=1.1.1.1 => host = 1.2.3.4")); matchWhen = ((ConditionRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation); - Assertions.assertEquals(false, matchWhen); + Assertions.assertFalse(matchWhen); router = new ConditionRouterFactory().getRouter(getRouteUrl("host !=4.4.4.4 & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4")); matchWhen = ((ConditionRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation); - Assertions.assertEquals(true, matchWhen); + Assertions.assertTrue(matchWhen); router = new ConditionRouterFactory().getRouter(getRouteUrl("host !=4.4.4.* & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4")); matchWhen = ((ConditionRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation); - Assertions.assertEquals(true, matchWhen); + Assertions.assertTrue(matchWhen); router = new ConditionRouterFactory().getRouter(getRouteUrl("host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.1 => host = 1.2.3.4")); matchWhen = ((ConditionRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation); - Assertions.assertEquals(false, matchWhen); + Assertions.assertFalse(matchWhen); router = new ConditionRouterFactory().getRouter(getRouteUrl("host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.2 => host = 1.2.3.4")); matchWhen = ((ConditionRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation); - Assertions.assertEquals(true, matchWhen); + Assertions.assertTrue(matchWhen); } @Test @@ -143,23 +143,23 @@ public void testRoute_methodRoute() { Router router = new ConditionRouterFactory().getRouter(getRouteUrl("methods=getFoo => host = 1.2.3.4")); boolean matchWhen = ((ConditionRouter) router).matchWhen( URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=setFoo,getFoo,findFoo"), invocation); - Assertions.assertEquals(true, matchWhen); + Assertions.assertTrue(matchWhen); // Exactly one method, match matchWhen = ((ConditionRouter) router).matchWhen( URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=getFoo"), invocation); - Assertions.assertEquals(true, matchWhen); + Assertions.assertTrue(matchWhen); // Method routing and Other condition routing can work together Router router2 = new ConditionRouterFactory() .getRouter(getRouteUrl("methods=getFoo & host!=1.1.1.1 => host = 1.2.3.4")); matchWhen = ((ConditionRouter) router2).matchWhen( URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=getFoo"), invocation); - Assertions.assertEquals(false, matchWhen); + Assertions.assertFalse(matchWhen); Router router3 = new ConditionRouterFactory() .getRouter(getRouteUrl("methods=getFoo & host=1.1.1.1 => host = 1.2.3.4")); matchWhen = ((ConditionRouter) router3).matchWhen( URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=getFoo"), invocation); - Assertions.assertEquals(true, matchWhen); + Assertions.assertTrue(matchWhen); // Test filter condition List> invokers = new ArrayList>(); Invoker invoker1 = new MockInvoker(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService")); diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java index 1ec574d022a..37402d8d9ae 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java @@ -174,13 +174,13 @@ public void testSelect_Invokersize0() throws Exception { Assertions.assertNotNull(l,"cluster.initLoadBalance returns null!"); { Invoker invoker = cluster.select(l, null, null, null); - Assertions.assertEquals(null, invoker); + Assertions.assertNull(invoker); } { invokers.clear(); selectedInvokers.clear(); Invoker invoker = cluster.select(l, null, invokers, null); - Assertions.assertEquals(null, invoker); + Assertions.assertNull(invoker); } } @@ -231,7 +231,7 @@ public void testCloseAvailablecheck() { initlistsize5(); Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers); - Assertions.assertEquals(false, sinvoker.isAvailable()); + Assertions.assertFalse(sinvoker.isAvailable()); Assertions.assertEquals(invoker1, sinvoker); } @@ -308,7 +308,7 @@ public void testSelectAgainAndCheckAvailable() { selectedInvokers.add(invoker3); selectedInvokers.add(invoker5); Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers); - Assertions.assertTrue(sinvoker == invoker4); + Assertions.assertSame(sinvoker, invoker4); } { //Boundary condition test . @@ -365,7 +365,7 @@ public void testSelect_multiInvokers(String lbname) throws Exception { initlistsize5(); for (int i = 0; i < runs; i++) { Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers); - Assertions.assertEquals(true, sinvoker.isAvailable()); + Assertions.assertTrue(sinvoker.isAvailable()); Mockito.clearInvocations(invoker1, invoker2, invoker3, invoker4, invoker5); } @@ -373,7 +373,7 @@ public void testSelect_multiInvokers(String lbname) throws Exception { selectedInvokers.clear(); selectedInvokers.add(invoker1); Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers); - Assertions.assertEquals(true, sinvoker.isAvailable()); + Assertions.assertTrue(sinvoker.isAvailable()); Mockito.clearInvocations(invoker1, invoker2, invoker3, invoker4, invoker5); } @@ -381,7 +381,7 @@ public void testSelect_multiInvokers(String lbname) throws Exception { selectedInvokers.clear(); selectedInvokers.add(invoker2); Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers); - Assertions.assertEquals(true, sinvoker.isAvailable()); + Assertions.assertTrue(sinvoker.isAvailable()); Mockito.clearInvocations(invoker1, invoker2, invoker3, invoker4, invoker5); } @@ -390,7 +390,7 @@ public void testSelect_multiInvokers(String lbname) throws Exception { selectedInvokers.add(invoker2); selectedInvokers.add(invoker4); Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers); - Assertions.assertEquals(true, sinvoker.isAvailable()); + Assertions.assertTrue(sinvoker.isAvailable()); Mockito.clearInvocations(invoker1, invoker2, invoker3, invoker4, invoker5); } @@ -400,7 +400,7 @@ public void testSelect_multiInvokers(String lbname) throws Exception { selectedInvokers.add(invoker3); selectedInvokers.add(invoker5); Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers); - Assertions.assertEquals(true, sinvoker.isAvailable()); + Assertions.assertTrue(sinvoker.isAvailable()); Mockito.clearInvocations(invoker1, invoker2, invoker3, invoker4, invoker5); } @@ -411,7 +411,7 @@ public void testSelect_multiInvokers(String lbname) throws Exception { selectedInvokers.add(invoker2); selectedInvokers.add(invoker3); Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers); - Assertions.assertEquals(true, sinvoker.isAvailable()); + Assertions.assertTrue(sinvoker.isAvailable()); Mockito.clearInvocations(invoker1, invoker2, invoker3, invoker4, invoker5); } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java index 9bc5686efd9..c133d353571 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java @@ -74,7 +74,7 @@ public void testMockInvokerInvoke_normal() { invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); ret = cluster.invoke(invocation); - Assertions.assertEquals(null, ret.getValue()); + Assertions.assertNull(ret.getValue()); } /** @@ -102,13 +102,13 @@ public void testMockInvokerInvoke_failmock() { invocation = new RpcInvocation(); invocation.setMethodName("getSomething2"); ret = cluster.invoke(invocation); - Assertions.assertEquals(null, ret.getValue()); + Assertions.assertNull(ret.getValue()); // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); ret = cluster.invoke(invocation); - Assertions.assertEquals(null, ret.getValue()); + Assertions.assertNull(ret.getValue()); } @@ -138,13 +138,13 @@ public void testMockInvokerInvoke_forcemock() { invocation = new RpcInvocation(); invocation.setMethodName("getSomething2"); ret = cluster.invoke(invocation); - Assertions.assertEquals(null, ret.getValue()); + Assertions.assertNull(ret.getValue()); // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); ret = cluster.invoke(invocation); - Assertions.assertEquals(null, ret.getValue()); + Assertions.assertNull(ret.getValue()); } @Test @@ -163,7 +163,7 @@ public void testMockInvokerInvoke_forcemock_defaultreturn() { RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); Result ret = cluster.invoke(invocation); - Assertions.assertEquals(null, ret.getValue()); + Assertions.assertNull(ret.getValue()); } /** @@ -197,7 +197,7 @@ public void testMockInvokerFromOverride_Invoke_Fock_someMethods() { invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); ret = cluster.invoke(invocation); - Assertions.assertEquals(null, ret.getValue()); + Assertions.assertNull(ret.getValue()); } /** @@ -260,13 +260,13 @@ public void testMockInvokerFromOverride_Invoke_Fock_WithDefault() { invocation = new RpcInvocation(); invocation.setMethodName("getSomething3"); ret = cluster.invoke(invocation); - Assertions.assertEquals(null, ret.getValue()); + Assertions.assertNull(ret.getValue()); // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); ret = cluster.invoke(invocation); - Assertions.assertEquals(null, ret.getValue()); + Assertions.assertNull(ret.getValue()); } /** @@ -481,7 +481,7 @@ public void testMockInvokerFromOverride_Invoke_check_boolean() { invocation.setMethodName("getBoolean1"); Result ret = cluster.invoke(invocation); Assertions.assertTrue(ret.getValue() instanceof Boolean, "result type must be Boolean but was : " + ret.getValue().getClass()); - Assertions.assertEquals(true, Boolean.parseBoolean(ret.getValue().toString())); + Assertions.assertTrue(Boolean.parseBoolean(ret.getValue().toString())); } @Test @@ -494,7 +494,7 @@ public void testMockInvokerFromOverride_Invoke_check_Boolean() { RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getBoolean2"); Result ret = cluster.invoke(invocation); - Assertions.assertEquals(true, Boolean.parseBoolean(ret.getValue().toString())); + Assertions.assertTrue(Boolean.parseBoolean(ret.getValue().toString())); } @SuppressWarnings("unchecked") diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/URLTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/URLTest.java index a74f7baa974..377bf893cca 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/URLTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/URLTest.java @@ -72,7 +72,7 @@ public void test_valueOf_noProtocol() throws Exception { assertNull(url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals(0, url.getPort()); - assertEquals(null, url.getPath()); + assertNull(url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("10.20.130.230:20880"); @@ -81,7 +81,7 @@ public void test_valueOf_noProtocol() throws Exception { assertNull(url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals(20880, url.getPort()); - assertEquals(null, url.getPath()); + assertNull(url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("10.20.130.230/context/path"); @@ -190,7 +190,7 @@ public void test_valueOf_WithProtocolHost() throws Exception { assertNull(url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals(0, url.getPort()); - assertEquals(null, url.getPath()); + assertNull(url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("dubbo://10.20.130.230:20880/context/path"); @@ -208,7 +208,7 @@ public void test_valueOf_WithProtocolHost() throws Exception { assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals(20880, url.getPort()); - assertEquals(null, url.getPath()); + assertNull(url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880?version=1.0.0"); @@ -217,7 +217,7 @@ public void test_valueOf_WithProtocolHost() throws Exception { assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals(20880, url.getPort()); - assertEquals(null, url.getPath()); + assertNull(url.getPath()); assertEquals(1, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); @@ -282,7 +282,7 @@ public void test_getAddress() throws Exception { @Test public void test_getAbsolutePath() throws Exception { URL url = new URL("p1", "1.2.2.2", 33); - assertEquals(null, url.getAbsolutePath()); + assertNull(url.getAbsolutePath()); url = new URL("file", null, 90, "/home/user1/route.js"); assertEquals("/home/user1/route.js", url.getAbsolutePath()); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java index 4b3654a73d5..68c7100f32b 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java @@ -54,7 +54,7 @@ public void testSerialize_Primitive() { public void testSerialize_Primitive_NUll() { JavaBeanDescriptor descriptor; descriptor = JavaBeanSerializeUtil.serialize(null); - Assertions.assertTrue(descriptor == null); + Assertions.assertNull(descriptor); } @Test @@ -146,7 +146,7 @@ public void testGetPrimitiveProperty() { public void testDeserialize_get_and_set() { JavaBeanDescriptor descriptor = new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_BEAN); descriptor.setType(JavaBeanDescriptor.TYPE_PRIMITIVE); - Assertions.assertTrue(descriptor.getType() == JavaBeanDescriptor.TYPE_PRIMITIVE); + Assertions.assertEquals(descriptor.getType(), JavaBeanDescriptor.TYPE_PRIMITIVE); descriptor.setClassName(JavaBeanDescriptor.class.getName()); Assertions.assertEquals(JavaBeanDescriptor.class.getName(), descriptor.getClassName()); } @@ -169,7 +169,7 @@ public void testSerialize_Array() { Assertions.assertEquals(integers.length, descriptor.propertySize()); for (int i = 0; i < integers.length; i++) { if (integers[i] == null) { - Assertions.assertTrue(integers[i] == descriptor.getProperty(i)); + Assertions.assertSame(integers[i], descriptor.getProperty(i)); } else { Assertions.assertEquals(integers[i], ((JavaBeanDescriptor) descriptor.getProperty(i)).getPrimitiveProperty()); } @@ -215,7 +215,7 @@ public void testConstructorArg() { Assertions.assertEquals((double) 0, JavaBeanSerializeUtil.getConstructorArg(Double.class)); Assertions.assertEquals((char) 0, JavaBeanSerializeUtil.getConstructorArg(char.class)); Assertions.assertEquals(new Character((char) 0), JavaBeanSerializeUtil.getConstructorArg(Character.class)); - Assertions.assertEquals(null, JavaBeanSerializeUtil.getConstructorArg(JavaBeanSerializeUtil.class)); + Assertions.assertNull(JavaBeanSerializeUtil.getConstructorArg(JavaBeanSerializeUtil.class)); } @Test @@ -228,7 +228,7 @@ public void testDeserialize_Array() { Object obj = JavaBeanSerializeUtil.deserialize(descriptor); Assertions.assertTrue(obj.getClass().isArray()); - Assertions.assertTrue(int.class == obj.getClass().getComponentType()); + Assertions.assertSame(int.class, obj.getClass().getComponentType()); for (int i = 0; i < len; i++) { Assertions.assertEquals(i, Array.get(obj, i)); } @@ -290,7 +290,7 @@ public void test_Circular_Reference() { assertEqualsPrimitive(parent.getEmail(), descriptor.getProperty("email")); JavaBeanDescriptor childDescriptor = (JavaBeanDescriptor) descriptor.getProperty("child"); - Assertions.assertTrue(descriptor == childDescriptor.getProperty("parent")); + Assertions.assertSame(descriptor, childDescriptor.getProperty("parent")); assertEqualsPrimitive(child.getName(), childDescriptor.getProperty("name")); assertEqualsPrimitive(child.getAge(), childDescriptor.getProperty("age")); } @@ -385,7 +385,7 @@ public void testDeserializeBean() { public void testSerializeJavaBeanDescriptor() { JavaBeanDescriptor descriptor = new JavaBeanDescriptor(); JavaBeanDescriptor result = JavaBeanSerializeUtil.serialize(descriptor); - Assertions.assertTrue(descriptor == result); + Assertions.assertSame(descriptor, result); Map map = new HashMap(); map.put("first", descriptor); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/MixinTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/MixinTest.java index 5ed7a6eff22..954ea51fdaa 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/MixinTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/MixinTest.java @@ -19,6 +19,7 @@ import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MixinTest { @@ -26,9 +27,9 @@ public class MixinTest { public void testMain() throws Exception { Mixin mixin = Mixin.mixin(new Class[]{I1.class, I2.class, I3.class}, new Class[]{C1.class, C2.class}); Object o = mixin.newInstance(new Object[]{new C1(), new C2()}); - assertEquals(o instanceof I1, true); - assertEquals(o instanceof I2, true); - assertEquals(o instanceof I3, true); + assertTrue(o instanceof I1); + assertTrue(o instanceof I2); + assertTrue(o instanceof I3); ((I1) o).m1(); ((I2) o).m2(); ((I3) o).m3(); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/WrapperTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/WrapperTest.java index ab5dff43393..03e7e318aba 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/WrapperTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/WrapperTest.java @@ -74,9 +74,9 @@ public void testHasMethod() throws Exception { @Test public void testWrapperObject() throws Exception { Wrapper w = Wrapper.getWrapper(Object.class); - Assertions.assertTrue(w.getMethodNames().length == 4); - Assertions.assertTrue(w.getPropertyNames().length == 0); - Assertions.assertEquals(null, w.getPropertyType(null)); + Assertions.assertEquals(4, w.getMethodNames().length); + Assertions.assertEquals(0, w.getPropertyNames().length); + Assertions.assertNull(w.getPropertyType(null)); } @Test @@ -102,7 +102,7 @@ public void testInvokeWrapperObject() throws Exception { Assertions.assertEquals(instance.getClass(), (Class) w.invokeMethod(instance, "getClass", null, null)); Assertions.assertEquals(instance.hashCode(), (int) w.invokeMethod(instance, "hashCode", null, null)); Assertions.assertEquals(instance.toString(), (String) w.invokeMethod(instance, "toString", null, null)); - Assertions.assertEquals(true, (boolean) w.invokeMethod(instance, "equals", null, new Object[]{instance})); + Assertions.assertTrue((boolean)w.invokeMethod(instance, "equals", null, new Object[] {instance})); } @Test diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/ClassUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/ClassUtilsTest.java index 8acf00bfeef..3f9a26bcb3d 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/ClassUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/ClassUtilsTest.java @@ -104,7 +104,7 @@ public void testBoxedAndUnboxed() { Assertions.assertEquals(Float.valueOf((float) 0), ClassUtils.boxed((float) 0)); Assertions.assertEquals(Double.valueOf((double) 0), ClassUtils.boxed((double) 0)); - Assertions.assertEquals(true, ClassUtils.unboxed(Boolean.valueOf(true))); + Assertions.assertTrue(ClassUtils.unboxed(Boolean.valueOf(true))); Assertions.assertEquals('0', ClassUtils.unboxed(Character.valueOf('0'))); Assertions.assertEquals((byte) 0, ClassUtils.unboxed(Byte.valueOf((byte) 0))); Assertions.assertEquals((short) 0, ClassUtils.unboxed(Short.valueOf((short) 0))); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoaderTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoaderTest.java index 89312eaf32e..f04ca89168b 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoaderTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoaderTest.java @@ -373,14 +373,14 @@ public void testLoadActivateExtension() throws Exception { List list = ExtensionLoader.getExtensionLoader(ActivateExt1.class) .getActivateExtension(url, new String[]{}, "default_group"); Assertions.assertEquals(1, list.size()); - Assertions.assertTrue(list.get(0).getClass() == ActivateExt1Impl1.class); + Assertions.assertSame(list.get(0).getClass(), ActivateExt1Impl1.class); // test group url = url.addParameter(GROUP_KEY, "group1"); list = ExtensionLoader.getExtensionLoader(ActivateExt1.class) .getActivateExtension(url, new String[]{}, "group1"); Assertions.assertEquals(1, list.size()); - Assertions.assertTrue(list.get(0).getClass() == GroupActivateExtImpl.class); + Assertions.assertSame(list.get(0).getClass(), GroupActivateExtImpl.class); // test old @Activate group url = url.addParameter(GROUP_KEY, "old_group"); @@ -397,7 +397,7 @@ public void testLoadActivateExtension() throws Exception { list = ExtensionLoader.getExtensionLoader(ActivateExt1.class) .getActivateExtension(url, new String[]{}, "value"); Assertions.assertEquals(1, list.size()); - Assertions.assertTrue(list.get(0).getClass() == ValueActivateExtImpl.class); + Assertions.assertSame(list.get(0).getClass(), ValueActivateExtImpl.class); // test order url = URL.valueOf("test://localhost/test"); @@ -405,8 +405,8 @@ public void testLoadActivateExtension() throws Exception { list = ExtensionLoader.getExtensionLoader(ActivateExt1.class) .getActivateExtension(url, new String[]{}, "order"); Assertions.assertEquals(2, list.size()); - Assertions.assertTrue(list.get(0).getClass() == OrderActivateExtImpl1.class); - Assertions.assertTrue(list.get(1).getClass() == OrderActivateExtImpl2.class); + Assertions.assertSame(list.get(0).getClass(), OrderActivateExtImpl1.class); + Assertions.assertSame(list.get(1).getClass(), OrderActivateExtImpl2.class); } @Test @@ -416,15 +416,15 @@ public void testLoadDefaultActivateExtension() throws Exception { List list = ExtensionLoader.getExtensionLoader(ActivateExt1.class) .getActivateExtension(url, "ext", "default_group"); Assertions.assertEquals(2, list.size()); - Assertions.assertTrue(list.get(0).getClass() == OrderActivateExtImpl1.class); - Assertions.assertTrue(list.get(1).getClass() == ActivateExt1Impl1.class); + Assertions.assertSame(list.get(0).getClass(), OrderActivateExtImpl1.class); + Assertions.assertSame(list.get(1).getClass(), ActivateExt1Impl1.class); url = URL.valueOf("test://localhost/test?ext=default,order1"); list = ExtensionLoader.getExtensionLoader(ActivateExt1.class) .getActivateExtension(url, "ext", "default_group"); Assertions.assertEquals(2, list.size()); - Assertions.assertTrue(list.get(0).getClass() == ActivateExt1Impl1.class); - Assertions.assertTrue(list.get(1).getClass() == OrderActivateExtImpl1.class); + Assertions.assertSame(list.get(0).getClass(), ActivateExt1Impl1.class); + Assertions.assertSame(list.get(1).getClass(), OrderActivateExtImpl1.class); } @Test diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/ActivateComparatorTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/ActivateComparatorTest.java index 9181766fc7f..8b9a1d6399f 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/ActivateComparatorTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/ActivateComparatorTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.extension.support; -import org.apache.dubbo.common.extension.Activate; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/json/JSONTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/json/JSONTest.java index 0a7f9063f33..98c342c2500 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/json/JSONTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/json/JSONTest.java @@ -28,6 +28,8 @@ import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; @Deprecated public class JSONTest { @@ -121,7 +123,7 @@ public void testParse2JSONObject() throws Exception { assertEquals(jo.getString("name"), "qianlei"); assertEquals(jo.getArray("array").length(), 5); assertEquals(jo.get("$2"), Boolean.FALSE); - assertEquals(jo.get("__3"), null); + assertNull(jo.get("__3")); for (int i = 0; i < 10000; i++) JSON.parse("{\"name\":\"qianlei\",\"array\":[1,2,3,4,98.123],\"displayName\":\"钱磊\"}"); @@ -150,7 +152,7 @@ public void testParse2Class() throws Exception { assertEquals(bean.getDisplayName(), "钱磊"); assertEquals(bean.array.length, 5); assertEquals(bean.$$, 214726); - assertEquals(bean.$b, true); + assertTrue(bean.$b); for (int i = 0; i < 10000; i++) JSON.parse("{name:'qianlei',array:[1,2,3,4,98.123],displayName:'钱磊'}", Bean1.class); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/threadlocal/InternalThreadLocalTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/threadlocal/InternalThreadLocalTest.java index 60067a3b737..8c63ec0aec6 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/threadlocal/InternalThreadLocalTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/threadlocal/InternalThreadLocalTest.java @@ -60,26 +60,26 @@ protected Integer initialValue() throws Exception { public void testRemoveAll() throws InterruptedException { final InternalThreadLocal internalThreadLocal = new InternalThreadLocal(); internalThreadLocal.set(1); - Assertions.assertTrue(internalThreadLocal.get() == 1, "set failed"); + Assertions.assertEquals(1, (int)internalThreadLocal.get(), "set failed"); final InternalThreadLocal internalThreadLocalString = new InternalThreadLocal(); internalThreadLocalString.set("value"); - Assertions.assertTrue("value".equals(internalThreadLocalString.get()), "set failed"); + Assertions.assertEquals("value", internalThreadLocalString.get(), "set failed"); InternalThreadLocal.removeAll(); - Assertions.assertTrue(internalThreadLocal.get() == null, "removeAll failed!"); - Assertions.assertTrue(internalThreadLocalString.get() == null, "removeAll failed!"); + Assertions.assertNull(internalThreadLocal.get(), "removeAll failed!"); + Assertions.assertNull(internalThreadLocalString.get(), "removeAll failed!"); } @Test public void testSize() throws InterruptedException { final InternalThreadLocal internalThreadLocal = new InternalThreadLocal(); internalThreadLocal.set(1); - Assertions.assertTrue(InternalThreadLocal.size() == 1, "size method is wrong!"); + Assertions.assertEquals(1, InternalThreadLocal.size(), "size method is wrong!"); final InternalThreadLocal internalThreadLocalString = new InternalThreadLocal(); internalThreadLocalString.set("value"); - Assertions.assertTrue(InternalThreadLocal.size() == 2, "size method is wrong!"); + Assertions.assertEquals(2, InternalThreadLocal.size(), "size method is wrong!"); } @Test @@ -87,18 +87,17 @@ public void testSetAndGet() { final Integer testVal = 10; final InternalThreadLocal internalThreadLocal = new InternalThreadLocal(); internalThreadLocal.set(testVal); - Assertions.assertTrue( - Objects.equals(testVal, internalThreadLocal.get()), "set is not equals get"); + Assertions.assertEquals(testVal, internalThreadLocal.get(), "set is not equals get"); } @Test public void testRemove() { final InternalThreadLocal internalThreadLocal = new InternalThreadLocal(); internalThreadLocal.set(1); - Assertions.assertTrue(internalThreadLocal.get() == 1, "get method false!"); + Assertions.assertEquals(1, (int)internalThreadLocal.get(), "get method false!"); internalThreadLocal.remove(); - Assertions.assertTrue(internalThreadLocal.get() == null, "remove failed!"); + Assertions.assertNull(internalThreadLocal.get(), "remove failed!"); } @Test @@ -112,10 +111,10 @@ protected void onRemoval(Integer value) throws Exception { } }; internalThreadLocal.set(1); - Assertions.assertTrue(internalThreadLocal.get() == 1, "get method false!"); + Assertions.assertEquals(1, (int)internalThreadLocal.get(), "get method false!"); internalThreadLocal.remove(); - Assertions.assertTrue(valueToRemove[0] == 2, "onRemove method failed!"); + Assertions.assertEquals(2, (int)valueToRemove[0], "onRemove method failed!"); } @Test @@ -129,8 +128,7 @@ public void testMultiThreadSetAndGet() throws InterruptedException { public void run() { internalThreadLocal.set(testVal1); - Assertions.assertTrue( - Objects.equals(testVal1, internalThreadLocal.get()), "set is not equals get"); + Assertions.assertEquals(testVal1, internalThreadLocal.get(), "set is not equals get"); countDownLatch.countDown(); } }); @@ -140,8 +138,7 @@ public void run() { @Override public void run() { internalThreadLocal.set(testVal2); - Assertions.assertTrue( - Objects.equals(testVal2, internalThreadLocal.get()), "set is not equals get"); + Assertions.assertEquals(testVal2, internalThreadLocal.get(), "set is not equals get"); countDownLatch.countDown(); } }); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/threadlocal/NamedInternalThreadFactoryTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/threadlocal/NamedInternalThreadFactoryTest.java index 7b9619f12b2..346da3a5236 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/threadlocal/NamedInternalThreadFactoryTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/threadlocal/NamedInternalThreadFactoryTest.java @@ -31,6 +31,6 @@ public void run() { } }); - Assertions.assertTrue(t.getClass().equals(InternalThread.class), "thread is not InternalThread"); + Assertions.assertEquals(t.getClass(), InternalThread.class, "thread is not InternalThread"); } } \ No newline at end of file diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolExecutorTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolExecutorTest.java index ddbe8a0580c..c7d610f2c05 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolExecutorTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolExecutorTest.java @@ -90,7 +90,7 @@ public void run() { } Thread.sleep(5000); // cores theads are all alive. - Assertions.assertTrue(executor.getPoolSize() == cores, "more than cores threads alive!"); + Assertions.assertEquals(executor.getPoolSize(), cores, "more than cores threads alive!"); } @Test @@ -98,9 +98,7 @@ public void testSPI() { ExecutorService executorService = (ExecutorService) ExtensionLoader.getExtensionLoader(ThreadPool.class) .getExtension("eager") .getExecutor(URL); - Assertions.assertTrue( - executorService.getClass() - .getSimpleName() - .equals("EagerThreadPoolExecutor"), "test spi fail!"); + Assertions.assertEquals("EagerThreadPoolExecutor", executorService.getClass() + .getSimpleName(), "test spi fail!"); } } \ No newline at end of file diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CompatibleTypeUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CompatibleTypeUtilsTest.java index ff1ebd58cd7..30b1d44e211 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CompatibleTypeUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CompatibleTypeUtilsTest.java @@ -86,7 +86,7 @@ public void testCompatibleTypeConvert() throws Exception { assertEquals(0, ((char[]) result).length); result = CompatibleTypeUtils.compatibleTypeConvert(null, char[].class); - assertEquals(null, result); + assertNull(result); } { diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MethodUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MethodUtilsTest.java index cc15d111690..817eb2d6943 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MethodUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MethodUtilsTest.java @@ -32,7 +32,7 @@ public void testGetMethod() { } } Assertions.assertNotNull(getMethod); - Assertions.assertTrue(getMethod.getName().equals("getValue")); + Assertions.assertEquals("getValue", getMethod.getName()); } @Test @@ -44,7 +44,7 @@ public void testSetMethod() { } } Assertions.assertNotNull(setMethod); - Assertions.assertTrue(setMethod.getName().equals("setValue")); + Assertions.assertEquals("setValue", setMethod.getName()); } public class MethodTestClazz { diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/PojoUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/PojoUtilsTest.java index dcaad275ea1..3595efb99f6 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/PojoUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/PojoUtilsTest.java @@ -560,9 +560,9 @@ public void testMapField() throws Exception { Object obj = PojoUtils.generalize(data); Assertions.assertEquals(3, data.getChildren().size()); - assertTrue(data.getChildren().get("first").getClass() == Child.class); + assertSame(data.getChildren().get("first").getClass(), Child.class); Assertions.assertEquals(1, data.getList().size()); - assertTrue(data.getList().get(0).getClass() == Child.class); + assertSame(data.getList().get(0).getClass(), Child.class); TestData realizadData = (TestData) PojoUtils.realize(obj, TestData.class); Assertions.assertEquals(data.getChildren().size(), realizadData.getChildren().size()); @@ -620,7 +620,7 @@ public void testPojoList() throws Exception { assertTrue(realizeObject instanceof ListResult); ListResult listResult = (ListResult) realizeObject; List l = listResult.getResult(); - assertTrue(l.size() == 1); + assertEquals(1, l.size()); assertTrue(l.get(0) instanceof Parent); Parent realizeParent = (Parent) l.get(0); Assertions.assertEquals(parent.getName(), realizeParent.getName()); diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/MethodConfigTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/MethodConfigTest.java index 06eada996ec..9c811f5c9e6 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/MethodConfigTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/MethodConfigTest.java @@ -42,6 +42,7 @@ import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; public class MethodConfigTest { @@ -114,7 +115,7 @@ public void testConverMethodConfig2AsyncInfo() throws Exception{ ConsumerMethodModel.AsyncMethodInfo methodInfo = org.apache.dubbo.config.MethodConfig.convertMethodConfig2AyncInfo(methodConfig); - assertTrue(methodInfo.getOninvokeMethod().equals( Person.class.getMethod("setName", String.class))); + assertEquals(methodInfo.getOninvokeMethod(), Person.class.getMethod("setName", String.class)); } @Test diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java index d1e02636dd7..b77a33cbf56 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java @@ -133,13 +133,13 @@ public void testReferenceRetry() { public void testConstructWithReferenceAnnotation() throws NoSuchFieldException { Reference reference = getClass().getDeclaredField("innerTest").getAnnotation(Reference.class); ReferenceConfig referenceConfig = new ReferenceConfig(reference); - Assertions.assertTrue(referenceConfig.getMethods().size() == 1); + Assertions.assertEquals(1, referenceConfig.getMethods().size()); Assertions.assertEquals(((MethodConfig) referenceConfig.getMethods().get(0)).getName(), "sayHello"); - Assertions.assertTrue(((MethodConfig) referenceConfig.getMethods().get(0)).getTimeout() == 1300); - Assertions.assertTrue(((MethodConfig) referenceConfig.getMethods().get(0)).getRetries() == 4); + Assertions.assertEquals(1300, (int)((MethodConfig)referenceConfig.getMethods().get(0)).getTimeout()); + Assertions.assertEquals(4, (int)((MethodConfig)referenceConfig.getMethods().get(0)).getRetries()); Assertions.assertEquals(((MethodConfig) referenceConfig.getMethods().get(0)).getLoadbalance(), "random"); - Assertions.assertTrue(((MethodConfig) referenceConfig.getMethods().get(0)).getActives() == 3); - Assertions.assertTrue(((MethodConfig) referenceConfig.getMethods().get(0)).getExecutes() == 5); + Assertions.assertEquals(3, (int)((MethodConfig)referenceConfig.getMethods().get(0)).getActives()); + Assertions.assertEquals(5, (int)((MethodConfig)referenceConfig.getMethods().get(0)).getExecutes()); Assertions.assertTrue(((MethodConfig) referenceConfig.getMethods().get(0)).isAsync()); Assertions.assertEquals(((MethodConfig) referenceConfig.getMethods().get(0)).getOninvoke(), "i"); Assertions.assertEquals(((MethodConfig) referenceConfig.getMethods().get(0)).getOnreturn(), "r"); diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationPropertyValuesAdapterTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationPropertyValuesAdapterTest.java index 5c0570e4ffc..70f3a963a3e 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationPropertyValuesAdapterTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationPropertyValuesAdapterTest.java @@ -131,11 +131,11 @@ public Map convert(String[] source) { Assert.assertEquals(data, referenceBean.getParameters()); // Bean compare - Assert.assertEquals(null, referenceBean.getApplication()); - Assert.assertEquals(null, referenceBean.getModule()); - Assert.assertEquals(null, referenceBean.getConsumer()); - Assert.assertEquals(null, referenceBean.getMonitor()); - Assert.assertEquals(null, referenceBean.getRegistry()); + Assert.assertNull(referenceBean.getApplication()); + Assert.assertNull(referenceBean.getModule()); + Assert.assertNull(referenceBean.getConsumer()); + Assert.assertNull(referenceBean.getMonitor()); + Assert.assertNull(referenceBean.getRegistry()); } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceBeanBuilderTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceBeanBuilderTest.java index 069de915a67..13f1e00a2c8 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceBeanBuilderTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceBeanBuilderTest.java @@ -82,7 +82,7 @@ public void testBuild() throws Exception { Assert.assertEquals(true, referenceBean.isGeneric()); Assert.assertNull(referenceBean.isInjvm()); Assert.assertEquals(false, referenceBean.isCheck()); - Assert.assertEquals(null, referenceBean.isInit()); + Assert.assertNull(referenceBean.isInit()); Assert.assertEquals(true, referenceBean.getLazy()); Assert.assertEquals(true, referenceBean.getStubevent()); Assert.assertEquals("reconnect", referenceBean.getReconnect()); diff --git a/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/filter/CacheFilterTest.java b/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/filter/CacheFilterTest.java index 217919f1d6f..332683358cc 100644 --- a/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/filter/CacheFilterTest.java +++ b/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/filter/CacheFilterTest.java @@ -131,7 +131,7 @@ public void testNull(String cacheType, CacheFactory cacheFactory) { cacheFilter.invoke(invoker4, invocation); Result result1 = cacheFilter.invoke(invoker1, invocation); Result result2 = cacheFilter.invoke(invoker2, invocation); - Assertions.assertEquals(result1.getValue(), null); - Assertions.assertEquals(result2.getValue(), null); + Assertions.assertNull(result1.getValue()); + Assertions.assertNull(result2.getValue()); } } diff --git a/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/JValidationTest.java b/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/JValidationTest.java index 4531efd0fd9..fbace3f21bd 100644 --- a/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/JValidationTest.java +++ b/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/JValidationTest.java @@ -24,7 +24,6 @@ import org.junit.jupiter.api.Test; import javax.validation.ValidationException; -import java.io.NotSerializableException; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/identifier/MetadataIdentifierTest.java b/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/identifier/MetadataIdentifierTest.java index 2467571ec29..c660a34cd21 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/identifier/MetadataIdentifierTest.java +++ b/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/identifier/MetadataIdentifierTest.java @@ -21,7 +21,6 @@ import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; -import static org.apache.dubbo.metadata.identifier.MetadataIdentifier.META_DATA_STORE_TAG; /** * 2019/1/7 diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportTest.java b/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportTest.java index d74c7905437..8a1ff7fdf26 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportTest.java +++ b/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportTest.java @@ -113,7 +113,7 @@ public void testRetry() throws InterruptedException, ClassNotFoundException { retryReport.metadataReportRetry.retryPeriod = 400L; URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic"); Assertions.assertNull(retryReport.metadataReportRetry.retryScheduledFuture); - Assertions.assertTrue(retryReport.metadataReportRetry.retryCounter.get() == 0); + Assertions.assertEquals(0,retryReport.metadataReportRetry.retryCounter.get()); Assertions.assertTrue(retryReport.store.isEmpty()); Assertions.assertTrue(retryReport.failedReports.isEmpty()); @@ -207,16 +207,16 @@ public void testPublishAll() throws ClassNotFoundException, InterruptedException Map tmpMapResult = (Map) abstractMetadataReport.allMetadataReports.get(consumerMetadataIdentifier); Assertions.assertEquals(tmpMapResult.get("testPKey"), "9090"); Assertions.assertEquals(tmpMapResult.get("testKey"), "value"); - Assertions.assertTrue(abstractMetadataReport.store.size() == 3); + Assertions.assertEquals(3,abstractMetadataReport.store.size()); abstractMetadataReport.store.clear(); - Assertions.assertTrue(abstractMetadataReport.store.size() == 0); + Assertions.assertEquals(0,abstractMetadataReport.store.size()); abstractMetadataReport.publishAll(); Thread.sleep(200); - Assertions.assertTrue(abstractMetadataReport.store.size() == 3); + Assertions.assertEquals(3,abstractMetadataReport.store.size()); String v = abstractMetadataReport.store.get(providerMetadataIdentifier1.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY)); Gson gson = new Gson(); diff --git a/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java b/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java index 56d372c1d2b..a24711fddaf 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java +++ b/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java @@ -133,7 +133,7 @@ public void testFilter() throws Exception { Assertions.assertEquals("aaa", lastStatistics.getParameter(MonitorService.METHOD)); Assertions.assertEquals(NetUtils.getLocalHost() + ":20880", lastStatistics.getParameter(MonitorService.PROVIDER)); Assertions.assertEquals(NetUtils.getLocalHost(), lastStatistics.getAddress()); - Assertions.assertEquals(null, lastStatistics.getParameter(MonitorService.CONSUMER)); + Assertions.assertNull(lastStatistics.getParameter(MonitorService.CONSUMER)); Assertions.assertEquals(1, lastStatistics.getParameter(MonitorService.SUCCESS, 0)); Assertions.assertEquals(0, lastStatistics.getParameter(MonitorService.FAILURE, 0)); Assertions.assertEquals(1, lastStatistics.getParameter(MonitorService.CONCURRENT, 0)); @@ -173,7 +173,7 @@ public void testGenericFilter() throws Exception { Assertions.assertEquals("xxx", lastStatistics.getParameter(MonitorService.METHOD)); Assertions.assertEquals(NetUtils.getLocalHost() + ":20880", lastStatistics.getParameter(MonitorService.PROVIDER)); Assertions.assertEquals(NetUtils.getLocalHost(), lastStatistics.getAddress()); - Assertions.assertEquals(null, lastStatistics.getParameter(MonitorService.CONSUMER)); + Assertions.assertNull(lastStatistics.getParameter(MonitorService.CONSUMER)); Assertions.assertEquals(1, lastStatistics.getParameter(MonitorService.SUCCESS, 0)); Assertions.assertEquals(0, lastStatistics.getParameter(MonitorService.FAILURE, 0)); Assertions.assertEquals(1, lastStatistics.getParameter(MonitorService.CONCURRENT, 0)); diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/util/CommandHelperTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/util/CommandHelperTest.java index c45c0f78185..8f6ebc5bb9d 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/util/CommandHelperTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/util/CommandHelperTest.java @@ -22,7 +22,6 @@ import org.apache.dubbo.qos.command.impl.Offline; import org.apache.dubbo.qos.command.impl.Online; import org.apache.dubbo.qos.command.impl.Quit; -import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import java.util.List; diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/PerformanceRegistryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/PerformanceRegistryTest.java index a71cd39dc45..7d5b7316384 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/PerformanceRegistryTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/PerformanceRegistryTest.java @@ -22,7 +22,6 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NetUtils; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryTest.java index 6f42a8d4fcf..8b57cba6ddc 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryTest.java @@ -550,7 +550,7 @@ public void getCacheUrlsTest() { abstractRegistry.notify(testUrl, listener, urls); Assertions.assertTrue(notifySuccess); List cacheUrl = abstractRegistry.getCacheUrls(testUrl); - Assertions.assertTrue(cacheUrl.size() == 1); + Assertions.assertEquals(1,cacheUrl.size()); URL nullUrl = URL.valueOf("http://1.2.3.4:9090/registry?check=false&file=N/A&interface=com.testa"); cacheUrl = abstractRegistry.getCacheUrls(nullUrl); Assertions.assertTrue(Objects.isNull(cacheUrl)); diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/FailbackRegistryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/FailbackRegistryTest.java index 3e4843328a6..ddcc783ef9f 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/FailbackRegistryTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/FailbackRegistryTest.java @@ -203,7 +203,7 @@ public void notify(List urls) { countDownLatch.await(); Assertions.assertEquals(0, mockRegistry.getFailedRegistered().size()); FailbackRegistry.Holder h = new FailbackRegistry.Holder(registryUrl, listener); - Assertions.assertEquals(null, mockRegistry.getFailedSubscribed().get(h)); + Assertions.assertNull(mockRegistry.getFailedSubscribed().get(h)); Assertions.assertEquals(countDownLatch.getCount(), 0); } diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java index 5b9123ff587..7bf8197bff4 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java @@ -102,7 +102,7 @@ private RegistryDirectory getRegistryDirectory(URL url) { // asert empty List invokers = registryDirectory.list(invocation); Assertions.assertEquals(0, invokers.size()); - Assertions.assertEquals(false, registryDirectory.isAvailable()); + Assertions.assertFalse(registryDirectory.isAvailable()); return registryDirectory; } @@ -164,7 +164,7 @@ public void testNotified_Normal_withRouters() { RegistryDirectory registryDirectory = getRegistryDirectory(); test_Notified1invokers(registryDirectory); test_Notified_only_routers(registryDirectory); - Assertions.assertEquals(true, registryDirectory.isAvailable()); + Assertions.assertTrue(registryDirectory.isAvailable()); Assertions.assertTrue(LogUtil.checkNoError(), "notify no invoker urls ,should not error"); LogUtil.stop(); test_Notified2invokers(registryDirectory); @@ -181,7 +181,7 @@ public void testNotified_WithError() { serviceUrls.add(SERVICEURL); registryDirectory.notify(serviceUrls); - Assertions.assertEquals(true, registryDirectory.isAvailable()); + Assertions.assertTrue(registryDirectory.isAvailable()); List invokers = registryDirectory.list(invocation); Assertions.assertEquals(1, invokers.size()); } @@ -205,8 +205,8 @@ private void testforbid(RegistryDirectory registryDirectory) { List serviceUrls = new ArrayList(); serviceUrls.add(new URL(EMPTY_PROTOCOL, ANYHOST_VALUE, 0, service, CATEGORY_KEY, PROVIDERS_CATEGORY)); registryDirectory.notify(serviceUrls); - Assertions.assertEquals(false, - registryDirectory.isAvailable(), "invokers size=0 ,then the registry directory is not available"); + Assertions.assertFalse(registryDirectory.isAvailable(), + "invokers size=0 ,then the registry directory is not available"); try { registryDirectory.list(invocation); fail("forbid must throw RpcException"); @@ -224,7 +224,7 @@ public void test_NotifiedDubbo1() { URL Dubbo1URL = URL.valueOf("dubbo://127.0.0.1:9098?lazy=true"); serviceUrls.add(Dubbo1URL.addParameter("methods", "getXXX")); registryDirectory.notify(serviceUrls); - Assertions.assertEquals(true, registryDirectory.isAvailable()); + Assertions.assertTrue(registryDirectory.isAvailable()); invocation = new RpcInvocation(); @@ -250,7 +250,7 @@ private void test_Notified1invokers(RegistryDirectory registryDirectory) { List serviceUrls = new ArrayList(); serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1").addParameter(APPLICATION_KEY, "mockApplicationName"));// .addParameter("refer.autodestroy", "true") registryDirectory.notify(serviceUrls); - Assertions.assertEquals(true, registryDirectory.isAvailable()); + Assertions.assertTrue(registryDirectory.isAvailable()); invocation = new RpcInvocation(); @@ -278,7 +278,7 @@ private void test_Notified2invokers(RegistryDirectory registryDirectory) { serviceUrls.add(SERVICEURL2.addParameter("methods", "getXXX1,getXXX2")); registryDirectory.notify(serviceUrls); - Assertions.assertEquals(true, registryDirectory.isAvailable()); + Assertions.assertTrue(registryDirectory.isAvailable()); invocation = new RpcInvocation(); @@ -302,7 +302,7 @@ private void test_Notified3invokers(RegistryDirectory registryDirectory) { serviceUrls.add(SERVICEURL3.addParameter("methods", "getXXX1,getXXX2,getXXX3")); registryDirectory.notify(serviceUrls); - Assertions.assertEquals(true, registryDirectory.isAvailable()); + Assertions.assertTrue(registryDirectory.isAvailable()); invocation = new RpcInvocation(); @@ -348,7 +348,7 @@ public void testParametersMerge() { Invoker invoker = (Invoker) invokers.get(0); URL url = invoker.getUrl(); - Assertions.assertEquals(null, url.getParameter("key")); + Assertions.assertNull(url.getParameter("key")); } // The parameters of the provider for the inspection service need merge { @@ -389,7 +389,7 @@ public void testParametersMerge() { Invoker invoker = (Invoker) invokers.get(0); URL url = invoker.getUrl(); - Assertions.assertEquals(false, url.getParameter(Constants.CHECK_KEY, false)); + Assertions.assertFalse(url.getParameter(Constants.CHECK_KEY, false)); } { serviceUrls.clear(); @@ -406,7 +406,7 @@ public void testParametersMerge() { } //test geturl { - Assertions.assertEquals(null, registryDirectory2.getUrl().getParameter("mock")); + Assertions.assertNull(registryDirectory2.getUrl().getParameter("mock")); serviceUrls.clear(); serviceUrls.add(SERVICEURL.addParameter(MOCK_KEY, "true")); registryDirectory2.notify(serviceUrls); @@ -429,18 +429,18 @@ public void testDestroy() { registryDirectory.notify(serviceUrls); List invokers = registryDirectory.list(invocation); - Assertions.assertEquals(true, registryDirectory.isAvailable()); - Assertions.assertEquals(true, invokers.get(0).isAvailable()); + Assertions.assertTrue(registryDirectory.isAvailable()); + Assertions.assertTrue(invokers.get(0).isAvailable()); registryDirectory.destroy(); - Assertions.assertEquals(false, registryDirectory.isAvailable()); - Assertions.assertEquals(false, invokers.get(0).isAvailable()); + Assertions.assertFalse(registryDirectory.isAvailable()); + Assertions.assertFalse(invokers.get(0).isAvailable()); registryDirectory.destroy(); List> cachedInvokers = registryDirectory.getInvokers(); Map> urlInvokerMap = registryDirectory.getUrlInvokerMap(); - Assertions.assertTrue(cachedInvokers == null); + Assertions.assertNull(cachedInvokers); Assertions.assertEquals(0, urlInvokerMap.size()); // List urls = mockRegistry.getSubscribedUrls(); @@ -535,7 +535,7 @@ public void testEmptyNotifyCauseForbidden() { invokers = registryDirectory.list(inv); } catch (RpcException e) { Assertions.assertEquals(RpcException.FORBIDDEN_EXCEPTION, e.getCode()); - Assertions.assertEquals(false, registryDirectory.isAvailable()); + Assertions.assertFalse(registryDirectory.isAvailable()); } serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1")); @@ -545,7 +545,7 @@ public void testEmptyNotifyCauseForbidden() { registryDirectory.notify(serviceUrls); inv.setMethodName("getXXX2"); invokers = registryDirectory.list(inv); - Assertions.assertEquals(true, registryDirectory.isAvailable()); + Assertions.assertTrue(registryDirectory.isAvailable()); Assertions.assertEquals(3, invokers.size()); } @@ -598,7 +598,7 @@ public void testNotifyoverrideUrls_beforeInvoker() { overrideUrls.add(URL.valueOf("override://0.0.0.0?timeout=1&connections=5")); registryDirectory.notify(overrideUrls); //The registry is initially pushed to override only, and the dirctory state should be false because there is no invoker. - Assertions.assertEquals(false, registryDirectory.isAvailable()); + Assertions.assertFalse(registryDirectory.isAvailable()); //After pushing two provider, the directory state is restored to true List serviceUrls = new ArrayList(); @@ -606,7 +606,7 @@ public void testNotifyoverrideUrls_beforeInvoker() { serviceUrls.add(SERVICEURL2.addParameter("timeout", "1000").addParameter("connections", "10")); registryDirectory.notify(serviceUrls); - Assertions.assertEquals(true, registryDirectory.isAvailable()); + Assertions.assertTrue(registryDirectory.isAvailable()); //Start validation of parameter values @@ -633,7 +633,7 @@ public void testNotifyoverrideUrls_afterInvoker() { serviceUrls.add(SERVICEURL2.addParameter("timeout", "1000").addParameter("connections", "10")); registryDirectory.notify(serviceUrls); - Assertions.assertEquals(true, registryDirectory.isAvailable()); + Assertions.assertTrue(registryDirectory.isAvailable()); List overrideUrls = new ArrayList(); overrideUrls.add(URL.valueOf("override://0.0.0.0?timeout=1&connections=5")); @@ -664,7 +664,7 @@ public void testNotifyoverrideUrls_withInvoker() { durls.add(URL.valueOf("override://0.0.0.0?timeout=1&connections=5")); registryDirectory.notify(durls); - Assertions.assertEquals(true, registryDirectory.isAvailable()); + Assertions.assertTrue(registryDirectory.isAvailable()); //Start validation of parameter values @@ -700,7 +700,7 @@ public void testNotifyoverrideUrls_Nouse() { durls = new ArrayList(); durls.add(URL.valueOf("override://0.0.0.0?timeout=1&connections=5")); registryDirectory.notify(durls); - Assertions.assertEquals(true, registryDirectory.isAvailable()); + Assertions.assertTrue(registryDirectory.isAvailable()); invokers = registryDirectory.list(invocation); Assertions.assertEquals(2, invokers.size()); @@ -710,10 +710,12 @@ public void testNotifyoverrideUrls_Nouse() { map2.put(invokers.get(1).getUrl().getAddress(), invokers.get(1)); //The parameters are different and must be rereferenced. - Assertions.assertFalse(map.get(SERVICEURL.getAddress()) == map2.get(SERVICEURL.getAddress()), "object should not same"); + Assertions.assertNotSame(map.get(SERVICEURL.getAddress()), map2.get(SERVICEURL.getAddress()), + "object should not same"); //The parameters can not be rereferenced - Assertions.assertTrue(map.get(SERVICEURL2.getAddress()) == map2.get(SERVICEURL2.getAddress()), "object should not same"); + Assertions.assertSame(map.get(SERVICEURL2.getAddress()), map2.get(SERVICEURL2.getAddress()), + "object should not same"); } /** @@ -781,7 +783,7 @@ public void testNofityOverrideUrls_CleanOnly() { List durls = new ArrayList(); durls.add(SERVICEURL.setHost("10.20.30.140").addParameter("timeout", "1")); registryDirectory.notify(durls); - Assertions.assertEquals(null, registryDirectory.getUrl().getParameter("mock")); + Assertions.assertNull(registryDirectory.getUrl().getParameter("mock")); //override durls = new ArrayList(); @@ -801,7 +803,7 @@ public void testNofityOverrideUrls_CleanOnly() { //Need to be restored to the original providerUrl Assertions.assertEquals("1", aInvoker.getUrl().getParameter("timeout")); - Assertions.assertEquals(null, registryDirectory.getUrl().getParameter("mock")); + Assertions.assertNull(registryDirectory.getUrl().getParameter("mock")); } /** @@ -976,7 +978,7 @@ public void testNotify_MockProviderOnly() { serviceUrls.add(SERVICEURL.setProtocol(MOCK_PROTOCOL)); registryDirectory.notify(serviceUrls); - Assertions.assertEquals(true, registryDirectory.isAvailable()); + Assertions.assertTrue(registryDirectory.isAvailable()); invocation = new RpcInvocation(); List invokers = registryDirectory.list(invocation); diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java index ee4e043fd95..5e84ece0348 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java @@ -44,6 +44,9 @@ import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY; import static org.apache.dubbo.registry.integration.RegistryProtocol.DEFAULT_REGISTER_PROVIDER_KEYS; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * RegistryProtocolTest @@ -112,7 +115,7 @@ public void testNotifyOverride() throws Exception { urls.add(URL.valueOf("override://0.0.0.0/" + service + "?x=y")); listener.notify(urls); - assertEquals(true, exporter.getInvoker().isAvailable()); + assertTrue(exporter.getInvoker().isAvailable()); assertEquals("100", exporter.getInvoker().getUrl().getParameter("timeout")); assertEquals("y", exporter.getInvoker().getUrl().getParameter("x")); @@ -139,8 +142,8 @@ public void testNotifyOverride_notmatch() throws Exception { List urls = new ArrayList(); urls.add(URL.valueOf("override://0.0.0.0/org.apache.dubbo.registry.protocol.HackService?timeout=100")); listener.notify(urls); - assertEquals(true, exporter.getInvoker().isAvailable()); - assertEquals(null, exporter.getInvoker().getUrl().getParameter("timeout")); + assertTrue(exporter.getInvoker().isAvailable()); + assertNull(exporter.getInvoker().getUrl().getParameter("timeout")); exporter.unexport(); destroyRegistryProtocol(); } @@ -159,7 +162,7 @@ public void testDestoryRegistry() { } catch (InterruptedException e) { e.printStackTrace(); } - assertEquals(false, exporter.getInvoker().isAvailable()); + assertFalse(exporter.getInvoker().isAvailable()); } diff --git a/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java b/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java index 15427903b81..f09ff804d15 100644 --- a/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java +++ b/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java @@ -124,13 +124,13 @@ public void test_unregister() { registry.register(serviceUrl); Set registered = registry.getRegistered(); - Assertions.assertTrue(registered.size() == 1); + Assertions.assertEquals(1, registered.size()); Assertions.assertTrue(registered.contains(serviceUrl)); registry.unregister(serviceUrl); registered = registry.getRegistered(); - Assertions.assertTrue(registered.size() == 0); + Assertions.assertEquals(0, registered.size()); } @Test @@ -152,8 +152,8 @@ public void notify(List urls) { @Test public void test_subscribe_when_register() throws InterruptedException { - Assertions.assertTrue(registry.getRegistered().size() == 0); - Assertions.assertTrue(registry.getSubscribed().size() == 0); + Assertions.assertEquals(0, registry.getRegistered().size()); + Assertions.assertEquals(0, registry.getSubscribed().size()); CountDownLatch notNotified = new CountDownLatch(2); @@ -177,8 +177,8 @@ public void notify(List urls) { @Test public void test_subscribe_when_register0() throws InterruptedException { - Assertions.assertTrue(registry.getRegistered().size() == 0); - Assertions.assertTrue(registry.getSubscribed().size() == 0); + Assertions.assertEquals(0, registry.getRegistered().size()); + Assertions.assertEquals(0, registry.getSubscribed().size()); CountDownLatch notNotified = new CountDownLatch(3); ConcurrentHashMap notifiedUrls = new ConcurrentHashMap<>(); @@ -210,8 +210,8 @@ public void notify(List urls) { @Test public void test_subscribe_when_register1() throws InterruptedException { - Assertions.assertTrue(registry.getRegistered().size() == 0); - Assertions.assertTrue(registry.getSubscribed().size() == 0); + Assertions.assertEquals(0, registry.getRegistered().size()); + Assertions.assertEquals(0, registry.getSubscribed().size()); CountDownLatch notNotified = new CountDownLatch(2); @@ -237,8 +237,8 @@ public void notify(List urls) { @Test public void test_subscribe_when_register2() throws InterruptedException { - Assertions.assertTrue(registry.getRegistered().size() == 0); - Assertions.assertTrue(registry.getSubscribed().size() == 0); + Assertions.assertEquals(0, registry.getRegistered().size()); + Assertions.assertEquals(0, registry.getSubscribed().size()); CountDownLatch notNotified = new CountDownLatch(3); @@ -263,7 +263,7 @@ public void notify(List urls) { registry.register(serviceUrl3); Assertions.assertTrue(notNotified.await(15, TimeUnit.SECONDS)); - Assertions.assertTrue(notifiedUrls.size() == 3); + Assertions.assertEquals(3, notifiedUrls.size()); Assertions.assertTrue(notifiedUrls.containsKey(serviceUrl)); Assertions.assertTrue(notifiedUrls.containsKey(serviceUrl2)); Assertions.assertTrue(notifiedUrls.containsKey(serviceUrl3)); @@ -272,8 +272,8 @@ public void notify(List urls) { @Test public void test_unsubscribe() throws InterruptedException { - Assertions.assertTrue(registry.getRegistered().size() == 0); - Assertions.assertTrue(registry.getSubscribed().size() == 0); + Assertions.assertEquals(0, registry.getRegistered().size()); + Assertions.assertEquals(0, registry.getSubscribed().size()); CountDownLatch notNotified = new CountDownLatch(2); @@ -299,13 +299,13 @@ public void notify(List urls) { Assertions.assertFalse(notNotified.await(2, TimeUnit.SECONDS)); // expect nothing happen - Assertions.assertTrue(notifiedUrl.get() == null); + Assertions.assertNull(notifiedUrl.get()); } @BeforeEach public void setUp() { registry = (EtcdRegistry) registryFactory.getRegistry(registryUrl); - Assertions.assertTrue(registry != null); + Assertions.assertNotNull(registry); if (!registry.isAvailable()) { AbstractRegistryFactory.destroyAll(); registry = (EtcdRegistry) registryFactory.getRegistry(registryUrl); diff --git a/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleRegistry2S2RTest.java b/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleRegistry2S2RTest.java index cfc15b2df95..88e4b1fa124 100644 --- a/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleRegistry2S2RTest.java +++ b/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleRegistry2S2RTest.java @@ -91,25 +91,25 @@ public static void tearDown() throws Exception { @Test public void testParamConfig() { - Assertions.assertTrue(multipleRegistry.origReferenceRegistryURLs.size() == 2); + Assertions.assertEquals(2, multipleRegistry.origReferenceRegistryURLs.size()); Assertions.assertTrue(multipleRegistry.origReferenceRegistryURLs.contains(zookeeperRegistryURLStr)); Assertions.assertTrue(multipleRegistry.origReferenceRegistryURLs.contains(redisRegistryURLStr)); - Assertions.assertTrue(multipleRegistry.origServiceRegistryURLs.size() == 2); + Assertions.assertEquals(2, multipleRegistry.origServiceRegistryURLs.size()); Assertions.assertTrue(multipleRegistry.origServiceRegistryURLs.contains(zookeeperRegistryURLStr)); Assertions.assertTrue(multipleRegistry.origServiceRegistryURLs.contains(redisRegistryURLStr)); - Assertions.assertTrue(multipleRegistry.effectReferenceRegistryURLs.size() == 2); + Assertions.assertEquals(2, multipleRegistry.effectReferenceRegistryURLs.size()); Assertions.assertTrue(multipleRegistry.effectReferenceRegistryURLs.contains(zookeeperRegistryURLStr)); Assertions.assertTrue(multipleRegistry.effectReferenceRegistryURLs.contains(redisRegistryURLStr)); - Assertions.assertTrue(multipleRegistry.effectServiceRegistryURLs.size() == 2); + Assertions.assertEquals(2, multipleRegistry.effectServiceRegistryURLs.size()); Assertions.assertTrue(multipleRegistry.effectServiceRegistryURLs.contains(zookeeperRegistryURLStr)); Assertions.assertTrue(multipleRegistry.effectServiceRegistryURLs.contains(redisRegistryURLStr)); Assertions.assertTrue(multipleRegistry.getServiceRegistries().containsKey(zookeeperRegistryURLStr)); Assertions.assertTrue(multipleRegistry.getServiceRegistries().containsKey(redisRegistryURLStr)); - Assertions.assertTrue(multipleRegistry.getServiceRegistries().values().size() == 2); + Assertions.assertEquals(2, multipleRegistry.getServiceRegistries().values().size()); // java.util.Iterator registryIterable = multipleRegistry.getServiceRegistries().values().iterator(); // Registry firstRegistry = registryIterable.next(); // Registry secondRegistry = registryIterable.next(); @@ -152,14 +152,14 @@ public void notify(List urls) { } }); Thread.sleep(1500); - Assertions.assertTrue(list.size() == 2); + Assertions.assertEquals(2, list.size()); multipleRegistry.unregister(serviceUrl); Thread.sleep(1500); - Assertions.assertTrue(list.size() == 1); + Assertions.assertEquals(1, list.size()); List urls = MultipleRegistryTestUtil.getProviderURLsFromNotifyURLS(list); - Assertions.assertTrue(list.size() == 1); - Assertions.assertTrue("empty".equals(list.get(0).getProtocol())); + Assertions.assertEquals(1, list.size()); + Assertions.assertEquals("empty", list.get(0).getProtocol()); } @Test @@ -185,22 +185,22 @@ public void notify(List urls) { } }); Thread.sleep(1500); - Assertions.assertTrue(list.size() == 2); + Assertions.assertEquals(2, list.size()); List serviceRegistries = new ArrayList(multipleRegistry.getServiceRegistries().values()); serviceRegistries.get(0).unregister(serviceUrl); Thread.sleep(1500); - Assertions.assertTrue(list.size() == 1); + Assertions.assertEquals(1, list.size()); List urls = MultipleRegistryTestUtil.getProviderURLsFromNotifyURLS(list); - Assertions.assertTrue(list.size() == 1); + Assertions.assertEquals(1, list.size()); Assertions.assertTrue(!"empty".equals(list.get(0).getProtocol())); serviceRegistries.get(1).unregister(serviceUrl); Thread.sleep(1500); - Assertions.assertTrue(list.size() == 1); + Assertions.assertEquals(1, list.size()); urls = MultipleRegistryTestUtil.getProviderURLsFromNotifyURLS(list); - Assertions.assertTrue(list.size() == 1); - Assertions.assertTrue("empty".equals(list.get(0).getProtocol())); + Assertions.assertEquals(1, list.size()); + Assertions.assertEquals("empty", list.get(0).getProtocol()); } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/ExchangeCodecTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/ExchangeCodecTest.java index 4fe272f3830..df3ac678249 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/ExchangeCodecTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/ExchangeCodecTest.java @@ -233,8 +233,8 @@ public void test_Decode_Return_Request_Event_Object() throws IOException { Request obj = (Request) decode(request); Assertions.assertEquals(person, obj.getData()); - Assertions.assertEquals(true, obj.isTwoWay()); - Assertions.assertEquals(true, obj.isEvent()); + Assertions.assertTrue(obj.isTwoWay()); + Assertions.assertTrue(obj.isEvent()); Assertions.assertEquals(Version.getProtocolVersion(), obj.getVersion()); System.out.println(obj); } @@ -248,8 +248,8 @@ public void test_Decode_Return_Request_Event_String() throws IOException { Request obj = (Request) decode(request); Assertions.assertEquals(event, obj.getData()); - Assertions.assertEquals(true, obj.isTwoWay()); - Assertions.assertEquals(true, obj.isEvent()); + Assertions.assertTrue(obj.isTwoWay()); + Assertions.assertTrue(obj.isEvent()); Assertions.assertEquals(Version.getProtocolVersion(), obj.getVersion()); System.out.println(obj); } @@ -260,9 +260,9 @@ public void test_Decode_Return_Request_Heartbeat_Object() throws IOException { byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, (byte) 0xe2, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; byte[] request = getRequestBytes(null, header); Request obj = (Request) decode(request); - Assertions.assertEquals(null, obj.getData()); - Assertions.assertEquals(true, obj.isTwoWay()); - Assertions.assertEquals(true, obj.isHeartbeat()); + Assertions.assertNull(obj.getData()); + Assertions.assertTrue(obj.isTwoWay()); + Assertions.assertTrue(obj.isHeartbeat()); Assertions.assertEquals(Version.getProtocolVersion(), obj.getVersion()); System.out.println(obj); } @@ -276,8 +276,8 @@ public void test_Decode_Return_Request_Object() throws IOException { Request obj = (Request) decode(request); Assertions.assertEquals(person, obj.getData()); - Assertions.assertEquals(true, obj.isTwoWay()); - Assertions.assertEquals(false, obj.isHeartbeat()); + Assertions.assertTrue(obj.isTwoWay()); + Assertions.assertFalse(obj.isHeartbeat()); Assertions.assertEquals(Version.getProtocolVersion(), obj.getVersion()); System.out.println(obj); } @@ -293,8 +293,8 @@ public void test_Decode_Error_Request_Object() throws IOException { System.arraycopy(badbytes, 0, request, 21, badbytes.length); Request obj = (Request) decode(request); - Assertions.assertEquals(true, obj.isBroken()); - Assertions.assertEquals(true, obj.getData() instanceof Throwable); + Assertions.assertTrue(obj.isBroken()); + Assertions.assertTrue(obj.getData() instanceof Throwable); } @Test @@ -398,7 +398,7 @@ public void test_Encode_Error_Response() throws IOException { Assertions.assertEquals(response.getStatus(), obj.getStatus()); Assertions.assertEquals(response.isHeartbeat(), obj.isHeartbeat()); Assertions.assertEquals(badString, obj.getErrorMessage()); - Assertions.assertEquals(null, obj.getResult()); + Assertions.assertNull(obj.getResult()); // Assertions.assertEquals(response.getProtocolVersion(), obj.getVersion()); } @@ -431,10 +431,10 @@ public void testMessageLengthGreaterThanMessageActualLength() throws Exception { /* request|1111...|request */ ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(out.toByteArray()); Request decodedRequest = (Request) codec.decode(channel, decodeBuffer); - Assertions.assertTrue(date.equals(decodedRequest.getData())); + Assertions.assertEquals(date, decodedRequest.getData()); Assertions.assertEquals(bytes.length + padding, decodeBuffer.readerIndex()); decodedRequest = (Request) codec.decode(channel, decodeBuffer); - Assertions.assertTrue(date.equals(decodedRequest.getData())); + Assertions.assertEquals(date, decodedRequest.getData()); } @Test diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/ConnectChannelHandlerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/ConnectChannelHandlerTest.java index b61a6004283..d3aeb5efa4a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/ConnectChannelHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/ConnectChannelHandlerTest.java @@ -136,7 +136,7 @@ public void test_Received_Event_invoke_direct() throws RemotingException { handler.received(new MockedChannel() { @Override public void send(Object message) throws RemotingException { - Assertions.assertEquals(true, ((Response) message).isHeartbeat(), "response.heartbeat"); + Assertions.assertTrue(((Response) message).isHeartbeat(), "response.heartbeat"); count.incrementAndGet(); } }, req); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/HeaderExchangeHandlerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/HeaderExchangeHandlerTest.java index ca26a647f34..531c51e5550 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/HeaderExchangeHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/HeaderExchangeHandlerTest.java @@ -70,7 +70,7 @@ public void send(Object message) throws RemotingException { Assertions.assertEquals(request.getVersion(), res.getVersion()); Assertions.assertEquals(Response.OK, res.getStatus()); Assertions.assertEquals(requestdata, res.getResult()); - Assertions.assertEquals(null, res.getErrorMessage()); + Assertions.assertNull(res.getErrorMessage()); count.incrementAndGet(); } }; diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/AbstractCodecTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/AbstractCodecTest.java index ec6c83d0873..44ea23338a2 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/AbstractCodecTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/AbstractCodecTest.java @@ -16,14 +16,13 @@ */ package org.apache.dubbo.remoting.transport; +import java.io.IOException; + import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Channel; -import org.junit.jupiter.api.Assertions; import org.hamcrest.CoreMatchers; import org.mockito.internal.verification.VerificationModeFactory; -import java.io.IOException; - import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.BDDMockito.given; diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientTest.java b/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientTest.java index 6dcf812987a..9f91a82144c 100644 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientTest.java +++ b/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientTest.java @@ -337,12 +337,12 @@ public void test_watch_on_recoverable_connection() throws InterruptedException { switch (notified.increaseAndGet()) { case 1: { notNotified.countDown(); - Assertions.assertTrue(children.size() == 1); + Assertions.assertEquals(1, children.size()); Assertions.assertEquals(child.substring(child.lastIndexOf("/") + 1), children.get(0)); break; } case 2: { - Assertions.assertTrue(children.size() == 0); + Assertions.assertEquals(0, children.size()); Assertions.assertEquals(path, parent); break; } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java index 27c8f718b23..04484096333 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java @@ -92,8 +92,8 @@ public void testHeartbeat() throws Exception { Thread.sleep(10000); System.err.println("++++++++++++++ disconnect count " + handler.disconnectCount); System.err.println("++++++++++++++ connect count " + handler.connectCount); - Assertions.assertTrue(handler.disconnectCount == 0); - Assertions.assertTrue(handler.connectCount == 1); + Assertions.assertEquals(0, handler.disconnectCount); + Assertions.assertEquals(1, handler.connectCount); } @Test diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientReconnectTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientReconnectTest.java index 939cd10b7c0..d328eb099d2 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientReconnectTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientReconnectTest.java @@ -45,24 +45,24 @@ public void testReconnect() throws RemotingException, InterruptedException { { int port = NetUtils.getAvailablePort(); Client client = startClient(port, 200); - Assertions.assertEquals(false, client.isConnected()); + Assertions.assertFalse(client.isConnected()); Server server = startServer(port); for (int i = 0; i < 100 && !client.isConnected(); i++) { Thread.sleep(10); } - Assertions.assertEquals(true, client.isConnected()); + Assertions.assertTrue(client.isConnected()); client.close(2000); server.close(2000); } { int port = NetUtils.getAvailablePort(); Client client = startClient(port, 20000); - Assertions.assertEquals(false, client.isConnected()); + Assertions.assertFalse(client.isConnected()); Server server = startServer(port); for (int i = 0; i < 5; i++) { Thread.sleep(200); } - Assertions.assertEquals(false, client.isConnected()); + Assertions.assertFalse(client.isConnected()); client.close(2000); server.close(2000); } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientReconnectTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientReconnectTest.java index 51c4907b361..9a2065a99cf 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientReconnectTest.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientReconnectTest.java @@ -47,24 +47,24 @@ public void testReconnect() throws RemotingException, InterruptedException { { int port = NetUtils.getAvailablePort(); Client client = startClient(port, 200); - Assertions.assertEquals(false, client.isConnected()); + Assertions.assertFalse(client.isConnected()); Server server = startServer(port); for (int i = 0; i < 100 && !client.isConnected(); i++) { Thread.sleep(10); } - Assertions.assertEquals(true, client.isConnected()); + Assertions.assertTrue(client.isConnected()); client.close(2000); server.close(2000); } { int port = NetUtils.getAvailablePort(); Client client = startClient(port, 20000); - Assertions.assertEquals(false, client.isConnected()); + Assertions.assertFalse(client.isConnected()); Server server = startServer(port); for (int i = 0; i < 5; i++) { Thread.sleep(200); } - Assertions.assertEquals(false, client.isConnected()); + Assertions.assertFalse(client.isConnected()); client.close(2000); server.close(2000); } diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperClientTest.java b/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperClientTest.java index f1882e1c759..1732e783684 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperClientTest.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperClientTest.java @@ -23,7 +23,6 @@ import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.cache.TreeCacheEvent; -import org.apache.curator.framework.recipes.cache.TreeCacheListener; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.test.TestingServer; import org.apache.zookeeper.WatchedEvent; diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperTransporterTest.java b/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperTransporterTest.java index 2fe78745add..e051dc9602e 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperTransporterTest.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperTransporterTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.zookeeper.curator; -import org.apache.curator.test.TestingServer; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.zookeeper.ZookeeperClient; diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/AppResponseTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/AppResponseTest.java index 2fcace07a9a..284e1df9c51 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/AppResponseTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/AppResponseTest.java @@ -44,7 +44,7 @@ public void testAppResponseWithEmptyStackTraceException() { StackTraceElement[] stackTrace = appResponse.getException().getStackTrace(); Assertions.assertNotNull(stackTrace); - Assertions.assertTrue(stackTrace.length == 0); + Assertions.assertEquals(0,stackTrace.length); } @Test @@ -72,7 +72,7 @@ public void testSetExceptionWithEmptyStackTraceException() { StackTraceElement[] stackTrace = appResponse.getException().getStackTrace(); Assertions.assertNotNull(stackTrace); - Assertions.assertTrue(stackTrace.length == 0); + Assertions.assertEquals(0,stackTrace.length); } private Throwable buildEmptyStackTraceException() { diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcContextTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcContextTest.java index 86717ef7011..c9154d9e90b 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcContextTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcContextTest.java @@ -50,17 +50,17 @@ public void testGetContext() { public void testAddress() { RpcContext context = RpcContext.getContext(); context.setLocalAddress("127.0.0.1", 20880); - Assertions.assertTrue(context.getLocalAddress().getPort() == 20880); + Assertions.assertEquals(20880, context.getLocalAddress().getPort()); Assertions.assertEquals("127.0.0.1:20880", context.getLocalAddressString()); context.setRemoteAddress("127.0.0.1", 20880); - Assertions.assertTrue(context.getRemoteAddress().getPort() == 20880); + Assertions.assertEquals(20880, context.getRemoteAddress().getPort()); Assertions.assertEquals("127.0.0.1:20880", context.getRemoteAddressString()); context.setRemoteAddress("127.0.0.1", -1); context.setLocalAddress("127.0.0.1", -1); - Assertions.assertTrue(context.getRemoteAddress().getPort() == 0); - Assertions.assertTrue(context.getLocalAddress().getPort() == 0); + Assertions.assertEquals(0, context.getRemoteAddress().getPort()); + Assertions.assertEquals(0, context.getLocalAddress().getPort()); Assertions.assertEquals("127.0.0.1", context.getRemoteHostName()); Assertions.assertEquals("127.0.0.1", context.getLocalHostName()); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/StatItemTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/StatItemTest.java index 86308072576..78c0c9cb0ec 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/StatItemTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/StatItemTest.java @@ -35,9 +35,9 @@ public void tearDown() throws Exception { public void testIsAllowable() throws Exception { statItem = new StatItem("test", 5, 1000L); long lastResetTime = statItem.getLastResetTime(); - assertEquals(true, statItem.isAllowable()); + assertTrue(statItem.isAllowable()); Thread.sleep(1100L); - assertEquals(true, statItem.isAllowable()); + assertTrue(statItem.isAllowable()); assertTrue(lastResetTime != statItem.getLastResetTime()); assertEquals(4, statItem.getToken()); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/RpcUtilsTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/RpcUtilsTest.java index a38c43777f2..6a326c295ae 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/RpcUtilsTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/RpcUtilsTest.java @@ -53,7 +53,7 @@ public void testAttachInvocationIdIfAsync_normal() { long id1 = RpcUtils.getInvocationId(inv); RpcUtils.attachInvocationIdIfAsync(url, inv); long id2 = RpcUtils.getInvocationId(inv); - assertTrue(id1 == id2); // verify if it's idempotent + assertEquals(id1, id2); // verify if it's idempotent assertTrue(id1 >= 0); assertEquals("bb", attachments.get("aa")); } @@ -139,8 +139,8 @@ public void testGetReturnTypes() throws Exception { Invocation inv4 = new RpcInvocation("testReturnType4", new Class[]{String.class}, null, null, invoker); java.lang.reflect.Type[] types4 = RpcUtils.getReturnTypes(inv4); Assertions.assertEquals(2, types4.length); - Assertions.assertEquals(null, types4[0]); - Assertions.assertEquals(null, types4[1]); + Assertions.assertNull(types4[0]); + Assertions.assertNull(types4[1]); Invocation inv5 = new RpcInvocation("testReturnType5", new Class[]{String.class}, null, null, invoker); java.lang.reflect.Type[] types5 = RpcUtils.getReturnTypes(inv5); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java index 1d8c212b99f..ec07a87b89e 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java @@ -65,9 +65,9 @@ public void test_Normal_available() { ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); DubboInvoker invoker = (DubboInvoker) protocol.protocolBindingRefer(IDemoService.class, url); - Assertions.assertEquals(true, invoker.isAvailable()); + Assertions.assertTrue(invoker.isAvailable()); invoker.destroy(); - Assertions.assertEquals(false, invoker.isAvailable()); + Assertions.assertFalse(invoker.isAvailable()); } @Test @@ -76,11 +76,11 @@ public void test_Normal_ChannelReadOnly() throws Exception { ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); DubboInvoker invoker = (DubboInvoker) protocol.protocolBindingRefer(IDemoService.class, url); - Assertions.assertEquals(true, invoker.isAvailable()); + Assertions.assertTrue(invoker.isAvailable()); getClients(invoker)[0].setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); - Assertions.assertEquals(false, invoker.isAvailable()); + Assertions.assertFalse(invoker.isAvailable()); // reset status since connection is shared among invokers getClients(invoker)[0].removeAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY); @@ -107,7 +107,7 @@ public void test_normal_channel_close_wait_gracefully() throws Exception { long waitTime = System.currentTimeMillis() - start; Assertions.assertTrue(waitTime >= 2000); - Assertions.assertEquals(false, invoker.isAvailable()); + Assertions.assertFalse(invoker.isAvailable()); } @Test @@ -119,7 +119,7 @@ public void test_NoInvokers() throws Exception { ExchangeClient[] clients = getClients(invoker); clients[0].close(); - Assertions.assertEquals(false, invoker.isAvailable()); + Assertions.assertFalse(invoker.isAvailable()); } @@ -129,7 +129,7 @@ public void test_Lazy_ChannelReadOnly() throws Exception { ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); AsyncToSyncInvoker invoker = (AsyncToSyncInvoker) protocol.refer(IDemoService.class, url); - Assertions.assertEquals(true, invoker.isAvailable()); + Assertions.assertTrue(invoker.isAvailable()); try { getClients((DubboInvoker) invoker.getInvoker())[0].setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); fail(); @@ -140,9 +140,9 @@ public void test_Lazy_ChannelReadOnly() throws Exception { IDemoService service = (IDemoService) proxy.getProxy(invoker); Assertions.assertEquals("ok", service.get()); - Assertions.assertEquals(true, invoker.isAvailable()); + Assertions.assertTrue(invoker.isAvailable()); getClients((DubboInvoker) invoker.getInvoker())[0].setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); - Assertions.assertEquals(false, invoker.isAvailable()); + Assertions.assertFalse(invoker.isAvailable()); } private ExchangeClient[] getClients(DubboInvoker invoker) throws Exception { diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ImplicitCallBackTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ImplicitCallBackTest.java index 0a3a9d161b5..5085a447cf8 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ImplicitCallBackTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ImplicitCallBackTest.java @@ -173,7 +173,7 @@ public void test_Ex_OnReturn() throws Exception { int requestId = 2; Person ret = demoProxy.get(requestId); - Assertions.assertEquals(null, ret); + Assertions.assertNull(ret); for (int i = 0; i < 10; i++) { if (!notify.errors.containsKey(requestId)) { Thread.sleep(200); @@ -193,7 +193,7 @@ public void test_Ex_OnInvoke() throws Exception { int requestId = 2; Person ret = demoProxy.get(requestId); - Assertions.assertEquals(null, ret); + Assertions.assertNull(ret); for (int i = 0; i < 10; i++) { if (!notify.inv.contains(requestId)) { Thread.sleep(200); @@ -213,7 +213,7 @@ public void test_Ex_Onthrow() throws Exception { int requestId = 2; Person ret = demoProxy.get(requestId); - Assertions.assertEquals(null, ret); + Assertions.assertNull(ret); for (int i = 0; i < 10; i++) { if (!notify.errors.containsKey(requestId)) { Thread.sleep(200); @@ -247,7 +247,7 @@ public void test_Async_Future() throws Exception { int requestId = 2; Person ret = demoProxy.get(requestId); - Assertions.assertEquals(null, ret); + Assertions.assertNull(ret); Future pFuture = RpcContext.getContext().getFuture(); ret = pFuture.get(1000 * 1000, TimeUnit.MICROSECONDS); Assertions.assertEquals(requestId, ret.getId()); @@ -261,12 +261,12 @@ public void test_Async_Future_Multi() throws Exception { int requestId1 = 1; Person ret = demoProxy.get(requestId1); - Assertions.assertEquals(null, ret); + Assertions.assertNull(ret); Future p1Future = RpcContext.getContext().getFuture(); int requestId2 = 1; Person ret2 = demoProxy.get(requestId2); - Assertions.assertEquals(null, ret2); + Assertions.assertNull(ret2); Future p2Future = RpcContext.getContext().getFuture(); ret = p1Future.get(1000 * 1000, TimeUnit.MICROSECONDS); @@ -285,7 +285,7 @@ public void test_Async_Future_Ex() throws Throwable { int requestId = 2; Person ret = demoProxy.get(requestId); - Assertions.assertEquals(null, ret); + Assertions.assertNull(ret); Future pFuture = RpcContext.getContext().getFuture(); ret = pFuture.get(1000 * 1000, TimeUnit.MICROSECONDS); Assertions.assertEquals(requestId, ret.getId()); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java index 52972801778..70c6ec8fba8 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java @@ -123,7 +123,7 @@ public void test_mult_share_connect() { Assertions.assertEquals(shareConnectionNum, demoReferenceClientList.size()); // because helloServiceInvoker and demoServiceInvoker use share connect, so client list must be equal - Assertions.assertTrue(Objects.equals(helloReferenceClientList, demoReferenceClientList)); + Assertions.assertEquals(helloReferenceClientList, demoReferenceClientList); Assertions.assertEquals(demoClient.getLocalAddress(), helloClient.getLocalAddress()); Assertions.assertEquals(demoClient, helloClient); @@ -186,7 +186,7 @@ public void test_counter_error() { DubboAppender.doStop(); // status switch to available once invoke again - Assertions.assertEquals(true, helloServiceInvoker.isAvailable(), "client status available"); + Assertions.assertTrue(helloServiceInvoker.isAvailable(), "client status available"); /** * This is the third time to close the same client. Under normal circumstances, @@ -201,8 +201,8 @@ public void test_counter_error() { // client has been replaced with lazy client. lazy client is fetched from referenceclientmap, and since it's // been invoked once, it's close status is false - Assertions.assertEquals(false, client.isClosed(), "client status close"); - Assertions.assertEquals(false, helloServiceInvoker.isAvailable(), "client status close"); + Assertions.assertFalse(client.isClosed(), "client status close"); + Assertions.assertFalse(helloServiceInvoker.isAvailable(), "client status close"); destoy(); } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/telnet/CurrentTelnetHandlerTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/telnet/CurrentTelnetHandlerTest.java index 81e971bea31..50be9435bfe 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/telnet/CurrentTelnetHandlerTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/telnet/CurrentTelnetHandlerTest.java @@ -20,7 +20,6 @@ import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.telnet.TelnetHandler; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/validation/ValidationTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/validation/ValidationTest.java index 691f925216c..06d9fa577b2 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/validation/ValidationTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/validation/ValidationTest.java @@ -134,7 +134,7 @@ public void testValidation() { Assertions.fail(); } catch (ConstraintViolationException ve) { Set> violations = ve.getConstraintViolations(); - Assertions.assertTrue(violations.size() == 3); + Assertions.assertEquals(3, violations.size()); Assertions.assertNotNull(violations); } diff --git a/dubbo-rpc/dubbo-rpc-http/src/test/java/org/apache/dubbo/rpc/protocol/http/HttpProtocolTest.java b/dubbo-rpc/dubbo-rpc-http/src/test/java/org/apache/dubbo/rpc/protocol/http/HttpProtocolTest.java index 009f01d1924..29a4b1c8ae5 100644 --- a/dubbo-rpc/dubbo-rpc-http/src/test/java/org/apache/dubbo/rpc/protocol/http/HttpProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-http/src/test/java/org/apache/dubbo/rpc/protocol/http/HttpProtocolTest.java @@ -174,7 +174,7 @@ public void testTimeOut() { client.timeOut(6000); fail(); } catch (RpcException expected) { - Assertions.assertEquals(true, expected.isTimeout()); + Assertions.assertTrue(expected.isTimeout()); } finally { invoker.destroy(); exporter.unexport(); diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerApiListingResourceTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerApiListingResourceTest.java index 15e685611ed..64f8b5da1cc 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerApiListingResourceTest.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerApiListingResourceTest.java @@ -25,10 +25,8 @@ import javax.servlet.ServletContext; import javax.ws.rs.core.Application; import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; import java.net.URI; -import java.net.URISyntaxException; import java.util.HashSet; import java.util.Set; diff --git a/dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocolTest.java b/dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocolTest.java index 4dcd21dfccb..3e50501b459 100644 --- a/dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocolTest.java @@ -32,6 +32,7 @@ import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class RmiProtocolTest { private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); @@ -54,8 +55,8 @@ public void testRmiProtocolTimeout() throws Exception { try { service.throwTimeout(); } catch (RpcException e) { - assertEquals(true, e.isTimeout()); - assertEquals(true, e.getMessage().contains("Read timed out")); + assertTrue(e.isTimeout()); + assertTrue(e.getMessage().contains("Read timed out")); } } finally { rpcExporter.unexport(); diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodecTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodecTest.java index 8cdbae7f99e..a8c66a71f85 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodecTest.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodecTest.java @@ -183,7 +183,7 @@ public void testDecodeReplyResponse() throws Exception { Assertions.assertNotNull(obj); - Assertions.assertEquals(true, obj instanceof Response); + Assertions.assertTrue(obj instanceof Response); Response response = (Response) obj; diff --git a/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/base/AbstractSerializationTest.java b/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/base/AbstractSerializationTest.java index 5ff4cb2344e..84d5edb6fe6 100644 --- a/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/base/AbstractSerializationTest.java +++ b/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/base/AbstractSerializationTest.java @@ -294,7 +294,7 @@ public void test_Float() throws Exception { byteArrayOutputStream.toByteArray()); ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - assertTrue(1.28F == deserialize.readFloat()); + assertEquals(1.28F,deserialize.readFloat()); try { deserialize.readFloat(); @@ -315,7 +315,7 @@ public void test_Double() throws Exception { byteArrayOutputStream.toByteArray()); ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - assertTrue(1.28 == deserialize.readDouble()); + assertEquals(1.28,deserialize.readDouble()); try { deserialize.readDouble(); @@ -1070,7 +1070,7 @@ public void test_MultiObject() throws Exception { byteArrayOutputStream.toByteArray()); ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - assertEquals(false, deserialize.readBool()); + assertFalse(deserialize.readBool()); assertEquals(bigPerson, deserialize.readObject()); assertEquals((byte) 23, deserialize.readByte()); assertEquals(mediaContent, deserialize.readObject()); @@ -1097,7 +1097,7 @@ public void test_MultiObject_WithType() throws Exception { byteArrayOutputStream.toByteArray()); ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - assertEquals(false, deserialize.readBool()); + assertFalse(deserialize.readBool()); assertEquals(bigPerson, deserialize.readObject(BigPerson.class)); assertEquals((byte) 23, deserialize.readByte()); assertEquals(mediaContent, deserialize.readObject(MediaContent.class)); diff --git a/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/hessian2/Hessian2PersonOkTest.java b/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/hessian2/Hessian2PersonOkTest.java index 8fa793c8b26..3d454b2c394 100644 --- a/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/hessian2/Hessian2PersonOkTest.java +++ b/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/hessian2/Hessian2PersonOkTest.java @@ -19,7 +19,6 @@ import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.common.serialize.base.AbstractSerializationPersonOkTest; -import org.apache.dubbo.common.serialize.java.JavaSerialization; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; diff --git a/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffSerializationTest.java b/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffSerializationTest.java index 02c278e00b0..07021f98eed 100644 --- a/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffSerializationTest.java +++ b/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffSerializationTest.java @@ -18,7 +18,6 @@ package org.apache.dubbo.common.serialize.protostuff; import org.apache.dubbo.common.serialize.base.AbstractSerializationTest; -import org.junit.jupiter.api.Test; public class ProtostuffSerializationTest extends AbstractSerializationTest { { diff --git a/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/support/SerializableClassRegistryTest.java b/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/support/SerializableClassRegistryTest.java index 2b7c9583e6e..8f5a9de13ff 100644 --- a/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/support/SerializableClassRegistryTest.java +++ b/dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/support/SerializableClassRegistryTest.java @@ -20,7 +20,6 @@ import org.apache.dubbo.common.serialize.model.person.Phone; import org.junit.jupiter.api.Test; -import java.io.Serializable; import java.util.Map; import static org.hamcrest.Matchers.equalTo; From e2965c2e1376d8ca597dbb60d55ea06f6ea0ed2f Mon Sep 17 00:00:00 2001 From: jimin Date: Sun, 2 Jun 2019 01:18:08 +0800 Subject: [PATCH 106/115] [Test] add test for common-config (#4208) --- .../config/EnvironmentConfigurationTest.java | 88 +++++++++++++ .../config/InmemoryConfigurationTest.java | 95 ++++++++++++++ .../config/SystemConfigurationTest.java | 117 ++++++++++++++++++ 3 files changed, 300 insertions(+) create mode 100644 dubbo-common/src/test/java/org/apache/dubbo/common/config/EnvironmentConfigurationTest.java create mode 100644 dubbo-common/src/test/java/org/apache/dubbo/common/config/InmemoryConfigurationTest.java create mode 100644 dubbo-common/src/test/java/org/apache/dubbo/common/config/SystemConfigurationTest.java diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/config/EnvironmentConfigurationTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/config/EnvironmentConfigurationTest.java new file mode 100644 index 00000000000..00fda4356b9 --- /dev/null +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/config/EnvironmentConfigurationTest.java @@ -0,0 +1,88 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.config; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * The type Environment configuration test. + */ +class EnvironmentConfigurationTest { + + private static EnvironmentConfiguration environmentConfig; + private static final String MOCK_KEY = "mockKey"; + private static final String MOCK_VALUE = "mockValue"; + private static final String PATH_KEY="PATH"; + + /** + * Init. + */ + @BeforeEach + public void init() { + + environmentConfig = new EnvironmentConfiguration(); + } + + /** + * Test get internal property. + */ + @Test + public void testGetInternalProperty(){ + Assertions.assertNull(environmentConfig.getInternalProperty(MOCK_KEY)); + Assertions.assertEquals(System.getenv(PATH_KEY),environmentConfig.getInternalProperty(PATH_KEY)); + + } + + /** + * Test contains key. + */ + @Test + public void testContainsKey(){ + Assertions.assertTrue(environmentConfig.containsKey(PATH_KEY)); + Assertions.assertFalse(environmentConfig.containsKey(MOCK_KEY)); + } + + /** + * Test get string. + */ + @Test + public void testGetString(){ + Assertions.assertNull(environmentConfig.getString(MOCK_KEY)); + Assertions.assertEquals(MOCK_VALUE,environmentConfig.getString(MOCK_KEY,MOCK_VALUE)); + } + + /** + * Test get property. + */ + @Test + public void testGetProperty(){ + Assertions.assertNull(environmentConfig.getProperty(MOCK_KEY)); + Assertions.assertEquals(MOCK_VALUE,environmentConfig.getProperty(MOCK_KEY,MOCK_VALUE)); + } + + /** + * Clean. + */ + @AfterEach + public void clean(){ + + } + +} \ No newline at end of file diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/config/InmemoryConfigurationTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/config/InmemoryConfigurationTest.java new file mode 100644 index 00000000000..b577631d366 --- /dev/null +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/config/InmemoryConfigurationTest.java @@ -0,0 +1,95 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.config; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * The type Inmemory configuration test. + */ +class InmemoryConfigurationTest { + + private static InmemoryConfiguration memConfig; + private static final String MOCK_KEY = "mockKey"; + private static final String MOCK_VALUE = "mockValue"; + private static final String MOCK_ONE_KEY = "one"; + private static final String MOCK_TWO_KEY = "two"; + private static final String MOCK_THREE_KEY = "three"; + + /** + * Init. + */ + @BeforeEach + public void init() { + + memConfig = new InmemoryConfiguration(); + } + + /** + * Test get mem property. + */ + @Test + public void testGetMemProperty() { + Assertions.assertNull(memConfig.getInternalProperty(MOCK_KEY)); + Assertions.assertFalse(memConfig.containsKey(MOCK_KEY)); + Assertions.assertNull(memConfig.getString(MOCK_KEY)); + Assertions.assertNull(memConfig.getProperty(MOCK_KEY)); + memConfig.addProperty(MOCK_KEY, MOCK_VALUE); + Assertions.assertTrue(memConfig.containsKey(MOCK_KEY)); + Assertions.assertEquals(MOCK_VALUE, memConfig.getInternalProperty(MOCK_KEY)); + Assertions.assertEquals(MOCK_VALUE, memConfig.getString(MOCK_KEY, MOCK_VALUE)); + Assertions.assertEquals(MOCK_VALUE, memConfig.getProperty(MOCK_KEY, MOCK_VALUE)); + + } + + /** + * Test get properties. + */ + @Test + public void testGetProperties() { + Assertions.assertNull(memConfig.getInternalProperty(MOCK_ONE_KEY)); + Assertions.assertNull(memConfig.getInternalProperty(MOCK_TWO_KEY)); + Map proMap = new HashMap<>(); + proMap.put(MOCK_ONE_KEY, MOCK_VALUE); + proMap.put(MOCK_TWO_KEY, MOCK_VALUE); + memConfig.addProperties(proMap); + Assertions.assertNotNull(memConfig.getInternalProperty(MOCK_ONE_KEY)); + Assertions.assertNotNull(memConfig.getInternalProperty(MOCK_TWO_KEY)); + Map anotherProMap = new HashMap<>(); + anotherProMap.put(MOCK_THREE_KEY, MOCK_VALUE); + memConfig.setProperties(anotherProMap); + Assertions.assertNotNull(memConfig.getInternalProperty(MOCK_THREE_KEY)); + Assertions.assertNull(memConfig.getInternalProperty(MOCK_ONE_KEY)); + Assertions.assertNull(memConfig.getInternalProperty(MOCK_TWO_KEY)); + + } + + /** + * Clean. + */ + @AfterEach + public void clean(){ + + } + +} \ No newline at end of file diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/config/SystemConfigurationTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/config/SystemConfigurationTest.java new file mode 100644 index 00000000000..75576be5b5a --- /dev/null +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/config/SystemConfigurationTest.java @@ -0,0 +1,117 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.config; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * The type System configuration test. + */ +class SystemConfigurationTest { + + private static SystemConfiguration sysConfig; + private static final String MOCK_KEY = "mockKey"; + private static final String MOCK_STRING_VALUE = "mockValue"; + private static final Boolean MOCK_BOOL_VALUE = Boolean.FALSE; + private static final Integer MOCK_INT_VALUE = Integer.MAX_VALUE; + private static final Long MOCK_LONG_VALUE = Long.MIN_VALUE; + private static final Short MOCK_SHORT_VALUE = Short.MIN_VALUE; + private static final Float MOCK_FLOAT_VALUE = Float.MIN_VALUE; + private static final Double MOCK_DOUBLE_VALUE = Double.MIN_VALUE; + private static final Byte MOCK_BYTE_VALUE = Byte.MIN_VALUE; + private static final String NOT_EXIST_KEY = "NOTEXIST"; + + /** + * Init. + */ + @BeforeEach + public void init() { + + sysConfig = new SystemConfiguration(); + } + + /** + * Test get sys property. + */ + @Test + public void testGetSysProperty() { + Assertions.assertNull(sysConfig.getInternalProperty(MOCK_KEY)); + Assertions.assertFalse(sysConfig.containsKey(MOCK_KEY)); + Assertions.assertNull(sysConfig.getString(MOCK_KEY)); + Assertions.assertNull(sysConfig.getProperty(MOCK_KEY)); + System.setProperty(MOCK_KEY, MOCK_STRING_VALUE); + Assertions.assertTrue(sysConfig.containsKey(MOCK_KEY)); + Assertions.assertEquals(MOCK_STRING_VALUE, sysConfig.getInternalProperty(MOCK_KEY)); + Assertions.assertEquals(MOCK_STRING_VALUE, sysConfig.getString(MOCK_KEY, MOCK_STRING_VALUE)); + Assertions.assertEquals(MOCK_STRING_VALUE, sysConfig.getProperty(MOCK_KEY, MOCK_STRING_VALUE)); + } + + /** + * Test convert. + */ + @Test + public void testConvert() { + Assertions.assertEquals( + MOCK_STRING_VALUE, sysConfig.convert(String.class, NOT_EXIST_KEY, MOCK_STRING_VALUE)); + System.setProperty(MOCK_KEY, String.valueOf(MOCK_BOOL_VALUE)); + Assertions.assertEquals(MOCK_BOOL_VALUE, sysConfig.convert(Boolean.class, MOCK_KEY, null)); + System.setProperty(MOCK_KEY, String.valueOf(MOCK_STRING_VALUE)); + Assertions.assertEquals(MOCK_STRING_VALUE, sysConfig.convert(String.class, MOCK_KEY, null)); + System.setProperty(MOCK_KEY, String.valueOf(MOCK_INT_VALUE)); + Assertions.assertEquals(MOCK_INT_VALUE, sysConfig.convert(Integer.class, MOCK_KEY, null)); + System.setProperty(MOCK_KEY, String.valueOf(MOCK_LONG_VALUE)); + Assertions.assertEquals(MOCK_LONG_VALUE, sysConfig.convert(Long.class, MOCK_KEY, null)); + System.setProperty(MOCK_KEY, String.valueOf(MOCK_SHORT_VALUE)); + Assertions.assertEquals(MOCK_SHORT_VALUE, sysConfig.convert(Short.class, MOCK_KEY, null)); + System.setProperty(MOCK_KEY, String.valueOf(MOCK_FLOAT_VALUE)); + Assertions.assertEquals(MOCK_FLOAT_VALUE, sysConfig.convert(Float.class, MOCK_KEY, null)); + System.setProperty(MOCK_KEY, String.valueOf(MOCK_DOUBLE_VALUE)); + Assertions.assertEquals(MOCK_DOUBLE_VALUE, sysConfig.convert(Double.class, MOCK_KEY, null)); + System.setProperty(MOCK_KEY, String.valueOf(MOCK_BYTE_VALUE)); + Assertions.assertEquals(MOCK_BYTE_VALUE, sysConfig.convert(Byte.class, MOCK_KEY, null)); + System.setProperty(MOCK_KEY, String.valueOf(ConfigMock.MockOne)); + Assertions.assertEquals(ConfigMock.MockOne, sysConfig.convert(ConfigMock.class, MOCK_KEY, null)); + } + + /** + * Clean. + */ + @AfterEach + public void clean() { + if (null != System.getProperty(MOCK_KEY)) { + System.clearProperty(MOCK_KEY); + } + } + + /** + * The enum Config mock. + */ + enum ConfigMock { + /** + * Mock one config mock. + */ + MockOne, + /** + * Mock two config mock. + */ + MockTwo + } + +} \ No newline at end of file From 346630e4132c9e45c547d9a2554c2b7702dabfad Mon Sep 17 00:00:00 2001 From: Peter Pan Date: Sun, 2 Jun 2019 03:04:23 +0200 Subject: [PATCH 107/115] Disclaimer removed (#4231) --- DISCLAIMER | 1 - 1 file changed, 1 deletion(-) delete mode 100644 DISCLAIMER diff --git a/DISCLAIMER b/DISCLAIMER deleted file mode 100644 index bed312a0d6e..00000000000 --- a/DISCLAIMER +++ /dev/null @@ -1 +0,0 @@ -Apache Dubbo is an effort undergoing incubation at The Apache Software Foundation (ASF), sponsored by the Incubator. Incubation is required of all newly accepted projects until a further review indicates that the infrastructure, communications, and decision making process have stabilized in a manner consistent with other successful ASF projects. While incubation status is not necessarily a reflection of the completeness or stability of the code, it does indicate that the project has yet to be fully endorsed by the ASF. \ No newline at end of file From 0b275651aa461dd241b77eaead7fd48fb656de47 Mon Sep 17 00:00:00 2001 From: web Date: Mon, 3 Jun 2019 16:24:58 +0800 Subject: [PATCH 108/115] [Dubbo-4218] Fix NPE when the TagRouterRule addresses config is null (#4218) (#4236) * Fix NPE when the TagRouterRule addresses config is null (#4218) * fix import * add more test --- .../router/tag/model/TagRouterRule.java | 8 +++- .../rpc/cluster/router/TagRouterTest.java | 45 +++++++++++++++++++ 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/TagRouterRule.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/TagRouterRule.java index 827518bda8e..154a161a214 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/TagRouterRule.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/TagRouterRule.java @@ -16,6 +16,7 @@ */ package org.apache.dubbo.rpc.cluster.router.tag.model; +import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.rpc.cluster.router.AbstractRouterRule; import java.util.ArrayList; @@ -50,7 +51,7 @@ public void init() { return; } - tags.forEach(tag -> { + tags.stream().filter(tag -> CollectionUtils.isNotEmpty(tag.getAddresses())).forEach(tag -> { tagnameToAddresses.put(tag.getName(), tag.getAddresses()); tag.getAddresses().forEach(addr -> { List tagNames = addressToTagnames.computeIfAbsent(addr, k -> new ArrayList<>()); @@ -60,7 +61,10 @@ public void init() { } public List getAddresses() { - return tags.stream().flatMap(tag -> tag.getAddresses().stream()).collect(Collectors.toList()); + return tags.stream() + .filter(tag -> CollectionUtils.isNotEmpty(tag.getAddresses())) + .flatMap(tag -> tag.getAddresses().stream()) + .collect(Collectors.toList()); } public List getTagNames() { diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/TagRouterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/TagRouterTest.java index 98cdaf4d4df..829208da27f 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/TagRouterTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/TagRouterTest.java @@ -19,6 +19,8 @@ import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; +import org.apache.dubbo.rpc.cluster.router.tag.model.TagRouterRule; +import org.apache.dubbo.rpc.cluster.router.tag.model.TagRuleParser; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -63,4 +65,47 @@ public void normalTagRuleTest() { private void setData(String path, String data) throws Exception { client.setData().forPath(path, data.getBytes()); } + + /** + * TagRouterRule parse test when the tags addresses is null + * + *

    +     *     ~ -> null
    +     *     null -> null
    +     * 
    + */ + @Test + public void tagRouterRuleParseTest(){ + String tagRouterRuleConfig = "---\n" + + "force: false\n" + + "runtime: true\n" + + "enabled: false\n" + + "priority: 1\n" + + "key: demo-provider\n" + + "tags:\n" + + " - name: tag1\n" + + " addresses: null\n" + + " - name: tag2\n" + + " addresses: [\"30.5.120.37:20880\"]\n" + + " - name: tag3\n" + + " addresses: []\n" + + " - name: tag4\n" + + " addresses: ~\n" + + "..."; + + TagRouterRule tagRouterRule = TagRuleParser.parse(tagRouterRuleConfig); + + // assert tags + assert tagRouterRule.getTagNames().contains("tag1"); + assert tagRouterRule.getTagNames().contains("tag2"); + assert tagRouterRule.getTagNames().contains("tag3"); + assert tagRouterRule.getTagNames().contains("tag4"); + // assert addresses + assert tagRouterRule.getAddresses().contains("30.5.120.37:20880"); + assert tagRouterRule.getTagnameToAddresses().get("tag1")==null; + assert tagRouterRule.getTagnameToAddresses().get("tag2").size()==1; + assert tagRouterRule.getTagnameToAddresses().get("tag3")==null; + assert tagRouterRule.getTagnameToAddresses().get("tag4")==null; + assert tagRouterRule.getAddresses().size()==1; + } } From d3a51664364471a4e54aeaa932546935e5bc99df Mon Sep 17 00:00:00 2001 From: Taosheng Wei Date: Tue, 4 Jun 2019 15:53:34 +0800 Subject: [PATCH 109/115] Delete useless code (#4242) --- .../apache/dubbo/common/config/AbstractPrefixConfiguration.java | 1 - 1 file changed, 1 deletion(-) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/AbstractPrefixConfiguration.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/AbstractPrefixConfiguration.java index c7d1598fc07..14efd7fa961 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/AbstractPrefixConfiguration.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/AbstractPrefixConfiguration.java @@ -26,7 +26,6 @@ public abstract class AbstractPrefixConfiguration implements Configuration { protected String prefix; public AbstractPrefixConfiguration(String prefix, String id) { - super(); if (StringUtils.isNotEmpty(prefix) && !prefix.endsWith(".")) { this.prefix = prefix + "."; } else { From 5d32b86f2af54dbe71f5842f75f552f7465937dc Mon Sep 17 00:00:00 2001 From: cvictory Date: Thu, 6 Jun 2019 17:14:40 +0800 Subject: [PATCH 110/115] Merge changes from 2.7.2-release (#4259) --- CHANGES.md | 89 +++++++++++++++++ README.md | 2 +- .../alibaba/dubbo/rpc/support/RpcUtils.java | 5 - .../nacos/NacosDynamicConfiguration.java | 96 ++++++++++--------- .../nacos/NacosDynamicConfigurationTest.java | 47 ++++++--- dubbo-dependencies-bom/pom.xml | 8 +- .../dubbo-dependencies-zookeeper/pom.xml | 2 +- .../store/nacos/NacosMetadataReport.java | 12 ++- .../store/nacos/NacosMetadataReportTest.java | 8 +- .../dubbo/registry/nacos/NacosRegistry.java | 2 +- .../java/org/apache/dubbo/rpc/Constants.java | 4 - .../org/apache/dubbo/rpc/RpcInvocation.java | 2 +- .../dubbo/rpc/proxy/AbstractProxyInvoker.java | 6 +- .../apache/dubbo/rpc/support/RpcUtils.java | 18 ++-- .../dubbo/rpc/protocol/dubbo/DubboCodec.java | 5 +- .../rpc/protocol/dubbo/DubboInvoker.java | 9 +- pom.xml | 2 +- 17 files changed, 212 insertions(+), 105 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 6296565891f..22495c441dd 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,94 @@ # Release Notes +## 2.7.2 + +### New Features + +- nacos config center / metadata center support. [#3846](https://github.com/apache/dubbo/issues/3846) +- Etcd support as config center and metadata center [#3653](https://github.com/apache/dubbo/issues/3653) +- Support Redis cluster in Metadata Report. [#3817](https://github.com/apache/dubbo/issues/3817) +- add new module for Dubbo Event. [#4096](https://github.com/apache/dubbo/issues/4096) +- Support multiple registry that including some effective registry, such as zk, redis [#3599](https://github.com/apache/dubbo/issues/3599) +- support nacos metadata [#4025](https://github.com/apache/dubbo/issues/4025) +- Dubbo support Google Protobuf generic reference [#3829](https://github.com/apache/dubbo/issues/3829) +- Merge serialization-native-hessian-for-apache-dubbo into incubator-dubbo [#3961](https://github.com/apache/dubbo/issues/3961) +- Merge rpc-native-thrift-for-apache-dubbo into incubator-dubbo [#3960](https://github.com/apache/dubbo/issues/3960) +- add socks5 proxy support [#3624](https://github.com/apache/dubbo/issues/3624) +- Integrate with SOFARegistry [#3874](https://github.com/apache/dubbo/issues/3874) +- Introduce CompletableFuture $invokeAsync for GenericService, now, for generic call, you can use: + $invoke for sync method call with normal return type. + $invokeAsync for async method call with CompletableFuture signature. [#3163](https://github.com/apache/dubbo/issues/3163) + +### Enhancement + +- Performance tuning for TimeoutTask in DefaultFuture. [#4129](https://github.com/apache/dubbo/issues/4129) +- Add a script to check dependencies license. [#3840](https://github.com/apache/dubbo/issues/3840) +- Change DynamicConfiguration definition to better adapt to Apollo's namespace storage model.[#3266](https://github.com/apache/dubbo/issues/3266) +- use equal explicit class to replace anonymous class [#4027](https://github.com/apache/dubbo/issues/4027) +- Seperate Constants.java into some SubConstants Class [#3137](https://github.com/apache/dubbo/issues/3137) +- Need to enhance DecodeableRpcResult error message [#3994](https://github.com/apache/dubbo/issues/3994) +- Provide more meaningful binary releases. [#2491](https://github.com/apache/dubbo/issues/2491) +- remove useless module-dubbo-test-integration [#3573](https://github.com/apache/dubbo/issues/3573) +- complete lookup method of consul registry and add integration test [#3890](https://github.com/apache/dubbo/issues/3890) +- Metrics Service [#3702](https://github.com/apache/dubbo/issues/3702) +- Update nacos-client to 1.0.0 [#3804](https://github.com/apache/dubbo/issues/3804) +- Fluent style builder API support [#3431](https://github.com/apache/dubbo/issues/3431) +- Update readme to remove the incubator prefix [#4159](https://github.com/apache/dubbo/issues/4159) +- update erlang link [#4100](https://github.com/apache/dubbo/issues/4100) +- optimize array code style [#4031](https://github.com/apache/dubbo/issues/4031) +- optimize some code style [#4006](https://github.com/apache/dubbo/issues/4006) +- remove useless module-dubbo-test-integration [#3989](https://github.com/apache/dubbo/issues/3989) +- optimize constant naming style [#3970](https://github.com/apache/dubbo/issues/3970) +- Use maven CI friendly versions: revision. [#3851](https://github.com/apache/dubbo/issues/3851) +- remove-parse-error-log [#3862](https://github.com/apache/dubbo/issues/3862) +- Complete xsd definition for ConfigCenterConfig. [#3854](https://github.com/apache/dubbo/issues/3854) +- add remoteApplicationName field in RpcContext [#3816](https://github.com/apache/dubbo/issues/3816) + +### Bugfixes + +- @Reference can't match the local @Service beans. [#4071](https://github.com/apache/dubbo/issues/4071) +- remove some illegal licence: jcip-annotations, jsr173_api. [#3790](https://github.com/apache/dubbo/issues/3790) +- Qos port can't be disabled by externalized property. [#3958](https://github.com/apache/dubbo/issues/3958) +- Fix consumer will generate wrong stackTrace. [#4137](https://github.com/apache/dubbo/issues/4137) +- nacos registry serviceName may conflict. [#4111](https://github.com/apache/dubbo/issues/4111) +- The client loses the listener when the network is reconnected. [#4115](https://github.com/apache/dubbo/issues/4115) +- fix registery urls increase forever when recreate reference proxy. [#4109](https://github.com/apache/dubbo/issues/4109) +- In dubbo 2.7.1,the watcher processor of zookeeper client throw Nullpointexception. [#3866](https://github.com/apache/dubbo/issues/3866) +- ReferenceConfig initialized not changed to false once subscribe throws exception [#4068](https://github.com/apache/dubbo/issues/4068) +- dubbo registry extension compatibility with dubbo 2.6.x. [#3882](https://github.com/apache/dubbo/issues/3882) +- Annotation mode cannot set service parameters in 2.7.0. [#3778](https://github.com/apache/dubbo/issues/3778) +- compatibility with Zipkin. [#3728](https://github.com/apache/dubbo/issues/3728) +- do local export before register any listener. [#3669](https://github.com/apache/dubbo/issues/3669) +- Cannot recognize 2.6.x compatible rules from dubbo-admin. [#4059](https://github.com/apache/dubbo/issues/4059) +- In Dubbo 2.7.0, the provider can't be configured to async [#3650](https://github.com/apache/dubbo/issues/3650) +- dubbox compatibility [#3991](https://github.com/apache/dubbo/issues/3991) +- dubbo-2.7.1 providers repeat register [#3785](https://github.com/apache/dubbo/issues/3785) +- consul registry: NullPointerException [#3923](https://github.com/apache/dubbo/issues/3923) +- cannot publish local ip address when local ip and public ip exist at the same time [#3802](https://github.com/apache/dubbo/issues/3802) +- roll back change made by 3520. [#3935](https://github.com/apache/dubbo/issues/3935) +- dubbo-registry-nacos module is not bundled into Apache Dubbo 2.7.1 [#3797](https://github.com/apache/dubbo/issues/3797) +- switch from CopyOnWriteArrayList to regular list in order to avoid potential UnsupportedOperationException [#3242](https://github.com/apache/dubbo/issues/3242) +- Serialization ContentTypeId conflict between avro protocol and protocoluff protocol [#3926](https://github.com/apache/dubbo/issues/3926) +- delay export function doesn't work. [#3952](https://github.com/apache/dubbo/issues/3952) +- org.apache.dubbo.rpc.support.MockInvoker#getInterface should not return null [#3713](https://github.com/apache/dubbo/issues/3713) +- dubbo TagRouter does not work with dubbo:parameter [#3875](https://github.com/apache/dubbo/issues/3875) +- make protocols a mutable list (a concrete ArrayList) [#3841](https://github.com/apache/dubbo/issues/3841) +- javadoc lint issue [#3646](https://github.com/apache/dubbo/issues/3646) +- The etcd3 lease should be recycled correctly [#3684](https://github.com/apache/dubbo/issues/3684) +- telnet can't work when parameter has no nullary constructor and some fields is primitive [#4007](https://github.com/apache/dubbo/issues/4007) +- Sort added router list before set the 'routers' field of the RouterChain [#3969](https://github.com/apache/dubbo/issues/3969) +- fix injvm and local call [#3638](https://github.com/apache/dubbo/issues/3638) +- spelling error in org.apache.dubbo.common.extension.AdaptiveClassCodeGenerator#generateReturnAndInovation [#3933](https://github.com/apache/dubbo/issues/3933) +- metadata report doesn't support redis with password [#3826](https://github.com/apache/dubbo/issues/3826) +- The dubbo protostuff protocol serializes the bug of java.sql.Timestamp [#3914](https://github.com/apache/dubbo/issues/3914) +- do not filter thread pool by port [#3919](https://github.com/apache/dubbo/issues/3919) +- 'dubbo-serialization-gson' maven package error [#3903](https://github.com/apache/dubbo/issues/3903) +- AbstractRegistry will be endless loop, when doSaveProperties method have no permission to save the file [#3746](https://github.com/apache/dubbo/issues/3746) +- fix fastjson serialization with generic return type [#3771](https://github.com/apache/dubbo/issues/3771) +- The dubbo-serialization -api modules should not dependency on third-party jar packages [#3762](https://github.com/apache/dubbo/issues/3762) +- when using protostuff to serialize, there is not to check whether the data is null [#3727](https://github.com/apache/dubbo/issues/3727) +- bugfix and enhancement for async [#3287](https://github.com/apache/dubbo/issues/3287) + ## 2.7.1 ### Notice diff --git a/README.md b/README.md index 6c8ae12fde5..d3c76302dcc 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ There's a [README](https://github.com/apache/dubbo-samples/tree/master/dubbo-sam ```xml - 2.7.1 + 2.7.2 diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/support/RpcUtils.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/support/RpcUtils.java index d7db04fe106..378f14adc29 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/support/RpcUtils.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/support/RpcUtils.java @@ -21,7 +21,6 @@ import com.alibaba.dubbo.rpc.Invocation; import java.lang.reflect.Type; -import java.util.Map; /** * 2019-04-18 @@ -76,8 +75,4 @@ public static boolean isReturnTypeFuture(Invocation inv) { public static boolean isOneway(URL url, Invocation inv) { return org.apache.dubbo.rpc.support.RpcUtils.isOneway(url.getOriginalURL(), inv); } - - public static Map getNecessaryAttachments(Invocation inv) { - return org.apache.dubbo.rpc.support.RpcUtils.getNecessaryAttachments(inv); - } } diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java index 96bec25f1dd..fa04c0036b7 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java @@ -46,9 +46,6 @@ import static com.alibaba.nacos.api.PropertyKeyConst.SECRET_KEY; import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; import static com.alibaba.nacos.client.naming.utils.UtilAndComs.NACOS_NAMING_LOG_NAME; -import static org.apache.dubbo.common.constants.CommonConstants.GROUP_CHAR_SEPERATOR; -import static org.apache.dubbo.common.constants.CommonConstants.PROPERTIES_CHAR_SEPERATOR; -import static org.apache.dubbo.configcenter.Constants.CONFIG_NAMESPACE_KEY; import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; /** @@ -57,11 +54,10 @@ public class NacosDynamicConfiguration implements DynamicConfiguration { private final Logger logger = LoggerFactory.getLogger(getClass()); - /** - * The final root path would be: /$NAME_SPACE/config + * the default timeout in millis to get config from nacos */ - private String rootPath; + private static final long DEFAULT_TIMEOUT = 5000L; /** * The nacos configService @@ -75,7 +71,6 @@ public class NacosDynamicConfiguration implements DynamicConfiguration { private final ConcurrentMap watchListenerMap; NacosDynamicConfiguration(URL url) { - rootPath = url.getParameter(CONFIG_NAMESPACE_KEY, DEFAULT_GROUP) + "-config"; buildConfigService(url); watchListenerMap = new ConcurrentHashMap<>(); } @@ -93,24 +88,6 @@ private ConfigService buildConfigService(URL url) { return configService; } - public void publishNacosConfig(String key, String value) { - try { - String[] keyAndGroup = getKeyAndGroup(key); - configService.publishConfig(keyAndGroup[0], keyAndGroup[1], value); - } catch (NacosException e) { - logger.error(e.getErrMsg()); - } - } - - private String[] getKeyAndGroup(String key) { - int i = key.lastIndexOf(GROUP_CHAR_SEPERATOR); - if (i < 0) { - return new String[]{key, null}; - } else { - return new String[]{key.substring(0, i), key.substring(i+1)}; - } - } - private Properties buildNacosProperties(URL url) { Properties properties = new Properties(); setServerAddr(url, properties); @@ -162,43 +139,70 @@ private NacosConfigListener createTargetListener(String key, String group) { return configListener; } + + /** + * FIXME: 2019-05-30 to remove this function + * Nacos server does not support * as valid character of data-id. + * If a Dubbo service specifies group. For example: + * + * + * + * The key passed to NacosDynamicConfiguration will be sth. like: + * test*org.apache.dubbo.demo.DemoService:1.0.0.test.configurators + * + * See logic in org.apache.dubbo.common.URL#getEncodedServiceKey() + * + * The purpose of this function is to convert the * into :, to keep align with + * the implementation in NacosRegistry. + * + * In the future this logic should be removed if Dubbo core can handle this. + * @param key + * @return + */ + private String normalizedKey(String key) { + return key.replaceFirst("\\*", ":"); + } + @Override public void addListener(String key, String group, ConfigurationListener listener) { - String[] keyAndGroup = getKeyAndGroup(key); - if (keyAndGroup[1] != null) { - group = keyAndGroup[1]; - } - String finalGroup = group; - NacosConfigListener nacosConfigListener = watchListenerMap.computeIfAbsent(generateKey(key, group), k -> createTargetListener(key, finalGroup)); - String keyInNacos = rootPath + PROPERTIES_CHAR_SEPERATOR + key; + String normalizedKey = normalizedKey(key); + NacosConfigListener nacosConfigListener = watchListenerMap.computeIfAbsent(normalizedKey, k -> createTargetListener(normalizedKey, group)); nacosConfigListener.addListener(listener); try { - configService.addListener(keyInNacos, group, nacosConfigListener); - System.out.println("1"); + configService.addListener(normalizedKey, group, nacosConfigListener); } catch (NacosException e) { logger.error(e.getMessage()); } } - private String generateKey(String key, String group) { - if (StringUtils.isNotEmpty(group)) { - key = key + GROUP_CHAR_SEPERATOR + group; - } - return key; - } - @Override public void removeListener(String key, String group, ConfigurationListener listener) { - NacosConfigListener eventListener = watchListenerMap.get(generateKey(key, group)); + String normalizedKey = normalizedKey(key); + NacosConfigListener eventListener = watchListenerMap.get(normalizedKey); if (eventListener != null) { eventListener.removeListener(listener); } } + /** + * FIXME the model of Zookeeper and Nacos is inconsistent, need to remove this function in next release. + */ + @Override + public String getConfig(String key) { + return getConfig(key, DEFAULT_GROUP, -1L); + } + @Override public String getConfig(String key, String group, long timeout) throws IllegalStateException { - key = generateKey(key, group); - return (String) getInternalProperty(rootPath + PROPERTIES_CHAR_SEPERATOR + key); + try { + String normalizedKey = normalizedKey(key); + long nacosTimeout = timeout < 0 ? DEFAULT_TIMEOUT : timeout; + return configService.getConfig(normalizedKey, group, nacosTimeout); + } catch (NacosException e) { + logger.error(e.getMessage()); + } + return null; } @Override @@ -209,8 +213,8 @@ public String getConfigs(String key, String group, long timeout) throws IllegalS @Override public Object getInternalProperty(String key) { try { - String[] keyAndGroup = getKeyAndGroup(key); - return configService.getConfig(keyAndGroup[0], keyAndGroup[1], 5000L); + String normalizedKey = normalizedKey(key); + return configService.getConfig(normalizedKey, DEFAULT_GROUP, DEFAULT_TIMEOUT); } catch (NacosException e) { logger.error(e.getMessage()); } diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java index ff785b974a6..28fa234b79f 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java @@ -17,10 +17,14 @@ package org.apache.dubbo.configcenter.support.nacos; +import com.alibaba.nacos.api.NacosFactory; +import com.alibaba.nacos.api.config.ConfigService; +import com.alibaba.nacos.api.exception.NacosException; import org.apache.dubbo.common.URL; import org.apache.dubbo.configcenter.ConfigChangeEvent; import org.apache.dubbo.configcenter.ConfigurationListener; +import org.apache.dubbo.configcenter.DynamicConfiguration; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -42,15 +46,22 @@ public class NacosDynamicConfigurationTest { private static NacosDynamicConfiguration config; + /** + * A test client to put data to Nacos server for testing purpose + */ + private static ConfigService nacosClient; + @Test public void testGetConfig() throws Exception { - - put("dubbo-config-org.apache.dubbo.nacos.testService.configurators", "hello"); + put("org.apache.dubbo.nacos.testService.configurators", "hello"); + Thread.sleep(200); + put("dubbo.properties", "test", "aaa=bbb"); Thread.sleep(200); - put("dubbo-config-dubbo.properties:test", "aaa=bbb"); + put("xxxx:org.apache.dubbo.demo.DemoService:1.0.0.test.configurators", "helloworld"); Thread.sleep(200); Assertions.assertEquals("hello", config.getConfig("org.apache.dubbo.nacos.testService.configurators")); Assertions.assertEquals("aaa=bbb", config.getConfig("dubbo.properties", "test")); + Assertions.assertEquals("helloworld", config.getConfig("xxxx*org.apache.dubbo.demo.DemoService:1.0.0.test.configurators")); } @Test @@ -67,19 +78,19 @@ public void testAddListener() throws Exception { config.addListener("testapp.tagrouters", listener3); config.addListener("testapp.tagrouters", listener4); - put("dubbo-config-AService.configurators", "new value1"); + put("AService.configurators", "new value1"); Thread.sleep(200); - put("dubbo-config-testapp.tagrouters", "new value2"); + put("testapp.tagrouters", "new value2"); Thread.sleep(200); - put("dubbo-config-testapp", "new value3"); + put("testapp", "new value3"); Thread.sleep(5000); latch.await(); - Assertions.assertEquals(1, listener1.getCount("dubbo-config-AService.configurators")); - Assertions.assertEquals(1, listener2.getCount("dubbo-config-AService.configurators")); - Assertions.assertEquals(1, listener3.getCount("dubbo-config-testapp.tagrouters")); - Assertions.assertEquals(1, listener4.getCount("dubbo-config-testapp.tagrouters")); + Assertions.assertEquals(1, listener1.getCount("AService.configurators")); + Assertions.assertEquals(1, listener2.getCount("AService.configurators")); + Assertions.assertEquals(1, listener3.getCount("testapp.tagrouters")); + Assertions.assertEquals(1, listener4.getCount("testapp.tagrouters")); Assertions.assertEquals("new value1", listener1.getValue()); Assertions.assertEquals("new value1", listener2.getValue()); @@ -89,8 +100,12 @@ public void testAddListener() throws Exception { } private void put(String key, String value) { + put(key, DynamicConfiguration.DEFAULT_GROUP, value); + } + + private void put(String key, String group, String value) { try { - config.publishNacosConfig(key, value); + nacosClient.publishConfig(key, group, value); } catch (Exception e) { System.out.println("Error put value to nacos."); } @@ -103,10 +118,18 @@ public static void setUp() { URL url = URL.valueOf(urlForDubbo) .addParameter(SESSION_TIMEOUT_KEY, 15000); config = new NacosDynamicConfiguration(url); + + + try { + nacosClient = NacosFactory.createConfigService("127.0.0.1:8848"); + } catch (NacosException e) { + e.printStackTrace(); + } } @AfterAll public static void tearDown() { + } private class TestListener implements ConfigurationListener { @@ -121,7 +144,7 @@ public TestListener(CountDownLatch latch) { @Override public void process(ConfigChangeEvent event) { System.out.println(this + ": " + event); - Integer count = countMap.computeIfAbsent(event.getKey(), k -> new Integer(0)); + Integer count = countMap.computeIfAbsent(event.getKey(), k -> 0); countMap.put(event.getKey(), ++count); value = event.getValue(); latch.countDown(); diff --git a/dubbo-dependencies-bom/pom.xml b/dubbo-dependencies-bom/pom.xml index 3573df1ed36..20c17b66317 100644 --- a/dubbo-dependencies-bom/pom.xml +++ b/dubbo-dependencies-bom/pom.xml @@ -153,7 +153,7 @@ 6.1.26 2.0 1.1.0 - 2.7.2-SNAPSHOT + 2.7.3-SNAPSHOT @@ -597,6 +597,12 @@ io.etcd jetcd-launcher ${etcd_launcher_version} + + + com.github.spotbugs + spotbugs-annotations + +
    org.testcontainers diff --git a/dubbo-dependencies/dubbo-dependencies-zookeeper/pom.xml b/dubbo-dependencies/dubbo-dependencies-zookeeper/pom.xml index 66dba910f4f..968e5e35bcb 100644 --- a/dubbo-dependencies/dubbo-dependencies-zookeeper/pom.xml +++ b/dubbo-dependencies/dubbo-dependencies-zookeeper/pom.xml @@ -32,7 +32,7 @@ pom - 2.7.2-SNAPSHOT + 2.7.3-SNAPSHOT 1.1.0 diff --git a/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java b/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java index 03bdeb8f958..b12e4f014f3 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java +++ b/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java @@ -37,18 +37,28 @@ import static com.alibaba.nacos.api.PropertyKeyConst.NAMESPACE; import static com.alibaba.nacos.api.PropertyKeyConst.CLUSTER_NAME; import static com.alibaba.nacos.client.naming.utils.UtilAndComs.NACOS_NAMING_LOG_NAME; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; /** * metadata report impl for nacos */ public class NacosMetadataReport extends AbstractMetadataReport { + private static final Logger logger = LoggerFactory.getLogger(NacosMetadataReport.class); + private ConfigService configService; + /** + * The group used to store metadata in Nacos + */ + private String group; + + public NacosMetadataReport(URL url) { super(url); this.configService = buildConfigService(url); + group = url.getParameter(GROUP_KEY, DEFAULT_ROOT); } public ConfigService buildConfigService(URL url) { @@ -113,7 +123,7 @@ protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdenti private void storeMetadata(MetadataIdentifier identifier, String value) { try { - boolean publishResult = configService.publishConfig(identifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY), identifier.getGroup(), value); + boolean publishResult = configService.publishConfig(identifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY), group, value); if (!publishResult) { throw new RuntimeException("publish nacos metadata failed"); } diff --git a/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java b/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java index 07d6f8b839a..a6cf8f5dc5f 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java +++ b/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java @@ -45,10 +45,12 @@ public class NacosMetadataReportTest { private NacosMetadataReportFactory nacosMetadataReportFactory; private ConfigService configService; + private static final String NACOS_GROUP = "zzz"; + @BeforeEach public void setUp() { // timeout in 15 seconds. - URL url = URL.valueOf("nacos://127.0.0.1:8848") + URL url = URL.valueOf("nacos://127.0.0.1:8848?group=" + NACOS_GROUP) .addParameter(SESSION_TIMEOUT_KEY, 15000); nacosMetadataReportFactory = new NacosMetadataReportFactory(); this.nacosMetadataReport = (NacosMetadataReport) nacosMetadataReportFactory.createMetadataReport(url); @@ -66,7 +68,7 @@ public void testStoreProvider() throws Exception { String application = "nacos-metdata-report-test"; MetadataIdentifier providerIdentifier = storeProvider(nacosMetadataReport, TEST_SERVICE, version, group, application); - String serverContent = configService.getConfig(providerIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY), group, 5000L); + String serverContent = configService.getConfig(providerIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY), NACOS_GROUP, 5000L); Assertions.assertNotNull(serverContent); Gson gson = new Gson(); @@ -81,7 +83,7 @@ public void testStoreConsumer() throws Exception { String application = "nacos-metadata-report-consumer-test"; MetadataIdentifier consumerIdentifier = storeConsumer(nacosMetadataReport, TEST_SERVICE, version, group, application); - String serverContent = configService.getConfig(consumerIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY), group, 5000L); + String serverContent = configService.getConfig(consumerIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY), NACOS_GROUP, 5000L); Assertions.assertNotNull(serverContent); Assertions.assertEquals(serverContent, "{\"paramConsumerTest\":\"nacosConsumer\"}"); } diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java index 6639962fa88..54830528471 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java @@ -383,7 +383,7 @@ private void notifySubscriber(URL url, NotifyListener listener, Collection attachment) { diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyInvoker.java index fe42fb2c6be..4008c447ba2 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyInvoker.java @@ -27,7 +27,6 @@ import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.support.RpcUtils; import java.lang.reflect.InvocationTargetException; import java.util.concurrent.CompletableFuture; @@ -112,10 +111,7 @@ public Result invoke(Invocation invocation) throws RpcException { private CompletableFuture wrapWithFuture (Object value, Invocation invocation) { if (RpcContext.getContext().isAsyncStarted()) { return ((AsyncContextImpl)(RpcContext.getContext().getAsyncContext())).getInternalFuture(); - } else if (RpcUtils.isReturnTypeFuture(invocation)) { - if (value == null) { - return CompletableFuture.completedFuture(null); - } + } else if (value instanceof CompletableFuture) { return (CompletableFuture) value; } return CompletableFuture.completedFuture(value); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java index 955cb31f986..2d70a9ed8e1 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java @@ -27,8 +27,6 @@ import java.lang.reflect.Method; import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicLong; @@ -36,7 +34,6 @@ import static org.apache.dubbo.rpc.Constants.$INVOKE_ASYNC; import static org.apache.dubbo.rpc.Constants.ASYNC_KEY; import static org.apache.dubbo.rpc.Constants.AUTO_ATTACH_INVOCATIONID_KEY; -import static org.apache.dubbo.rpc.Constants.FUTURE_GENERATED_KEY; import static org.apache.dubbo.rpc.Constants.ID_KEY; import static org.apache.dubbo.rpc.Constants.RETURN_KEY; /** @@ -171,7 +168,12 @@ public static boolean isAsync(URL url, Invocation inv) { } public static boolean isReturnTypeFuture(Invocation inv) { - Class clazz = getReturnType(inv); + Class clazz; + if (inv instanceof RpcInvocation) { + clazz = ((RpcInvocation) inv).getReturnType(); + } else { + clazz = getReturnType(inv); + } return (clazz != null && CompletableFuture.class.isAssignableFrom(clazz)) || isGenericAsync(inv); } @@ -198,12 +200,4 @@ public static boolean isOneway(URL url, Invocation inv) { } return isOneway; } - - public static Map getNecessaryAttachments(Invocation inv) { - Map attachments = new HashMap<>(inv.getAttachments()); - attachments.remove(ASYNC_KEY); - attachments.remove(FUTURE_GENERATED_KEY); - return attachments; - } - } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java index dd3e8477486..3b8fe669011 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java @@ -33,17 +33,16 @@ import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.support.RpcUtils; import java.io.IOException; import java.io.InputStream; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.remoting.Constants.DUBBO_VERSION_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.CallbackServiceCodec.encodeInvocationArgument; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.DECODE_IN_IO_THREAD_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.DEFAULT_DECODE_IN_IO_THREAD; -import static org.apache.dubbo.remoting.Constants.DUBBO_VERSION_KEY; /** * Dubbo codec. @@ -186,7 +185,7 @@ protected void encodeRequestData(Channel channel, ObjectOutput out, Object data, out.writeObject(encodeInvocationArgument(channel, inv, i)); } } - out.writeObject(RpcUtils.getNecessaryAttachments(inv)); + out.writeObject(inv.getAttachments()); } @Override diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java index f40b664e160..ece71497c53 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java @@ -23,7 +23,6 @@ import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.TimeoutException; import org.apache.dubbo.remoting.exchange.ExchangeClient; -import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -97,13 +96,7 @@ protected Result doInvoke(final Invocation invocation) throws Throwable { } else { AsyncRpcResult asyncRpcResult = new AsyncRpcResult(inv); CompletableFuture responseFuture = currentClient.request(inv, timeout); - responseFuture.whenComplete((obj, t) -> { - if (t != null) { - asyncRpcResult.completeExceptionally(t); - } else { - asyncRpcResult.complete((AppResponse) obj); - } - }); + asyncRpcResult.subscribeTo(responseFuture); RpcContext.getContext().setFuture(new FutureAdapter(asyncRpcResult)); return asyncRpcResult; } diff --git a/pom.xml b/pom.xml index 16afc2714ff..338a613b453 100644 --- a/pom.xml +++ b/pom.xml @@ -125,7 +125,7 @@ true true - 2.7.2-SNAPSHOT + 2.7.3-SNAPSHOT From 78aea48cd710fc797b69c4eb2176f72554be3fd7 Mon Sep 17 00:00:00 2001 From: Huang YunKun Date: Thu, 6 Jun 2019 22:52:44 +0800 Subject: [PATCH 111/115] [Dubbo-4183] Fix unstable tests in ConditionRouterTest (#4226) --- .../router/condition/ConditionRouterTest.java | 109 +++++++++--------- .../store/etcd/EtcdMetadataReportTest.java | 2 + 2 files changed, 56 insertions(+), 55 deletions(-) diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java index a88a7591610..ba400f0e7c5 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionRouterTest.java @@ -18,7 +18,6 @@ import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; @@ -37,7 +36,7 @@ import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY; public class ConditionRouterTest { - + private static final String LOCAL_HOST = "127.0.0.1"; private URL SCRIPT_URL = URL.valueOf("condition://0.0.0.0/com.foo.BarService"); @BeforeAll @@ -90,9 +89,9 @@ public void testRoute_matchFilter() { List> invokers = new ArrayList>(); Invoker invoker1 = new MockInvoker(URL.valueOf( "dubbo://10.20.3.3:20880/com.foo.BarService?default.serialization=fastjson")); - Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); - Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); invokers.add(invoker1); invokers.add(invoker2); @@ -102,32 +101,32 @@ public void testRoute_matchFilter() { System.err.println(invoker3.getUrl().getAddress()); Router router1 = new ConditionRouterFactory().getRouter(getRouteUrl( - "host = " + NetUtils.getLocalHost() + " => " + " host = 10.20.3.3").addParameter(FORCE_KEY, + "host = " + LOCAL_HOST + " => " + " host = 10.20.3.3").addParameter(FORCE_KEY, String.valueOf(true))); Router router2 = new ConditionRouterFactory().getRouter(getRouteUrl( - "host = " + NetUtils.getLocalHost() + " => " + " host = 10.20.3.* & host != 10.20.3.3").addParameter( + "host = " + LOCAL_HOST + " => " + " host = 10.20.3.* & host != 10.20.3.3").addParameter( FORCE_KEY, String.valueOf(true))); Router router3 = new ConditionRouterFactory().getRouter(getRouteUrl( - "host = " + NetUtils.getLocalHost() + " => " + " host = 10.20.3.3 & host != 10.20.3.3").addParameter( + "host = " + LOCAL_HOST + " => " + " host = 10.20.3.3 & host != 10.20.3.3").addParameter( FORCE_KEY, String.valueOf(true))); Router router4 = new ConditionRouterFactory().getRouter(getRouteUrl( - "host = " + NetUtils.getLocalHost() + " => " + " host = 10.20.3.2,10.20.3.3,10.20.3.4").addParameter( + "host = " + LOCAL_HOST + " => " + " host = 10.20.3.2,10.20.3.3,10.20.3.4").addParameter( FORCE_KEY, String.valueOf(true))); Router router5 = new ConditionRouterFactory().getRouter(getRouteUrl( - "host = " + NetUtils.getLocalHost() + " => " + " host != 10.20.3.3").addParameter(FORCE_KEY, + "host = " + LOCAL_HOST + " => " + " host != 10.20.3.3").addParameter(FORCE_KEY, String.valueOf(true))); Router router6 = new ConditionRouterFactory().getRouter(getRouteUrl( - "host = " + NetUtils.getLocalHost() + " => " + " serialization = fastjson").addParameter( + "host = " + LOCAL_HOST + " => " + " serialization = fastjson").addParameter( FORCE_KEY, String.valueOf(true))); - List> filteredInvokers1 = router1.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation()); - List> filteredInvokers2 = router2.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation()); - List> filteredInvokers3 = router3.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation()); - List> filteredInvokers4 = router4.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation()); - List> filteredInvokers5 = router5.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation()); - List> filteredInvokers6 = router6.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation()); + List> filteredInvokers1 = router1.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation()); + List> filteredInvokers2 = router2.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation()); + List> filteredInvokers3 = router3.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation()); + List> filteredInvokers4 = router4.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation()); + List> filteredInvokers5 = router5.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation()); + List> filteredInvokers6 = router6.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation()); Assertions.assertEquals(1, filteredInvokers1.size()); Assertions.assertEquals(0, filteredInvokers2.size()); Assertions.assertEquals(0, filteredInvokers3.size()); @@ -163,74 +162,74 @@ public void testRoute_methodRoute() { // Test filter condition List> invokers = new ArrayList>(); Invoker invoker1 = new MockInvoker(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService")); - Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); - Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); invokers.add(invoker1); invokers.add(invoker2); invokers.add(invoker3); Router router4 = new ConditionRouterFactory().getRouter(getRouteUrl( - "host = " + NetUtils.getLocalHost() + " & methods = getFoo => " + " host = 10.20.3.3").addParameter( + "host = " + LOCAL_HOST + " & methods = getFoo => " + " host = 10.20.3.3").addParameter( FORCE_KEY, String.valueOf(true))); List> filteredInvokers1 = router4.route(invokers, - URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), invocation); + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), invocation); Assertions.assertEquals(1, filteredInvokers1.size()); Router router5 = new ConditionRouterFactory().getRouter(getRouteUrl( - "host = " + NetUtils.getLocalHost() + " & methods = unvalidmethod => " + " host = 10.20.3.3") + "host = " + LOCAL_HOST + " & methods = unvalidmethod => " + " host = 10.20.3.3") .addParameter(FORCE_KEY, String.valueOf(true))); List> filteredInvokers2 = router5.route(invokers, - URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), invocation); + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), invocation); Assertions.assertEquals(3, filteredInvokers2.size()); // Request a non-exists method } @Test public void testRoute_ReturnFalse() { - Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + NetUtils.getLocalHost() + " => false")); + Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + LOCAL_HOST + " => false")); List> invokers = new ArrayList>(); invokers.add(new MockInvoker()); invokers.add(new MockInvoker()); invokers.add(new MockInvoker()); - List> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation()); + List> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation()); Assertions.assertEquals(0, filteredInvokers.size()); } @Test public void testRoute_ReturnEmpty() { - Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + NetUtils.getLocalHost() + " => ")); + Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + LOCAL_HOST + " => ")); List> invokers = new ArrayList>(); invokers.add(new MockInvoker()); invokers.add(new MockInvoker()); invokers.add(new MockInvoker()); - List> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation()); + List> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation()); Assertions.assertEquals(0, filteredInvokers.size()); } @Test public void testRoute_ReturnAll() { - Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + NetUtils.getLocalHost() + " => " + " host = " + NetUtils.getLocalHost())); + Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + LOCAL_HOST + " => " + " host = " + LOCAL_HOST)); List> invokers = new ArrayList>(); - invokers.add(new MockInvoker(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService"))); - invokers.add(new MockInvoker(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService"))); - invokers.add(new MockInvoker(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService"))); - List> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation()); + invokers.add(new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"))); + invokers.add(new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"))); + invokers.add(new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"))); + List> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation()); Assertions.assertEquals(invokers, filteredInvokers); } @Test public void testRoute_HostFilter() { - Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + NetUtils.getLocalHost() + " => " + " host = " + NetUtils.getLocalHost())); + Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + LOCAL_HOST + " => " + " host = " + LOCAL_HOST)); List> invokers = new ArrayList>(); Invoker invoker1 = new MockInvoker(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService")); - Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService")); - Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService")); + Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); invokers.add(invoker1); invokers.add(invoker2); invokers.add(invoker3); - List> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation()); + List> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation()); Assertions.assertEquals(2, filteredInvokers.size()); Assertions.assertEquals(invoker2, filteredInvokers.get(0)); Assertions.assertEquals(invoker3, filteredInvokers.get(1)); @@ -238,15 +237,15 @@ public void testRoute_HostFilter() { @Test public void testRoute_Empty_HostFilter() { - Router router = new ConditionRouterFactory().getRouter(getRouteUrl(" => " + " host = " + NetUtils.getLocalHost())); + Router router = new ConditionRouterFactory().getRouter(getRouteUrl(" => " + " host = " + LOCAL_HOST)); List> invokers = new ArrayList>(); Invoker invoker1 = new MockInvoker(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService")); - Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService")); - Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService")); + Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); invokers.add(invoker1); invokers.add(invoker2); invokers.add(invoker3); - List> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation()); + List> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation()); Assertions.assertEquals(2, filteredInvokers.size()); Assertions.assertEquals(invoker2, filteredInvokers.get(0)); Assertions.assertEquals(invoker3, filteredInvokers.get(1)); @@ -254,15 +253,15 @@ public void testRoute_Empty_HostFilter() { @Test public void testRoute_False_HostFilter() { - Router router = new ConditionRouterFactory().getRouter(getRouteUrl("true => " + " host = " + NetUtils.getLocalHost())); + Router router = new ConditionRouterFactory().getRouter(getRouteUrl("true => " + " host = " + LOCAL_HOST)); List> invokers = new ArrayList>(); Invoker invoker1 = new MockInvoker(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService")); - Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService")); - Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService")); + Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); invokers.add(invoker1); invokers.add(invoker2); invokers.add(invoker3); - List> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation()); + List> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation()); Assertions.assertEquals(2, filteredInvokers.size()); Assertions.assertEquals(invoker2, filteredInvokers.get(0)); Assertions.assertEquals(invoker3, filteredInvokers.get(1)); @@ -270,15 +269,15 @@ public void testRoute_False_HostFilter() { @Test public void testRoute_Placeholder() { - Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + NetUtils.getLocalHost() + " => " + " host = $host")); + Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + LOCAL_HOST + " => " + " host = $host")); List> invokers = new ArrayList>(); Invoker invoker1 = new MockInvoker(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService")); - Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService")); - Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService")); + Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); invokers.add(invoker1); invokers.add(invoker2); invokers.add(invoker3); - List> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation()); + List> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation()); Assertions.assertEquals(2, filteredInvokers.size()); Assertions.assertEquals(invoker2, filteredInvokers.get(0)); Assertions.assertEquals(invoker3, filteredInvokers.get(1)); @@ -286,29 +285,29 @@ public void testRoute_Placeholder() { @Test public void testRoute_NoForce() { - Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + NetUtils.getLocalHost() + " => " + " host = 1.2.3.4")); + Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + LOCAL_HOST + " => " + " host = 1.2.3.4")); List> invokers = new ArrayList>(); Invoker invoker1 = new MockInvoker(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService")); - Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService")); - Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService")); + Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); invokers.add(invoker1); invokers.add(invoker2); invokers.add(invoker3); - List> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation()); + List> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation()); Assertions.assertEquals(invokers, filteredInvokers); } @Test public void testRoute_Force() { - Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + NetUtils.getLocalHost() + " => " + " host = 1.2.3.4").addParameter(FORCE_KEY, String.valueOf(true))); + Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + LOCAL_HOST + " => " + " host = 1.2.3.4").addParameter(FORCE_KEY, String.valueOf(true))); List> invokers = new ArrayList>(); Invoker invoker1 = new MockInvoker(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService")); - Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService")); - Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService")); + Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); invokers.add(invoker1); invokers.add(invoker2); invokers.add(invoker3); - List> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation()); + List> filteredInvokers = router.route(invokers, URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation()); Assertions.assertEquals(0, filteredInvokers.size()); } diff --git a/dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java b/dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java index 770b058e070..2f45171b451 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java +++ b/dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java @@ -32,6 +32,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.net.URI; @@ -73,6 +74,7 @@ public void tearDown() throws Exception { } @Test + @Disabled("Disabled because https://github.com/apache/dubbo/issues/4185") public void testStoreProvider() throws Exception { String version = "1.0.0"; String group = null; From 76d65620f1daca9526111dc106909baecbbff5a5 Mon Sep 17 00:00:00 2001 From: Huang YunKun Date: Thu, 6 Jun 2019 22:57:24 +0800 Subject: [PATCH 112/115] [CI] Add jenkinsfile for dubbo snapshot deployment (#4205) --- Jenkinsfile | 138 ++++++++++++++++++++++++++++++++++++++++++++++++++++ pom.xml | 1 + 2 files changed, 139 insertions(+) create mode 100644 Jenkinsfile diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 00000000000..ebf2d30446a --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,138 @@ +import groovy.json.JsonSlurper + +pipeline { + agent { + node { + label 'ubuntu' + } + } + + options { + buildDiscarder(logRotator(daysToKeepStr: '14', artifactNumToKeepStr: '10')) + } + + environment { + JAVA_HOME = "${tool 'JDK 1.8 (latest)'}" + } + + tools { + maven 'Maven 3 (latest)' + jdk 'JDK 1.8 (latest)' + } + + triggers { + cron '''TZ=Asia/Shanghai + H 2,14 * * *''' + pollSCM '''TZ=Asia/Shanghai + H H/2 * * *''' + } + + + stages { + stage('Clone') { + steps { + checkout([$class: 'GitSCM', branches: [[name: '*/master']], doGenerateSubmoduleConfigurations: false, extensions: [[$class: 'CloneOption', noTags: true, reference: '', shallow: true]], gitTool: 'Default', submoduleCfg: [], userRemoteConfigs: [[url: 'https://github.com/apache/dubbo.git']]]) + } + } + + stage('Duplicate deploy check') { + steps { + script { + def deployedCommitId = sh(returnStdout: true, script: "curl --silent https://builds.apache.org/job/Apache%20Dubbo/job/${env.JOB_BASE_NAME}/lastSuccessfulBuild/artifact/DEPLOY_COMMIT_ID || true").trim() + env.DEPLOYED_COMMIT_ID = deployedCommitId + def commitId = sh(returnStdout: true, script: 'git rev-parse HEAD').trim() + env.COMMIT_ID = commitId + + if (commitId == deployedCommitId) { + env.STATUS_CHECK = "false" + println "Latest deployed commit id is $deployedCommitId, Skip deployment this time" + } else { + env.STATUS_CHECK = "true" + println "Current commit id hasn't been deployed, continue" + } + } + } + } + + stage('Commit status check') { + when { + expression { + return env.STATUS_CHECK == "true"; + } + } + steps { + script { + def commitId = env.COMMIT_ID + println "Current commit id: $commitId" + + def commitStatusJson = sh(script: "curl --silent https://api.github.com/repos/apache/dubbo/commits/$commitId/status", returnStdout: true).trim() + println "Commit status: \r\n$commitStatusJson" + + def jsonSlurper = new JsonSlurper() + def jsonObject = jsonSlurper.parseText(commitStatusJson) + + def status = jsonObject.state + + println "Current commit status is $status" + + if (status == "success") { + env.STATUS_CHECK = "true" + println "Continue to deploy snapshot" + } else { + env.STATUS_CHECK = "false" + println "Current commit status not allow to deploy snapshot" + } + } + } + } + + stage('Snapshot version check') { + when { + expression { + return env.STATUS_CHECK == "true"; + } + } + steps { + sh 'env' + sh 'java -version' + sh './mvnw clean install -pl "dubbo-dependencies-bom" && ./mvnw clean install -DskipTests=true && ./mvnw clean validate -Psnapshot-ci-deploy -pl "dubbo-all"' + } + } + + stage('Deploy snapshot') { + when { + expression { + return env.STATUS_CHECK == "true"; + } + } + steps { + timeout(35) { + sh './mvnw --version' + sh './mvnw clean package deploy -pl dubbo-dependencies-bom && ./mvnw clean package deploy -DskipTests=true' + } + } + } + + stage('Save deployed commit id') { + steps { + script { + if (env.STATUS_CHECK != "true") { + println "Not pass status check" + env.COMMIT_ID = env.DEPLOYED_COMMIT_ID + } + } + writeFile file: 'DEPLOY_COMMIT_ID', text: "${env.COMMIT_ID}" + archiveArtifacts 'DEPLOY_COMMIT_ID' + } + } + } + + post { + failure { + mail bcc: '', body: '''Project: ${env.JOB_NAME} + Build Number: ${env.BUILD_NUMBER} + URL: ${env.BUILD_URL}''', cc: '', from: '', replyTo: '', subject: 'Apache Dubbo snapshot deployment fail', to: 'dev@dubbo.apache.org' + } + } + +} diff --git a/pom.xml b/pom.xml index 338a613b453..97c992126ee 100644 --- a/pom.xml +++ b/pom.xml @@ -514,6 +514,7 @@ PULL_REQUEST_TEMPLATE.md CONTRIBUTING.md README.md + Jenkinsfile **/codestyle/* **/resources/META-INF/** From 3acf5b8af129f58b31bcdae876ce4c73f520e161 Mon Sep 17 00:00:00 2001 From: zhangjianwei Date: Sat, 8 Jun 2019 09:36:40 +0800 Subject: [PATCH 113/115] fix org.apache.dubbo.common.URL#toMap change password key, from USERNAME_KEY to PASSWORD_KEY (#4267) LGTM --- dubbo-common/src/main/java/org/apache/dubbo/common/URL.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java b/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java index 106bebc70c2..2935387295a 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java @@ -1168,7 +1168,7 @@ public Map toMap() { map.put(USERNAME_KEY, username); } if (password != null) { - map.put(USERNAME_KEY, password); + map.put(PASSWORD_KEY, password); } if (host != null) { map.put(HOST_KEY, host); From 6f3a05ca820dc6e3dab127cd9a5daa375709347a Mon Sep 17 00:00:00 2001 From: andyqian <940753574@qq.com> Date: Fri, 14 Jun 2019 00:42:11 +0800 Subject: [PATCH 114/115] =?UTF-8?q?1.=20=E5=B0=86URL=E4=B8=AD=E7=9A=84?= =?UTF-8?q?=E9=BB=98=E8=AE=A4=E5=80=BC=E4=BD=BF=E7=94=A8=E4=B8=89=E7=9B=AE?= =?UTF-8?q?=E8=BF=90=E7=AE=97=E7=AC=A6=E8=A1=A8=E7=A4=BA=E3=80=82=20(#4301?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/org/apache/dubbo/common/URL.java | 117 ++++-------------- 1 file changed, 25 insertions(+), 92 deletions(-) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java b/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java index 2935387295a..bf8e62c08eb 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java @@ -493,26 +493,17 @@ public String getParameterAndDecoded(String key, String defaultValue) { public String getParameter(String key) { String value = parameters.get(key); - if (StringUtils.isEmpty(value)) { - value = parameters.get(DEFAULT_KEY_PREFIX + key); - } - return value; + return StringUtils.isEmpty(value) ? parameters.get(DEFAULT_KEY_PREFIX + key) : value; } public String getParameter(String key, String defaultValue) { String value = getParameter(key); - if (StringUtils.isEmpty(value)) { - return defaultValue; - } - return value; + return StringUtils.isEmpty(value) ? defaultValue : value; } public String[] getParameter(String key, String[] defaultValue) { String value = getParameter(key); - if (StringUtils.isEmpty(value)) { - return defaultValue; - } - return COMMA_SPLIT_PATTERN.split(value); + return StringUtils.isEmpty(value) ? defaultValue : COMMA_SPLIT_PATTERN.split(value); } public List getParameter(String key, List defaultValue) { @@ -525,17 +516,13 @@ public List getParameter(String key, List defaultValue) { } private Map getNumbers() { - if (numbers == null) { // concurrent initialization is tolerant - numbers = new ConcurrentHashMap<>(); - } - return numbers; + // concurrent initialization is tolerant + return numbers == null ? new ConcurrentHashMap<>() : numbers; } private Map getUrls() { - if (urls == null) { // concurrent initialization is tolerant - urls = new ConcurrentHashMap<>(); - } - return urls; + // concurrent initialization is tolerant + return urls == null ? new ConcurrentHashMap<>() : urls; } public URL getUrlParameter(String key) { @@ -641,10 +628,7 @@ public float getPositiveParameter(String key, float defaultValue) { throw new IllegalArgumentException("defaultValue <= 0"); } float value = getParameter(key, defaultValue); - if (value <= 0) { - return defaultValue; - } - return value; + return value <= 0 ? defaultValue : value; } public double getPositiveParameter(String key, double defaultValue) { @@ -652,10 +636,7 @@ public double getPositiveParameter(String key, double defaultValue) { throw new IllegalArgumentException("defaultValue <= 0"); } double value = getParameter(key, defaultValue); - if (value <= 0) { - return defaultValue; - } - return value; + return value <= 0 ? defaultValue : value; } public long getPositiveParameter(String key, long defaultValue) { @@ -663,10 +644,7 @@ public long getPositiveParameter(String key, long defaultValue) { throw new IllegalArgumentException("defaultValue <= 0"); } long value = getParameter(key, defaultValue); - if (value <= 0) { - return defaultValue; - } - return value; + return value <= 0 ? defaultValue : value; } public int getPositiveParameter(String key, int defaultValue) { @@ -674,10 +652,7 @@ public int getPositiveParameter(String key, int defaultValue) { throw new IllegalArgumentException("defaultValue <= 0"); } int value = getParameter(key, defaultValue); - if (value <= 0) { - return defaultValue; - } - return value; + return value <= 0 ? defaultValue : value; } public short getPositiveParameter(String key, short defaultValue) { @@ -685,10 +660,7 @@ public short getPositiveParameter(String key, short defaultValue) { throw new IllegalArgumentException("defaultValue <= 0"); } short value = getParameter(key, defaultValue); - if (value <= 0) { - return defaultValue; - } - return value; + return value <= 0 ? defaultValue : value; } public byte getPositiveParameter(String key, byte defaultValue) { @@ -696,26 +668,17 @@ public byte getPositiveParameter(String key, byte defaultValue) { throw new IllegalArgumentException("defaultValue <= 0"); } byte value = getParameter(key, defaultValue); - if (value <= 0) { - return defaultValue; - } - return value; + return value <= 0 ? defaultValue : value; } public char getParameter(String key, char defaultValue) { String value = getParameter(key); - if (StringUtils.isEmpty(value)) { - return defaultValue; - } - return value.charAt(0); + return StringUtils.isEmpty(value) ? defaultValue : value.charAt(0); } public boolean getParameter(String key, boolean defaultValue) { String value = getParameter(key); - if (StringUtils.isEmpty(value)) { - return defaultValue; - } - return Boolean.parseBoolean(value); + return StringUtils.isEmpty(value) ? defaultValue : Boolean.parseBoolean(value); } public boolean hasParameter(String key) { @@ -733,18 +696,12 @@ public String getMethodParameterAndDecoded(String method, String key, String def public String getMethodParameter(String method, String key) { String value = parameters.get(method + "." + key); - if (StringUtils.isEmpty(value)) { - return getParameter(key); - } - return value; + return StringUtils.isEmpty(value) ? getParameter(key) : value; } public String getMethodParameter(String method, String key, String defaultValue) { String value = getMethodParameter(method, key); - if (StringUtils.isEmpty(value)) { - return defaultValue; - } - return value; + return StringUtils.isEmpty(value) ? defaultValue : value; } public double getMethodParameter(String method, String key, double defaultValue) { @@ -842,10 +799,7 @@ public double getMethodPositiveParameter(String method, String key, double defau throw new IllegalArgumentException("defaultValue <= 0"); } double value = getMethodParameter(method, key, defaultValue); - if (value <= 0) { - return defaultValue; - } - return value; + return value <= 0 ? defaultValue : value; } public float getMethodPositiveParameter(String method, String key, float defaultValue) { @@ -853,10 +807,7 @@ public float getMethodPositiveParameter(String method, String key, float default throw new IllegalArgumentException("defaultValue <= 0"); } float value = getMethodParameter(method, key, defaultValue); - if (value <= 0) { - return defaultValue; - } - return value; + return value <= 0 ? defaultValue : value; } public long getMethodPositiveParameter(String method, String key, long defaultValue) { @@ -864,10 +815,7 @@ public long getMethodPositiveParameter(String method, String key, long defaultVa throw new IllegalArgumentException("defaultValue <= 0"); } long value = getMethodParameter(method, key, defaultValue); - if (value <= 0) { - return defaultValue; - } - return value; + return value <= 0 ? defaultValue : value; } public int getMethodPositiveParameter(String method, String key, int defaultValue) { @@ -875,10 +823,7 @@ public int getMethodPositiveParameter(String method, String key, int defaultValu throw new IllegalArgumentException("defaultValue <= 0"); } int value = getMethodParameter(method, key, defaultValue); - if (value <= 0) { - return defaultValue; - } - return value; + return value <= 0 ? defaultValue : value; } public short getMethodPositiveParameter(String method, String key, short defaultValue) { @@ -886,10 +831,7 @@ public short getMethodPositiveParameter(String method, String key, short default throw new IllegalArgumentException("defaultValue <= 0"); } short value = getMethodParameter(method, key, defaultValue); - if (value <= 0) { - return defaultValue; - } - return value; + return value <= 0 ? defaultValue : value; } public byte getMethodPositiveParameter(String method, String key, byte defaultValue) { @@ -897,26 +839,17 @@ public byte getMethodPositiveParameter(String method, String key, byte defaultVa throw new IllegalArgumentException("defaultValue <= 0"); } byte value = getMethodParameter(method, key, defaultValue); - if (value <= 0) { - return defaultValue; - } - return value; + return value <= 0 ? defaultValue : value; } public char getMethodParameter(String method, String key, char defaultValue) { String value = getMethodParameter(method, key); - if (StringUtils.isEmpty(value)) { - return defaultValue; - } - return value.charAt(0); + return StringUtils.isEmpty(value) ? defaultValue : value.charAt(0); } public boolean getMethodParameter(String method, String key, boolean defaultValue) { String value = getMethodParameter(method, key); - if (StringUtils.isEmpty(value)) { - return defaultValue; - } - return Boolean.parseBoolean(value); + return StringUtils.isEmpty(value) ? defaultValue : Boolean.parseBoolean(value); } public boolean hasMethodParameter(String method, String key) { From 041a6addc185fd2ec948fb6e007cb9cced09646f Mon Sep 17 00:00:00 2001 From: jimin Date: Tue, 18 Jun 2019 11:04:29 +0800 Subject: [PATCH 115/115] [Dubbo-4323]fix use AtomicInteger instead of volatile to inc (#4324) Signed-off-by: slievrly --- .../org/apache/dubbo/cache/support/expiring/ExpiringMap.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringMap.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringMap.java index 8f25c8d835e..895f11408c0 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringMap.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringMap.java @@ -22,6 +22,7 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; /** @@ -40,7 +41,7 @@ public class ExpiringMap implements Map { */ private static final int DEFAULT_EXPIRATION_INTERVAL = 1; - private static volatile int expireCount = 1; + private static AtomicInteger expireCount = new AtomicInteger(1); private final ConcurrentHashMap delegateMap; @@ -263,7 +264,7 @@ public String toString() { } public ExpireThread() { - expirerThread = new Thread(this, "ExpiryMapExpire-" + expireCount++); + expirerThread = new Thread(this, "ExpiryMapExpire-" + expireCount.getAndIncrement()); expirerThread.setDaemon(true); }