diff --git a/FAQ.md b/FAQ.md index a490847f0412..28e2f0cc564d 100644 --- a/FAQ.md +++ b/FAQ.md @@ -22,4 +22,4 @@ For committers, make sure select the right label and target branch for every PR, [Example question](https://github.com/alibaba/dubbo/issues/742) -Dubbo support to specify ip/port via system environment variables, examples can be found [here](https://github.com/dubbo/dubbo-samples/tree/master/dubbo-samples-docker). \ No newline at end of file +Dubbo supports specifying ip/port via system environment variables, examples can be found [here](https://github.com/dubbo/dubbo-samples/tree/master/dubbo-samples-docker). diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md index 403cb9135873..5427becaba5c 100644 --- a/PULL_REQUEST_TEMPLATE.md +++ b/PULL_REQUEST_TEMPLATE.md @@ -12,7 +12,7 @@ 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) filed 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/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). diff --git a/README.md b/README.md index 75ec9704bdcb..6f41ccfda56d 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ There's a [README](https://github.com/dubbo/dubbo-samples/blob/master/dubbo-samp com.alibaba dubbo - 2.6.4 + 2.6.5 ``` diff --git a/codestyle/checkstyle.xml b/codestyle/checkstyle.xml index ffdafd15f441..621a9e37bca9 100644 --- a/codestyle/checkstyle.xml +++ b/codestyle/checkstyle.xml @@ -20,5 +20,11 @@ + + + + + + \ No newline at end of file diff --git a/codestyle/dubbo_codestyle_for_idea.xml b/codestyle/dubbo_codestyle_for_idea.xml index 4c632e4b2888..1f87caa71352 100644 --- a/codestyle/dubbo_codestyle_for_idea.xml +++ b/codestyle/dubbo_codestyle_for_idea.xml @@ -5,8 +5,6 @@ - - diff --git a/dubbo-all/pom.xml b/dubbo-all/pom.xml index f26a1e26bd47..12d9ec9efd30 100644 --- a/dubbo-all/pom.xml +++ b/dubbo-all/pom.xml @@ -320,7 +320,7 @@ org.apache.dubbo - dubbo-bootstrap + dubbo-serialization-protostuff ${project.version} compile true @@ -431,7 +431,7 @@ org.apache.dubbo:dubbo-serialization-fst org.apache.dubbo:dubbo-serialization-kryo org.apache.dubbo:dubbo-serialization-jdk - org.apache.dubbo:dubbo-bootstrap + org.apache.dubbo:dubbo-serialization-protostuff @@ -595,4 +595,4 @@ - \ No newline at end of file + diff --git a/dubbo-bom/pom.xml b/dubbo-bom/pom.xml index 0bf81218d6aa..dac2456d830a 100644 --- a/dubbo-bom/pom.xml +++ b/dubbo-bom/pom.xml @@ -280,7 +280,7 @@ org.apache.dubbo - dubbo-bootstrap + dubbo-serialization-protostuff ${project.version} diff --git a/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java deleted file mode 100644 index b896c0ee8473..000000000000 --- a/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java +++ /dev/null @@ -1,111 +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.bootstrap; - -import org.apache.dubbo.config.DubboShutdownHook; -import org.apache.dubbo.config.ServiceConfig; - -import java.util.ArrayList; -import java.util.List; - -/** - * A bootstrap class to easily start and stop Dubbo via programmatic API. - * The bootstrap class will be responsible to cleanup the resources during stop. - */ -public class DubboBootstrap { - - /** - * The list of ServiceConfig - */ - private List serviceConfigList; - - /** - * Whether register the shutdown hook during start? - */ - private final boolean registerShutdownHookOnStart; - - /** - * The shutdown hook used when Dubbo is running under embedded environment - */ - private DubboShutdownHook shutdownHook; - - public DubboBootstrap() { - this(true, DubboShutdownHook.getDubboShutdownHook()); - } - - public DubboBootstrap(boolean registerShutdownHookOnStart) { - this(registerShutdownHookOnStart, DubboShutdownHook.getDubboShutdownHook()); - } - - public DubboBootstrap(boolean registerShutdownHookOnStart, DubboShutdownHook shutdownHook) { - this.serviceConfigList = new ArrayList(); - this.shutdownHook = shutdownHook; - this.registerShutdownHookOnStart = registerShutdownHookOnStart; - } - - /** - * Register service config to bootstrap, which will be called during {@link DubboBootstrap#stop()} - * @param serviceConfig the service - * @return the bootstrap instance - */ - public DubboBootstrap registerServiceConfig(ServiceConfig serviceConfig) { - serviceConfigList.add(serviceConfig); - return this; - } - - public void start() { - if (registerShutdownHookOnStart) { - registerShutdownHook(); - } else { - // DubboShutdown hook has been registered in AbstractConfig, - // we need to remove it explicitly - removeShutdownHook(); - } - for (ServiceConfig serviceConfig: serviceConfigList) { - serviceConfig.export(); - } - } - - public void stop() { - for (ServiceConfig serviceConfig: serviceConfigList) { - serviceConfig.unexport(); - } - shutdownHook.destroyAll(); - if (registerShutdownHookOnStart) { - removeShutdownHook(); - } - } - - /** - * Register the shutdown hook - */ - public void registerShutdownHook() { - Runtime.getRuntime().addShutdownHook(shutdownHook); - } - - /** - * Remove this shutdown hook - */ - public void removeShutdownHook() { - try { - Runtime.getRuntime().removeShutdownHook(shutdownHook); - } - catch (IllegalStateException ex) { - // ignore - VM is already shutting down - } - } -} diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalance.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalance.java index 90bc60cf91c3..eea0ca319db4 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalance.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalance.java @@ -34,13 +34,13 @@ public class RandomLoadBalance extends AbstractLoadBalance { @Override protected Invoker doSelect(List> invokers, URL url, Invocation invocation) { int length = invokers.size(); // Number of invokers - int totalWeight = 0; // The sum of weights boolean sameWeight = true; // Every invoker has the same weight? - for (int i = 0; i < length; i++) { + int firstWeight = getWeight(invokers.get(0), invocation); + int totalWeight = firstWeight; // The sum of weights + for (int i = 1; i < length; i++) { int weight = getWeight(invokers.get(i), invocation); totalWeight += weight; // Sum - if (sameWeight && i > 0 - && weight != getWeight(invokers.get(i - 1), invocation)) { + if (sameWeight && weight != firstWeight) { sameWeight = false; } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RoundRobinLoadBalance.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RoundRobinLoadBalance.java index f3b802ef680a..f0bd58ef3441 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RoundRobinLoadBalance.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RoundRobinLoadBalance.java @@ -17,68 +17,137 @@ package org.apache.dubbo.rpc.cluster.loadbalance; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.AtomicPositiveInteger; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; -import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; import java.util.List; +import java.util.Map; +import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; /** * Round robin load balance. */ public class RoundRobinLoadBalance extends AbstractLoadBalance { - public static final String NAME = "roundrobin"; + + private static int RECYCLE_PERIOD = 60000; + + protected static class WeightedRoundRobin { + private int weight; + private AtomicLong current = new AtomicLong(0); + private long lastUpdate; + public int getWeight() { + return weight; + } + public void setWeight(int weight) { + this.weight = weight; + current.set(0); + } + public long increaseCurrent() { + return current.addAndGet(weight); + } + public void sel(int total) { + current.addAndGet(-1 * total); + } + public long getLastUpdate() { + return lastUpdate; + } + public void setLastUpdate(long lastUpdate) { + this.lastUpdate = lastUpdate; + } + } - private final ConcurrentMap sequences = new ConcurrentHashMap(); - - private final ConcurrentMap indexSeqs = new ConcurrentHashMap(); - + private ConcurrentMap> methodWeightMap = new ConcurrentHashMap>(); + private AtomicBoolean updateLock = new AtomicBoolean(); + + /** + * get invoker addr list cached for specified invocation + *

+ * for unit test only + * + * @param invokers + * @param invocation + * @return + */ + protected Collection getInvokerAddrList(List> invokers, Invocation invocation) { + String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName(); + Map map = methodWeightMap.get(key); + if (map != null) { + return map.keySet(); + } + return null; + } + @Override protected Invoker doSelect(List> invokers, URL url, Invocation invocation) { String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName(); - int length = invokers.size(); // Number of invokers - int maxWeight = 0; // The maximum weight - int minWeight = Integer.MAX_VALUE; // The minimum weight - final List> nonZeroWeightedInvokers = new ArrayList<>(); - for (int i = 0; i < length; i++) { - int weight = getWeight(invokers.get(i), invocation); - maxWeight = Math.max(maxWeight, weight); // Choose the maximum weight - minWeight = Math.min(minWeight, weight); // Choose the minimum weight - if (weight > 0) { - nonZeroWeightedInvokers.add(invokers.get(i)); - } - } - AtomicPositiveInteger sequence = sequences.get(key); - if (sequence == null) { - sequences.putIfAbsent(key, new AtomicPositiveInteger()); - sequence = sequences.get(key); + ConcurrentMap map = methodWeightMap.get(key); + if (map == null) { + methodWeightMap.putIfAbsent(key, new ConcurrentHashMap()); + map = methodWeightMap.get(key); } - - if (maxWeight > 0 && minWeight < maxWeight) { - AtomicPositiveInteger indexSeq = indexSeqs.get(key); - if (indexSeq == null) { - indexSeqs.putIfAbsent(key, new AtomicPositiveInteger(-1)); - indexSeq = indexSeqs.get(key); + int totalWeight = 0; + long maxCurrent = Long.MIN_VALUE; + long now = System.currentTimeMillis(); + Invoker selectedInvoker = null; + WeightedRoundRobin selectedWRR = null; + for (Invoker invoker : invokers) { + String identifyString = invoker.getUrl().toIdentityString(); + WeightedRoundRobin weightedRoundRobin = map.get(identifyString); + int weight = getWeight(invoker, invocation); + if (weight < 0) { + weight = 0; } - length = nonZeroWeightedInvokers.size(); - while (true) { - int index = indexSeq.incrementAndGet() % length; - int currentWeight; - if (index == 0) { - currentWeight = sequence.incrementAndGet() % maxWeight; - } else { - currentWeight = sequence.get() % maxWeight; - } - if (getWeight(nonZeroWeightedInvokers.get(index), invocation) > currentWeight) { - return nonZeroWeightedInvokers.get(index); + if (weightedRoundRobin == null) { + weightedRoundRobin = new WeightedRoundRobin(); + weightedRoundRobin.setWeight(weight); + map.putIfAbsent(identifyString, weightedRoundRobin); + weightedRoundRobin = map.get(identifyString); + } + if (weight != weightedRoundRobin.getWeight()) { + //weight changed + weightedRoundRobin.setWeight(weight); + } + long cur = weightedRoundRobin.increaseCurrent(); + weightedRoundRobin.setLastUpdate(now); + if (cur > maxCurrent) { + maxCurrent = cur; + selectedInvoker = invoker; + selectedWRR = weightedRoundRobin; + } + totalWeight += weight; + } + if (!updateLock.get() && invokers.size() != map.size()) { + if (updateLock.compareAndSet(false, true)) { + try { + // copy -> modify -> update reference + ConcurrentMap newMap = new ConcurrentHashMap(); + newMap.putAll(map); + Iterator> it = newMap.entrySet().iterator(); + while (it.hasNext()) { + Entry item = it.next(); + if (now - item.getValue().getLastUpdate() > RECYCLE_PERIOD) { + it.remove(); + } + } + methodWeightMap.put(key, newMap); + } finally { + updateLock.set(false); } } } - // Round robin - return invokers.get(sequence.getAndIncrement() % length); + if (selectedInvoker != null) { + selectedWRR.sel(totalWeight); + return selectedInvoker; + } + // should not happen here + return invokers.get(0); } + } 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 503ede9430ba..f45741ea97b1 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 @@ -42,7 +42,7 @@ * ConditionRouter * */ -public class ConditionRouter implements Router, Comparable { +public class ConditionRouter implements Router { private static final Logger logger = LoggerFactory.getLogger(ConditionRouter.class); private static Pattern ROUTE_PATTERN = Pattern.compile("([&!=,]*)\\s*([^&!=,\\s]+)"); 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 38fd6166effc..4bcb43b7c08f 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,7 +16,6 @@ */ 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.logger.Logger; @@ -34,7 +33,7 @@ /** * TagRouter */ -public class TagRouter implements Router, Comparable { +public class TagRouter implements Router { private static final Logger logger = LoggerFactory.getLogger(TagRouter.class); diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouterFactory.java index 05ad427ce6eb..f827b08d51fb 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouterFactory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouterFactory.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.router.tag; - import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.cluster.Router; import org.apache.dubbo.rpc.cluster.RouterFactory; 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 59b16ed500d5..e8b80595e7da 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 @@ -26,10 +26,10 @@ import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.RpcContext; -import org.apache.dubbo.rpc.RpcInvocation; 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.cluster.Directory; import org.apache.dubbo.rpc.cluster.LoadBalance; import org.apache.dubbo.rpc.support.RpcUtils; @@ -138,10 +138,12 @@ protected Invoker select(LoadBalance loadbalance, Invocation invocation, List } private Invoker doSelect(LoadBalance loadbalance, Invocation invocation, List> invokers, List> selected) throws RpcException { - if (invokers == null || invokers.isEmpty()) + if (invokers == null || invokers.isEmpty()) { return null; - if (invokers.size() == 1) + } + if (invokers.size() == 1) { return invokers.get(0); + } Invoker invoker = loadbalance.select(invokers, getUrl(), invocation); //If the `invoker` is in the `selected` or invoker is unavailable && availablecheck is true, reselect. 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 25d4704602dc..0ae150f4be3d 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 @@ -53,8 +53,8 @@ public FailoverClusterInvoker(Directory directory) { @Override @SuppressWarnings({"unchecked", "rawtypes"}) public Result doInvoke(Invocation invocation, final List> invokers, LoadBalance loadbalance) throws RpcException { - List> copyinvokers = invokers; - checkInvokers(copyinvokers, invocation); + List> copyInvokers = invokers; + checkInvokers(copyInvokers, invocation); String methodName = RpcUtils.getMethodName(invocation); int len = getUrl().getMethodParameter(methodName, Constants.RETRIES_KEY, Constants.DEFAULT_RETRIES) + 1; if (len <= 0) { @@ -62,18 +62,18 @@ public Result doInvoke(Invocation invocation, final List> invokers, L } // retry loop. RpcException le = null; // last exception. - List> invoked = new ArrayList>(copyinvokers.size()); // invoked invokers. + List> invoked = new ArrayList>(copyInvokers.size()); // invoked invokers. Set providers = new HashSet(len); for (int i = 0; i < len; i++) { //Reselect before retry to avoid a change of candidate `invokers`. //NOTE: if `invokers` changed, then `invoked` also lose accuracy. if (i > 0) { checkWhetherDestroyed(); - copyinvokers = list(invocation); + copyInvokers = list(invocation); // check again - checkInvokers(copyinvokers, invocation); + checkInvokers(copyInvokers, invocation); } - Invoker invoker = select(loadbalance, invocation, copyinvokers, invoked); + Invoker invoker = select(loadbalance, invocation, copyInvokers, invoked); invoked.add(invoker); RpcContext.getContext().setInvokers((List) invoked); try { @@ -83,7 +83,7 @@ public Result doInvoke(Invocation invocation, final List> invokers, L + " in the service " + getInterface().getName() + " was successful by the provider " + invoker.getUrl().getAddress() + ", but there have been failed providers " + providers - + " (" + providers.size() + "/" + copyinvokers.size() + + " (" + providers.size() + "/" + copyInvokers.size() + ") from the registry " + directory.getUrl().getAddress() + " on the consumer " + NetUtils.getLocalHost() + " using the dubbo version " + Version.getVersion() + ". Last error is: " @@ -104,7 +104,7 @@ public Result doInvoke(Invocation invocation, final List> invokers, L throw new RpcException(le.getCode(), "Failed to invoke the method " + methodName + " in the service " + getInterface().getName() + ". Tried " + len + " times of the providers " + providers - + " (" + providers.size() + "/" + copyinvokers.size() + + " (" + providers.size() + "/" + copyInvokers.size() + ") from the registry " + directory.getUrl().getAddress() + " on the consumer " + NetUtils.getLocalHost() + " using the dubbo version " + Version.getVersion() + ". Last error is: " 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 ded3ad6af694..869ac524464c 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 @@ -114,12 +114,12 @@ public int testSticky(String methodName, boolean check) { given(invoker1.invoke(invocation)).willReturn(result); given(invoker1.isAvailable()).willReturn(true); - given(invoker1.getUrl()).willReturn(url); + given(invoker1.getUrl()).willReturn(url.setPort(1)); given(invoker1.getInterface()).willReturn(StickyTest.class); given(invoker2.invoke(invocation)).willReturn(result); given(invoker2.isAvailable()).willReturn(true); - given(invoker2.getUrl()).willReturn(url); + given(invoker2.getUrl()).willReturn(url.setPort(2)); given(invoker2.getInterface()).willReturn(StickyTest.class); invocation.setMethodName(methodName); 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 f9db9aeca091..f2af3d39dff1 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 @@ -29,6 +29,9 @@ import org.junit.BeforeClass; import org.junit.Test; +import com.alibaba.fastjson.JSON; +import org.mockito.Mockito; + import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -114,16 +117,21 @@ public void setUp() throws Exception { public Map getInvokeCounter(int runs, String loadbalanceName) { Map counter = new ConcurrentHashMap(); - LoadBalance lb = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(loadbalanceName); + LoadBalance lb = getLoadBalance(loadbalanceName); for (Invoker invoker : invokers) { counter.put(invoker, new AtomicLong(0)); } + URL url = invokers.get(0).getUrl(); for (int i = 0; i < runs; i++) { - Invoker sinvoker = lb.select(invokers, invokers.get(0).getUrl(), invocation); + Invoker sinvoker = lb.select(invokers, url, invocation); counter.get(sinvoker).incrementAndGet(); } return counter; } + + protected AbstractLoadBalance getLoadBalance(String loadbalanceName) { + return (AbstractLoadBalance) ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(loadbalanceName); + } @Test public void testLoadBalanceWarmup() { @@ -153,44 +161,83 @@ private static int calculateDefaultWarmupWeight(int uptime) { } /*------------------------------------test invokers for weight---------------------------------------*/ + + protected static class InvokeResult { + private AtomicLong count = new AtomicLong(); + private int weight = 0; + private int totalWeight = 0; + + public InvokeResult(int weight) { + this.weight = 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); + } + } protected List> weightInvokers = new ArrayList>(); protected Invoker weightInvoker1; protected Invoker weightInvoker2; protected Invoker weightInvoker3; + protected Invoker weightInvokerTmp; @Before public void before() throws Exception { - weightInvoker1 = mock(Invoker.class); - weightInvoker2 = mock(Invoker.class); - weightInvoker3 = mock(Invoker.class); + weightInvoker1 = mock(Invoker.class, Mockito.withSettings().stubOnly()); + weightInvoker2 = mock(Invoker.class, Mockito.withSettings().stubOnly()); + weightInvoker3 = mock(Invoker.class, Mockito.withSettings().stubOnly()); + weightInvokerTmp = mock(Invoker.class, Mockito.withSettings().stubOnly()); weightTestInvocation = new RpcInvocation(); weightTestInvocation.setMethodName("test"); - URL url1 = URL.valueOf("test1://0:1/DemoService"); - url1 = url1.addParameter(Constants.WEIGHT_KEY, 1); - url1 = url1.addParameter(weightTestInvocation.getMethodName() + "." + Constants.WEIGHT_KEY, 1); - url1 = url1.addParameter("active", 0); - - URL url2 = URL.valueOf("test2://0:9/DemoService"); - url2 = url2.addParameter(Constants.WEIGHT_KEY, 9); - url2 = url2.addParameter(weightTestInvocation.getMethodName() + "." + Constants.WEIGHT_KEY, 9); - url2 = url2.addParameter("active", 0); - - URL url3 = URL.valueOf("test3://1:6/DemoService"); - url3 = url3.addParameter(Constants.WEIGHT_KEY, 6); - url3 = url3.addParameter(weightTestInvocation.getMethodName() + "." + Constants.WEIGHT_KEY, 6); - url3 = url3.addParameter("active", 1); + URL url1 = URL.valueOf("test1://127.0.0.1:11/DemoService?weight=1&active=0"); + URL url2 = URL.valueOf("test2://127.0.0.1:12/DemoService?weight=9&active=0"); + URL url3 = URL.valueOf("test3://127.0.0.1:13/DemoService?weight=6&active=1"); + URL urlTmp = URL.valueOf("test4://127.0.0.1:9999/DemoService?weight=11&active=0"); 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); weightInvokers.add(weightInvoker1); weightInvokers.add(weightInvoker2); @@ -203,4 +250,25 @@ 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); + int totalWeight = 0; + for (int i = 0; i < weightInvokers.size(); i ++) { + InvokeResult invokeResult = new InvokeResult(lb.getWeight(weightInvokers.get(i), weightTestInvocation)); + counter.put(weightInvokers.get(i), invokeResult); + totalWeight += invokeResult.getWeight(); + } + for (InvokeResult invokeResult : counter.values()) { + invokeResult.setTotalWeight(totalWeight); + } + URL url = weightInvokers.get(0).getUrl(); + for (int i = 0; i < runs; i++) { + Invoker sinvoker = lb.select(weightInvokers, url, weightTestInvocation); + counter.get(sinvoker).getCount().incrementAndGet(); + } + return counter; + } + } \ No newline at end of file diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/RoundRobinLoadBalanceTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/RoundRobinLoadBalanceTest.java index e10f69fea62e..5242f90badaf 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/RoundRobinLoadBalanceTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/RoundRobinLoadBalanceTest.java @@ -20,10 +20,29 @@ import org.junit.Assert; import org.junit.Test; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; public class RoundRobinLoadBalanceTest extends LoadBalanceBaseTest { + + private void assertStrictWRRResult(int loop, Map resultMap) { + int invokeCount = 0; + for (InvokeResult invokeResult : resultMap.values()) { + int count = (int) invokeResult.getCount().get(); + // Because it's a strictly round robin, so the abs delta should be < 10 too + Assert.assertTrue("delta with expected count should < 10", + Math.abs(invokeResult.getExpected(loop) - count) < 10); + invokeCount += count; + } + Assert.assertEquals("select failed!", invokeCount, loop); + } + @Test public void testRoundRobinLoadBalanceSelect() { int runs = 10000; @@ -36,33 +55,114 @@ public void testRoundRobinLoadBalanceSelect() { @Test public void testSelectByWeight() { - int sumInvoker1 = 0; - int sumInvoker2 = 0; - int sumInvoker3 = 0; - int loop = 10000; - - RoundRobinLoadBalance lb = new RoundRobinLoadBalance(); - for (int i = 0; i < loop; i++) { - Invoker selected = lb.select(weightInvokers, null, weightTestInvocation); - - if (selected.getUrl().getProtocol().equals("test1")) { - sumInvoker1++; - } - - if (selected.getUrl().getProtocol().equals("test2")) { - sumInvoker2++; + final Map totalMap = new HashMap(); + final AtomicBoolean shouldBegin = new AtomicBoolean(false); + final int runs = 10000; + List threads = new ArrayList(); + int threadNum = 10; + for (int i = 0; i < threadNum; i ++) { + threads.add(new Thread() { + @Override + public void run() { + while (!shouldBegin.get()) { + try { + sleep(5); + } catch (InterruptedException e) { + } + } + Map resultMap = getWeightedInvokeResult(runs, RoundRobinLoadBalance.NAME); + synchronized (totalMap) { + for (Entry entry : resultMap.entrySet()) { + if (!totalMap.containsKey(entry.getKey())) { + totalMap.put(entry.getKey(), entry.getValue()); + } else { + totalMap.get(entry.getKey()).getCount().addAndGet(entry.getValue().getCount().get()); + } + } + } + } + }); + } + for (Thread thread : threads) { + thread.start(); + } + // let's rock it! + shouldBegin.set(true); + for (Thread thread : threads) { + try { + thread.join(); + } catch (InterruptedException e) { } - - if (selected.getUrl().getProtocol().equals("test3")) { - sumInvoker3++; + } + assertStrictWRRResult(runs * threadNum, totalMap); + } + + @Test + public void testNodeCacheShouldNotRecycle() { + int loop = 10000; + //tmperately add a new invoker + weightInvokers.add(weightInvokerTmp); + try { + Map resultMap = getWeightedInvokeResult(loop, RoundRobinLoadBalance.NAME); + assertStrictWRRResult(loop, resultMap); + + // inner nodes cache judgement + RoundRobinLoadBalance lb = (RoundRobinLoadBalance)getLoadBalance(RoundRobinLoadBalance.NAME); + Assert.assertEquals(weightInvokers.size(), lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size()); + + weightInvokers.remove(weightInvokerTmp); + + resultMap = getWeightedInvokeResult(loop, RoundRobinLoadBalance.NAME); + assertStrictWRRResult(loop, resultMap); + + Assert.assertNotEquals(weightInvokers.size(), lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size()); + } finally { + //prevent other UT's failure + weightInvokers.remove(weightInvokerTmp); + } + } + + @Test + public void testNodeCacheShouldRecycle() { + { + Field recycleTimeField = null; + try { + //change recycle time to 1 ms + recycleTimeField = RoundRobinLoadBalance.class.getDeclaredField("RECYCLE_PERIOD"); + recycleTimeField.setAccessible(true); + recycleTimeField.setInt(RoundRobinLoadBalance.class, 10); + } catch (NoSuchFieldException e) { + Assert.assertTrue("getField failed", true); + } catch (SecurityException e) { + Assert.assertTrue("getField failed", true); + } catch (IllegalArgumentException e) { + Assert.assertTrue("getField failed", true); + } catch (IllegalAccessException e) { + Assert.assertTrue("getField failed", true); } } - - // 1 : 9 : 6 - System.out.println(sumInvoker1); - System.out.println(sumInvoker2); - System.out.println(sumInvoker3); - Assert.assertEquals("select failed!", sumInvoker1 + sumInvoker2 + sumInvoker3, loop); + + int loop = 10000; + //tmperately add a new invoker + weightInvokers.add(weightInvokerTmp); + try { + Map resultMap = getWeightedInvokeResult(loop, RoundRobinLoadBalance.NAME); + assertStrictWRRResult(loop, resultMap); + + // inner nodes cache judgement + RoundRobinLoadBalance lb = (RoundRobinLoadBalance)getLoadBalance(RoundRobinLoadBalance.NAME); + Assert.assertEquals(weightInvokers.size(), lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size()); + + weightInvokers.remove(weightInvokerTmp); + + resultMap = getWeightedInvokeResult(loop, RoundRobinLoadBalance.NAME); + assertStrictWRRResult(loop, resultMap); + + Assert.assertEquals(weightInvokers.size(), lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size()); + } finally { + //prevent other UT's failure + weightInvokers.remove(weightInvokerTmp); + } } - + } 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 8a01a99ec5e5..3d94b16b8200 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,22 +17,20 @@ package org.apache.dubbo.rpc.cluster.router.script; +import java.util.ArrayList; +import java.util.List; + import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.Router; import org.apache.dubbo.rpc.cluster.router.MockInvoker; - import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import javax.script.ScriptException; -import java.util.ArrayList; -import java.util.List; - public class ScriptRouterTest { private URL SCRIPT_URL = URL.valueOf("script://javascript?type=javascript"); @@ -85,5 +83,48 @@ public void testRoutePickInvokers() { Assert.assertEquals(invoker3, filteredInvokers.get(1)); } - //TODO Add tests for abnormal scene + @Test + public void testRouteHostFilter() { + List> invokers = new ArrayList>(); + MockInvoker invoker1 = new MockInvoker(URL.valueOf("dubbo://10.134.108.1:20880/com.dubbo.HelloService")); + MockInvoker invoker2 = new MockInvoker(URL.valueOf("dubbo://10.134.108.2:20880/com.dubbo.HelloService")); + MockInvoker invoker3 = new MockInvoker(URL.valueOf("dubbo://10.134.108.3:20880/com.dubbo.HelloService")); + invokers.add(invoker1); + invokers.add(invoker2); + invokers.add(invoker3); + + String script = "function route(invokers, invocation, context){ " + + " var result = new java.util.ArrayList(invokers.size()); " + + " var targetHost = new java.util.ArrayList(); " + + " targetHost.add(\"10.134.108.2\"); " + + " for (var i = 0; i < invokers.length; i++) { " + + " if(targetHost.contains(invokers[i].getUrl().getHost())){ " + + " result.add(invokers[i]); " + + " } " + + " } " + + " return result; " + + "} " + + "route(invokers, invocation, context) "; + + Router router = new ScriptRouterFactory().getRouter(getRouteUrl(script)); + List> routeResult = router.route(invokers, invokers.get(0).getUrl(), new RpcInvocation()); + Assert.assertEquals(1, routeResult.size()); + Assert.assertEquals(invoker2,routeResult.get(0)); + } + + @Test + public void testRoute_throwException() { + List> invokers = new ArrayList>(); + MockInvoker invoker1 = new MockInvoker(URL.valueOf("dubbo://10.134.108.1:20880/com.dubbo.HelloService")); + MockInvoker invoker2 = new MockInvoker(URL.valueOf("dubbo://10.134.108.2:20880/com.dubbo.HelloService")); + MockInvoker invoker3 = new MockInvoker(URL.valueOf("dubbo://10.134.108.3:20880/com.dubbo.HelloService")); + invokers.add(invoker1); + invokers.add(invoker2); + invokers.add(invoker3); + + String script = "/"; + Router router = new ScriptRouterFactory().getRouter(getRouteUrl(script)); + List> routeResult = router.route(invokers, invokers.get(0).getUrl(), new RpcInvocation()); + Assert.assertEquals(3, routeResult.size()); + } } \ No newline at end of file diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouterTest.java index 839af44efe9f..a3ba09240139 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouterTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouterTest.java @@ -26,8 +26,8 @@ import org.apache.dubbo.rpc.cluster.Router; import org.apache.dubbo.rpc.cluster.RouterFactory; import org.apache.dubbo.rpc.cluster.router.MockInvoker; +import org.junit.After; import org.junit.Assert; -import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -47,8 +47,9 @@ public class TagRouterTest { public static void setUpBeforeClass() throws Exception { } - @Before - public void setUp() throws Exception { + @After + public void teardown() throws Exception { + RpcContext.getContext().clearAttachments(); } @Test 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 247a719ad84e..2039b0a0e4c2 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 @@ -34,6 +34,7 @@ import org.apache.dubbo.rpc.cluster.loadbalance.RandomLoadBalance; import org.apache.dubbo.rpc.cluster.loadbalance.RoundRobinLoadBalance; +import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; @@ -74,6 +75,11 @@ public class AbstractClusterInvokerTest { public static void setUpBeforeClass() throws Exception { } + @After + public void teardown() throws Exception { + RpcContext.getContext().clearAttachments(); + } + @SuppressWarnings({"unchecked"}) @Before public void setUp() throws Exception { @@ -90,27 +96,27 @@ public void setUp() throws Exception { given(invoker1.isAvailable()).willReturn(false); given(invoker1.getInterface()).willReturn(IHelloService.class); - given(invoker1.getUrl()).willReturn(turl.addParameter("name", "invoker1")); + given(invoker1.getUrl()).willReturn(turl.setPort(1).addParameter("name", "invoker1")); given(invoker2.isAvailable()).willReturn(true); given(invoker2.getInterface()).willReturn(IHelloService.class); - given(invoker2.getUrl()).willReturn(turl.addParameter("name", "invoker2")); + given(invoker2.getUrl()).willReturn(turl.setPort(2).addParameter("name", "invoker2")); given(invoker3.isAvailable()).willReturn(false); given(invoker3.getInterface()).willReturn(IHelloService.class); - given(invoker3.getUrl()).willReturn(turl.addParameter("name", "invoker3")); + given(invoker3.getUrl()).willReturn(turl.setPort(3).addParameter("name", "invoker3")); given(invoker4.isAvailable()).willReturn(true); given(invoker4.getInterface()).willReturn(IHelloService.class); - given(invoker4.getUrl()).willReturn(turl.addParameter("name", "invoker4")); + given(invoker4.getUrl()).willReturn(turl.setPort(4).addParameter("name", "invoker4")); given(invoker5.isAvailable()).willReturn(false); given(invoker5.getInterface()).willReturn(IHelloService.class); - given(invoker5.getUrl()).willReturn(turl.addParameter("name", "invoker5")); + given(invoker5.getUrl()).willReturn(turl.setPort(5).addParameter("name", "invoker5")); given(mockedInvoker1.isAvailable()).willReturn(false); given(mockedInvoker1.getInterface()).willReturn(IHelloService.class); - given(mockedInvoker1.getUrl()).willReturn(turl.setProtocol("mock")); + given(mockedInvoker1.getUrl()).willReturn(turl.setPort(999).setProtocol("mock")); invokers.add(invoker1); dic = new StaticDirectory(url, invokers, null); 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 4d6e7585cf24..18ad19f5246e 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 @@ -19,6 +19,7 @@ import java.util.concurrent.ExecutorService; import java.util.regex.Pattern; + /** * Constants */ @@ -246,6 +247,23 @@ public class Constants { 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; + + /** + * ticks per wheel. Currently only contains two tasks, so 16 locations are enough + */ + public static final int TICKS_PER_WHEEL = 16; + public static final String HEARTBEAT_TIMEOUT_KEY = "heartbeat.timeout"; public static final String CONNECT_TIMEOUT_KEY = "connect.timeout"; 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 39999279ecdd..529d3feb910c 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 @@ -19,6 +19,7 @@ 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.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; import java.io.UnsupportedEncodingException; @@ -42,20 +43,11 @@ public Parameters(String... pairs) { } public Parameters(Map parameters) { - this.parameters = Collections.unmodifiableMap(parameters != null ? new HashMap(parameters) : new HashMap(0)); + this.parameters = Collections.unmodifiableMap(parameters != null ? new HashMap<>(parameters) : new HashMap<>(0)); } private static Map toMap(String... pairs) { - Map parameters = new HashMap(); - if (pairs.length > 0) { - if (pairs.length % 2 != 0) { - throw new IllegalArgumentException("pairs must be even."); - } - for (int i = 0; i < pairs.length; i = i + 2) { - parameters.put(pairs[i], pairs[i + 1]); - } - } - return parameters; + return CollectionUtils.toStringMap(pairs); } public static Parameters parseParameters(String query) { 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 a83ca91e227e..7a092ffd25de 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 @@ -118,7 +118,7 @@ public URL(String protocol, String host, int port) { this(protocol, null, null, host, port, null, (Map) null); } - public URL(String protocol, String host, int port, String[] pairs) { // varargs ... confilict with the following path argument, use array instead. + public URL(String protocol, String host, int port, String[] pairs) { // varargs ... conflict with the following path argument, use array instead. this(protocol, null, null, host, port, null, CollectionUtils.toStringMap(pairs)); } @@ -206,14 +206,18 @@ public static URL valueOf(String url) { } i = url.indexOf("://"); if (i >= 0) { - if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); + if (i == 0) { + throw new IllegalStateException("url missing protocol: \"" + url + "\""); + } protocol = url.substring(0, i); url = url.substring(i + 3); } else { // case: file:/path/to/file.txt i = url.indexOf(":/"); if (i >= 0) { - if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); + if (i == 0) { + throw new IllegalStateException("url missing protocol: \"" + url + "\""); + } protocol = url.substring(0, i); url = url.substring(i + 1); } @@ -246,7 +250,9 @@ public static URL valueOf(String url) { url = url.substring(0, i); } } - if (url.length() > 0) host = url; + if (url.length() > 0) { + host = url; + } return new URL(protocol, username, password, host, port, path, parameters); } @@ -915,17 +921,23 @@ public URL addParameter(String key, double value) { } public URL addParameter(String key, Enum value) { - if (value == null) return this; + if (value == null) { + return this; + } return addParameter(key, String.valueOf(value)); } public URL addParameter(String key, Number value) { - if (value == null) return this; + if (value == null) { + return this; + } return addParameter(key, String.valueOf(value)); } public URL addParameter(String key, CharSequence value) { - if (value == null || value.length() == 0) return this; + if (value == null || value.length() == 0) { + return this; + } return addParameter(key, String.valueOf(value)); } @@ -984,7 +996,9 @@ public URL addParameters(Map parameters) { } } // return immediately if there's no change - if (hasAndEqual) return this; + if (hasAndEqual) { + return this; + } Map map = new HashMap(getParameters()); map.putAll(parameters); @@ -1055,35 +1069,47 @@ public URL clearParameters() { } public String getRawParameter(String key) { - if ("protocol".equals(key)) + if ("protocol".equals(key)) { return protocol; - if ("username".equals(key)) + } + if ("username".equals(key)) { return username; - if ("password".equals(key)) + } + if ("password".equals(key)) { return password; - if ("host".equals(key)) + } + if ("host".equals(key)) { return host; - if ("port".equals(key)) + } + if ("port".equals(key)) { return String.valueOf(port); - if ("path".equals(key)) + } + if ("path".equals(key)) { return path; + } return getParameter(key); } public Map toMap() { Map map = new HashMap(parameters); - if (protocol != null) + if (protocol != null) { map.put("protocol", protocol); - if (username != null) + } + if (username != null) { map.put("username", username); - if (password != null) + } + if (password != null) { map.put("password", password); - if (host != null) + } + if (host != null) { map.put("host", host); - if (port > 0) + } + if (port > 0) { map.put("port", String.valueOf(port)); - if (path != null) + } + if (path != null) { map.put("path", path); + } return map; } @@ -1218,7 +1244,9 @@ public InetSocketAddress toInetSocketAddress() { public String getServiceKey() { String inf = getServiceInterface(); - if (inf == null) return null; + if (inf == null) { + return null; + } StringBuilder buf = new StringBuilder(); String group = getParameter(Constants.GROUP_KEY); if (group != null && group.length() > 0) { @@ -1359,45 +1387,61 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } URL other = (URL) obj; if (host == null) { - if (other.host != null) + if (other.host != null) { return false; - } else if (!host.equals(other.host)) + } + } else if (!host.equals(other.host)) { return false; + } if (parameters == null) { - if (other.parameters != null) + if (other.parameters != null) { return false; - } else if (!parameters.equals(other.parameters)) + } + } else if (!parameters.equals(other.parameters)) { return false; + } if (password == null) { - if (other.password != null) + if (other.password != null) { return false; - } else if (!password.equals(other.password)) + } + } else if (!password.equals(other.password)) { return false; + } if (path == null) { - if (other.path != null) + if (other.path != null) { return false; - } else if (!path.equals(other.path)) + } + } else if (!path.equals(other.path)) { return false; - if (port != other.port) + } + if (port != other.port) { return false; + } if (protocol == null) { - if (other.protocol != null) + if (other.protocol != null) { return false; - } else if (!protocol.equals(other.protocol)) + } + } else if (!protocol.equals(other.protocol)) { return false; + } if (username == null) { - if (other.username != null) + if (other.username != null) { return false; - } else if (!username.equals(other.username)) + } + } else if (!username.equals(other.username)) { return false; + } return true; } 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 983cbb98e1dc..5c0ab763a70c 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 @@ -41,9 +41,9 @@ public final class Version { /** * For protocol compatibility purpose. - * Because {@link #isSupportResponseAttatchment} is checked for every call, int compare expect to has higher performance than string. + * Because {@link #isSupportResponseAttachment} is checked for every call, int compare expect to has higher performance than string. */ - private static final int LOWEST_VERSION_FOR_RESPONSE_ATTATCHMENT = 20002; // 2.0.2 + private static final int LOWEST_VERSION_FOR_RESPONSE_ATTACHMENT = 20002; // 2.0.2 private static final Map VERSION2INT = new HashMap(); static { @@ -62,7 +62,7 @@ public static String getVersion() { return VERSION; } - public static boolean isSupportResponseAttatchment(String version) { + public static boolean isSupportResponseAttachment(String version) { if (version == null || version.length() == 0) { return false; } @@ -72,7 +72,7 @@ public static boolean isSupportResponseAttatchment(String version) { return false; } - return iVersion >= LOWEST_VERSION_FOR_RESPONSE_ATTATCHMENT; + return iVersion >= LOWEST_VERSION_FOR_RESPONSE_ATTACHMENT; } public static int getIntVersion(String version) { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/beanutil/JavaBeanSerializeUtil.java b/dubbo-common/src/main/java/org/apache/dubbo/common/beanutil/JavaBeanSerializeUtil.java index ea9f582648ac..a1bdc7af5eb6 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/beanutil/JavaBeanSerializeUtil.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/beanutil/JavaBeanSerializeUtil.java @@ -399,14 +399,16 @@ private static Object instantiateForDeserialize(JavaBeanDescriptor beanDescripto } result = Array.newInstance(componentType, beanDescriptor.propertySize()); cache.put(beanDescriptor, result); - } else try { - Class cl = name2Class(loader, beanDescriptor.getClassName()); - result = instantiate(cl); - cache.put(beanDescriptor, result); - } catch (ClassNotFoundException e) { - throw new RuntimeException(e.getMessage(), e); - } catch (Exception e) { - throw new RuntimeException(e.getMessage(), e); + } else { + try { + Class cl = name2Class(loader, beanDescriptor.getClassName()); + result = instantiate(cl); + cache.put(beanDescriptor, result); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e.getMessage(), e); + } catch (Exception e) { + throw new RuntimeException(e.getMessage(), e); + } } return result; 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 d9cee452a907..c044c7b297a0 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 @@ -1,391 +1,391 @@ -/* - * 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.bytecode; - -import org.apache.dubbo.common.utils.ClassHelper; -import org.apache.dubbo.common.utils.ReflectUtils; - -import javassist.CannotCompileException; -import javassist.ClassPool; -import javassist.CtClass; -import javassist.CtConstructor; -import javassist.CtField; -import javassist.CtMethod; -import javassist.CtNewConstructor; -import javassist.CtNewMethod; -import javassist.LoaderClassPath; -import javassist.NotFoundException; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.security.ProtectionDomain; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicLong; - -/** - * ClassGenerator - */ -public final class ClassGenerator { - - private static final AtomicLong CLASS_NAME_COUNTER = new AtomicLong(0); - private static final String SIMPLE_NAME_TAG = ""; - private static final Map POOL_MAP = new ConcurrentHashMap(); //ClassLoader - ClassPool - private ClassPool mPool; - private CtClass mCtc; - private String mClassName; - private String mSuperClass; - private Set mInterfaces; - private List mFields; - private List mConstructors; - private List mMethods; - private Map mCopyMethods; // - private Map> mCopyConstructors; // - private boolean mDefaultConstructor = false; - - private ClassGenerator() { - } - - private ClassGenerator(ClassPool pool) { - mPool = pool; - } - - public static ClassGenerator newInstance() { - return new ClassGenerator(getClassPool(Thread.currentThread().getContextClassLoader())); - } - - public static ClassGenerator newInstance(ClassLoader loader) { - return new ClassGenerator(getClassPool(loader)); - } - - public static boolean isDynamicClass(Class cl) { - return ClassGenerator.DC.class.isAssignableFrom(cl); - } - - public static ClassPool getClassPool(ClassLoader loader) { - if (loader == null) { - return ClassPool.getDefault(); - } - - ClassPool pool = POOL_MAP.get(loader); - if (pool == null) { - pool = new ClassPool(true); - pool.appendClassPath(new LoaderClassPath(loader)); - POOL_MAP.put(loader, pool); - } - return pool; - } - - private static String modifier(int mod) { - StringBuilder modifier = new StringBuilder(); - if (Modifier.isPublic(mod)) { - modifier.append("public"); - } - if (Modifier.isProtected(mod)) { - modifier.append("protected"); - } - if (Modifier.isPrivate(mod)) { - modifier.append("private"); - } - - if (Modifier.isStatic(mod)) { - modifier.append(" static"); - } - if (Modifier.isVolatile(mod)) { - modifier.append(" volatile"); - } - - return modifier.toString(); - } - - public String getClassName() { - return mClassName; - } - - public ClassGenerator setClassName(String name) { - mClassName = name; - return this; - } - - public ClassGenerator addInterface(String cn) { - if (mInterfaces == null) { - mInterfaces = new HashSet(); - } - mInterfaces.add(cn); - return this; - } - - public ClassGenerator addInterface(Class cl) { - return addInterface(cl.getName()); - } - - public ClassGenerator setSuperClass(String cn) { - mSuperClass = cn; - return this; - } - - public ClassGenerator setSuperClass(Class cl) { - mSuperClass = cl.getName(); - return this; - } - - public ClassGenerator addField(String code) { - if (mFields == null) { - mFields = new ArrayList(); - } - mFields.add(code); - return this; - } - - public ClassGenerator addField(String name, int mod, Class type) { - return addField(name, mod, type, null); - } - - public ClassGenerator addField(String name, int mod, Class type, String def) { - StringBuilder sb = new StringBuilder(); - sb.append(modifier(mod)).append(' ').append(ReflectUtils.getName(type)).append(' '); - sb.append(name); - if (def != null && def.length() > 0) { - sb.append('='); - sb.append(def); - } - sb.append(';'); - return addField(sb.toString()); - } - - public ClassGenerator addMethod(String code) { - if (mMethods == null) { - mMethods = new ArrayList(); - } - mMethods.add(code); - return this; - } - - public ClassGenerator addMethod(String name, int mod, Class rt, Class[] pts, String body) { - return addMethod(name, mod, rt, pts, null, body); - } - - public ClassGenerator addMethod(String name, int mod, Class rt, Class[] pts, Class[] ets, - String body) { - StringBuilder sb = new StringBuilder(); - sb.append(modifier(mod)).append(' ').append(ReflectUtils.getName(rt)).append(' ').append(name); - sb.append('('); - for (int i = 0; i < pts.length; i++) { - if (i > 0) { - sb.append(','); - } - sb.append(ReflectUtils.getName(pts[i])); - sb.append(" arg").append(i); - } - sb.append(')'); - if (ets != null && ets.length > 0) { - sb.append(" throws "); - for (int i = 0; i < ets.length; i++) { - if (i > 0) { - sb.append(','); - } - sb.append(ReflectUtils.getName(ets[i])); - } - } - sb.append('{').append(body).append('}'); - return addMethod(sb.toString()); - } - - public ClassGenerator addMethod(Method m) { - addMethod(m.getName(), m); - return this; - } - - public ClassGenerator addMethod(String name, Method m) { - String desc = name + ReflectUtils.getDescWithoutMethodName(m); - addMethod(':' + desc); - if (mCopyMethods == null) { - mCopyMethods = new ConcurrentHashMap(8); - } - mCopyMethods.put(desc, m); - return this; - } - - public ClassGenerator addConstructor(String code) { - if (mConstructors == null) { - mConstructors = new LinkedList(); - } - mConstructors.add(code); - return this; - } - - public ClassGenerator addConstructor(int mod, Class[] pts, String body) { - return addConstructor(mod, pts, null, body); - } - - public ClassGenerator addConstructor(int mod, Class[] pts, Class[] ets, String body) { - StringBuilder sb = new StringBuilder(); - sb.append(modifier(mod)).append(' ').append(SIMPLE_NAME_TAG); - sb.append('('); - for (int i = 0; i < pts.length; i++) { - if (i > 0) { - sb.append(','); - } - sb.append(ReflectUtils.getName(pts[i])); - sb.append(" arg").append(i); - } - sb.append(')'); - if (ets != null && ets.length > 0) { - sb.append(" throws "); - for (int i = 0; i < ets.length; i++) { - if (i > 0) { - sb.append(','); - } - sb.append(ReflectUtils.getName(ets[i])); - } - } - sb.append('{').append(body).append('}'); - return addConstructor(sb.toString()); - } - - public ClassGenerator addConstructor(Constructor c) { - String desc = ReflectUtils.getDesc(c); - addConstructor(":" + desc); - if (mCopyConstructors == null) { - mCopyConstructors = new ConcurrentHashMap>(4); - } - mCopyConstructors.put(desc, c); - return this; - } - - public ClassGenerator addDefaultConstructor() { - mDefaultConstructor = true; - return this; - } - - public ClassPool getClassPool() { - return mPool; - } - - public Class toClass() { - return toClass(ClassHelper.getClassLoader(ClassGenerator.class), - getClass().getProtectionDomain()); - } - - public Class toClass(ClassLoader loader, ProtectionDomain pd) { - if (mCtc != null) { - mCtc.detach(); - } - long id = CLASS_NAME_COUNTER.getAndIncrement(); - try { - CtClass ctcs = mSuperClass == null ? null : mPool.get(mSuperClass); - if (mClassName == null) { - mClassName = (mSuperClass == null || javassist.Modifier.isPublic(ctcs.getModifiers()) - ? ClassGenerator.class.getName() : mSuperClass + "$sc") + id; - } - mCtc = mPool.makeClass(mClassName); - if (mSuperClass != null) { - mCtc.setSuperclass(ctcs); - } - mCtc.addInterface(mPool.get(DC.class.getName())); // add dynamic class tag. - if (mInterfaces != null) { - for (String cl : mInterfaces) { - mCtc.addInterface(mPool.get(cl)); - } - } - if (mFields != null) { - for (String code : mFields) { - mCtc.addField(CtField.make(code, mCtc)); - } - } - if (mMethods != null) { - for (String code : mMethods) { - if (code.charAt(0) == ':') { - mCtc.addMethod(CtNewMethod.copy(getCtMethod(mCopyMethods.get(code.substring(1))), - code.substring(1, code.indexOf('(')), mCtc, null)); - } else { - mCtc.addMethod(CtNewMethod.make(code, mCtc)); - } - } - } - if (mDefaultConstructor) { - mCtc.addConstructor(CtNewConstructor.defaultConstructor(mCtc)); - } - if (mConstructors != null) { - for (String code : mConstructors) { - if (code.charAt(0) == ':') { - mCtc.addConstructor(CtNewConstructor - .copy(getCtConstructor(mCopyConstructors.get(code.substring(1))), mCtc, null)); - } else { - String[] sn = mCtc.getSimpleName().split("\\$+"); // inner class name include $. - mCtc.addConstructor( - CtNewConstructor.make(code.replaceFirst(SIMPLE_NAME_TAG, sn[sn.length - 1]), mCtc)); - } - } - } - return mCtc.toClass(loader, pd); - } catch (RuntimeException e) { - throw e; - } catch (NotFoundException e) { - throw new RuntimeException(e.getMessage(), e); - } catch (CannotCompileException e) { - throw new RuntimeException(e.getMessage(), e); - } - } - - public void release() { - if (mCtc != null) { - mCtc.detach(); - } - if (mInterfaces != null) { - mInterfaces.clear(); - } - if (mFields != null) { - mFields.clear(); - } - if (mMethods != null) { - mMethods.clear(); - } - if (mConstructors != null) { - mConstructors.clear(); - } - if (mCopyMethods != null) { - mCopyMethods.clear(); - } - if (mCopyConstructors != null) { - mCopyConstructors.clear(); - } - } - - private CtClass getCtClass(Class c) throws NotFoundException { - return mPool.get(c.getName()); - } - - private CtMethod getCtMethod(Method m) throws NotFoundException { - return getCtClass(m.getDeclaringClass()) - .getMethod(m.getName(), ReflectUtils.getDescWithoutMethodName(m)); - } - - private CtConstructor getCtConstructor(Constructor c) throws NotFoundException { - return getCtClass(c.getDeclaringClass()).getConstructor(ReflectUtils.getDesc(c)); - } - - public static interface DC { - - } // dynamic class tag interface. +/* + * 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.bytecode; + +import org.apache.dubbo.common.utils.ClassHelper; +import org.apache.dubbo.common.utils.ReflectUtils; + +import javassist.CannotCompileException; +import javassist.ClassPool; +import javassist.CtClass; +import javassist.CtConstructor; +import javassist.CtField; +import javassist.CtMethod; +import javassist.CtNewConstructor; +import javassist.CtNewMethod; +import javassist.LoaderClassPath; +import javassist.NotFoundException; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.security.ProtectionDomain; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicLong; + +/** + * ClassGenerator + */ +public final class ClassGenerator { + + private static final AtomicLong CLASS_NAME_COUNTER = new AtomicLong(0); + private static final String SIMPLE_NAME_TAG = ""; + private static final Map POOL_MAP = new ConcurrentHashMap(); //ClassLoader - ClassPool + private ClassPool mPool; + private CtClass mCtc; + private String mClassName; + private String mSuperClass; + private Set mInterfaces; + private List mFields; + private List mConstructors; + private List mMethods; + private Map mCopyMethods; // + private Map> mCopyConstructors; // + private boolean mDefaultConstructor = false; + + private ClassGenerator() { + } + + private ClassGenerator(ClassPool pool) { + mPool = pool; + } + + public static ClassGenerator newInstance() { + return new ClassGenerator(getClassPool(Thread.currentThread().getContextClassLoader())); + } + + public static ClassGenerator newInstance(ClassLoader loader) { + return new ClassGenerator(getClassPool(loader)); + } + + public static boolean isDynamicClass(Class cl) { + return ClassGenerator.DC.class.isAssignableFrom(cl); + } + + public static ClassPool getClassPool(ClassLoader loader) { + if (loader == null) { + return ClassPool.getDefault(); + } + + ClassPool pool = POOL_MAP.get(loader); + if (pool == null) { + pool = new ClassPool(true); + pool.appendClassPath(new LoaderClassPath(loader)); + POOL_MAP.put(loader, pool); + } + return pool; + } + + private static String modifier(int mod) { + StringBuilder modifier = new StringBuilder(); + if (Modifier.isPublic(mod)) { + modifier.append("public"); + } + if (Modifier.isProtected(mod)) { + modifier.append("protected"); + } + if (Modifier.isPrivate(mod)) { + modifier.append("private"); + } + + if (Modifier.isStatic(mod)) { + modifier.append(" static"); + } + if (Modifier.isVolatile(mod)) { + modifier.append(" volatile"); + } + + return modifier.toString(); + } + + public String getClassName() { + return mClassName; + } + + public ClassGenerator setClassName(String name) { + mClassName = name; + return this; + } + + public ClassGenerator addInterface(String cn) { + if (mInterfaces == null) { + mInterfaces = new HashSet(); + } + mInterfaces.add(cn); + return this; + } + + public ClassGenerator addInterface(Class cl) { + return addInterface(cl.getName()); + } + + public ClassGenerator setSuperClass(String cn) { + mSuperClass = cn; + return this; + } + + public ClassGenerator setSuperClass(Class cl) { + mSuperClass = cl.getName(); + return this; + } + + public ClassGenerator addField(String code) { + if (mFields == null) { + mFields = new ArrayList(); + } + mFields.add(code); + return this; + } + + public ClassGenerator addField(String name, int mod, Class type) { + return addField(name, mod, type, null); + } + + public ClassGenerator addField(String name, int mod, Class type, String def) { + StringBuilder sb = new StringBuilder(); + sb.append(modifier(mod)).append(' ').append(ReflectUtils.getName(type)).append(' '); + sb.append(name); + if (def != null && def.length() > 0) { + sb.append('='); + sb.append(def); + } + sb.append(';'); + return addField(sb.toString()); + } + + public ClassGenerator addMethod(String code) { + if (mMethods == null) { + mMethods = new ArrayList(); + } + mMethods.add(code); + return this; + } + + public ClassGenerator addMethod(String name, int mod, Class rt, Class[] pts, String body) { + return addMethod(name, mod, rt, pts, null, body); + } + + public ClassGenerator addMethod(String name, int mod, Class rt, Class[] pts, Class[] ets, + String body) { + StringBuilder sb = new StringBuilder(); + sb.append(modifier(mod)).append(' ').append(ReflectUtils.getName(rt)).append(' ').append(name); + sb.append('('); + for (int i = 0; i < pts.length; i++) { + if (i > 0) { + sb.append(','); + } + sb.append(ReflectUtils.getName(pts[i])); + sb.append(" arg").append(i); + } + sb.append(')'); + if (ets != null && ets.length > 0) { + sb.append(" throws "); + for (int i = 0; i < ets.length; i++) { + if (i > 0) { + sb.append(','); + } + sb.append(ReflectUtils.getName(ets[i])); + } + } + sb.append('{').append(body).append('}'); + return addMethod(sb.toString()); + } + + public ClassGenerator addMethod(Method m) { + addMethod(m.getName(), m); + return this; + } + + public ClassGenerator addMethod(String name, Method m) { + String desc = name + ReflectUtils.getDescWithoutMethodName(m); + addMethod(':' + desc); + if (mCopyMethods == null) { + mCopyMethods = new ConcurrentHashMap(8); + } + mCopyMethods.put(desc, m); + return this; + } + + public ClassGenerator addConstructor(String code) { + if (mConstructors == null) { + mConstructors = new LinkedList(); + } + mConstructors.add(code); + return this; + } + + public ClassGenerator addConstructor(int mod, Class[] pts, String body) { + return addConstructor(mod, pts, null, body); + } + + public ClassGenerator addConstructor(int mod, Class[] pts, Class[] ets, String body) { + StringBuilder sb = new StringBuilder(); + sb.append(modifier(mod)).append(' ').append(SIMPLE_NAME_TAG); + sb.append('('); + for (int i = 0; i < pts.length; i++) { + if (i > 0) { + sb.append(','); + } + sb.append(ReflectUtils.getName(pts[i])); + sb.append(" arg").append(i); + } + sb.append(')'); + if (ets != null && ets.length > 0) { + sb.append(" throws "); + for (int i = 0; i < ets.length; i++) { + if (i > 0) { + sb.append(','); + } + sb.append(ReflectUtils.getName(ets[i])); + } + } + sb.append('{').append(body).append('}'); + return addConstructor(sb.toString()); + } + + public ClassGenerator addConstructor(Constructor c) { + String desc = ReflectUtils.getDesc(c); + addConstructor(":" + desc); + if (mCopyConstructors == null) { + mCopyConstructors = new ConcurrentHashMap>(4); + } + mCopyConstructors.put(desc, c); + return this; + } + + public ClassGenerator addDefaultConstructor() { + mDefaultConstructor = true; + return this; + } + + public ClassPool getClassPool() { + return mPool; + } + + public Class toClass() { + return toClass(ClassHelper.getClassLoader(ClassGenerator.class), + getClass().getProtectionDomain()); + } + + public Class toClass(ClassLoader loader, ProtectionDomain pd) { + if (mCtc != null) { + mCtc.detach(); + } + long id = CLASS_NAME_COUNTER.getAndIncrement(); + try { + CtClass ctcs = mSuperClass == null ? null : mPool.get(mSuperClass); + if (mClassName == null) { + mClassName = (mSuperClass == null || javassist.Modifier.isPublic(ctcs.getModifiers()) + ? ClassGenerator.class.getName() : mSuperClass + "$sc") + id; + } + mCtc = mPool.makeClass(mClassName); + if (mSuperClass != null) { + mCtc.setSuperclass(ctcs); + } + mCtc.addInterface(mPool.get(DC.class.getName())); // add dynamic class tag. + if (mInterfaces != null) { + for (String cl : mInterfaces) { + mCtc.addInterface(mPool.get(cl)); + } + } + if (mFields != null) { + for (String code : mFields) { + mCtc.addField(CtField.make(code, mCtc)); + } + } + if (mMethods != null) { + for (String code : mMethods) { + if (code.charAt(0) == ':') { + mCtc.addMethod(CtNewMethod.copy(getCtMethod(mCopyMethods.get(code.substring(1))), + code.substring(1, code.indexOf('(')), mCtc, null)); + } else { + mCtc.addMethod(CtNewMethod.make(code, mCtc)); + } + } + } + if (mDefaultConstructor) { + mCtc.addConstructor(CtNewConstructor.defaultConstructor(mCtc)); + } + if (mConstructors != null) { + for (String code : mConstructors) { + if (code.charAt(0) == ':') { + mCtc.addConstructor(CtNewConstructor + .copy(getCtConstructor(mCopyConstructors.get(code.substring(1))), mCtc, null)); + } else { + String[] sn = mCtc.getSimpleName().split("\\$+"); // inner class name include $. + mCtc.addConstructor( + CtNewConstructor.make(code.replaceFirst(SIMPLE_NAME_TAG, sn[sn.length - 1]), mCtc)); + } + } + } + return mCtc.toClass(loader, pd); + } catch (RuntimeException e) { + throw e; + } catch (NotFoundException e) { + throw new RuntimeException(e.getMessage(), e); + } catch (CannotCompileException e) { + throw new RuntimeException(e.getMessage(), e); + } + } + + public void release() { + if (mCtc != null) { + mCtc.detach(); + } + if (mInterfaces != null) { + mInterfaces.clear(); + } + if (mFields != null) { + mFields.clear(); + } + if (mMethods != null) { + mMethods.clear(); + } + if (mConstructors != null) { + mConstructors.clear(); + } + if (mCopyMethods != null) { + mCopyMethods.clear(); + } + if (mCopyConstructors != null) { + mCopyConstructors.clear(); + } + } + + private CtClass getCtClass(Class c) throws NotFoundException { + return mPool.get(c.getName()); + } + + private CtMethod getCtMethod(Method m) throws NotFoundException { + return getCtClass(m.getDeclaringClass()) + .getMethod(m.getName(), ReflectUtils.getDescWithoutMethodName(m)); + } + + private CtConstructor getCtConstructor(Constructor c) throws NotFoundException { + return getCtClass(c.getDeclaringClass()).getConstructor(ReflectUtils.getDesc(c)); + } + + public static interface DC { + + } // dynamic class tag interface. } \ No newline at end of file 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 fe37f2f03140..df95dabf4452 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 @@ -98,16 +98,18 @@ public static Mixin mixin(Class[] ics, Class[] dcs, ClassLoader cl) { if (pkg == null) { pkg = npkg; } else { - if (!pkg.equals(npkg)) + if (!pkg.equals(npkg)) { throw new IllegalArgumentException("non-public interfaces class from different packages"); + } } } ccp.addField("private " + dcs[i].getName() + " d" + i + ";"); code.append("d").append(i).append(" = (").append(dcs[i].getName()).append(")$1[").append(i).append("];\n"); - if (MixinAware.class.isAssignableFrom(dcs[i])) + if (MixinAware.class.isAssignableFrom(dcs[i])) { code.append("d").append(i).append(".setMixinInstance(this);\n"); + } } ccp.addConstructor(Modifier.PUBLIC, new Class[]{Object[].class}, code.toString()); @@ -119,39 +121,45 @@ public static Mixin mixin(Class[] ics, Class[] dcs, ClassLoader cl) { if (pkg == null) { pkg = npkg; } else { - if (!pkg.equals(npkg)) + if (!pkg.equals(npkg)) { throw new IllegalArgumentException("non-public delegate class from different packages"); + } } } ccp.addInterface(ics[i]); for (Method method : ics[i].getMethods()) { - if ("java.lang.Object".equals(method.getDeclaringClass().getName())) + if ("java.lang.Object".equals(method.getDeclaringClass().getName())) { continue; + } String desc = ReflectUtils.getDesc(method); - if (worked.contains(desc)) + if (worked.contains(desc)) { continue; + } worked.add(desc); int ix = findMethod(dcs, desc); - if (ix < 0) + if (ix < 0) { throw new RuntimeException("Missing method [" + desc + "] implement."); + } Class rt = method.getReturnType(); String mn = method.getName(); - if (Void.TYPE.equals(rt)) + if (Void.TYPE.equals(rt)) { ccp.addMethod(mn, method.getModifiers(), rt, method.getParameterTypes(), method.getExceptionTypes(), "d" + ix + "." + mn + "($$);"); - else + } else { ccp.addMethod(mn, method.getModifiers(), rt, method.getParameterTypes(), method.getExceptionTypes(), "return ($r)d" + ix + "." + mn + "($$);"); + } } } - if (pkg == null) + if (pkg == null) { pkg = PACKAGE_NAME; + } // create MixinInstance class. String micn = pkg + ".mixin" + id; @@ -173,10 +181,12 @@ public static Mixin mixin(Class[] ics, Class[] dcs, ClassLoader cl) { throw new RuntimeException(e.getMessage(), e); } finally { // release ClassGenerator - if (ccp != null) + if (ccp != null) { ccp.release(); - if (ccm != null) + } + if (ccm != null) { ccm.release(); + } } } @@ -187,17 +197,20 @@ private static int findMethod(Class[] dcs, String desc) { cl = dcs[i]; methods = cl.getMethods(); for (Method method : methods) { - if (desc.equals(ReflectUtils.getDesc(method))) + if (desc.equals(ReflectUtils.getDesc(method))) { return i; + } } } return -1; } private static void assertInterfaceArray(Class[] ics) { - for (int i = 0; i < ics.length; i++) - if (!ics[i].isInterface()) + for (int i = 0; i < ics.length; i++) { + if (!ics[i].isInterface()) { throw new RuntimeException("Class " + ics[i].getName() + " is not a interface."); + } + } } /** 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 91c534f20149..150e946b6905 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 @@ -77,14 +77,16 @@ public static Proxy getProxy(Class... ics) { * @return Proxy instance. */ public static Proxy getProxy(ClassLoader cl, Class... ics) { - if (ics.length > 65535) + if (ics.length > 65535) { throw new IllegalArgumentException("interface limit exceeded"); + } StringBuilder sb = new StringBuilder(); for (int i = 0; i < ics.length; i++) { String itf = ics[i].getName(); - if (!ics[i].isInterface()) + if (!ics[i].isInterface()) { throw new RuntimeException(itf + " is not a interface."); + } Class tmp = null; try { @@ -92,8 +94,9 @@ public static Proxy getProxy(ClassLoader cl, Class... ics) { } catch (ClassNotFoundException e) { } - if (tmp != ics[i]) + if (tmp != ics[i]) { throw new IllegalArgumentException(ics[i] + " is not visible from class loader"); + } sb.append(itf).append(';'); } @@ -117,8 +120,9 @@ public static Proxy getProxy(ClassLoader cl, Class... ics) { Object value = cache.get(key); if (value instanceof Reference) { proxy = (Proxy) ((Reference) value).get(); - if (proxy != null) + if (proxy != null) { return proxy; + } } if (value == PendingGenerationMarker) { @@ -149,16 +153,18 @@ public static Proxy getProxy(ClassLoader cl, Class... ics) { if (pkg == null) { pkg = npkg; } else { - if (!pkg.equals(npkg)) + if (!pkg.equals(npkg)) { throw new IllegalArgumentException("non-public interfaces from different packages"); + } } } ccp.addInterface(ics[i]); for (Method method : ics[i].getMethods()) { String desc = ReflectUtils.getDesc(method); - if (worked.contains(desc)) + if (worked.contains(desc)) { continue; + } worked.add(desc); int ix = methods.size(); @@ -166,19 +172,22 @@ public static Proxy getProxy(ClassLoader cl, Class... ics) { Class[] pts = method.getParameterTypes(); StringBuilder code = new StringBuilder("Object[] args = new Object[").append(pts.length).append("];"); - for (int j = 0; j < pts.length; j++) + for (int j = 0; j < pts.length; j++) { code.append(" args[").append(j).append("] = ($w)$").append(j + 1).append(";"); + } code.append(" Object ret = handler.invoke(this, methods[" + ix + "], args);"); - if (!Void.TYPE.equals(rt)) + if (!Void.TYPE.equals(rt)) { code.append(" return ").append(asArgument(rt, "ret")).append(";"); + } methods.add(method); ccp.addMethod(method.getName(), method.getModifiers(), rt, pts, method.getExceptionTypes(), code.toString()); } } - if (pkg == null) + if (pkg == null) { pkg = PACKAGE_NAME; + } // create ProxyInstance class. String pcn = pkg + ".proxy" + id; @@ -205,15 +214,18 @@ public static Proxy getProxy(ClassLoader cl, Class... ics) { throw new RuntimeException(e.getMessage(), e); } finally { // release ClassGenerator - if (ccp != null) + if (ccp != null) { ccp.release(); - if (ccm != null) + } + if (ccm != null) { ccm.release(); + } synchronized (cache) { - if (proxy == null) + if (proxy == null) { cache.remove(key); - else + } else { cache.put(key, new WeakReference(proxy)); + } cache.notifyAll(); } } @@ -222,22 +234,30 @@ public static Proxy getProxy(ClassLoader cl, Class... ics) { private static String asArgument(Class cl, String name) { if (cl.isPrimitive()) { - if (Boolean.TYPE == cl) + if (Boolean.TYPE == cl) { return name + "==null?false:((Boolean)" + name + ").booleanValue()"; - if (Byte.TYPE == cl) + } + if (Byte.TYPE == cl) { return name + "==null?(byte)0:((Byte)" + name + ").byteValue()"; - if (Character.TYPE == cl) + } + if (Character.TYPE == cl) { return name + "==null?(char)0:((Character)" + name + ").charValue()"; - if (Double.TYPE == cl) + } + if (Double.TYPE == cl) { return name + "==null?(double)0:((Double)" + name + ").doubleValue()"; - if (Float.TYPE == cl) + } + if (Float.TYPE == cl) { return name + "==null?(float)0:((Float)" + name + ").floatValue()"; - if (Integer.TYPE == cl) + } + if (Integer.TYPE == cl) { return name + "==null?(int)0:((Integer)" + name + ").intValue()"; - if (Long.TYPE == cl) + } + if (Long.TYPE == cl) { return name + "==null?(long)0:((Long)" + name + ").longValue()"; - if (Short.TYPE == cl) + } + if (Short.TYPE == cl) { return name + "==null?(short)0:((Short)" + name + ").shortValue()"; + } throw new RuntimeException(name + " is unknown primitive type."); } return "(" + ReflectUtils.getName(cl) + ")" + name; 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 aebcda60a869..76113ba2e7b4 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 @@ -77,11 +77,19 @@ public boolean hasProperty(String name) { @Override public Object invokeMethod(Object instance, String mn, Class[] types, Object[] args) throws NoSuchMethodException { - if ("getClass".equals(mn)) return instance.getClass(); - if ("hashCode".equals(mn)) return instance.hashCode(); - if ("toString".equals(mn)) return instance.toString(); + if ("getClass".equals(mn)) { + return instance.getClass(); + } + if ("hashCode".equals(mn)) { + return instance.hashCode(); + } + if ("toString".equals(mn)) { + return instance.toString(); + } if ("equals".equals(mn)) { - if (args.length == 1) return instance.equals(args[0]); + if (args.length == 1) { + return instance.equals(args[0]); + } throw new IllegalArgumentException("Invoke method [" + mn + "] argument number error."); } throw new NoSuchMethodException("Method [" + mn + "] not found."); @@ -97,10 +105,13 @@ public Object invokeMethod(Object instance, String mn, Class[] types, Object[ */ public static Wrapper getWrapper(Class c) { while (ClassGenerator.isDynamicClass(c)) // can not wrapper on dynamic class. + { c = c.getSuperclass(); + } - if (c == Object.class) + if (c == Object.class) { return OBJECT_WRAPPER; + } Wrapper ret = WRAPPER_MAP.get(c); if (ret == null) { @@ -111,8 +122,9 @@ public static Wrapper getWrapper(Class c) { } private static Wrapper makeWrapper(Class c) { - if (c.isPrimitive()) + if (c.isPrimitive()) { throw new IllegalArgumentException("Can not create wrapper for primitive type: " + c); + } String name = c.getName(); ClassLoader cl = ClassHelper.getClassLoader(c); @@ -134,8 +146,9 @@ private static Wrapper makeWrapper(Class c) { for (Field f : c.getFields()) { String fn = f.getName(); Class ft = f.getType(); - if (Modifier.isStatic(f.getModifiers()) || Modifier.isTransient(f.getModifiers())) + if (Modifier.isStatic(f.getModifiers()) || Modifier.isTransient(f.getModifiers())) { continue; + } c1.append(" if( $2.equals(\"").append(fn).append("\") ){ w.").append(fn).append("=").append(arg(ft, "$3")).append("; return; }"); c2.append(" if( $2.equals(\"").append(fn).append("\") ){ return ($w)w.").append(fn).append("; }"); @@ -150,7 +163,9 @@ private static Wrapper makeWrapper(Class c) { } for (Method m : methods) { if (m.getDeclaringClass() == Object.class) //ignore Object's method. + { continue; + } String mn = m.getName(); c3.append(" if( \"").append(mn).append("\".equals( $2 ) "); @@ -175,16 +190,18 @@ private static Wrapper makeWrapper(Class c) { c3.append(" ) { "); - if (m.getReturnType() == Void.TYPE) + if (m.getReturnType() == Void.TYPE) { c3.append(" w.").append(mn).append('(').append(args(m.getParameterTypes(), "$4")).append(");").append(" return null;"); - else + } else { c3.append(" return ($w)w.").append(mn).append('(').append(args(m.getParameterTypes(), "$4")).append(");"); + } c3.append(" }"); mns.add(mn); - if (m.getDeclaringClass() == c) + if (m.getDeclaringClass() == c) { dmns.add(mn); + } ms.put(ReflectUtils.getDesc(m), m); } if (hasMethod) { @@ -215,8 +232,8 @@ private static Wrapper makeWrapper(Class c) { pts.put(pn, pt); } } - c1.append(" throw new " + NoSuchPropertyException.class.getName() + "(\"Not found property \\\"\"+$2+\"\\\" filed or setter method in class " + c.getName() + ".\"); }"); - c2.append(" throw new " + NoSuchPropertyException.class.getName() + "(\"Not found property \\\"\"+$2+\"\\\" filed or setter method in class " + c.getName() + ".\"); }"); + c1.append(" throw new " + NoSuchPropertyException.class.getName() + "(\"Not found property \\\"\"+$2+\"\\\" field or setter method in class " + c.getName() + ".\"); }"); + c2.append(" throw new " + NoSuchPropertyException.class.getName() + "(\"Not found property \\\"\"+$2+\"\\\" field or setter method in class " + c.getName() + ".\"); }"); // make class long id = WRAPPER_CLASS_COUNTER.getAndIncrement(); @@ -229,8 +246,9 @@ private static Wrapper makeWrapper(Class c) { cc.addField("public static " + Map.class.getName() + " pts;"); // property type map. cc.addField("public static String[] mns;"); // all method name array. cc.addField("public static String[] dmns;"); // declared method name array. - for (int i = 0, len = ms.size(); i < len; i++) + for (int i = 0, len = ms.size(); i < len; i++) { cc.addField("public static Class[] mts" + i + ";"); + } cc.addMethod("public String[] getPropertyNames(){ return pns; }"); cc.addMethod("public boolean hasProperty(String n){ return pts.containsKey($1); }"); @@ -249,8 +267,9 @@ private static Wrapper makeWrapper(Class c) { wc.getField("mns").set(null, mns.toArray(new String[0])); wc.getField("dmns").set(null, dmns.toArray(new String[0])); int ix = 0; - for (Method m : ms.values()) + for (Method m : ms.values()) { wc.getField("mts" + ix++).set(null, m.getParameterTypes()); + } return (Wrapper) wc.newInstance(); } catch (RuntimeException e) { throw e; @@ -266,22 +285,30 @@ private static Wrapper makeWrapper(Class c) { private static String arg(Class cl, String name) { if (cl.isPrimitive()) { - if (cl == Boolean.TYPE) + if (cl == Boolean.TYPE) { return "((Boolean)" + name + ").booleanValue()"; - if (cl == Byte.TYPE) + } + if (cl == Byte.TYPE) { return "((Byte)" + name + ").byteValue()"; - if (cl == Character.TYPE) + } + if (cl == Character.TYPE) { return "((Character)" + name + ").charValue()"; - if (cl == Double.TYPE) + } + if (cl == Double.TYPE) { return "((Number)" + name + ").doubleValue()"; - if (cl == Float.TYPE) + } + if (cl == Float.TYPE) { return "((Number)" + name + ").floatValue()"; - if (cl == Integer.TYPE) + } + if (cl == Integer.TYPE) { return "((Number)" + name + ").intValue()"; - if (cl == Long.TYPE) + } + if (cl == Long.TYPE) { return "((Number)" + name + ").longValue()"; - if (cl == Short.TYPE) + } + if (cl == Short.TYPE) { return "((Number)" + name + ").shortValue()"; + } throw new RuntimeException("Unknown primitive type: " + cl.getName()); } return "(" + ReflectUtils.getName(cl) + ")" + name; @@ -289,11 +316,14 @@ private static String arg(Class cl, String name) { private static String args(Class[] cs, String name) { int len = cs.length; - if (len == 0) return ""; + if (len == 0) { + return ""; + } StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { - if (i > 0) + if (i > 0) { sb.append(','); + } sb.append(arg(cs[i], name + "[" + i + "]")); } return sb.toString(); @@ -365,8 +395,9 @@ private static boolean hasMethods(Method[] methods) { */ public Object[] getPropertyValues(Object instance, String[] pns) throws NoSuchPropertyException, IllegalArgumentException { Object[] ret = new Object[pns.length]; - for (int i = 0; i < ret.length; i++) + for (int i = 0; i < ret.length; i++) { ret[i] = getPropertyValue(instance, pns[i]); + } return ret; } @@ -378,11 +409,13 @@ public Object[] getPropertyValues(Object instance, String[] pns) throws NoSuchPr * @param pvs property value array. */ public void setPropertyValues(Object instance, String[] pns, Object[] pvs) throws NoSuchPropertyException, IllegalArgumentException { - if (pns.length != pvs.length) + if (pns.length != pvs.length) { throw new IllegalArgumentException("pns.length != pvs.length"); + } - for (int i = 0; i < pns.length; i++) + for (int i = 0; i < pns.length; i++) { setPropertyValue(instance, pns[i], pvs[i]); + } } /** @@ -406,8 +439,11 @@ public void setPropertyValues(Object instance, String[] pns, Object[] pvs) throw * @return has or has not. */ public boolean hasMethod(String name) { - for (String mn : getMethodNames()) - if (mn.equals(name)) return true; + for (String mn : getMethodNames()) { + if (mn.equals(name)) { + return true; + } + } return false; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/Compiler.java b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/Compiler.java index 7c55a2910a3a..3b8961d83f23 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/Compiler.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/Compiler.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.compiler; - import org.apache.dubbo.common.extension.SPI; /** diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/AdaptiveCompiler.java b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/AdaptiveCompiler.java index b47857c6861f..a0c5cc6b4152 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/AdaptiveCompiler.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/AdaptiveCompiler.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.compiler.support; - import org.apache.dubbo.common.compiler.Compiler; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.ExtensionLoader; 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 8a8580d03d3b..9c2800cc217f 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 @@ -168,8 +168,9 @@ public JavaFileManagerImpl(JavaFileManager fileManager, ClassLoaderImpl classLoa @Override public FileObject getFileForInput(Location location, String packageName, String relativeName) throws IOException { FileObject o = fileObjects.get(uri(location, packageName, relativeName)); - if (o != null) + if (o != null) { return o; + } return super.getFileForInput(location, packageName, relativeName); } @@ -196,8 +197,9 @@ public ClassLoader getClassLoader(JavaFileManager.Location location) { @Override public String inferBinaryName(Location loc, JavaFileObject file) { - if (file instanceof JavaFileObjectImpl) + if (file instanceof JavaFileObjectImpl) { return file.getName(); + } return super.inferBinaryName(loc, file); } diff --git a/dubbo-serialization/dubbo-serialization-fastjson/src/test/java/org/apache/dubbo/common/serialize/fastjson/model/Person.java b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/DisableInject.java similarity index 68% rename from dubbo-serialization/dubbo-serialization-fastjson/src/test/java/org/apache/dubbo/common/serialize/fastjson/model/Person.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/extension/DisableInject.java index eadb684d15a3..577a28df6b4b 100644 --- a/dubbo-serialization/dubbo-serialization-fastjson/src/test/java/org/apache/dubbo/common/serialize/fastjson/model/Person.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/DisableInject.java @@ -14,25 +14,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.common.serialize.fastjson.model; +package org.apache.dubbo.common.extension; -public class Person { - private String name; - private int age; +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD}) +public @interface DisableInject { } 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 fcbb292ec728..31f72e669e7e 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionLoader.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionLoader.java @@ -105,8 +105,9 @@ private static boolean withExtensionAnnotation(Class type) { @SuppressWarnings("unchecked") public static ExtensionLoader getExtensionLoader(Class type) { - if (type == null) + if (type == null) { throw new IllegalArgumentException("Extension type == null"); + } if (!type.isInterface()) { throw new IllegalArgumentException("Extension type(" + type + ") is not interface!"); } @@ -277,8 +278,9 @@ private boolean isActive(String[] keys, URL url) { */ @SuppressWarnings("unchecked") public T getLoadedExtension(String name) { - if (name == null || name.length() == 0) + if (name == null || name.length() == 0) { throw new IllegalArgumentException("Extension name == null"); + } Holder holder = cachedInstances.get(name); if (holder == null) { cachedInstances.putIfAbsent(name, new Holder()); @@ -304,8 +306,9 @@ public Set getLoadedExtensions() { */ @SuppressWarnings("unchecked") public T getExtension(String name) { - if (name == null || name.length() == 0) + if (name == null || name.length() == 0) { throw new IllegalArgumentException("Extension name == null"); + } if ("true".equals(name)) { return getDefaultExtension(); } @@ -340,8 +343,9 @@ public T getDefaultExtension() { } public boolean hasExtension(String name) { - if (name == null || name.length() == 0) + if (name == null || name.length() == 0) { throw new IllegalArgumentException("Extension name == null"); + } try { this.getExtensionClass(name); return true; @@ -528,6 +532,12 @@ private T injectExtension(T instance) { if (method.getName().startsWith("set") && method.getParameterTypes().length == 1 && Modifier.isPublic(method.getModifiers())) { + /** + * Check {@link DisableInject} to see if we need auto injection for this property + */ + if (method.getAnnotation(DisableInject.class) != null) { + continue; + } Class pt = method.getParameterTypes()[0]; try { String property = method.getName().length() > 3 ? method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4) : ""; @@ -549,13 +559,16 @@ private T injectExtension(T instance) { } private Class getExtensionClass(String name) { - if (type == null) + if (type == null) { throw new IllegalArgumentException("Extension type == null"); - if (name == null) + } + if (name == null) { throw new IllegalArgumentException("Extension name == null"); + } Class clazz = getExtensionClasses().get(name); - if (clazz == null) + if (clazz == null) { throw new IllegalStateException("No such extension \"" + name + "\" for " + type.getName() + "!"); + } return clazz; } @@ -584,7 +597,9 @@ private Map> loadExtensionClasses() { throw new IllegalStateException("more than 1 default extension name on extension " + type.getName() + ": " + Arrays.toString(names)); } - if (names.length == 1) cachedDefaultName = names[0]; + if (names.length == 1) { + cachedDefaultName = names[0]; + } } } @@ -627,7 +642,9 @@ private void loadResource(Map> extensionClasses, ClassLoader cl String line; while ((line = reader.readLine()) != null) { final int ci = line.indexOf('#'); - if (ci >= 0) line = line.substring(0, ci); + if (ci >= 0) { + line = line.substring(0, ci); + } line = line.trim(); if (line.length() > 0) { try { @@ -768,8 +785,9 @@ private String createAdaptiveExtensionClassCode() { } } // no need to generate adaptive class since there's no adaptive method found. - if (!hasAdaptiveAnnotation) + if (!hasAdaptiveAnnotation) { throw new IllegalStateException("No adaptive method on extension " + type.getName() + ", refuse to create the adaptive class!"); + } codeBuilder.append("package ").append(type.getPackage().getName()).append(";"); codeBuilder.append("\nimport ").append(ExtensionLoader.class.getName()).append(";"); @@ -848,24 +866,13 @@ private String createAdaptiveExtensionClassCode() { String[] value = adaptiveAnnotation.value(); // value is not set, use the value generated from class name as the key if (value.length == 0) { - char[] charArray = type.getSimpleName().toCharArray(); - StringBuilder sb = new StringBuilder(128); - for (int i = 0; i < charArray.length; i++) { - if (Character.isUpperCase(charArray[i])) { - if (i != 0) { - sb.append("."); - } - sb.append(Character.toLowerCase(charArray[i])); - } else { - sb.append(charArray[i]); - } - } - value = new String[]{sb.toString()}; + String splitName = StringUtils.camelToSplitName(type.getSimpleName(), "."); + value = new String[]{splitName}; } boolean hasInvocation = false; for (int i = 0; i < pts.length; ++i) { - if (pts[i].getName().equals("org.apache.dubbo.rpc.Invocation")) { + if (("org.apache.dubbo.rpc.Invocation").equals(pts[i].getName())) { // Null Point check String s = String.format("\nif (arg%d == null) throw new IllegalArgumentException(\"invocation == null\");", i); code.append(s); @@ -881,30 +888,36 @@ private String createAdaptiveExtensionClassCode() { for (int i = value.length - 1; i >= 0; --i) { if (i == value.length - 1) { if (null != defaultExtName) { - if (!"protocol".equals(value[i])) - if (hasInvocation) + if (!"protocol".equals(value[i])) { + if (hasInvocation) { getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName); - else + } else { getNameCode = String.format("url.getParameter(\"%s\", \"%s\")", value[i], defaultExtName); - else + } + } else { getNameCode = String.format("( url.getProtocol() == null ? \"%s\" : url.getProtocol() )", defaultExtName); + } } else { - if (!"protocol".equals(value[i])) - if (hasInvocation) + if (!"protocol".equals(value[i])) { + if (hasInvocation) { getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName); - else + } else { getNameCode = String.format("url.getParameter(\"%s\")", value[i]); - else + } + } else { getNameCode = "url.getProtocol()"; + } } } else { - if (!"protocol".equals(value[i])) - if (hasInvocation) + if (!"protocol".equals(value[i])) { + if (hasInvocation) { getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName); - else + } else { getNameCode = String.format("url.getParameter(\"%s\", %s)", value[i], getNameCode); - else + } + } else { getNameCode = String.format("url.getProtocol() == null ? (%s) : url.getProtocol()", getNameCode); + } } } code.append("\nString extName = ").append(getNameCode).append(";"); @@ -929,8 +942,9 @@ private String createAdaptiveExtensionClassCode() { s = String.format("extension.%s(", method.getName()); code.append(s); for (int i = 0; i < pts.length; i++) { - if (i != 0) + if (i != 0) { code.append(", "); + } code.append("arg").append(i); } code.append(");"); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/io/Bytes.java b/dubbo-common/src/main/java/org/apache/dubbo/common/io/Bytes.java index a2cc9835c577..263e7b9f67c8 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/io/Bytes.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/io/Bytes.java @@ -395,12 +395,15 @@ public static String bytes2hex(byte[] bs) { * @return hex string. */ public static String bytes2hex(byte[] bs, int off, int len) { - if (off < 0) + if (off < 0) { throw new IndexOutOfBoundsException("bytes2hex: offset < 0, offset is " + off); - if (len < 0) + } + if (len < 0) { throw new IndexOutOfBoundsException("bytes2hex: length < 0, length is " + len); - if (off + len > bs.length) + } + if (off + len > bs.length) { throw new IndexOutOfBoundsException("bytes2hex: offset + length > array length."); + } byte b; int r = off, w = 0; @@ -432,20 +435,25 @@ public static byte[] hex2bytes(String str) { * @return byte array. */ public static byte[] hex2bytes(final String str, final int off, int len) { - if ((len & 1) == 1) + if ((len & 1) == 1) { throw new IllegalArgumentException("hex2bytes: ( len & 1 ) == 1."); + } - if (off < 0) + if (off < 0) { throw new IndexOutOfBoundsException("hex2bytes: offset < 0, offset is " + off); - if (len < 0) + } + if (len < 0) { throw new IndexOutOfBoundsException("hex2bytes: length < 0, length is " + len); - if (off + len > str.length()) + } + if (off + len > str.length()) { throw new IndexOutOfBoundsException("hex2bytes: offset + length > array length."); + } int num = len / 2, r = off, w = 0; byte[] b = new byte[num]; - for (int i = 0; i < num; i++) + for (int i = 0; i < num; i++) { b[w++] = (byte) (hex(str.charAt(r++)) << 4 | hex(str.charAt(r++))); + } return b; } @@ -488,8 +496,9 @@ public static String bytes2base64(byte[] b, String code) { * @return base64 string. */ public static String bytes2base64(byte[] b, int offset, int length, String code) { - if (code.length() < 64) + if (code.length() < 64) { throw new IllegalArgumentException("Base64 code length < 64."); + } return bytes2base64(b, offset, length, code.toCharArray()); } @@ -515,15 +524,19 @@ public static String bytes2base64(byte[] b, char[] code) { * @return base64 string. */ public static String bytes2base64(final byte[] bs, final int off, final int len, final char[] code) { - if (off < 0) + if (off < 0) { throw new IndexOutOfBoundsException("bytes2base64: offset < 0, offset is " + off); - if (len < 0) + } + if (len < 0) { throw new IndexOutOfBoundsException("bytes2base64: length < 0, length is " + len); - if (off + len > bs.length) + } + if (off + len > bs.length) { throw new IndexOutOfBoundsException("bytes2base64: offset + length > array length."); + } - if (code.length < 64) + if (code.length < 64) { throw new IllegalArgumentException("Base64 code length < 64."); + } boolean pad = code.length > 64; // has pad char. int num = len / 3, rem = len % 3, r = off, w = 0; @@ -551,8 +564,9 @@ public static String bytes2base64(final byte[] bs, final int off, final int len, cs[w++] = code[b1 >> 2]; cs[w++] = code[(b1 << 4) & MASK6 | (b2 >> 4)]; cs[w++] = code[(b2 << 2) & MASK6]; - if (pad) + if (pad) { cs[w++] = code[64]; + } } return new String(cs); } @@ -600,24 +614,30 @@ public static byte[] base642bytes(String str, String code) { * @return byte array. */ public static byte[] base642bytes(final String str, final int off, final int len, final String code) { - if (off < 0) + if (off < 0) { throw new IndexOutOfBoundsException("base642bytes: offset < 0, offset is " + off); - if (len < 0) + } + if (len < 0) { throw new IndexOutOfBoundsException("base642bytes: length < 0, length is " + len); - if (off + len > str.length()) + } + if (off + len > str.length()) { throw new IndexOutOfBoundsException("base642bytes: offset + length > string length."); + } - if (code.length() < 64) + if (code.length() < 64) { throw new IllegalArgumentException("Base64 code length < 64."); + } int rem = len % 4; - if (rem == 1) + if (rem == 1) { throw new IllegalArgumentException("base642bytes: base64 string length % 4 == 1."); + } int num = len / 4, size = num * 3; if (code.length() > 64) { - if (rem != 0) + if (rem != 0) { throw new IllegalArgumentException("base642bytes: base64 string length error."); + } char pc = code.charAt(64); if (str.charAt(off + len - 2) == pc) { @@ -630,10 +650,11 @@ public static byte[] base642bytes(final String str, final int off, final int len rem = 3; } } else { - if (rem == 2) + if (rem == 2) { size++; - else if (rem == 3) + } else if (rem == 3) { size += 2; + } } int r = off, w = 0; @@ -681,35 +702,43 @@ public static byte[] base642bytes(String str, char[] code) { * @return byte array. */ public static byte[] base642bytes(final String str, final int off, final int len, final char[] code) { - if (off < 0) + if (off < 0) { throw new IndexOutOfBoundsException("base642bytes: offset < 0, offset is " + off); - if (len < 0) + } + if (len < 0) { throw new IndexOutOfBoundsException("base642bytes: length < 0, length is " + len); - if (off + len > str.length()) + } + if (off + len > str.length()) { throw new IndexOutOfBoundsException("base642bytes: offset + length > string length."); + } - if (code.length < 64) + if (code.length < 64) { throw new IllegalArgumentException("Base64 code length < 64."); + } int rem = len % 4; - if (rem == 1) + if (rem == 1) { throw new IllegalArgumentException("base642bytes: base64 string length % 4 == 1."); + } int num = len / 4, size = num * 3; if (code.length > 64) { - if (rem != 0) + if (rem != 0) { throw new IllegalArgumentException("base642bytes: base64 string length error."); + } char pc = code[64]; - if (str.charAt(off + len - 2) == pc) + if (str.charAt(off + len - 2) == pc) { size -= 2; - else if (str.charAt(off + len - 1) == pc) + } else if (str.charAt(off + len - 1) == pc) { size--; + } } else { - if (rem == 2) + if (rem == 2) { size++; - else if (rem == 3) + } else if (rem == 3) { size += 2; + } } int r = off, w = 0; @@ -823,15 +852,24 @@ public static byte[] getMD5(InputStream is) throws IOException { } private static byte hex(char c) { - if (c <= '9') return (byte) (c - '0'); - if (c >= 'a' && c <= 'f') return (byte) (c - 'a' + 10); - if (c >= 'A' && c <= 'F') return (byte) (c - 'A' + 10); + if (c <= '9') { + return (byte) (c - '0'); + } + if (c >= 'a' && c <= 'f') { + return (byte) (c - 'a' + 10); + } + if (c >= 'A' && c <= 'F') { + return (byte) (c - 'A' + 10); + } throw new IllegalArgumentException("hex string format error [" + c + "]."); } private static int indexOf(char[] cs, char c) { - for (int i = 0, len = cs.length; i < len; i++) - if (cs[i] == c) return i; + for (int i = 0, len = cs.length; i < len; i++) { + if (cs[i] == c) { + return i; + } + } return -1; } @@ -839,14 +877,18 @@ private static byte[] decodeTable(String code) { int hash = code.hashCode(); byte[] ret = DECODE_TABLE_MAP.get(hash); if (ret == null) { - if (code.length() < 64) + if (code.length() < 64) { throw new IllegalArgumentException("Base64 code length < 64."); + } // create new decode table. ret = new byte[128]; for (int i = 0; i < 128; i++) // init table. + { ret[i] = -1; - for (int i = 0; i < 64; i++) + } + for (int i = 0; i < 64; i++) { ret[code.charAt(i)] = (byte) i; + } DECODE_TABLE_MAP.put(hash, ret); } return ret; @@ -858,8 +900,9 @@ private static byte[] getMD5(InputStream is, int bs) throws IOException { while (is.available() > 0) { int read, total = 0; do { - if ((read = is.read(buf, total, bs - total)) <= 0) + if ((read = is.read(buf, total, bs - total)) <= 0) { break; + } total += read; } while (total < bs); 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 5798f020fb5a..0bb950531fee 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 @@ -41,20 +41,25 @@ public int read() throws IOException { @Override public int read(byte b[], int off, int len) throws IOException { - if (b == null) + if (b == null) { throw new NullPointerException(); + } - if (off < 0 || len < 0 || len > b.length - off) + if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); + } - if (mPosition >= mLimit) + if (mPosition >= mLimit) { return -1; + } - if (mPosition + len > mLimit) + if (mPosition + len > mLimit) { len = mLimit - mPosition; + } - if (len <= 0) + if (len <= 0) { return 0; + } is.read(b, off, len); mPosition += len; @@ -63,11 +68,13 @@ public int read(byte b[], int off, int len) throws IOException { @Override public long skip(long len) throws IOException { - if (mPosition + len > mLimit) + if (mPosition + len > mLimit) { len = mLimit - mPosition; + } - if (len <= 0) + if (len <= 0) { return 0; + } is.skip(len); mPosition += len; @@ -128,7 +135,9 @@ public int read() throws IOException { } if (!mInReset) { - if (mDry) return -1; + if (mDry) { + return -1; + } if (null == mMarkBuffer) { mMarkBuffer = new byte[markBufferSize]; @@ -196,7 +205,9 @@ public boolean markSupported() { public int available() throws IOException { int available = is.available(); - if (mInMarked && mInReset) available += mCount - mPosition; + if (mInMarked && mInReset) { + available += mCount - mPosition; + } return available; } 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 b221da99f2fb..16bb0d6c479a 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 @@ -48,16 +48,21 @@ public int read() { @Override public int read(byte b[], int off, int len) { - if (b == null) + if (b == null) { throw new NullPointerException(); - if (off < 0 || len < 0 || len > b.length - off) + } + if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); - if (mPosition >= mLimit) + } + if (mPosition >= mLimit) { return -1; - if (mPosition + len > mLimit) + } + if (mPosition + len > mLimit) { len = mLimit - mPosition; - if (len <= 0) + } + if (len <= 0) { return 0; + } System.arraycopy(mData, mPosition, b, off, len); mPosition += len; return len; @@ -65,10 +70,12 @@ public int read(byte b[], int off, int len) { @Override public long skip(long len) { - if (mPosition + len > mLimit) + if (mPosition + len > mLimit) { len = mLimit - mPosition; - if (len <= 0) + } + if (len <= 0) { return 0; + } mPosition += len; return len; } 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 a5227c3fafc9..1ac43c893ddd 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 @@ -34,29 +34,34 @@ public UnsafeByteArrayOutputStream() { } public UnsafeByteArrayOutputStream(int size) { - if (size < 0) + if (size < 0) { throw new IllegalArgumentException("Negative initial size: " + size); + } mBuffer = new byte[size]; } @Override public void write(int b) { int newcount = mCount + 1; - if (newcount > mBuffer.length) + if (newcount > mBuffer.length) { mBuffer = Bytes.copyOf(mBuffer, Math.max(mBuffer.length << 1, newcount)); + } mBuffer[mCount] = (byte) b; mCount = newcount; } @Override public void write(byte b[], int off, int len) { - if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) + if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); - if (len == 0) + } + if (len == 0) { return; + } int newcount = mCount + len; - if (newcount > mBuffer.length) + if (newcount > mBuffer.length) { mBuffer = Bytes.copyOf(mBuffer, Math.max(mBuffer.length << 1, newcount)); + } System.arraycopy(b, off, mBuffer, mCount, len); mCount = newcount; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeStringReader.java b/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeStringReader.java index dd8334ebb4dd..ad37476bd72e 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeStringReader.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeStringReader.java @@ -36,8 +36,9 @@ public UnsafeStringReader(String str) { @Override public int read() throws IOException { ensureOpen(); - if (mPosition >= mLimit) + if (mPosition >= mLimit) { return -1; + } return mString.charAt(mPosition++); } @@ -46,14 +47,17 @@ public int read() throws IOException { public int read(char[] cs, int off, int len) throws IOException { ensureOpen(); if ((off < 0) || (off > cs.length) || (len < 0) || - ((off + len) > cs.length) || ((off + len) < 0)) + ((off + len) > cs.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); + } - if (len == 0) + if (len == 0) { return 0; + } - if (mPosition >= mLimit) + if (mPosition >= mLimit) { return -1; + } int n = Math.min(mLimit - mPosition, len); mString.getChars(mPosition, mPosition + n, cs, off); @@ -64,8 +68,9 @@ public int read(char[] cs, int off, int len) throws IOException { @Override public long skip(long ns) throws IOException { ensureOpen(); - if (mPosition >= mLimit) + if (mPosition >= mLimit) { return 0; + } long n = Math.min(mLimit - mPosition, ns); n = Math.max(-mPosition, n); @@ -86,8 +91,9 @@ public boolean markSupported() { @Override public void mark(int readAheadLimit) throws IOException { - if (readAheadLimit < 0) + if (readAheadLimit < 0) { throw new IllegalArgumentException("Read-ahead limit < 0"); + } ensureOpen(); mMark = mPosition; @@ -105,7 +111,8 @@ public void close() throws IOException { } private void ensureOpen() throws IOException { - if (mString == null) + if (mString == null) { throw new IOException("Stream closed"); + } } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeStringWriter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeStringWriter.java index ec99514e5880..47e9a3a1aa50 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeStringWriter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeStringWriter.java @@ -30,8 +30,9 @@ public UnsafeStringWriter() { } public UnsafeStringWriter(int size) { - if (size < 0) + if (size < 0) { throw new IllegalArgumentException("Negative buffer size"); + } lock = mBuffer = new StringBuilder(); } @@ -49,11 +50,13 @@ public void write(char[] cs) throws IOException { @Override public void write(char[] cs, int off, int len) throws IOException { if ((off < 0) || (off > cs.length) || (len < 0) || - ((off + len) > cs.length) || ((off + len) < 0)) + ((off + len) > cs.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); + } - if (len > 0) + if (len > 0) { mBuffer.append(cs, off, len); + } } @Override @@ -68,10 +71,11 @@ public void write(String str, int off, int len) { @Override public Writer append(CharSequence csq) { - if (csq == null) + if (csq == null) { write("null"); - else + } else { write(csq.toString()); + } return this; } 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 f06089f0350f..166c19288e60 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 @@ -141,7 +141,9 @@ public Object decode(Object jv) { d = new Decoder() { @Override public Object decode(Object jv) { - if (jv instanceof Boolean) return ((Boolean) jv).booleanValue(); + if (jv instanceof Boolean) { + return ((Boolean) jv).booleanValue(); + } return false; } }; @@ -150,7 +152,9 @@ public Object decode(Object jv) { d = new Decoder() { @Override public Object decode(Object jv) { - if (jv instanceof Boolean) return (Boolean) jv; + if (jv instanceof Boolean) { + return (Boolean) jv; + } return (Boolean) null; } }; @@ -159,7 +163,9 @@ public Object decode(Object jv) { d = new Decoder() { @Override public Object decode(Object jv) { - if (jv instanceof String && ((String) jv).length() > 0) return ((String) jv).charAt(0); + if (jv instanceof String && ((String) jv).length() > 0) { + return ((String) jv).charAt(0); + } return (char) 0; } }; @@ -168,7 +174,9 @@ public Object decode(Object jv) { d = new Decoder() { @Override public Object decode(Object jv) { - if (jv instanceof String && ((String) jv).length() > 0) return ((String) jv).charAt(0); + if (jv instanceof String && ((String) jv).length() > 0) { + return ((String) jv).charAt(0); + } return (Character) null; } }; @@ -177,7 +185,9 @@ public Object decode(Object jv) { d = new Decoder() { @Override public Object decode(Object jv) { - if (jv instanceof Number) return ((Number) jv).intValue(); + if (jv instanceof Number) { + return ((Number) jv).intValue(); + } return 0; } }; @@ -186,7 +196,9 @@ public Object decode(Object jv) { d = new Decoder() { @Override public Object decode(Object jv) { - if (jv instanceof Number) return Integer.valueOf(((Number) jv).intValue()); + if (jv instanceof Number) { + return Integer.valueOf(((Number) jv).intValue()); + } return (Integer) null; } }; @@ -195,7 +207,9 @@ public Object decode(Object jv) { d = new Decoder() { @Override public Object decode(Object jv) { - if (jv instanceof Number) return ((Number) jv).shortValue(); + if (jv instanceof Number) { + return ((Number) jv).shortValue(); + } return (short) 0; } }; @@ -204,7 +218,9 @@ public Object decode(Object jv) { d = new Decoder() { @Override public Object decode(Object jv) { - if (jv instanceof Number) return Short.valueOf(((Number) jv).shortValue()); + if (jv instanceof Number) { + return Short.valueOf(((Number) jv).shortValue()); + } return (Short) null; } }; @@ -213,7 +229,9 @@ public Object decode(Object jv) { d = new Decoder() { @Override public Object decode(Object jv) { - if (jv instanceof Number) return ((Number) jv).longValue(); + if (jv instanceof Number) { + return ((Number) jv).longValue(); + } return (long) 0; } }; @@ -222,7 +240,9 @@ public Object decode(Object jv) { d = new Decoder() { @Override public Object decode(Object jv) { - if (jv instanceof Number) return Long.valueOf(((Number) jv).longValue()); + if (jv instanceof Number) { + return Long.valueOf(((Number) jv).longValue()); + } return (Long) null; } }; @@ -231,7 +251,9 @@ public Object decode(Object jv) { d = new Decoder() { @Override public Object decode(Object jv) { - if (jv instanceof Number) return ((Number) jv).floatValue(); + if (jv instanceof Number) { + return ((Number) jv).floatValue(); + } return (float) 0; } }; @@ -240,7 +262,9 @@ public Object decode(Object jv) { d = new Decoder() { @Override public Object decode(Object jv) { - if (jv instanceof Number) return new Float(((Number) jv).floatValue()); + if (jv instanceof Number) { + return new Float(((Number) jv).floatValue()); + } return (Float) null; } }; @@ -249,7 +273,9 @@ public Object decode(Object jv) { d = new Decoder() { @Override public Object decode(Object jv) { - if (jv instanceof Number) return ((Number) jv).doubleValue(); + if (jv instanceof Number) { + return ((Number) jv).doubleValue(); + } return (double) 0; } }; @@ -258,7 +284,9 @@ public Object decode(Object jv) { d = new Decoder() { @Override public Object decode(Object jv) { - if (jv instanceof Number) return new Double(((Number) jv).doubleValue()); + if (jv instanceof Number) { + return new Double(((Number) jv).doubleValue()); + } return (Double) null; } }; @@ -267,7 +295,9 @@ public Object decode(Object jv) { d = new Decoder() { @Override public Object decode(Object jv) { - if (jv instanceof Number) return ((Number) jv).byteValue(); + if (jv instanceof Number) { + return ((Number) jv).byteValue(); + } return (byte) 0; } }; @@ -276,7 +306,9 @@ public Object decode(Object jv) { d = new Decoder() { @Override public Object decode(Object jv) { - if (jv instanceof Number) return Byte.valueOf(((Number) jv).byteValue()); + if (jv instanceof Number) { + return Byte.valueOf(((Number) jv).byteValue()); + } return (Byte) null; } }; @@ -285,7 +317,9 @@ public Object decode(Object jv) { d = new Decoder() { @Override public Object decode(Object jv) throws IOException { - if (jv instanceof String) return Bytes.base642bytes((String) jv); + if (jv instanceof String) { + return Bytes.base642bytes((String) jv); + } return (byte[]) null; } }; @@ -310,7 +344,9 @@ public Object decode(Object jv) throws IOException { d = new Decoder() { @Override public Object decode(Object jv) throws IOException { - if (jv instanceof Number) return BigInteger.valueOf(((Number) jv).longValue()); + if (jv instanceof Number) { + return BigInteger.valueOf(((Number) jv).longValue()); + } return (BigInteger) null; } }; @@ -319,7 +355,9 @@ public Object decode(Object jv) throws IOException { d = new Decoder() { @Override public Object decode(Object jv) throws IOException { - if (jv instanceof Number) return BigDecimal.valueOf(((Number) jv).doubleValue()); + if (jv instanceof Number) { + return BigDecimal.valueOf(((Number) jv).doubleValue()); + } return (BigDecimal) null; } }; @@ -328,7 +366,9 @@ public Object decode(Object jv) throws IOException { d = new Decoder() { @Override public Object decode(Object jv) throws IOException { - if (jv instanceof Number) return new AtomicInteger(((Number) jv).intValue()); + if (jv instanceof Number) { + return new AtomicInteger(((Number) jv).intValue()); + } return (AtomicInteger) null; } }; @@ -337,7 +377,9 @@ public Object decode(Object jv) throws IOException { d = new Decoder() { @Override public Object decode(Object jv) throws IOException { - if (jv instanceof Number) return new AtomicLong(((Number) jv).longValue()); + if (jv instanceof Number) { + return new AtomicLong(((Number) jv).longValue()); + } return (AtomicLong) null; } }; @@ -353,8 +395,9 @@ public Object decode(Object jv) throws IOException { throw new IllegalArgumentException(e.getMessage(), e); } } - if (jv instanceof Number) + if (jv instanceof Number) { return new Date(((Number) jv).longValue()); + } return (Date) null; } }; @@ -398,32 +441,36 @@ public void writeValue(Object obj, JSONWriter jb, boolean writeClass) throws IOE } else if (c.isArray()) { int len = Array.getLength(obj); jb.arrayBegin(); - for (int i = 0; i < len; i++) + for (int i = 0; i < len; i++) { writeValue(Array.get(obj, i), jb, writeClass); + } jb.arrayEnd(); } else if (Map.class.isAssignableFrom(c)) { Object key, value; jb.objectBegin(); for (Map.Entry entry : ((Map) obj).entrySet()) { key = entry.getKey(); - if (key == null) + if (key == null) { continue; + } jb.objectItem(key.toString()); value = entry.getValue(); - if (value == null) + if (value == null) { jb.valueNull(); - else + } else { writeValue(value, jb, writeClass); + } } jb.objectEnd(); } else if (Collection.class.isAssignableFrom(c)) { jb.arrayBegin(); for (Object item : (Collection) obj) { - if (item == null) + if (item == null) { jb.valueNull(); - else + } else { writeValue(item, jb, writeClass); + } } jb.arrayEnd(); } else if(obj instanceof Locale) { @@ -446,10 +493,11 @@ public void writeValue(Object obj, JSONWriter jb, boolean writeClass) throws IOE jb.objectItem(pn); Object value = w.getPropertyValue(obj, pn); - if (value == null || value == obj) + if (value == null || value == obj) { jb.valueNull(); - else + } else { writeValue(value, jb, writeClass); + } } if (writeClass) { jb.objectItem(JSONVisitor.CLASS_PROPERTY); 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 eeeac018561d..fdcf674c5904 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 @@ -92,105 +92,131 @@ private static Object toArray(Class c, Stack list, int len) throws Pa } } if (c == boolean.class) { - if (len == 0) return EMPTY_BOOL_ARRAY; + if (len == 0) { + return EMPTY_BOOL_ARRAY; + } Object o; boolean[] ret = new boolean[len]; for (int i = len - 1; i >= 0; i--) { o = list.pop(); - if (o instanceof Boolean) + if (o instanceof Boolean) { ret[i] = ((Boolean) o).booleanValue(); + } } return ret; } if (c == int.class) { - if (len == 0) return EMPTY_INT_ARRAY; + if (len == 0) { + return EMPTY_INT_ARRAY; + } Object o; int[] ret = new int[len]; for (int i = len - 1; i >= 0; i--) { o = list.pop(); - if (o instanceof Number) + if (o instanceof Number) { ret[i] = ((Number) o).intValue(); + } } return ret; } if (c == long.class) { - if (len == 0) return EMPTY_LONG_ARRAY; + if (len == 0) { + return EMPTY_LONG_ARRAY; + } Object o; long[] ret = new long[len]; for (int i = len - 1; i >= 0; i--) { o = list.pop(); - if (o instanceof Number) + if (o instanceof Number) { ret[i] = ((Number) o).longValue(); + } } return ret; } if (c == float.class) { - if (len == 0) return EMPTY_FLOAT_ARRAY; + if (len == 0) { + return EMPTY_FLOAT_ARRAY; + } Object o; float[] ret = new float[len]; for (int i = len - 1; i >= 0; i--) { o = list.pop(); - if (o instanceof Number) + if (o instanceof Number) { ret[i] = ((Number) o).floatValue(); + } } return ret; } if (c == double.class) { - if (len == 0) return EMPTY_DOUBLE_ARRAY; + if (len == 0) { + return EMPTY_DOUBLE_ARRAY; + } Object o; double[] ret = new double[len]; for (int i = len - 1; i >= 0; i--) { o = list.pop(); - if (o instanceof Number) + if (o instanceof Number) { ret[i] = ((Number) o).doubleValue(); + } } return ret; } if (c == byte.class) { - if (len == 0) return EMPTY_BYTE_ARRAY; + if (len == 0) { + return EMPTY_BYTE_ARRAY; + } Object o; byte[] ret = new byte[len]; for (int i = len - 1; i >= 0; i--) { o = list.pop(); - if (o instanceof Number) + if (o instanceof Number) { ret[i] = ((Number) o).byteValue(); + } } return ret; } if (c == char.class) { - if (len == 0) return EMPTY_CHAR_ARRAY; + if (len == 0) { + return EMPTY_CHAR_ARRAY; + } Object o; char[] ret = new char[len]; for (int i = len - 1; i >= 0; i--) { o = list.pop(); - if (o instanceof Character) + if (o instanceof Character) { ret[i] = ((Character) o).charValue(); + } } return ret; } if (c == short.class) { - if (len == 0) return EMPTY_SHORT_ARRAY; + if (len == 0) { + return EMPTY_SHORT_ARRAY; + } Object o; short[] ret = new short[len]; for (int i = len - 1; i >= 0; i--) { o = list.pop(); - if (o instanceof Number) + if (o instanceof Number) { ret[i] = ((Number) o).shortValue(); + } } return ret; } Object ret = Array.newInstance(c, len); - for (int i = len - 1; i >= 0; i--) + for (int i = len - 1; i >= 0; i--) { Array.set(ret, i, list.pop()); + } return ret; } private static String name(Class[] types) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < types.length; i++) { - if (i > 0) + if (i > 0) { sb.append(", "); + } sb.append(types[i].getName()); } return sb.toString(); @@ -294,12 +320,13 @@ public void objectItemValue(Object obj, boolean isValue) throws ParseException { public void arrayBegin() throws ParseException { mStack.push(mType); - if (mType.isArray()) + if (mType.isArray()) { mType = mType.getComponentType(); - else if (mType == Object.class || Collection.class.isAssignableFrom(mType)) + } else if (mType == Object.class || Collection.class.isAssignableFrom(mType)) { mType = Object.class; - else + } else { throw new ParseException("Convert error, can not load json array data into class [" + mType.getName() + "]."); + } } @Override @@ -331,8 +358,9 @@ public Object arrayEnd(int count) throws ParseException { } else { throw new ParseException("Convert error, can not load json array data into class [" + mType.getName() + "]."); } - for (int i = 0; i < count; i++) + for (int i = 0; i < count; i++) { items.add(mStack.remove(i - count)); + } ret = items; } mStack.pop(); @@ -342,10 +370,11 @@ public Object arrayEnd(int count) throws ParseException { @Override public void arrayItem(int index) throws ParseException { if (mTypes != null && mStack.size() == index + 1) { - if (index < mTypes.length) + if (index < mTypes.length) { mType = mTypes[index]; - else + } else { throw new ParseException("Can not load json array data into [" + name(mTypes) + "]."); + } } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/json/JSON.java b/dubbo-common/src/main/java/org/apache/dubbo/common/json/JSON.java index 24718568991e..1d3aa8891d25 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/json/JSON.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/json/JSON.java @@ -52,7 +52,9 @@ private JSON() { * @throws IOException */ public static String json(Object obj) throws IOException { - if (obj == null) return NULL; + if (obj == null) { + return NULL; + } StringWriter sw = new StringWriter(); try { json(obj, sw); @@ -74,10 +76,11 @@ public static void json(Object obj, Writer writer) throws IOException { } public static void json(Object obj, Writer writer, boolean writeClass) throws IOException { - if (obj == null) + if (obj == null) { writer.write(NULL); - else + } else { json(obj, new JSONWriter(writer), writeClass); + } } /** @@ -89,7 +92,9 @@ public static void json(Object obj, Writer writer, boolean writeClass) throws IO * @throws IOException */ public static String json(Object obj, String[] properties) throws IOException { - if (obj == null) return NULL; + if (obj == null) { + return NULL; + } StringWriter sw = new StringWriter(); try { json(obj, properties, sw); @@ -112,17 +117,19 @@ public static void json(Object obj, final String[] properties, Writer writer) th * @throws IOException */ public static void json(Object obj, final String[] properties, Writer writer, boolean writeClass) throws IOException { - if (obj == null) + if (obj == null) { writer.write(NULL); - else + } else { json(obj, properties, new JSONWriter(writer), writeClass); + } } private static void json(Object obj, JSONWriter jb, boolean writeClass) throws IOException { - if (obj == null) + if (obj == null) { jb.valueNull(); - else + } else { DEFAULT_CONVERTER.writeValue(obj, jb, writeClass); + } } private static void json(Object obj, String[] properties, JSONWriter jb, boolean writeClass) throws IOException { @@ -136,10 +143,11 @@ private static void json(Object obj, String[] properties, JSONWriter jb, boolean for (String prop : properties) { jb.objectItem(prop); value = wrapper.getPropertyValue(obj, prop); - if (value == null) + if (value == null) { jb.valueNull(); - else + } else { DEFAULT_CONVERTER.writeValue(value, jb, writeClass); + } } jb.objectEnd(); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/json/JSONArray.java b/dubbo-common/src/main/java/org/apache/dubbo/common/json/JSONArray.java index 9c9cadf34065..f5e039c3be88 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/json/JSONArray.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/json/JSONArray.java @@ -151,8 +151,9 @@ public void add(Object ele) { * add items. */ public void addAll(Object[] eles) { - for (Object ele : eles) + for (Object ele : eles) { mArray.add(ele); + } } /** @@ -172,10 +173,11 @@ public void addAll(Collection c) { public void writeJSON(JSONConverter jc, JSONWriter jb, boolean writeClass) throws IOException { jb.arrayBegin(); for (Object item : mArray) { - if (item == null) + if (item == null) { jb.valueNull(); - else + } else { jc.writeValue(item, jb, writeClass); + } } jb.arrayEnd(); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/json/JSONObject.java b/dubbo-common/src/main/java/org/apache/dubbo/common/json/JSONObject.java index 52c1990ba076..052f35269dde 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/json/JSONObject.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/json/JSONObject.java @@ -167,8 +167,9 @@ public void put(String name, Object value) { * @param values value array. */ public void putAll(String[] names, Object[] values) { - for (int i = 0, len = Math.min(names.length, values.length); i < len; i++) + for (int i = 0, len = Math.min(names.length, values.length); i < len; i++) { mMap.put(names[i], values[i]); + } } /** @@ -177,8 +178,9 @@ public void putAll(String[] names, Object[] values) { * @param map map. */ public void putAll(Map map) { - for (Map.Entry entry : map.entrySet()) + for (Map.Entry entry : map.entrySet()) { mMap.put(entry.getKey(), entry.getValue()); + } } /** @@ -196,10 +198,11 @@ public void writeJSON(JSONConverter jc, JSONWriter jb, boolean writeClass) throw key = entry.getKey(); jb.objectItem(key); value = entry.getValue(); - if (value == null) + if (value == null) { jb.valueNull(); - else + } else { jc.writeValue(value, jb, writeClass); + } } jb.objectEnd(); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/json/JSONReader.java b/dubbo-common/src/main/java/org/apache/dubbo/common/json/JSONReader.java index 2fbf4f6df298..616a15f5972d 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/json/JSONReader.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/json/JSONReader.java @@ -57,10 +57,12 @@ public JSONToken nextToken() throws IOException, ParseException { public JSONToken nextToken(int expect) throws IOException, ParseException { JSONToken ret = mLex.yylex(); - if (ret == null) + if (ret == null) { throw new ParseException("EOF error."); - if (expect != JSONToken.ANY && expect != ret.type) + } + if (expect != JSONToken.ANY && expect != ret.type) { throw new ParseException("Unexpected token."); + } return ret; } } \ No newline at end of file diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/json/JSONWriter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/json/JSONWriter.java index ee45e129bf32..094832134c08 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/json/JSONWriter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/json/JSONWriter.java @@ -53,11 +53,13 @@ public JSONWriter(OutputStream is, String charset) throws UnsupportedEncodingExc } private static String escape(String str) { - if (str == null) + if (str == null) { return str; + } int len = str.length(); - if (len == 0) + if (len == 0) { return str; + } char c; StringBuilder sb = null; @@ -82,8 +84,9 @@ private static String escape(String str) { sb.append('\\').append(c); break; default: - if (sb != null) + if (sb != null) { sb.append(c); + } } } } @@ -263,8 +266,9 @@ public JSONWriter valueDouble(double value) throws IOException { private void beforeValue() throws IOException { switch (mState.type) { case ARRAY: - if (mState.itemCount++ > 0) + if (mState.itemCount++ > 0) { mWriter.write(JSON.COMMA); + } return; case OBJECT: throw new IOException("Must call objectItem first."); @@ -280,8 +284,9 @@ private void beforeObjectItem() throws IOException { mWriter.write(JSON.NULL); case OBJECT: mState.type = OBJECT_VALUE; - if (mState.itemCount++ > 0) + if (mState.itemCount++ > 0) { mWriter.write(JSON.COMMA); + } return; default: throw new IOException("Must call objectBegin first."); 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 c7b11e95297c..8abb42d1ab2a 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 @@ -340,7 +340,9 @@ private static int zzUnpackAction(String packed, int offset, int[] result) { while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); - do result[j++] = value; while (--count > 0); + do { + result[j++] = value; + } while (--count > 0); } return j; } @@ -393,7 +395,9 @@ private static int zzUnpackAttribute(String packed, int offset, int[] result) { while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); - do result[j++] = value; while (--count > 0); + do { + result[j++] = value; + } while (--count > 0); } return j; } @@ -411,7 +415,9 @@ private static char[] zzUnpackCMap(String packed) { while (i < 122) { int count = packed.charAt(i++); char value = packed.charAt(i++); - do map[j++] = value; while (--count > 0); + do { + map[j++] = value; + } while (--count > 0); } return map; } @@ -477,8 +483,9 @@ public final void yyclose() throws java.io.IOException { zzAtEOF = true; /* indicate end of file */ zzEndRead = zzStartRead; /* invalidate buffer */ - if (zzReader != null) + if (zzReader != null) { zzReader.close(); + } } @@ -588,8 +595,9 @@ private void zzScanError(int errorCode) { * This number must not be greater than yylength()! */ public void yypushback(int number) { - if (number > yylength()) + if (number > yylength()) { zzScanError(ZZ_PUSHBACK_2BIG); + } zzMarkedPos -= number; } @@ -631,9 +639,9 @@ public JSONToken yylex() throws java.io.IOException, ParseException { { while (true) { - if (zzCurrentPosL < zzEndReadL) + if (zzCurrentPosL < zzEndReadL) { zzInput = zzBufferL[zzCurrentPosL++]; - else if (zzAtEOF) { + } else if (zzAtEOF) { zzInput = YYEOF; break zzForAction; } else { @@ -654,14 +662,18 @@ else if (zzAtEOF) { } } int zzNext = zzTransL[zzRowMapL[zzState] + zzCMapL[zzInput]]; - if (zzNext == -1) break zzForAction; + if (zzNext == -1) { + break zzForAction; + } zzState = zzNext; int zzAttributes = zzAttrL[zzState]; if ((zzAttributes & 1) == 1) { zzAction = zzState; zzMarkedPosL = zzCurrentPosL; - if ((zzAttributes & 8) == 8) break zzForAction; + if ((zzAttributes & 8) == 8) { + break zzForAction; + } } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jcl/JclLogger.java b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jcl/JclLogger.java index c88c1ab0bf1c..59e30e24bb04 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jcl/JclLogger.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jcl/JclLogger.java @@ -17,6 +17,7 @@ package org.apache.dubbo.common.logger.jcl; import org.apache.dubbo.common.logger.Logger; + import org.apache.commons.logging.Log; import java.io.Serializable; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jcl/JclLoggerAdapter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jcl/JclLoggerAdapter.java index 6a80695250bd..4ff23c66b96c 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jcl/JclLoggerAdapter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jcl/JclLoggerAdapter.java @@ -19,6 +19,7 @@ import org.apache.dubbo.common.logger.Level; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerAdapter; + import org.apache.commons.logging.LogFactory; import java.io.File; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jdk/JdkLoggerAdapter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jdk/JdkLoggerAdapter.java index 4419c154df69..19041304b116 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jdk/JdkLoggerAdapter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jdk/JdkLoggerAdapter.java @@ -61,35 +61,47 @@ public JdkLoggerAdapter() { } private static java.util.logging.Level toJdkLevel(Level level) { - if (level == Level.ALL) + if (level == Level.ALL) { return java.util.logging.Level.ALL; - if (level == Level.TRACE) + } + if (level == Level.TRACE) { return java.util.logging.Level.FINER; - if (level == Level.DEBUG) + } + if (level == Level.DEBUG) { return java.util.logging.Level.FINE; - if (level == Level.INFO) + } + if (level == Level.INFO) { return java.util.logging.Level.INFO; - if (level == Level.WARN) + } + if (level == Level.WARN) { return java.util.logging.Level.WARNING; - if (level == Level.ERROR) + } + if (level == Level.ERROR) { return java.util.logging.Level.SEVERE; + } // if (level == Level.OFF) return java.util.logging.Level.OFF; } private static Level fromJdkLevel(java.util.logging.Level level) { - if (level == java.util.logging.Level.ALL) + if (level == java.util.logging.Level.ALL) { return Level.ALL; - if (level == java.util.logging.Level.FINER) + } + if (level == java.util.logging.Level.FINER) { return Level.TRACE; - if (level == java.util.logging.Level.FINE) + } + if (level == java.util.logging.Level.FINE) { return Level.DEBUG; - if (level == java.util.logging.Level.INFO) + } + if (level == java.util.logging.Level.INFO) { return Level.INFO; - if (level == java.util.logging.Level.WARNING) + } + if (level == java.util.logging.Level.WARNING) { return Level.WARN; - if (level == java.util.logging.Level.SEVERE) + } + if (level == java.util.logging.Level.SEVERE) { return Level.ERROR; + } // if (level == java.util.logging.Level.OFF) return Level.OFF; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/log4j/Log4jLoggerAdapter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/log4j/Log4jLoggerAdapter.java index e92a0971e9c0..5febaf2501d5 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/log4j/Log4jLoggerAdapter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/log4j/Log4jLoggerAdapter.java @@ -54,35 +54,47 @@ public Log4jLoggerAdapter() { } private static org.apache.log4j.Level toLog4jLevel(Level level) { - if (level == Level.ALL) + if (level == Level.ALL) { return org.apache.log4j.Level.ALL; - if (level == Level.TRACE) + } + if (level == Level.TRACE) { return org.apache.log4j.Level.TRACE; - if (level == Level.DEBUG) + } + if (level == Level.DEBUG) { return org.apache.log4j.Level.DEBUG; - if (level == Level.INFO) + } + if (level == Level.INFO) { return org.apache.log4j.Level.INFO; - if (level == Level.WARN) + } + if (level == Level.WARN) { return org.apache.log4j.Level.WARN; - if (level == Level.ERROR) + } + if (level == Level.ERROR) { return org.apache.log4j.Level.ERROR; + } // if (level == Level.OFF) return org.apache.log4j.Level.OFF; } private static Level fromLog4jLevel(org.apache.log4j.Level level) { - if (level == org.apache.log4j.Level.ALL) + if (level == org.apache.log4j.Level.ALL) { return Level.ALL; - if (level == org.apache.log4j.Level.TRACE) + } + if (level == org.apache.log4j.Level.TRACE) { return Level.TRACE; - if (level == org.apache.log4j.Level.DEBUG) + } + if (level == org.apache.log4j.Level.DEBUG) { return Level.DEBUG; - if (level == org.apache.log4j.Level.INFO) + } + if (level == org.apache.log4j.Level.INFO) { return Level.INFO; - if (level == org.apache.log4j.Level.WARN) + } + if (level == org.apache.log4j.Level.WARN) { return Level.WARN; - if (level == org.apache.log4j.Level.ERROR) + } + if (level == org.apache.log4j.Level.ERROR) { return Level.ERROR; + } // if (level == org.apache.log4j.Level.OFF) return Level.OFF; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/store/support/SimpleDataStore.java b/dubbo-common/src/main/java/org/apache/dubbo/common/store/support/SimpleDataStore.java index 2252e8308ef6..d60cc5d13165 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/store/support/SimpleDataStore.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/store/support/SimpleDataStore.java @@ -33,7 +33,9 @@ public class SimpleDataStore implements DataStore { @Override public Map get(String componentName) { ConcurrentMap value = data.get(componentName); - if (value == null) return new HashMap(); + if (value == null) { + return new HashMap(); + } return new HashMap(value); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolExecutor.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolExecutor.java index f8eb5df2c851..d35e8d8f6cdd 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolExecutor.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolExecutor.java @@ -17,11 +17,11 @@ package org.apache.dubbo.common.threadpool.support.eager; +import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.atomic.AtomicInteger; /** 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 a54cc70b9b48..f786caeb8cc8 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 @@ -20,17 +20,17 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ClassHelper; -import java.util.Queue; -import java.util.Set; -import java.util.HashSet; import java.util.Collections; +import java.util.HashSet; import java.util.Locale; +import java.util.Queue; +import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; +import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; -import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; @@ -367,6 +367,11 @@ public Set stop() { return worker.unprocessedTimeouts(); } + @Override + public boolean isStop() { + return WORKER_STATE_SHUTDOWN == WORKER_STATE_UPDATER.get(this); + } + @Override public Timeout newTimeout(TimerTask task, long delay, TimeUnit unit) { if (task == null) { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/timer/Timer.java b/dubbo-common/src/main/java/org/apache/dubbo/common/timer/Timer.java index 9e87059124fb..881fab95a572 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/timer/Timer.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/timer/Timer.java @@ -45,4 +45,11 @@ public interface Timer { * this method */ Set stop(); + + /** + * the timer is stop + * + * @return true for stop + */ + boolean isStop(); } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ServiceClassHolder.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ArrayUtils.java similarity index 54% rename from dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ServiceClassHolder.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/utils/ArrayUtils.java index bbbf755f1f77..a0b62bd402c3 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ServiceClassHolder.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ArrayUtils.java @@ -14,32 +14,34 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.rpc; + +package org.apache.dubbo.common.utils; /** - * TODO this is just a workaround for rest protocol, and now we just ensure it works in the most common dubbo usages - * + * Contains some methods to check array. */ -public class ServiceClassHolder { - - private static final ServiceClassHolder INSTANCE = new ServiceClassHolder(); - - private final ThreadLocal holder = new ThreadLocal(); - - public static ServiceClassHolder getInstance() { - return INSTANCE; - } +public final class ArrayUtils { - private ServiceClassHolder() { + private ArrayUtils() { } - public Class popServiceClass() { - Class clazz = holder.get(); - holder.remove(); - return clazz; + /** + *

Checks if the array is null or empty.

+ * + * @param array th array to check + * @return {@code true} if the array is null or empty. + */ + public static boolean isEmpty(final Object[] array) { + return array == null || array.length == 0; } - public void pushServiceClass(Class clazz) { - holder.set(clazz); + /** + *

Checks if the array is not null or empty.

+ * + * @param array th array to check + * @return {@code true} if the array is not null or empty. + */ + public static boolean isNotEmpty(final Object[] array) { + return !isEmpty(array); } } 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 1f92b642eb91..4a13c6c4acd5 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 @@ -142,8 +142,12 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) return true; - if (!(obj instanceof AtomicPositiveInteger)) return false; + if (this == obj) { + return true; + } + if (!(obj instanceof AtomicPositiveInteger)) { + return false; + } AtomicPositiveInteger other = (AtomicPositiveInteger) obj; return intValue() == other.intValue(); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CollectionUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CollectionUtils.java index eca847f6e7e6..37271087c999 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CollectionUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CollectionUtils.java @@ -72,7 +72,7 @@ public static Map> splitAll(Map if (list == null) { return null; } - Map> result = new HashMap>(); + Map> result = new HashMap<>(); for (Map.Entry> entry : list.entrySet()) { result.put(entry.getKey(), split(entry.getValue(), separator)); } @@ -83,7 +83,7 @@ public static Map> joinAll(Map> if (map == null) { return null; } - Map> result = new HashMap>(); + Map> result = new HashMap<>(); for (Map.Entry> entry : map.entrySet()) { result.put(entry.getKey(), join(entry.getValue(), separator)); } @@ -94,7 +94,7 @@ public static Map split(List list, String separator) { if (list == null) { return null; } - Map map = new HashMap(); + Map map = new HashMap<>(); if (list.isEmpty()) { return map; } @@ -113,7 +113,7 @@ public static List join(Map map, String separator) { if (map == null) { return null; } - List list = new ArrayList(); + List list = new ArrayList<>(); if (map.size() == 0) { return list; } @@ -172,7 +172,7 @@ private static boolean objectEquals(Object obj1, Object obj2) { } public static Map toStringMap(String... pairs) { - Map parameters = new HashMap(); + Map parameters = new HashMap<>(); if (pairs.length > 0) { if (pairs.length % 2 != 0) { throw new IllegalArgumentException("pairs must be even."); @@ -186,8 +186,10 @@ public static Map toStringMap(String... pairs) { @SuppressWarnings("unchecked") public static Map toMap(Object... pairs) { - Map ret = new HashMap(); - if (pairs == null || pairs.length == 0) return ret; + Map ret = new HashMap<>(); + if (pairs == null || pairs.length == 0) { + return ret; + } if (pairs.length % 2 != 0) { throw new IllegalArgumentException("Map pairs can not be odd number."); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/IOUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/IOUtils.java index 7129c34011ed..14d5b81ea3cd 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/IOUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/IOUtils.java @@ -147,8 +147,9 @@ public static long write(Reader reader, Writer writer, int bufferSize) throws IO * @throws IOException */ public static String[] readLines(File file) throws IOException { - if (file == null || !file.exists() || !file.canRead()) + if (file == null || !file.exists() || !file.canRead()) { return new String[0]; + } return readLines(new FileInputStream(file)); } @@ -165,8 +166,9 @@ public static String[] readLines(InputStream is) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); try { String line; - while ((line = reader.readLine()) != null) + while ((line = reader.readLine()) != null) { lines.add(line); + } return lines.toArray(new String[0]); } finally { reader.close(); @@ -183,8 +185,9 @@ public static String[] readLines(InputStream is) throws IOException { public static void writeLines(OutputStream os, String[] lines) throws IOException { PrintWriter writer = new PrintWriter(new OutputStreamWriter(os)); try { - for (String line : lines) + for (String line : lines) { writer.println(line); + } writer.flush(); } finally { writer.close(); @@ -199,8 +202,9 @@ public static void writeLines(OutputStream os, String[] lines) throws IOExceptio * @throws IOException */ public static void writeLines(File file, String[] lines) throws IOException { - if (file == null) + if (file == null) { throw new IOException("File is null."); + } writeLines(new FileOutputStream(file), lines); } @@ -212,8 +216,9 @@ public static void writeLines(File file, String[] lines) throws IOException { * @throws IOException */ public static void appendLines(File file, String[] lines) throws IOException { - if (file == null) + if (file == null) { throw new IOException("File is null."); + } writeLines(new FileOutputStream(file, true), lines); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Log.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Log.java index 6604c2b93f59..974058ffb1e7 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Log.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Log.java @@ -72,22 +72,44 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } Log other = (Log) obj; if (logLevel == null) { - if (other.logLevel != null) return false; - } else if (!logLevel.equals(other.logLevel)) return false; + if (other.logLevel != null) { + return false; + } + } else if (!logLevel.equals(other.logLevel)) { + return false; + } if (logMessage == null) { - if (other.logMessage != null) return false; - } else if (!logMessage.equals(other.logMessage)) return false; + if (other.logMessage != null) { + return false; + } + } else if (!logMessage.equals(other.logMessage)) { + return false; + } if (logName == null) { - if (other.logName != null) return false; - } else if (!logName.equals(other.logName)) return false; + if (other.logName != null) { + return false; + } + } else if (!logName.equals(other.logName)) { + return false; + } if (logThread == null) { - if (other.logThread != null) return false; - } else if (!logThread.equals(other.logThread)) return false; + if (other.logThread != null) { + return false; + } + } else if (!logThread.equals(other.logThread)) { + return false; + } return true; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LogUtil.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LogUtil.java index d5b3e2b71305..6b5eff58c2d3 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LogUtil.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LogUtil.java @@ -50,7 +50,9 @@ public static int findName(String expectedLogName) { List logList = DubboAppender.logList; for (int i = 0; i < logList.size(); i++) { String logName = logList.get(i).getLogName(); - if (logName.contains(expectedLogName)) count++; + if (logName.contains(expectedLogName)) { + count++; + } } return count; } @@ -60,7 +62,9 @@ public static int findLevel(Level expectedLevel) { List logList = DubboAppender.logList; for (int i = 0; i < logList.size(); i++) { Level logLevel = logList.get(i).getLogLevel(); - if (logLevel.equals(expectedLevel)) count++; + if (logLevel.equals(expectedLevel)) { + count++; + } } return count; } @@ -70,8 +74,9 @@ public static int findLevelWithThreadName(Level expectedLevel, String threadName List logList = DubboAppender.logList; for (int i = 0; i < logList.size(); i++) { Log log = logList.get(i); - if (log.getLogLevel().equals(expectedLevel) && log.getLogThread().equals(threadName)) + if (log.getLogLevel().equals(expectedLevel) && log.getLogThread().equals(threadName)) { count++; + } } return count; } @@ -81,7 +86,9 @@ public static int findThread(String expectedThread) { List logList = DubboAppender.logList; for (int i = 0; i < logList.size(); i++) { String logThread = logList.get(i).getLogThread(); - if (logThread.contains(expectedThread)) count++; + if (logThread.contains(expectedThread)) { + count++; + } } return count; } @@ -91,7 +98,9 @@ public static int findMessage(String expectedMessage) { List logList = DubboAppender.logList; for (int i = 0; i < logList.size(); i++) { String logMessage = logList.get(i).getLogMessage(); - if (logMessage.contains(expectedMessage)) count++; + if (logMessage.contains(expectedMessage)) { + count++; + } } return count; } @@ -103,7 +112,9 @@ public static int findMessage(Level expectedLevel, String expectedMessage) { Level logLevel = logList.get(i).getLogLevel(); if (logLevel.equals(expectedLevel)) { String logMessage = logList.get(i).getLogMessage(); - if (logMessage.contains(expectedMessage)) count++; + if (logMessage.contains(expectedMessage)) { + count++; + } } } return count; 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 70d6006cbe81..29d79a30f0fb 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 @@ -134,8 +134,9 @@ public static InetSocketAddress getLocalSocketAddress(String host, int port) { } static boolean isValidAddress(InetAddress address) { - if (address == null || address.isLoopbackAddress()) + if (address == null || address.isLoopbackAddress()) { return false; + } String name = address.getHostAddress(); return (name != null && !ANYHOST.equals(name) @@ -221,8 +222,9 @@ public static String filterLocalHost(String host) { * @return first valid local IP */ public static InetAddress getLocalAddress() { - if (LOCAL_ADDRESS != null) + if (LOCAL_ADDRESS != null) { return LOCAL_ADDRESS; + } InetAddress localAddress = getLocalAddress0(); LOCAL_ADDRESS = localAddress; return localAddress; @@ -333,8 +335,9 @@ public static String toURL(String protocol, String host, int port, String path) StringBuilder sb = new StringBuilder(); sb.append(protocol).append("://"); sb.append(host).append(':').append(port); - if (path.charAt(0) != '/') + if (path.charAt(0) != '/') { sb.append('/'); + } sb.append(path); return sb.toString(); } 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 09fd234d8bf5..d8c00f31ce7b 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 @@ -82,8 +82,9 @@ public static Object[] realize(Object[] objs, Class[] types) { } public static Object[] realize(Object[] objs, Class[] types, Type[] gtypes) { - if (objs.length != types.length || objs.length != gtypes.length) + if (objs.length != types.length || objs.length != gtypes.length) { throw new IllegalArgumentException("args.length != types.length"); + } Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = realize(objs[i], types[i], gtypes[i]); @@ -448,8 +449,9 @@ private static Object realize0(Object pojo, Class type, Type genericType, fin Method method = getSetterMethod(dest.getClass(), name, value.getClass()); Field field = getField(dest.getClass(), name); if (method != null) { - if (!method.isAccessible()) + if (!method.isAccessible()) { method.setAccessible(true); + } Type ptype = method.getGenericParameterTypes()[0]; value = realize0(value, method.getParameterTypes()[0], ptype, history); try { @@ -464,7 +466,7 @@ private static Object realize0(Object pojo, Class type, Type genericType, fin try { field.set(dest, value); } catch (IllegalAccessException e) { - throw new RuntimeException("Failed to set filed " + name + " of pojo " + dest.getClass().getName() + " : " + e.getMessage(), e); + throw new RuntimeException("Failed to set field " + name + " of pojo " + dest.getClass().getName() + " : " + e.getMessage(), e); } } } @@ -474,11 +476,11 @@ private static Object realize0(Object pojo, Class type, Type genericType, fin Object message = map.get("message"); if (message instanceof String) { try { - Field filed = Throwable.class.getDeclaredField("detailMessage"); - if (!filed.isAccessible()) { - filed.setAccessible(true); + Field field = Throwable.class.getDeclaredField("detailMessage"); + if (!field.isAccessible()) { + field.setAccessible(true); } - filed.set(dest, message); + field.set(dest, message); } catch (Exception e) { } } 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 78f7b92b014c..20e091acc453 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 @@ -138,22 +138,23 @@ public static boolean isPrimitive(Class cls) { } public static Class getBoxedClass(Class c) { - if (c == int.class) + if (c == int.class) { c = Integer.class; - else if (c == boolean.class) + } else if (c == boolean.class) { c = Boolean.class; - else if (c == long.class) + } else if (c == long.class) { c = Long.class; - else if (c == float.class) + } else if (c == float.class) { c = Float.class; - else if (c == double.class) + } else if (c == double.class) { c = Double.class; - else if (c == char.class) + } else if (c == char.class) { c = Character.class; - else if (c == byte.class) + } else if (c == byte.class) { c = Byte.class; - else if (c == short.class) + } else if (c == short.class) { c = Short.class; + } return c; } @@ -186,25 +187,36 @@ public static boolean isCompatible(Class c, Object o) { */ public static boolean isCompatible(Class[] cs, Object[] os) { int len = cs.length; - if (len != os.length) return false; - if (len == 0) return true; - for (int i = 0; i < len; i++) - if (!isCompatible(cs[i], os[i])) return false; + if (len != os.length) { + return false; + } + if (len == 0) { + return true; + } + for (int i = 0; i < len; i++) { + if (!isCompatible(cs[i], os[i])) { + return false; + } + } return true; } public static String getCodeBase(Class cls) { - if (cls == null) + if (cls == null) { return null; + } ProtectionDomain domain = cls.getProtectionDomain(); - if (domain == null) + if (domain == null) { return null; + } CodeSource source = domain.getCodeSource(); - if (source == null) + if (source == null) { return null; + } URL location = source.getLocation(); - if (location == null) + if (location == null) { return null; + } return location.getFile(); } @@ -266,8 +278,9 @@ public static String getName(final Method m) { ret.append(m.getName()).append('('); Class[] parameterTypes = m.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { - if (i > 0) + if (i > 0) { ret.append(','); + } ret.append(getName(parameterTypes[i])); } ret.append(')'); @@ -303,8 +316,9 @@ public static String getName(final Constructor c) { StringBuilder ret = new StringBuilder("("); Class[] parameterTypes = c.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { - if (i > 0) + if (i > 0) { ret.append(','); + } ret.append(getName(parameterTypes[i])); } ret.append(')'); @@ -330,15 +344,25 @@ public static String getDesc(Class c) { if (c.isPrimitive()) { String t = c.getName(); - if ("void".equals(t)) ret.append(JVM_VOID); - else if ("boolean".equals(t)) ret.append(JVM_BOOLEAN); - else if ("byte".equals(t)) ret.append(JVM_BYTE); - else if ("char".equals(t)) ret.append(JVM_CHAR); - else if ("double".equals(t)) ret.append(JVM_DOUBLE); - else if ("float".equals(t)) ret.append(JVM_FLOAT); - else if ("int".equals(t)) ret.append(JVM_INT); - else if ("long".equals(t)) ret.append(JVM_LONG); - else if ("short".equals(t)) ret.append(JVM_SHORT); + if ("void".equals(t)) { + ret.append(JVM_VOID); + } else if ("boolean".equals(t)) { + ret.append(JVM_BOOLEAN); + } else if ("byte".equals(t)) { + ret.append(JVM_BYTE); + } else if ("char".equals(t)) { + ret.append(JVM_CHAR); + } else if ("double".equals(t)) { + ret.append(JVM_DOUBLE); + } else if ("float".equals(t)) { + ret.append(JVM_FLOAT); + } else if ("int".equals(t)) { + ret.append(JVM_INT); + } else if ("long".equals(t)) { + ret.append(JVM_LONG); + } else if ("short".equals(t)) { + ret.append(JVM_SHORT); + } } else { ret.append('L'); ret.append(c.getName().replace('.', '/')); @@ -356,12 +380,14 @@ public static String getDesc(Class c) { * @throws NotFoundException */ public static String getDesc(final Class[] cs) { - if (cs.length == 0) + if (cs.length == 0) { return ""; + } StringBuilder sb = new StringBuilder(64); - for (Class c : cs) + for (Class c : cs) { sb.append(getDesc(c)); + } return sb.toString(); } @@ -376,8 +402,9 @@ public static String getDesc(final Class[] cs) { public static String getDesc(final Method m) { StringBuilder ret = new StringBuilder(m.getName()).append('('); Class[] parameterTypes = m.getParameterTypes(); - for (int i = 0; i < parameterTypes.length; i++) + for (int i = 0; i < parameterTypes.length; i++) { ret.append(getDesc(parameterTypes[i])); + } ret.append(')').append(getDesc(m.getReturnType())); return ret.toString(); } @@ -392,8 +419,9 @@ public static String getDesc(final Method m) { public static String getDesc(final Constructor c) { StringBuilder ret = new StringBuilder("("); Class[] parameterTypes = c.getParameterTypes(); - for (int i = 0; i < parameterTypes.length; i++) + for (int i = 0; i < parameterTypes.length; i++) { ret.append(getDesc(parameterTypes[i])); + } ret.append(')').append('V'); return ret.toString(); } @@ -409,8 +437,9 @@ public static String getDescWithoutMethodName(Method m) { StringBuilder ret = new StringBuilder(); ret.append('('); Class[] parameterTypes = m.getParameterTypes(); - for (int i = 0; i < parameterTypes.length; i++) + for (int i = 0; i < parameterTypes.length; i++) { ret.append(getDesc(parameterTypes[i])); + } ret.append(')').append(getDesc(m.getReturnType())); return ret.toString(); } @@ -431,15 +460,25 @@ public static String getDesc(final CtClass c) throws NotFoundException { ret.append(getDesc(c.getComponentType())); } else if (c.isPrimitive()) { String t = c.getName(); - if ("void".equals(t)) ret.append(JVM_VOID); - else if ("boolean".equals(t)) ret.append(JVM_BOOLEAN); - else if ("byte".equals(t)) ret.append(JVM_BYTE); - else if ("char".equals(t)) ret.append(JVM_CHAR); - else if ("double".equals(t)) ret.append(JVM_DOUBLE); - else if ("float".equals(t)) ret.append(JVM_FLOAT); - else if ("int".equals(t)) ret.append(JVM_INT); - else if ("long".equals(t)) ret.append(JVM_LONG); - else if ("short".equals(t)) ret.append(JVM_SHORT); + if ("void".equals(t)) { + ret.append(JVM_VOID); + } else if ("boolean".equals(t)) { + ret.append(JVM_BOOLEAN); + } else if ("byte".equals(t)) { + ret.append(JVM_BYTE); + } else if ("char".equals(t)) { + ret.append(JVM_CHAR); + } else if ("double".equals(t)) { + ret.append(JVM_DOUBLE); + } else if ("float".equals(t)) { + ret.append(JVM_FLOAT); + } else if ("int".equals(t)) { + ret.append(JVM_INT); + } else if ("long".equals(t)) { + ret.append(JVM_LONG); + } else if ("short".equals(t)) { + ret.append(JVM_SHORT); + } } else { ret.append('L'); ret.append(c.getName().replace('.', '/')); @@ -458,8 +497,9 @@ public static String getDesc(final CtClass c) throws NotFoundException { public static String getDesc(final CtMethod m) throws NotFoundException { StringBuilder ret = new StringBuilder(m.getName()).append('('); CtClass[] parameterTypes = m.getParameterTypes(); - for (int i = 0; i < parameterTypes.length; i++) + for (int i = 0; i < parameterTypes.length; i++) { ret.append(getDesc(parameterTypes[i])); + } ret.append(')').append(getDesc(m.getReturnType())); return ret.toString(); } @@ -474,8 +514,9 @@ public static String getDesc(final CtMethod m) throws NotFoundException { public static String getDesc(final CtConstructor c) throws NotFoundException { StringBuilder ret = new StringBuilder("("); CtClass[] parameterTypes = c.getParameterTypes(); - for (int i = 0; i < parameterTypes.length; i++) + for (int i = 0; i < parameterTypes.length; i++) { ret.append(getDesc(parameterTypes[i])); + } ret.append(')').append('V'); return ret.toString(); } @@ -491,8 +532,9 @@ public static String getDescWithoutMethodName(final CtMethod m) throws NotFoundE StringBuilder ret = new StringBuilder(); ret.append('('); CtClass[] parameterTypes = m.getParameterTypes(); - for (int i = 0; i < parameterTypes.length; i++) + for (int i = 0; i < parameterTypes.length; i++) { ret.append(getDesc(parameterTypes[i])); + } ret.append(')').append(getDesc(m.getReturnType())); return ret.toString(); } @@ -511,17 +553,30 @@ public static String name2desc(String name) { c = (name.length() - index) / 2; name = name.substring(0, index); } - while (c-- > 0) sb.append("["); - if ("void".equals(name)) sb.append(JVM_VOID); - else if ("boolean".equals(name)) sb.append(JVM_BOOLEAN); - else if ("byte".equals(name)) sb.append(JVM_BYTE); - else if ("char".equals(name)) sb.append(JVM_CHAR); - else if ("double".equals(name)) sb.append(JVM_DOUBLE); - else if ("float".equals(name)) sb.append(JVM_FLOAT); - else if ("int".equals(name)) sb.append(JVM_INT); - else if ("long".equals(name)) sb.append(JVM_LONG); - else if ("short".equals(name)) sb.append(JVM_SHORT); - else sb.append('L').append(name.replace('.', '/')).append(';'); + while (c-- > 0) { + sb.append("["); + } + if ("void".equals(name)) { + sb.append(JVM_VOID); + } else if ("boolean".equals(name)) { + sb.append(JVM_BOOLEAN); + } else if ("byte".equals(name)) { + sb.append(JVM_BYTE); + } else if ("char".equals(name)) { + sb.append(JVM_CHAR); + } else if ("double".equals(name)) { + sb.append(JVM_DOUBLE); + } else if ("float".equals(name)) { + sb.append(JVM_FLOAT); + } else if ("int".equals(name)) { + sb.append(JVM_INT); + } else if ("long".equals(name)) { + sb.append(JVM_LONG); + } else if ("short".equals(name)) { + sb.append(JVM_SHORT); + } else { + sb.append('L').append(name.replace('.', '/')).append(';'); + } return sb.toString(); } @@ -579,7 +634,9 @@ public static String desc2name(String desc) { } else { sb.append(desc.substring(c + 1, desc.length() - 1).replace('/', '.')); } - while (c-- > 0) sb.append("[]"); + while (c-- > 0) { + sb.append("[]"); + } return sb.toString(); } @@ -628,34 +685,57 @@ private static Class name2class(ClassLoader cl, String name) throws ClassNotF } if (c > 0) { StringBuilder sb = new StringBuilder(); - while (c-- > 0) + while (c-- > 0) { sb.append("["); + } - if ("void".equals(name)) sb.append(JVM_VOID); - else if ("boolean".equals(name)) sb.append(JVM_BOOLEAN); - else if ("byte".equals(name)) sb.append(JVM_BYTE); - else if ("char".equals(name)) sb.append(JVM_CHAR); - else if ("double".equals(name)) sb.append(JVM_DOUBLE); - else if ("float".equals(name)) sb.append(JVM_FLOAT); - else if ("int".equals(name)) sb.append(JVM_INT); - else if ("long".equals(name)) sb.append(JVM_LONG); - else if ("short".equals(name)) sb.append(JVM_SHORT); - else sb.append('L').append(name).append(';'); // "java.lang.Object" ==> "Ljava.lang.Object;" + if ("void".equals(name)) { + sb.append(JVM_VOID); + } else if ("boolean".equals(name)) { + sb.append(JVM_BOOLEAN); + } else if ("byte".equals(name)) { + sb.append(JVM_BYTE); + } else if ("char".equals(name)) { + sb.append(JVM_CHAR); + } else if ("double".equals(name)) { + sb.append(JVM_DOUBLE); + } else if ("float".equals(name)) { + sb.append(JVM_FLOAT); + } else if ("int".equals(name)) { + sb.append(JVM_INT); + } else if ("long".equals(name)) { + sb.append(JVM_LONG); + } else if ("short".equals(name)) { + sb.append(JVM_SHORT); + } else { + sb.append('L').append(name).append(';'); // "java.lang.Object" ==> "Ljava.lang.Object;" + } name = sb.toString(); } else { - if ("void".equals(name)) return void.class; - else if ("boolean".equals(name)) return boolean.class; - else if ("byte".equals(name)) return byte.class; - else if ("char".equals(name)) return char.class; - else if ("double".equals(name)) return double.class; - else if ("float".equals(name)) return float.class; - else if ("int".equals(name)) return int.class; - else if ("long".equals(name)) return long.class; - else if ("short".equals(name)) return short.class; - } - - if (cl == null) + if ("void".equals(name)) { + return void.class; + } else if ("boolean".equals(name)) { + return boolean.class; + } else if ("byte".equals(name)) { + return byte.class; + } else if ("char".equals(name)) { + return char.class; + } else if ("double".equals(name)) { + return double.class; + } else if ("float".equals(name)) { + return float.class; + } else if ("int".equals(name)) { + return int.class; + } else if ("long".equals(name)) { + return long.class; + } else if ("short".equals(name)) { + return short.class; + } + } + + if (cl == null) { cl = ClassHelper.getClassLoader(); + } Class clazz = NAME_CLASS_CACHE.get(name); if (clazz == null) { clazz = Class.forName(name, true, cl); @@ -717,8 +797,9 @@ private static Class desc2class(ClassLoader cl, String desc) throws ClassNotF throw new ClassNotFoundException("Class not found: " + desc); } - if (cl == null) + if (cl == null) { cl = ClassHelper.getClassLoader(); + } Class clazz = DESC_CLASS_CACHE.get(desc); if (clazz == null) { clazz = Class.forName(desc, true, cl); @@ -748,13 +829,15 @@ public static Class[] desc2classArray(String desc) throws ClassNotFoundExcept * @throws ClassNotFoundException */ private static Class[] desc2classArray(ClassLoader cl, String desc) throws ClassNotFoundException { - if (desc.length() == 0) + if (desc.length() == 0) { return EMPTY_CLASS_ARRAY; + } List> cs = new ArrayList>(); Matcher m = DESC_PATTERN.matcher(desc); - while (m.find()) + while (m.find()) { cs.add(desc2class(cl, m.group())); + } return cs.toArray(EMPTY_CLASS_ARRAY); } @@ -862,8 +945,9 @@ public static Object getEmptyObject(Class returnType) { } private static Object getEmptyObject(Class returnType, Map, Object> emptyInstances, int level) { - if (level > 2) + if (level > 2) { return null; + } if (returnType == null) { return null; } else if (returnType == boolean.class || returnType == Boolean.class) { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Stack.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Stack.java index 867f7f83b7d9..1283d831b746 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Stack.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Stack.java @@ -38,10 +38,11 @@ public Stack() { * @param ele */ public void push(E ele) { - if (mElements.size() > mSize) + if (mElements.size() > mSize) { mElements.set(mSize, ele); - else + } else { mElements.add(ele); + } mSize++; } @@ -51,8 +52,9 @@ public void push(E ele) { * @return the last element. */ public E pop() { - if (mSize == 0) + if (mSize == 0) { throw new EmptyStackException(); + } return mElements.set(--mSize, null); } @@ -62,8 +64,9 @@ public E pop() { * @return the last element. */ public E peek() { - if (mSize == 0) + if (mSize == 0) { throw new EmptyStackException(); + } return mElements.get(mSize - 1); } @@ -74,8 +77,9 @@ public E peek() { * @return element. */ public E get(int index) { - if (index >= mSize) + if (index >= mSize) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + mSize); + } return index < 0 ? mElements.get(index + mSize) : mElements.get(index); } @@ -88,8 +92,9 @@ public E get(int index) { * @return old element. */ public E set(int index, E value) { - if (index >= mSize) + if (index >= mSize) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + mSize); + } return mElements.set(index < 0 ? index + mSize : index, value); } @@ -101,8 +106,9 @@ public E set(int index, E value) { * @return element */ public E remove(int index) { - if (index >= mSize) + if (index >= mSize) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + mSize); + } E ret = mElements.remove(index < 0 ? index + mSize : index); mSize--; 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 ccc5a10ccc89..f599218f4108 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 @@ -18,10 +18,11 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.io.UnsafeStringWriter; -import com.alibaba.fastjson.JSON; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; +import com.alibaba.fastjson.JSON; + import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; @@ -173,7 +174,7 @@ public static String repeat(final String str, final String separator, final int * {@code null} if null String input */ public static String removeEnd(final String str, final String remove) { - if (isEmpty(str) || isEmpty(remove)) { + if (isAnyEmpty(str, remove)) { return str; } if (str.endsWith(remove)) { @@ -313,7 +314,7 @@ public static String replace(final String text, final String searchString, final * {@code null} if null String input */ public static String replace(final String text, final String searchString, final String replacement, int max) { - if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0) { + if (isAnyEmpty(text, searchString) || replacement == null || max == 0) { return text; } int start = 0; @@ -339,9 +340,7 @@ public static String replace(final String text, final String searchString, final } public static boolean isBlank(String str) { - if (str == null || str.length() == 0) - return true; - return false; + return isEmpty(str); } /** @@ -351,9 +350,57 @@ public static boolean isBlank(String str) { * @return is empty. */ public static boolean isEmpty(String str) { - if (str == null || str.length() == 0) - return true; - return false; + return str == null || str.isEmpty(); + } + + /** + *

Checks if the strings contain empty or null elements.

+ * + *

+     * StringUtils.isNoneEmpty(null)            = false
+     * StringUtils.isNoneEmpty("")              = false
+     * StringUtils.isNoneEmpty(" ")             = true
+     * StringUtils.isNoneEmpty("abc")           = true
+     * StringUtils.isNoneEmpty("abc", "def")    = true
+     * StringUtils.isNoneEmpty("abc", null)     = false
+     * StringUtils.isNoneEmpty("abc", "")       = false
+     * StringUtils.isNoneEmpty("abc", " ")      = true
+     * 
+ * + * @param ss the strings to check + * @return {@code true} if all strings are not empty or null + */ + public static boolean isNoneEmpty(final String... ss) { + if (ArrayUtils.isEmpty(ss)) { + return false; + } + for (final String s : ss){ + if (isEmpty(s)) { + return false; + } + } + return true; + } + + /** + *

Checks if the strings contain at least on empty or null element.

+ * + *

+     * StringUtils.isAnyEmpty(null)            = true
+     * StringUtils.isAnyEmpty("")              = true
+     * StringUtils.isAnyEmpty(" ")             = false
+     * StringUtils.isAnyEmpty("abc")           = false
+     * StringUtils.isAnyEmpty("abc", "def")    = false
+     * StringUtils.isAnyEmpty("abc", null)     = true
+     * StringUtils.isAnyEmpty("abc", "")       = true
+     * StringUtils.isAnyEmpty("abc", " ")      = false
+     * 
+ * + * @param ss the strings to check + * @return {@code true} if at least one in the strings is empty or null + */ + public static boolean isAnyEmpty(final String... ss) { + return !isNoneEmpty(ss); } /** @@ -363,7 +410,7 @@ public static boolean isEmpty(String str) { * @return is not empty. */ public static boolean isNotEmpty(String str) { - return str != null && str.length() > 0; + return !isEmpty(str); } /** @@ -372,10 +419,12 @@ public static boolean isNotEmpty(String str) { * @return equals */ public static boolean isEquals(String s1, String s2) { - if (s1 == null && s2 == null) + if (s1 == null && s2 == null) { return true; - if (s1 == null || s2 == null) + } + if (s1 == null || s2 == null) { return false; + } return s1.equals(s2); } @@ -386,15 +435,11 @@ public static boolean isEquals(String s1, String s2) { * @return is integer */ public static boolean isInteger(String str) { - if (str == null || str.length() == 0) - return false; - return INT_PATTERN.matcher(str).matches(); + return isNotEmpty(str) && INT_PATTERN.matcher(str).matches(); } public static int parseInteger(String str) { - if (!isInteger(str)) - return 0; - return Integer.parseInt(str); + return isInteger(str) ? Integer.parseInt(str) : 0; } /** @@ -402,7 +447,7 @@ public static int parseInteger(String str) { * more info. */ public static boolean isJavaIdentifier(String s) { - if (s.length() == 0 || !Character.isJavaIdentifierStart(s.charAt(0))) { + if (isEmpty(s) || !Character.isJavaIdentifierStart(s.charAt(0))) { return false; } for (int i = 1; i < s.length(); i++) { @@ -414,10 +459,7 @@ public static boolean isJavaIdentifier(String s) { } public static boolean isContains(String values, String value) { - if (values == null || values.length() == 0) { - return false; - } - return isContains(Constants.COMMA_SPLIT_PATTERN.split(values), value); + return isNotEmpty(values) && isContains(Constants.COMMA_SPLIT_PATTERN.split(values), value); } /** @@ -426,7 +468,7 @@ public static boolean isContains(String values, String value) { * @return contains */ public static boolean isContains(String[] values, String value) { - if (value != null && value.length() > 0 && values != null && values.length > 0) { + if (isNotEmpty(value) && ArrayUtils.isNotEmpty(values)) { for (String v : values) { if (value.equals(v)) { return true; @@ -442,7 +484,7 @@ public static boolean isNumeric(String str) { } int sz = str.length(); for (int i = 0; i < sz; i++) { - if (Character.isDigit(str.charAt(i)) == false) { + if (!Character.isDigit(str.charAt(i))) { return false; } } @@ -487,15 +529,17 @@ public static String toString(String msg, Throwable e) { } /** - * translat. + * translate. * * @param src source string. * @param from src char table. * @param to target char table. * @return String. */ - public static String translat(String src, String from, String to) { - if (isEmpty(src)) return src; + public static String translate(String src, String from, String to) { + if (isEmpty(src)) { + return src; + } StringBuilder sb = null; int ix; char c; @@ -503,15 +547,17 @@ public static String translat(String src, String from, String to) { c = src.charAt(i); ix = from.indexOf(c); if (ix == -1) { - if (sb != null) + if (sb != null) { sb.append(c); + } } else { if (sb == null) { sb = new StringBuilder(len); sb.append(src, 0, i); } - if (ix < to.length()) + if (ix < to.length()) { sb.append(to.charAt(ix)); + } } } return sb == null ? src : sb.toString(); @@ -530,14 +576,16 @@ public static String[] split(String str, char ch) { for (int i = 0; i < len; i++) { c = str.charAt(i); if (c == ch) { - if (list == null) + if (list == null) { list = new ArrayList(); + } list.add(str.substring(ix, i)); ix = i + 1; } } - if (ix > 0) + if (ix > 0) { list.add(str.substring(ix)); + } return list == null ? EMPTY_STRING_ARRAY : (String[]) list.toArray(EMPTY_STRING_ARRAY); } @@ -548,10 +596,13 @@ public static String[] split(String str, char ch) { * @return String. */ public static String join(String[] array) { - if (array.length == 0) return ""; + if (ArrayUtils.isEmpty(array)) { + return EMPTY; + } StringBuilder sb = new StringBuilder(); - for (String s : array) + for (String s : array) { sb.append(s); + } return sb.toString(); } @@ -563,11 +614,14 @@ public static String join(String[] array) { * @return String. */ public static String join(String[] array, char split) { - if (array.length == 0) return ""; + if (ArrayUtils.isEmpty(array)) { + return EMPTY; + } StringBuilder sb = new StringBuilder(); for (int i = 0; i < array.length; i++) { - if (i > 0) + if (i > 0) { sb.append(split); + } sb.append(array[i]); } return sb.toString(); @@ -581,24 +635,32 @@ public static String join(String[] array, char split) { * @return String. */ public static String join(String[] array, String split) { - if (array.length == 0) return ""; + if (ArrayUtils.isEmpty(array)) { + return EMPTY; + } StringBuilder sb = new StringBuilder(); for (int i = 0; i < array.length; i++) { - if (i > 0) + if (i > 0) { sb.append(split); + } sb.append(array[i]); } return sb.toString(); } public static String join(Collection coll, String split) { - if (coll.isEmpty()) return ""; + if (CollectionUtils.isEmpty(coll)) { + return EMPTY; + } StringBuilder sb = new StringBuilder(); boolean isFirst = true; for (String s : coll) { - if (isFirst) isFirst = false; - else sb.append(split); + if (isFirst) { + isFirst = false; + } else { + sb.append(split); + } sb.append(s); } return sb.toString(); @@ -616,8 +678,9 @@ private static Map parseKeyValuePair(String str, String itemSepa Map map = new HashMap(tmp.length); for (int i = 0; i < tmp.length; i++) { Matcher matcher = KVP_PATTERN.matcher(tmp[i]); - if (matcher.matches() == false) + if (!matcher.matches()) { continue; + } map.put(matcher.group(1), matcher.group(2)); } return map; @@ -635,20 +698,21 @@ public static String getQueryStringValue(String qs, String key) { * @return Parameters instance. */ public static Map parseQueryString(String qs) { - if (qs == null || qs.length() == 0) + if (isEmpty(qs)) { return new HashMap(); + } return parseKeyValuePair(qs, "\\&"); } public static String getServiceKey(Map ps) { StringBuilder buf = new StringBuilder(); String group = ps.get(Constants.GROUP_KEY); - if (group != null && group.length() > 0) { + if (isNotEmpty(group)) { buf.append(group).append("/"); } buf.append(ps.get(Constants.INTERFACE_KEY)); String version = ps.get(Constants.VERSION_KEY); - if (version != null && version.length() > 0) { + if (isNotEmpty(group)) { buf.append(":").append(version); } return buf.toString(); @@ -660,8 +724,7 @@ public static String toQueryString(Map ps) { for (Map.Entry entry : new TreeMap(ps).entrySet()) { String key = entry.getKey(); String value = entry.getValue(); - if (key != null && key.length() > 0 - && value != null && value.length() > 0) { + if (isNoneEmpty(key, value)) { if (buf.length() > 0) { buf.append("&"); } @@ -675,7 +738,7 @@ public static String toQueryString(Map ps) { } public static String camelToSplitName(String camelName, String split) { - if (camelName == null || camelName.length() == 0) { + if (isEmpty(camelName)) { return camelName; } StringBuilder buf = null; 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 a7b33013e421..f9e6f4ec3c75 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 @@ -361,8 +361,9 @@ public static boolean isMatchCategory(String category, String categories) { public static boolean isMatch(URL consumerUrl, URL providerUrl) { String consumerInterface = consumerUrl.getServiceInterface(); String providerInterface = providerUrl.getServiceInterface(); - if (!(Constants.ANY_VALUE.equals(consumerInterface) || StringUtils.isEquals(consumerInterface, providerInterface))) + if (!(Constants.ANY_VALUE.equals(consumerInterface) || StringUtils.isEquals(consumerInterface, providerInterface))) { return false; + } if (!isMatchCategory(providerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY), consumerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY))) { @@ -393,14 +394,17 @@ public static boolean isMatchGlobPattern(String pattern, String value, URL param } public static boolean isMatchGlobPattern(String pattern, String value) { - if ("*".equals(pattern)) + if ("*".equals(pattern)) { return true; + } if ((pattern == null || pattern.length() == 0) - && (value == null || value.length() == 0)) + && (value == null || value.length() == 0)) { return true; + } if ((pattern == null || pattern.length() == 0) - || (value == null || value.length() == 0)) + || (value == null || value.length() == 0)) { return false; + } int i = pattern.lastIndexOf('*'); // doesn't find "*" 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 b14170750117..185296fa16f9 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 @@ -47,7 +47,8 @@ import org.apache.dubbo.common.extension.ext8_add.impl.AddExt4_ManualAdaptive; import org.apache.dubbo.common.extension.ext9_empty.Ext9Empty; import org.apache.dubbo.common.extension.ext9_empty.impl.Ext9EmptyImpl; - +import org.apache.dubbo.common.extension.injection.InjectExt; +import org.apache.dubbo.common.extension.injection.impl.InjectExtImpl; import org.junit.Assert; import org.junit.Test; @@ -425,4 +426,14 @@ public void testLoadDefaultActivateExtension() throws Exception { Assert.assertTrue(list.get(1).getClass() == OrderActivateExtImpl1.class); } + @Test + public void testInjectExtension() { + // test default + InjectExt injectExt = ExtensionLoader.getExtensionLoader(InjectExt.class).getExtension("injection"); + InjectExtImpl injectExtImpl = (InjectExtImpl) injectExt; + Assert.assertNotNull(injectExtImpl.getSimpleExt()); + Assert.assertNull(injectExtImpl.getSimpleExt1()); + Assert.assertNull(injectExtImpl.getGenericType()); + } + } \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-fst/src/test/java/org/apache/dubbo/common/serialize/fst/model/AnimalEnum.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/injection/InjectExt.java similarity index 80% rename from dubbo-serialization/dubbo-serialization-fst/src/test/java/org/apache/dubbo/common/serialize/fst/model/AnimalEnum.java rename to dubbo-common/src/test/java/org/apache/dubbo/common/extension/injection/InjectExt.java index 0f1b98bfc357..f2ffe41c69d4 100644 --- a/dubbo-serialization/dubbo-serialization-fst/src/test/java/org/apache/dubbo/common/serialize/fst/model/AnimalEnum.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/injection/InjectExt.java @@ -14,8 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.common.serialize.fst.model; +package org.apache.dubbo.common.extension.injection; -public enum AnimalEnum { - dog, cat, rat, cow, bull, horse; -} \ No newline at end of file +import org.apache.dubbo.common.extension.SPI; + +/** + * + */ +@SPI("injection") +public interface InjectExt { + String echo(String msg); +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/injection/impl/InjectExtImpl.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/injection/impl/InjectExtImpl.java new file mode 100644 index 000000000000..ccff9547f536 --- /dev/null +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/injection/impl/InjectExtImpl.java @@ -0,0 +1,60 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.extension.injection.impl; + +import org.apache.dubbo.common.extension.DisableInject; +import org.apache.dubbo.common.extension.ext1.SimpleExt; +import org.apache.dubbo.common.extension.injection.InjectExt; + +public class InjectExtImpl implements InjectExt { + + private SimpleExt simpleExt; + + private SimpleExt simpleExt1; + + private Object genericType; + + public void setSimpleExt(SimpleExt simpleExt) { + this.simpleExt = simpleExt; + } + + @DisableInject + public void setSimpleExt1(SimpleExt simpleExt1) { + this.simpleExt1 = simpleExt1; + } + + public void setGenericType(Object genericType) { + this.genericType = genericType; + } + + @Override + public String echo(String msg) { + return null; + } + + public SimpleExt getSimpleExt() { + return simpleExt; + } + + public SimpleExt getSimpleExt1() { + return simpleExt1; + } + + public Object getGenericType() { + return genericType; + } +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/model/AnimalEnum.java b/dubbo-common/src/test/java/org/apache/dubbo/common/model/AnimalEnum.java deleted file mode 100644 index ddfc736e0834..000000000000 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/model/AnimalEnum.java +++ /dev/null @@ -1,21 +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.model; - -public enum AnimalEnum { - dog, cat, rat, cow, bull, horse; -} \ No newline at end of file diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/model/media/MediaContent.java b/dubbo-common/src/test/java/org/apache/dubbo/common/model/media/MediaContent.java deleted file mode 100644 index 7991f5061012..000000000000 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/model/media/MediaContent.java +++ /dev/null @@ -1,78 +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.model.media; - -import java.util.List; - -@SuppressWarnings("serial") -public class MediaContent implements java.io.Serializable { - public Media media; - public List images; - - public MediaContent() { - } - - public MediaContent(Media media, List images) { - this.media = media; - this.images = images; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - MediaContent that = (MediaContent) o; - - if (images != null ? !images.equals(that.images) : that.images != null) return false; - if (media != null ? !media.equals(that.media) : that.media != null) return false; - - return true; - } - - @Override - public int hashCode() { - int result = media != null ? media.hashCode() : 0; - result = 31 * result + (images != null ? images.hashCode() : 0); - return result; - } - - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("[MediaContent: "); - sb.append("media=").append(media); - sb.append(", images=").append(images); - sb.append("]"); - return sb.toString(); - } - - public Media getMedia() { - return media; - } - - public void setMedia(Media media) { - this.media = media; - } - - public List getImages() { - return images; - } - - public void setImages(List images) { - this.images = images; - } -} \ No newline at end of file diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/model/BizException.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ArrayUtilsTest.java similarity index 55% rename from dubbo-common/src/test/java/org/apache/dubbo/common/model/BizException.java rename to dubbo-common/src/test/java/org/apache/dubbo/common/utils/ArrayUtilsTest.java index 51fd04b7b889..76fb7884bd1e 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/model/BizException.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ArrayUtilsTest.java @@ -1,29 +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.model; - -public class BizException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - public BizException(String message) { - super(message); - } - - public BizException() { - } +/* + * 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 static junit.framework.TestCase.assertFalse; +import static junit.framework.TestCase.assertTrue; + +import org.junit.Test; + +public class ArrayUtilsTest { + + @Test + public void isEmpty() throws Exception { + assertTrue(ArrayUtils.isEmpty(null)); + assertTrue(ArrayUtils.isEmpty(new Object[0])); + assertFalse(ArrayUtils.isEmpty(new Object[]{"abc"})); + } + + @Test + public void isNotEmpty() throws Exception { + assertFalse(ArrayUtils.isNotEmpty(null)); + assertFalse(ArrayUtils.isNotEmpty(new Object[0])); + assertTrue(ArrayUtils.isNotEmpty(new Object[]{"abc"})); + } + } \ No newline at end of file diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/StringUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/StringUtilsTest.java index fa95bfb834c4..111544155b96 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 @@ -111,6 +111,30 @@ public void testIsEmpty() throws Exception { assertFalse(StringUtils.isEmpty("abc")); } + @Test + public void testIsNoneEmpty() throws Exception { + assertFalse(StringUtils.isNoneEmpty(null)); + assertFalse(StringUtils.isNoneEmpty("")); + assertTrue(StringUtils.isNoneEmpty(" ")); + assertTrue(StringUtils.isNoneEmpty("abc")); + assertTrue(StringUtils.isNoneEmpty("abc", "def")); + assertFalse(StringUtils.isNoneEmpty("abc", null)); + assertFalse(StringUtils.isNoneEmpty("abc", "")); + assertTrue(StringUtils.isNoneEmpty("abc", " ")); + } + + @Test + public void testIsAnyEmpty() throws Exception { + assertTrue(StringUtils.isAnyEmpty(null)); + assertTrue(StringUtils.isAnyEmpty("")); + assertFalse(StringUtils.isAnyEmpty(" ")); + assertFalse(StringUtils.isAnyEmpty("abc")); + assertFalse(StringUtils.isAnyEmpty("abc", "def")); + assertTrue(StringUtils.isAnyEmpty("abc", null)); + assertTrue(StringUtils.isAnyEmpty("abc", "")); + assertFalse(StringUtils.isAnyEmpty("abc", " ")); + } + @Test public void testIsNotEmpty() throws Exception { assertFalse(StringUtils.isNotEmpty(null)); @@ -200,10 +224,10 @@ public void testSplit() throws Exception { } @Test - public void testTranslat() throws Exception { + public void testTranslate() throws Exception { String s = "16314"; - assertEquals(StringUtils.translat(s, "123456", "abcdef"), "afcad"); - assertEquals(StringUtils.translat(s, "123456", "abcd"), "acad"); + assertEquals(StringUtils.translate(s, "123456", "abcdef"), "afcad"); + assertEquals(StringUtils.translate(s, "123456", "abcd"), "acad"); } @Test diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/version/VersionTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/version/VersionTest.java index d03e69855ea3..a129f53e58c9 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/version/VersionTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/version/VersionTest.java @@ -30,9 +30,9 @@ public void testGetProtocolVersion() { } @Test - public void testSupportResponseAttatchment() { - Assert.assertTrue(Version.isSupportResponseAttatchment("2.0.2")); - Assert.assertTrue(Version.isSupportResponseAttatchment("2.0.3")); - Assert.assertFalse(Version.isSupportResponseAttatchment("2.0.0")); + public void testSupportResponseAttachment() { + Assert.assertTrue(Version.isSupportResponseAttachment("2.0.2")); + Assert.assertTrue(Version.isSupportResponseAttachment("2.0.3")); + Assert.assertFalse(Version.isSupportResponseAttachment("2.0.0")); } } diff --git a/dubbo-common/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.extension.injection.InjectExt b/dubbo-common/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.extension.injection.InjectExt new file mode 100644 index 000000000000..b3d82a05b113 --- /dev/null +++ b/dubbo-common/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.extension.injection.InjectExt @@ -0,0 +1 @@ +injection=org.apache.dubbo.common.extension.injection.impl.InjectExtImpl \ No newline at end of file diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/URL.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/URL.java index 2f479ce897d7..76b09f43db9b 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/URL.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/URL.java @@ -79,71 +79,88 @@ public static String decode(String value) { return org.apache.dubbo.common.URL.decode(value); } + @Override public String getProtocol() { return super.getProtocol(); } + @Override public URL setProtocol(String protocol) { return new URL(protocol, super.getUsername(), super.getPassword(), super.getHost(), super.getPort(), super.getPath(), super.getParameters()); } + @Override public String getUsername() { return super.getUsername(); } + @Override public URL setUsername(String username) { return new URL(super.getProtocol(), username, super.getPassword(), super.getHost(), super.getPort(), super.getPath(), super.getParameters()); } + @Override public String getPassword() { return super.getPassword(); } + @Override public URL setPassword(String password) { return new URL(super.getProtocol(), super.getUsername(), password, super.getHost(), super.getPort(), super.getPath(), super.getParameters()); } + @Override public String getAuthority() { return super.getAuthority(); } + @Override public String getHost() { return super.getHost(); } + @Override public URL setHost(String host) { return new URL(super.getProtocol(), super.getUsername(), super.getPassword(), host, super.getPort(), super.getPath(), super.getParameters()); } + @Override public String getIp() { return super.getIp(); } + @Override public int getPort() { return super.getPort(); } + @Override public URL setPort(int port) { return new URL(super.getProtocol(), super.getUsername(), super.getPassword(), super.getHost(), port, super.getPath(), super.getParameters()); } + @Override public int getPort(int defaultPort) { return super.getPort(); } + @Override public String getAddress() { return super.getAddress(); } + @Override public URL setAddress(String address) { org.apache.dubbo.common.URL result = super.setAddress(address); return new URL(result); } + @Override public String getBackupAddress() { return super.getBackupAddress(); } + @Override public String getBackupAddress(int defaultPort) { return super.getBackupAddress(defaultPort); } @@ -153,191 +170,238 @@ public String getBackupAddress(int defaultPort) { // return res.stream().map(url -> new URL(url)).collect(Collectors.toList()); // } + @Override public String getPath() { return super.getPath(); } + @Override public URL setPath(String path) { return new URL(super.getProtocol(), super.getUsername(), super.getPassword(), super.getHost(), super.getPort(), path, super.getParameters()); } + @Override public String getAbsolutePath() { return super.getAbsolutePath(); } + @Override public Map getParameters() { return super.getParameters(); } + @Override public String getParameterAndDecoded(String key) { return super.getParameterAndDecoded(key); } + @Override public String getParameterAndDecoded(String key, String defaultValue) { - return super.decode(getParameter(key, defaultValue)); + return org.apache.dubbo.common.URL.decode(getParameter(key, defaultValue)); } + @Override public String getParameter(String key) { return super.getParameter(key); } + @Override public String getParameter(String key, String defaultValue) { return super.getParameter(key, defaultValue); } + @Override public String[] getParameter(String key, String[] defaultValue) { return super.getParameter(key, defaultValue); } + @Override public URL getUrlParameter(String key) { org.apache.dubbo.common.URL result = super.getUrlParameter(key); return new URL(result); } + @Override public double getParameter(String key, double defaultValue) { return super.getParameter(key, defaultValue); } + @Override public float getParameter(String key, float defaultValue) { return super.getParameter(key, defaultValue); } + @Override public long getParameter(String key, long defaultValue) { return super.getParameter(key, defaultValue); } + @Override public int getParameter(String key, int defaultValue) { return super.getParameter(key, defaultValue); } + @Override public short getParameter(String key, short defaultValue) { return super.getParameter(key, defaultValue); } + @Override public byte getParameter(String key, byte defaultValue) { return super.getParameter(key, defaultValue); } + @Override public float getPositiveParameter(String key, float defaultValue) { return super.getPositiveParameter(key, defaultValue); } + @Override public double getPositiveParameter(String key, double defaultValue) { return super.getPositiveParameter(key, defaultValue); } + @Override public long getPositiveParameter(String key, long defaultValue) { return super.getPositiveParameter(key, defaultValue); } + @Override public int getPositiveParameter(String key, int defaultValue) { return super.getPositiveParameter(key, defaultValue); } + @Override public short getPositiveParameter(String key, short defaultValue) { return super.getPositiveParameter(key, defaultValue); } + @Override public byte getPositiveParameter(String key, byte defaultValue) { return super.getPositiveParameter(key, defaultValue); } + @Override public char getParameter(String key, char defaultValue) { return super.getParameter(key, defaultValue); } + @Override public boolean getParameter(String key, boolean defaultValue) { return super.getParameter(key, defaultValue); } + @Override public boolean hasParameter(String key) { return super.hasParameter(key); } + @Override public String getMethodParameterAndDecoded(String method, String key) { return super.getMethodParameterAndDecoded(method, key); } + @Override public String getMethodParameterAndDecoded(String method, String key, String defaultValue) { return super.getMethodParameterAndDecoded(method, key, defaultValue); } + @Override public String getMethodParameter(String method, String key) { return super.getMethodParameter(method, key); } + @Override public String getMethodParameter(String method, String key, String defaultValue) { return super.getMethodParameter(method, key, defaultValue); } + @Override public double getMethodParameter(String method, String key, double defaultValue) { return super.getMethodParameter(method, key, defaultValue); } + @Override public float getMethodParameter(String method, String key, float defaultValue) { return super.getMethodParameter(method, key, defaultValue); } + @Override public long getMethodParameter(String method, String key, long defaultValue) { return super.getMethodParameter(method, key, defaultValue); } + @Override public int getMethodParameter(String method, String key, int defaultValue) { return super.getMethodParameter(method, key, defaultValue); } + @Override public short getMethodParameter(String method, String key, short defaultValue) { return super.getMethodParameter(method, key, defaultValue); } + @Override public byte getMethodParameter(String method, String key, byte defaultValue) { return super.getMethodParameter(method, key, defaultValue); } + @Override public double getMethodPositiveParameter(String method, String key, double defaultValue) { return super.getMethodPositiveParameter(method, key, defaultValue); } + @Override public float getMethodPositiveParameter(String method, String key, float defaultValue) { return super.getMethodPositiveParameter(method, key, defaultValue); } + @Override public long getMethodPositiveParameter(String method, String key, long defaultValue) { return super.getMethodPositiveParameter(method, key, defaultValue); } + @Override public int getMethodPositiveParameter(String method, String key, int defaultValue) { return super.getMethodPositiveParameter(method, key, defaultValue); } + @Override public short getMethodPositiveParameter(String method, String key, short defaultValue) { return super.getMethodPositiveParameter(method, key, defaultValue); } + @Override public byte getMethodPositiveParameter(String method, String key, byte defaultValue) { return super.getMethodPositiveParameter(method, key, defaultValue); } + @Override public char getMethodParameter(String method, String key, char defaultValue) { return super.getMethodParameter(method, key, defaultValue); } + @Override public boolean getMethodParameter(String method, String key, boolean defaultValue) { return super.getMethodParameter(method, key, defaultValue); } + @Override public boolean hasMethodParameter(String method, String key) { return super.hasMethodParameter(method, key); } + @Override public boolean isLocalHost() { return super.isLocalHost(); } + @Override public boolean isAnyHost() { return super.isAnyHost(); } + @Override public URL addParameterAndEncoded(String key, String value) { if (value == null || value.length() == 0) { return this; @@ -345,107 +409,136 @@ public URL addParameterAndEncoded(String key, String value) { return addParameter(key, encode(value)); } + @Override public URL addParameter(String key, boolean value) { return addParameter(key, String.valueOf(value)); } + @Override public URL addParameter(String key, char value) { return addParameter(key, String.valueOf(value)); } + @Override public URL addParameter(String key, byte value) { return addParameter(key, String.valueOf(value)); } + @Override public URL addParameter(String key, short value) { return addParameter(key, String.valueOf(value)); } + @Override public URL addParameter(String key, int value) { return addParameter(key, String.valueOf(value)); } + @Override public URL addParameter(String key, long value) { return addParameter(key, String.valueOf(value)); } + @Override public URL addParameter(String key, float value) { return addParameter(key, String.valueOf(value)); } + @Override public URL addParameter(String key, double value) { return addParameter(key, String.valueOf(value)); } + @Override public URL addParameter(String key, Enum value) { - if (value == null) return this; + if (value == null) { + return this; + } return addParameter(key, String.valueOf(value)); } + @Override public URL addParameter(String key, Number value) { - if (value == null) return this; + if (value == null) { + return this; + } return addParameter(key, String.valueOf(value)); } + @Override public URL addParameter(String key, CharSequence value) { - if (value == null || value.length() == 0) return this; + if (value == null || value.length() == 0) { + return this; + } return addParameter(key, String.valueOf(value)); } + @Override public URL addParameter(String key, String value) { org.apache.dubbo.common.URL result = super.addParameter(key, value); return new URL(result); } + @Override public URL addParameterIfAbsent(String key, String value) { org.apache.dubbo.common.URL result = super.addParameterIfAbsent(key, value); return new URL(result); } + @Override public URL addParameters(Map parameters) { org.apache.dubbo.common.URL result = super.addParameters(parameters); return new URL(result); } + @Override public URL addParametersIfAbsent(Map parameters) { org.apache.dubbo.common.URL result = super.addParametersIfAbsent(parameters); return new URL(result); } + @Override public URL addParameters(String... pairs) { org.apache.dubbo.common.URL result = super.addParameters(pairs); return new URL(result); } + @Override public URL addParameterString(String query) { org.apache.dubbo.common.URL result = super.addParameterString(query); return new URL(result); } + @Override public URL removeParameter(String key) { org.apache.dubbo.common.URL result = super.removeParameter(key); return new URL(result); } + @Override public URL removeParameters(Collection keys) { org.apache.dubbo.common.URL result = super.removeParameters(keys); return new URL(result); } + @Override public URL removeParameters(String... keys) { org.apache.dubbo.common.URL result = super.removeParameters(keys); return new URL(result); } + @Override public URL clearParameters() { org.apache.dubbo.common.URL result = super.clearParameters(); return new URL(result); } + @Override public String getRawParameter(String key) { return super.getRawParameter(key); } + @Override public Map toMap() { return super.toMap(); } @@ -455,58 +548,72 @@ public String toString() { return super.toString(); } + @Override public String toString(String... parameters) { return super.toString(parameters); } + @Override public String toIdentityString() { return super.toIdentityString(); } + @Override public String toIdentityString(String... parameters) { return super.toIdentityString(parameters); } + @Override public String toFullString() { return super.toFullString(); } + @Override public String toFullString(String... parameters) { return super.toFullString(parameters); } + @Override public String toParameterString() { return super.toParameterString(); } + @Override public String toParameterString(String... parameters) { return super.toParameterString(parameters); } + @Override public java.net.URL toJavaURL() { return super.toJavaURL(); } + @Override public InetSocketAddress toInetSocketAddress() { return super.toInetSocketAddress(); } + @Override public String getServiceKey() { return super.getServiceKey(); } + @Override public String toServiceStringWithoutResolving() { return super.toServiceStringWithoutResolving(); } + @Override public String toServiceString() { return super.toServiceString(); } + @Override public String getServiceInterface() { return super.getServiceInterface(); } + @Override public URL setServiceInterface(String service) { org.apache.dubbo.common.URL result = super.setServiceInterface(service); return new URL(result); diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/status/StatusChecker.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/status/StatusChecker.java index a1405475459b..3f74c133ffac 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/status/StatusChecker.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/status/StatusChecker.java @@ -20,5 +20,6 @@ @Deprecated public interface StatusChecker extends org.apache.dubbo.common.status.StatusChecker { + @Override Status check(); } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/spring/context/annotation/EnableDubbo.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/spring/context/annotation/EnableDubbo.java index 0c25432403aa..1310d1a2032c 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/spring/context/annotation/EnableDubbo.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/spring/context/annotation/EnableDubbo.java @@ -20,6 +20,7 @@ import org.apache.dubbo.config.AbstractConfig; import org.apache.dubbo.config.spring.context.annotation.CompatibleDubboComponentScan; import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfig; + import org.springframework.core.annotation.AliasFor; import java.lang.annotation.Documented; diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/monitor/Monitor.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/monitor/Monitor.java index 7444d865738b..3d4abb3cd652 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/monitor/Monitor.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/monitor/Monitor.java @@ -25,6 +25,7 @@ @Deprecated public interface Monitor extends org.apache.dubbo.monitor.Monitor { + @Override com.alibaba.dubbo.common.URL getUrl(); void collect(com.alibaba.dubbo.common.URL statistics); diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/Registry.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/Registry.java index c5a84231a44d..cc9ceb14ee16 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/Registry.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/Registry.java @@ -26,6 +26,7 @@ @Deprecated public interface Registry extends org.apache.dubbo.registry.Registry { + @Override com.alibaba.dubbo.common.URL getUrl(); void register(com.alibaba.dubbo.common.URL url); diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Channel.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Channel.java index c1606e7facc9..a900047fb98a 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Channel.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Channel.java @@ -20,7 +20,9 @@ @Deprecated public interface Channel extends org.apache.dubbo.remoting.Channel { + @Override com.alibaba.dubbo.common.URL getUrl(); + @Override com.alibaba.dubbo.remoting.ChannelHandler getChannelHandler(); } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Exporter.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Exporter.java index 84ef9fe06fc5..c1fadeb9d833 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Exporter.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Exporter.java @@ -20,6 +20,7 @@ @Deprecated public interface Exporter extends org.apache.dubbo.rpc.Exporter { + @Override Invoker getInvoker(); class CompatibleExporter implements Exporter { diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Filter.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Filter.java index 8da72027632a..4ccde294e3a2 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Filter.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Filter.java @@ -22,6 +22,7 @@ public interface Filter extends org.apache.dubbo.rpc.Filter { Result invoke(Invoker invoker, Invocation invocation) throws RpcException; + @Override default org.apache.dubbo.rpc.Result invoke(org.apache.dubbo.rpc.Invoker invoker, org.apache.dubbo.rpc.Invocation invocation) throws org.apache.dubbo.rpc.RpcException { 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 2306e3ecb504..b96d14d1ee4a 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 @@ -22,6 +22,7 @@ @Deprecated public interface Invocation extends org.apache.dubbo.rpc.Invocation { + @Override Invoker getInvoker(); default org.apache.dubbo.rpc.Invocation getOriginal() { @@ -71,6 +72,7 @@ public Invoker getInvoker() { return new Invoker.CompatibleInvoker(delegate.getInvoker()); } + @Override public org.apache.dubbo.rpc.Invocation getOriginal() { return delegate; } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invoker.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invoker.java index 3e796765406f..55a948083f03 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invoker.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invoker.java @@ -22,6 +22,7 @@ @Deprecated public interface Invoker extends org.apache.dubbo.rpc.Invoker { + @Override Result invoke(org.apache.dubbo.rpc.Invocation invocation) throws RpcException; default org.apache.dubbo.rpc.Invoker getOriginal() { @@ -61,6 +62,7 @@ public void destroy() { invoker.destroy(); } + @Override public org.apache.dubbo.rpc.Invoker getOriginal() { return invoker; } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Directory.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Directory.java index d883f84abccd..6e87c613513e 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Directory.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Directory.java @@ -17,18 +17,19 @@ package com.alibaba.dubbo.rpc.cluster; -import com.alibaba.dubbo.common.URL; - import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; +import com.alibaba.dubbo.common.URL; + import java.util.List; import java.util.stream.Collectors; @Deprecated public interface Directory extends org.apache.dubbo.rpc.cluster.Directory { + @Override URL getUrl(); List> list(com.alibaba.dubbo.rpc.Invocation invocation) throws com.alibaba.dubbo.rpc.RpcException; diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Router.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Router.java index f3d5ddca5954..8a2750386811 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Router.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Router.java @@ -28,6 +28,7 @@ @Deprecated public interface Router extends org.apache.dubbo.rpc.cluster.Router { + @Override com.alibaba.dubbo.common.URL getUrl(); List> route(List> invokers, diff --git a/dubbo-compatible/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/CompatibleReferenceAnnotationBeanPostProcessor.java b/dubbo-compatible/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/CompatibleReferenceAnnotationBeanPostProcessor.java index 009bd28f8050..544b1cb0bdc5 100644 --- a/dubbo-compatible/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/CompatibleReferenceAnnotationBeanPostProcessor.java +++ b/dubbo-compatible/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/CompatibleReferenceAnnotationBeanPostProcessor.java @@ -16,9 +16,9 @@ */ package org.apache.dubbo.config.spring.beans.factory.annotation; -import com.alibaba.dubbo.config.annotation.Reference; - import org.apache.dubbo.config.spring.ReferenceBean; + +import com.alibaba.dubbo.config.annotation.Reference; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeanUtils; diff --git a/dubbo-compatible/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/CompatibleReferenceBeanBuilder.java b/dubbo-compatible/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/CompatibleReferenceBeanBuilder.java index 924ffcbee3a5..cb2ba68a51a2 100644 --- a/dubbo-compatible/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/CompatibleReferenceBeanBuilder.java +++ b/dubbo-compatible/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/CompatibleReferenceBeanBuilder.java @@ -16,12 +16,12 @@ */ package org.apache.dubbo.config.spring.beans.factory.annotation; -import com.alibaba.dubbo.config.annotation.Reference; - import org.apache.dubbo.config.ConsumerConfig; import org.apache.dubbo.config.spring.ReferenceBean; import org.apache.dubbo.config.spring.convert.converter.StringArrayToMapConverter; import org.apache.dubbo.config.spring.convert.converter.StringArrayToStringConverter; + +import com.alibaba.dubbo.config.annotation.Reference; import org.springframework.context.ApplicationContext; import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.support.DefaultConversionService; 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 b2ab6151be59..5f4d99035213 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 @@ -16,12 +16,12 @@ */ package org.apache.dubbo.config.spring.beans.factory.annotation; -import com.alibaba.dubbo.config.annotation.Service; - import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; 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; diff --git a/dubbo-compatible/src/main/java/org/apache/dubbo/config/spring/context/annotation/CompatibleDubboComponentScanRegistrar.java b/dubbo-compatible/src/main/java/org/apache/dubbo/config/spring/context/annotation/CompatibleDubboComponentScanRegistrar.java index df41b6e131bd..089bdda8cdfd 100644 --- a/dubbo-compatible/src/main/java/org/apache/dubbo/config/spring/context/annotation/CompatibleDubboComponentScanRegistrar.java +++ b/dubbo-compatible/src/main/java/org/apache/dubbo/config/spring/context/annotation/CompatibleDubboComponentScanRegistrar.java @@ -19,6 +19,7 @@ import org.apache.dubbo.config.spring.beans.factory.annotation.CompatibleReferenceAnnotationBeanPostProcessor; import org.apache.dubbo.config.spring.beans.factory.annotation.CompatibleServiceAnnotationBeanPostProcessor; import org.apache.dubbo.config.spring.util.BeanRegistrar; + import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.AbstractBeanDefinition; diff --git a/dubbo-compatible/src/main/java/org/apache/dubbo/config/spring/schema/CompatibleAnnotationBeanDefinitionParser.java b/dubbo-compatible/src/main/java/org/apache/dubbo/config/spring/schema/CompatibleAnnotationBeanDefinitionParser.java index c5e7bfaca8c1..66d6ac2dcc34 100644 --- a/dubbo-compatible/src/main/java/org/apache/dubbo/config/spring/schema/CompatibleAnnotationBeanDefinitionParser.java +++ b/dubbo-compatible/src/main/java/org/apache/dubbo/config/spring/schema/CompatibleAnnotationBeanDefinitionParser.java @@ -17,11 +17,10 @@ package org.apache.dubbo.config.spring.schema; import org.apache.dubbo.config.spring.AnnotationBean; - import org.apache.dubbo.config.spring.beans.factory.annotation.CompatibleReferenceAnnotationBeanPostProcessor; import org.apache.dubbo.config.spring.beans.factory.annotation.CompatibleServiceAnnotationBeanPostProcessor; - import org.apache.dubbo.config.spring.util.BeanRegistrar; + import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; 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 a7c5e99a03c2..e7e0601e2b3a 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,6 +20,9 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.config.MethodConfig; import com.alibaba.dubbo.config.ArgumentConfig; + +import org.apache.dubbo.rpc.model.ConsumerMethodModel; +import org.apache.dubbo.service.Person; import org.hamcrest.Matchers; import org.junit.Test; @@ -34,6 +37,7 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; public class MethodConfigTest { @Test @@ -97,12 +101,23 @@ public void testSticky() throws Exception { assertThat(method.getSticky(), is(true)); } + @Test + public void testConverMethodConfig2AsyncInfo() throws Exception{ + org.apache.dubbo.config.MethodConfig methodConfig = new org.apache.dubbo.config.MethodConfig(); + methodConfig.setOninvokeMethod("setName"); + methodConfig.setOninvoke(new Person()); + + ConsumerMethodModel.AsyncMethodInfo methodInfo = org.apache.dubbo.config.MethodConfig.convertMethodConfig2AyncInfo(methodConfig); + + assertTrue(methodInfo.getOninvokeMethod().equals( Person.class.getMethod("setName", String.class))); + } + @Test public void testOnreturn() throws Exception { MethodConfig method = new MethodConfig(); method.setOnreturn("on-return-object"); assertThat(method.getOnreturn(), equalTo((Object) "on-return-object")); - Map attribute = new HashMap(); + Map attribute = new HashMap(); MethodConfig.appendAttributes(attribute, method); assertThat(attribute, hasEntry((Object) Constants.ON_RETURN_INSTANCE_KEY, (Object) "on-return-object")); Map parameters = new HashMap(); @@ -115,7 +130,7 @@ public void testOnreturnMethod() throws Exception { MethodConfig method = new MethodConfig(); method.setOnreturnMethod("on-return-method"); assertThat(method.getOnreturnMethod(), equalTo("on-return-method")); - Map attribute = new HashMap(); + Map attribute = new HashMap(); MethodConfig.appendAttributes(attribute, method); assertThat(attribute, hasEntry((Object) Constants.ON_RETURN_METHOD_KEY, (Object) "on-return-method")); Map parameters = new HashMap(); @@ -128,7 +143,7 @@ public void testOnthrow() throws Exception { MethodConfig method = new MethodConfig(); method.setOnthrow("on-throw-object"); assertThat(method.getOnthrow(), equalTo((Object) "on-throw-object")); - Map attribute = new HashMap(); + Map attribute = new HashMap(); MethodConfig.appendAttributes(attribute, method); assertThat(attribute, hasEntry((Object) Constants.ON_THROW_INSTANCE_KEY, (Object) "on-throw-object")); Map parameters = new HashMap(); @@ -141,7 +156,7 @@ public void testOnthrowMethod() throws Exception { MethodConfig method = new MethodConfig(); method.setOnthrowMethod("on-throw-method"); assertThat(method.getOnthrowMethod(), equalTo("on-throw-method")); - Map attribute = new HashMap(); + Map attribute = new HashMap(); MethodConfig.appendAttributes(attribute, method); assertThat(attribute, hasEntry((Object) Constants.ON_THROW_METHOD_KEY, (Object) "on-throw-method")); Map parameters = new HashMap(); @@ -154,7 +169,7 @@ public void testOninvoke() throws Exception { MethodConfig method = new MethodConfig(); method.setOninvoke("on-invoke-object"); assertThat(method.getOninvoke(), equalTo((Object) "on-invoke-object")); - Map attribute = new HashMap(); + Map attribute = new HashMap(); MethodConfig.appendAttributes(attribute, method); assertThat(attribute, hasEntry((Object) Constants.ON_INVOKE_INSTANCE_KEY, (Object) "on-invoke-object")); Map parameters = new HashMap(); @@ -167,7 +182,7 @@ public void testOninvokeMethod() throws Exception { MethodConfig method = new MethodConfig(); method.setOninvokeMethod("on-invoke-method"); assertThat(method.getOninvokeMethod(), equalTo("on-invoke-method")); - Map attribute = new HashMap(); + Map attribute = new HashMap(); MethodConfig.appendAttributes(attribute, method); assertThat(attribute, hasEntry((Object) Constants.ON_INVOKE_METHOD_KEY, (Object) "on-invoke-method")); Map parameters = new HashMap(); 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 a4b037b62a80..fada00eb90f9 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 @@ -1,486 +1,535 @@ -/* - * 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; - -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; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.CollectionUtils; -import org.apache.dubbo.common.utils.ConfigUtils; -import org.apache.dubbo.common.utils.ReflectUtils; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.config.support.Parameter; - -import java.io.Serializable; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.HashMap; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Utility methods and public methods for parsing configuration - * - * @export - */ -public abstract class AbstractConfig implements Serializable { - - protected static final Logger logger = LoggerFactory.getLogger(AbstractConfig.class); - private static final long serialVersionUID = 4267533505537413570L; - private static final int MAX_LENGTH = 200; - - private static final int MAX_PATH_LENGTH = 200; - - private static final Pattern PATTERN_NAME = Pattern.compile("[\\-._0-9a-zA-Z]+"); - - private static final Pattern PATTERN_MULTI_NAME = Pattern.compile("[,\\-._0-9a-zA-Z]+"); - - private static final Pattern PATTERN_METHOD_NAME = Pattern.compile("[a-zA-Z][0-9a-zA-Z]*"); - - private static final Pattern PATTERN_PATH = Pattern.compile("[/\\-$._0-9a-zA-Z]+"); - - private static final Pattern PATTERN_NAME_HAS_SYMBOL = Pattern.compile("[:*,/\\-._0-9a-zA-Z]+"); - - private static final Pattern PATTERN_KEY = Pattern.compile("[*,\\-._0-9a-zA-Z]+"); - private static final Map legacyProperties = new HashMap(); - 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"); - - // this is only for compatibility - Runtime.getRuntime().addShutdownHook(DubboShutdownHook.getDubboShutdownHook()); - } - - protected String id; - - private static String convertLegacyValue(String key, String value) { - if (value != null && value.length() > 0) { - if ("dubbo.service.max.retry.providers".equals(key)) { - return String.valueOf(Integer.parseInt(value) - 1); - } else if ("dubbo.service.allow.no.provider".equals(key)) { - return String.valueOf(!Boolean.parseBoolean(value)); - } - } - return value; - } - - protected static void appendProperties(AbstractConfig config) { - if (config == null) { - return; - } - String prefix = "dubbo." + getTagName(config.getClass()) + "."; - Method[] methods = config.getClass().getMethods(); - for (Method method : methods) { - try { - String name = method.getName(); - if (name.length() > 3 && name.startsWith("set") && Modifier.isPublic(method.getModifiers()) - && method.getParameterTypes().length == 1 && isPrimitive(method.getParameterTypes()[0])) { - String property = StringUtils.camelToSplitName(name.substring(3, 4).toLowerCase() + name.substring(4), "."); - - String value = null; - if (config.getId() != null && config.getId().length() > 0) { - String pn = prefix + config.getId() + "." + property; - value = System.getProperty(pn); - if (!StringUtils.isBlank(value)) { - logger.info("Use System Property " + pn + " to config dubbo"); - } - } - if (value == null || value.length() == 0) { - String pn = prefix + property; - value = System.getProperty(pn); - if (!StringUtils.isBlank(value)) { - logger.info("Use System Property " + pn + " to config dubbo"); - } - } - if (value == null || value.length() == 0) { - Method getter; - try { - getter = config.getClass().getMethod("get" + name.substring(3)); - } catch (NoSuchMethodException e) { - try { - getter = config.getClass().getMethod("is" + name.substring(3)); - } catch (NoSuchMethodException e2) { - getter = null; - } - } - if (getter != null) { - if (getter.invoke(config) == null) { - if (config.getId() != null && config.getId().length() > 0) { - value = ConfigUtils.getProperty(prefix + config.getId() + "." + property); - } - if (value == null || value.length() == 0) { - value = ConfigUtils.getProperty(prefix + property); - } - if (value == null || value.length() == 0) { - String legacyKey = legacyProperties.get(prefix + property); - if (legacyKey != null && legacyKey.length() > 0) { - value = convertLegacyValue(legacyKey, ConfigUtils.getProperty(legacyKey)); - } - } - - } - } - } - if (value != null && value.length() > 0) { - method.invoke(config, convertPrimitive(method.getParameterTypes()[0], value)); - } - } - } catch (Exception e) { - logger.error(e.getMessage(), e); - } - } - } - - private static String getTagName(Class cls) { - String tag = cls.getSimpleName(); - for (String suffix : SUFFIXES) { - if (tag.endsWith(suffix)) { - tag = tag.substring(0, tag.length() - suffix.length()); - break; - } - } - tag = tag.toLowerCase(); - return tag; - } - - protected static void appendParameters(Map parameters, Object config) { - appendParameters(parameters, config, null); - } - - @SuppressWarnings("unchecked") - protected static void appendParameters(Map parameters, Object config, String prefix) { - if (config == null) { - return; - } - Method[] methods = config.getClass().getMethods(); - for (Method method : methods) { - try { - String name = method.getName(); - if ((name.startsWith("get") || name.startsWith("is")) - && !"getClass".equals(name) - && Modifier.isPublic(method.getModifiers()) - && method.getParameterTypes().length == 0 - && isPrimitive(method.getReturnType())) { - Parameter parameter = method.getAnnotation(Parameter.class); - if (method.getReturnType() == Object.class || parameter != null && parameter.excluded()) { - continue; - } - int i = name.startsWith("get") ? 3 : 2; - String prop = StringUtils.camelToSplitName(name.substring(i, i + 1).toLowerCase() + name.substring(i + 1), "."); - String key; - if (parameter != null && parameter.key().length() > 0) { - key = parameter.key(); - } else { - key = prop; - } - Object value = method.invoke(config); - String str = String.valueOf(value).trim(); - if (value != null && str.length() > 0) { - if (parameter != null && parameter.escaped()) { - str = URL.encode(str); - } - if (parameter != null && parameter.append()) { - String pre = parameters.get(Constants.DEFAULT_KEY + "." + key); - if (pre != null && pre.length() > 0) { - str = pre + "," + str; - } - pre = parameters.get(key); - if (pre != null && pre.length() > 0) { - str = pre + "," + str; - } - } - if (prefix != null && prefix.length() > 0) { - key = prefix + "." + key; - } - parameters.put(key, str); - } else if (parameter != null && parameter.required()) { - throw new IllegalStateException(config.getClass().getSimpleName() + "." + key + " == null"); - } - } else if ("getParameters".equals(name) - && Modifier.isPublic(method.getModifiers()) - && method.getParameterTypes().length == 0 - && method.getReturnType() == Map.class) { - Map map = (Map) method.invoke(config, new Object[0]); - if (map != null && map.size() > 0) { - String pre = (prefix != null && prefix.length() > 0 ? prefix + "." : ""); - for (Map.Entry entry : map.entrySet()) { - parameters.put(pre + entry.getKey().replace('-', '.'), entry.getValue()); - } - } - } - } catch (Exception e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - } - - protected static void appendAttributes(Map parameters, Object config) { - appendAttributes(parameters, config, null); - } - - protected static void appendAttributes(Map parameters, Object config, String prefix) { - if (config == null) { - return; - } - Method[] methods = config.getClass().getMethods(); - for (Method method : methods) { - try { - String name = method.getName(); - if ((name.startsWith("get") || name.startsWith("is")) - && !"getClass".equals(name) - && Modifier.isPublic(method.getModifiers()) - && method.getParameterTypes().length == 0 - && isPrimitive(method.getReturnType())) { - Parameter parameter = method.getAnnotation(Parameter.class); - if (parameter == null || !parameter.attribute()) - continue; - String key; - if (parameter.key().length() > 0) { - key = parameter.key(); - } else { - int i = name.startsWith("get") ? 3 : 2; - key = name.substring(i, i + 1).toLowerCase() + name.substring(i + 1); - } - Object value = method.invoke(config); - if (value != null) { - if (prefix != null && prefix.length() > 0) { - key = prefix + "." + key; - } - parameters.put(key, value); - } - } - } catch (Exception e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - } - - private 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; - } - - private static Object convertPrimitive(Class type, String value) { - 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); - } else 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); - } - return value; - } - - protected static void checkExtension(Class type, String property, String value) { - checkName(property, value); - if (value != null && value.length() > 0 - && !ExtensionLoader.getExtensionLoader(type).hasExtension(value)) { - throw new IllegalStateException("No such extension " + value + " for " + property + "/" + type.getName()); - } - } - - protected static void checkMultiExtension(Class type, String property, String value) { - checkMultiName(property, value); - if (value != null && value.length() > 0) { - String[] values = value.split("\\s*[,]+\\s*"); - for (String v : values) { - if (v.startsWith(Constants.REMOVE_VALUE_PREFIX)) { - v = v.substring(1); - } - if (Constants.DEFAULT_KEY.equals(v)) { - continue; - } - if (!ExtensionLoader.getExtensionLoader(type).hasExtension(v)) { - throw new IllegalStateException("No such extension " + v + " for " + property + "/" + type.getName()); - } - } - } - } - - protected static void checkLength(String property, String value) { - checkProperty(property, value, MAX_LENGTH, null); - } - - protected static void checkPathLength(String property, String value) { - checkProperty(property, value, MAX_PATH_LENGTH, null); - } - - protected static void checkName(String property, String value) { - checkProperty(property, value, MAX_LENGTH, PATTERN_NAME); - } - - protected static void checkNameHasSymbol(String property, String value) { - checkProperty(property, value, MAX_LENGTH, PATTERN_NAME_HAS_SYMBOL); - } - - protected static void checkKey(String property, String value) { - checkProperty(property, value, MAX_LENGTH, PATTERN_KEY); - } - - protected static void checkMultiName(String property, String value) { - checkProperty(property, value, MAX_LENGTH, PATTERN_MULTI_NAME); - } - - protected static void checkPathName(String property, String value) { - checkProperty(property, value, MAX_PATH_LENGTH, PATTERN_PATH); - } - - protected static void checkMethodName(String property, String value) { - checkProperty(property, value, MAX_LENGTH, PATTERN_METHOD_NAME); - } - - protected static void checkParameterName(Map parameters) { - if (parameters == null || parameters.size() == 0) { - return; - } - for (Map.Entry entry : parameters.entrySet()) { - checkNameHasSymbol(entry.getKey(), entry.getValue()); - } - } - - protected static void checkProperty(String property, String value, int maxlength, Pattern pattern) { - if (value == null || value.length() == 0) { - return; - } - if (value.length() > maxlength) { - throw new IllegalStateException("Invalid " + property + "=\"" + value + "\" is longer than " + maxlength); - } - if (pattern != null) { - Matcher matcher = pattern.matcher(value); - if (!matcher.matches()) { - throw new IllegalStateException("Invalid " + property + "=\"" + value + "\" contains illegal " + - "character, only digit, letter, '-', '_' or '.' is legal."); - } - } - } - - @Parameter(excluded = true) - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - protected void appendAnnotation(Class annotationClass, Object annotation) { - Method[] methods = annotationClass.getMethods(); - for (Method method : methods) { - if (method.getDeclaringClass() != Object.class - && method.getReturnType() != void.class - && method.getParameterTypes().length == 0 - && Modifier.isPublic(method.getModifiers()) - && !Modifier.isStatic(method.getModifiers())) { - try { - String property = method.getName(); - if ("interfaceClass".equals(property) || "interfaceName".equals(property)) { - property = "interface"; - } - String setter = "set" + property.substring(0, 1).toUpperCase() + property.substring(1); - Object value = method.invoke(annotation); - if (value != null && !value.equals(method.getDefaultValue())) { - Class parameterType = ReflectUtils.getBoxedClass(method.getReturnType()); - if ("filter".equals(property) || "listener".equals(property)) { - parameterType = String.class; - value = StringUtils.join((String[]) value, ","); - } else if ("parameters".equals(property)) { - parameterType = Map.class; - value = CollectionUtils.toStringMap((String[]) value); - } - try { - Method setterMethod = getClass().getMethod(setter, parameterType); - setterMethod.invoke(this, value); - } catch (NoSuchMethodException e) { - // ignore - } - } - } catch (Throwable e) { - logger.error(e.getMessage(), e); - } - } - } - } - - @Override - public String toString() { - try { - StringBuilder buf = new StringBuilder(); - buf.append(""); - return buf.toString(); - } catch (Throwable t) { - logger.warn(t.getMessage(), t); - return super.toString(); - } - } - -} +/* + * 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; + +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; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.common.utils.CollectionUtils; +import org.apache.dubbo.common.utils.ConfigUtils; +import org.apache.dubbo.common.utils.ReflectUtils; +import org.apache.dubbo.common.utils.StringUtils; +import org.apache.dubbo.config.support.Parameter; +import org.apache.dubbo.rpc.model.ConsumerMethodModel; + +import java.io.Serializable; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Utility methods and public methods for parsing configuration + * + * @export + */ +public abstract class AbstractConfig implements Serializable { + + protected static final Logger logger = LoggerFactory.getLogger(AbstractConfig.class); + private static final long serialVersionUID = 4267533505537413570L; + private static final int MAX_LENGTH = 200; + + private static final int MAX_PATH_LENGTH = 200; + + private static final Pattern PATTERN_NAME = Pattern.compile("[\\-._0-9a-zA-Z]+"); + + private static final Pattern PATTERN_MULTI_NAME = Pattern.compile("[,\\-._0-9a-zA-Z]+"); + + private static final Pattern PATTERN_METHOD_NAME = Pattern.compile("[a-zA-Z][0-9a-zA-Z]*"); + + private static final Pattern PATTERN_PATH = Pattern.compile("[/\\-$._0-9a-zA-Z]+"); + + private static final Pattern PATTERN_NAME_HAS_SYMBOL = Pattern.compile("[:*,\\s/\\-._0-9a-zA-Z]+"); + + private static final Pattern PATTERN_KEY = Pattern.compile("[*,\\-._0-9a-zA-Z]+"); + private static final Map legacyProperties = new HashMap(); + 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"); + + // this is only for compatibility + Runtime.getRuntime().addShutdownHook(DubboShutdownHook.getDubboShutdownHook()); + } + + protected String id; + + private static String convertLegacyValue(String key, String value) { + if (value != null && value.length() > 0) { + if ("dubbo.service.max.retry.providers".equals(key)) { + return String.valueOf(Integer.parseInt(value) - 1); + } else if ("dubbo.service.allow.no.provider".equals(key)) { + return String.valueOf(!Boolean.parseBoolean(value)); + } + } + return value; + } + + protected static void appendProperties(AbstractConfig config) { + if (config == null) { + return; + } + String prefix = "dubbo." + getTagName(config.getClass()) + "."; + Method[] methods = config.getClass().getMethods(); + for (Method method : methods) { + try { + String name = method.getName(); + if (name.length() > 3 && name.startsWith("set") && Modifier.isPublic(method.getModifiers()) + && method.getParameterTypes().length == 1 && isPrimitive(method.getParameterTypes()[0])) { + String property = StringUtils.camelToSplitName(name.substring(3, 4).toLowerCase() + name.substring(4), "."); + + String value = null; + if (config.getId() != null && config.getId().length() > 0) { + String pn = prefix + config.getId() + "." + property; + value = System.getProperty(pn); + if (!StringUtils.isBlank(value)) { + logger.info("Use System Property " + pn + " to config dubbo"); + } + } + if (value == null || value.length() == 0) { + String pn = prefix + property; + value = System.getProperty(pn); + if (!StringUtils.isBlank(value)) { + logger.info("Use System Property " + pn + " to config dubbo"); + } + } + if (value == null || value.length() == 0) { + Method getter; + try { + getter = config.getClass().getMethod("get" + name.substring(3)); + } catch (NoSuchMethodException e) { + try { + getter = config.getClass().getMethod("is" + name.substring(3)); + } catch (NoSuchMethodException e2) { + getter = null; + } + } + if (getter != null) { + if (getter.invoke(config) == null) { + if (config.getId() != null && config.getId().length() > 0) { + value = ConfigUtils.getProperty(prefix + config.getId() + "." + property); + } + if (value == null || value.length() == 0) { + value = ConfigUtils.getProperty(prefix + property); + } + if (value == null || value.length() == 0) { + String legacyKey = legacyProperties.get(prefix + property); + if (legacyKey != null && legacyKey.length() > 0) { + value = convertLegacyValue(legacyKey, ConfigUtils.getProperty(legacyKey)); + } + } + + } + } + } + if (value != null && value.length() > 0) { + method.invoke(config, convertPrimitive(method.getParameterTypes()[0], value)); + } + } + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + } + } + + private static String getTagName(Class cls) { + String tag = cls.getSimpleName(); + for (String suffix : SUFFIXES) { + if (tag.endsWith(suffix)) { + tag = tag.substring(0, tag.length() - suffix.length()); + break; + } + } + tag = tag.toLowerCase(); + return tag; + } + + protected static void appendParameters(Map parameters, Object config) { + appendParameters(parameters, config, null); + } + + @SuppressWarnings("unchecked") + protected static void appendParameters(Map parameters, Object config, String prefix) { + if (config == null) { + return; + } + Method[] methods = config.getClass().getMethods(); + for (Method method : methods) { + try { + String name = method.getName(); + if ((name.startsWith("get") || name.startsWith("is")) + && !"getClass".equals(name) + && Modifier.isPublic(method.getModifiers()) + && method.getParameterTypes().length == 0 + && isPrimitive(method.getReturnType())) { + Parameter parameter = method.getAnnotation(Parameter.class); + if (method.getReturnType() == Object.class || parameter != null && parameter.excluded()) { + continue; + } + int i = name.startsWith("get") ? 3 : 2; + String prop = StringUtils.camelToSplitName(name.substring(i, i + 1).toLowerCase() + name.substring(i + 1), "."); + String key; + if (parameter != null && parameter.key().length() > 0) { + key = parameter.key(); + } else { + key = prop; + } + Object value = method.invoke(config); + String str = String.valueOf(value).trim(); + if (value != null && str.length() > 0) { + if (parameter != null && parameter.escaped()) { + str = URL.encode(str); + } + if (parameter != null && parameter.append()) { + String pre = parameters.get(Constants.DEFAULT_KEY + "." + key); + if (pre != null && pre.length() > 0) { + str = pre + "," + str; + } + pre = parameters.get(key); + if (pre != null && pre.length() > 0) { + str = pre + "," + str; + } + } + if (prefix != null && prefix.length() > 0) { + key = prefix + "." + key; + } + parameters.put(key, str); + } else if (parameter != null && parameter.required()) { + throw new IllegalStateException(config.getClass().getSimpleName() + "." + key + " == null"); + } + } else if ("getParameters".equals(name) + && Modifier.isPublic(method.getModifiers()) + && method.getParameterTypes().length == 0 + && method.getReturnType() == Map.class) { + Map map = (Map) method.invoke(config, new Object[0]); + if (map != null && map.size() > 0) { + String pre = (prefix != null && prefix.length() > 0 ? prefix + "." : ""); + for (Map.Entry entry : map.entrySet()) { + parameters.put(pre + entry.getKey().replace('-', '.'), entry.getValue()); + } + } + } + } catch (Exception e) { + throw new IllegalStateException(e.getMessage(), e); + } + } + } + + protected static void appendAttributes(Map parameters, Object config) { + appendAttributes(parameters, config, null); + } + + protected static void appendAttributes(Map parameters, Object config, String prefix) { + if (config == null) { + return; + } + Method[] methods = config.getClass().getMethods(); + for (Method method : methods) { + try { + Parameter parameter = method.getAnnotation(Parameter.class); + if (parameter == null || !parameter.attribute()) { + continue; + } + String name = method.getName(); + if ((name.startsWith("get") || name.startsWith("is")) + && !"getClass".equals(name) + && Modifier.isPublic(method.getModifiers()) + && method.getParameterTypes().length == 0 + && isPrimitive(method.getReturnType())) { + String key; + if (parameter.key().length() > 0) { + key = parameter.key(); + } else { + int i = name.startsWith("get") ? 3 : 2; + key = name.substring(i, i + 1).toLowerCase() + name.substring(i + 1); + } + Object value = method.invoke(config); + if (value != null) { + if (prefix != null && prefix.length() > 0) { + key = prefix + "." + key; + } + parameters.put(key, value); + } + } + } catch (Exception e) { + throw new IllegalStateException(e.getMessage(), e); + } + } + } + + protected static ConsumerMethodModel.AsyncMethodInfo convertMethodConfig2AyncInfo(MethodConfig methodConfig) { + if (methodConfig == null || (methodConfig.getOninvoke() == null && methodConfig.getOnreturn() == null && methodConfig.getOnthrow() == null)) { + return null; + } + + //check config conflict + if (Boolean.FALSE.equals(methodConfig.isReturn()) && (methodConfig.getOnreturn() != null || methodConfig.getOnthrow() != null)) { + throw new IllegalStateException("method config error : return attribute must be set true when onreturn or onthrow has been set."); + } + + ConsumerMethodModel.AsyncMethodInfo asyncMethodInfo = new ConsumerMethodModel.AsyncMethodInfo(); + + asyncMethodInfo.setOninvokeInstance(methodConfig.getOninvoke()); + asyncMethodInfo.setOnreturnInstance(methodConfig.getOnreturn()); + asyncMethodInfo.setOnthrowInstance(methodConfig.getOnthrow()); + + try { + String oninvokeMethod = methodConfig.getOninvokeMethod(); + if (StringUtils.isNotEmpty(oninvokeMethod)) { + asyncMethodInfo.setOninvokeMethod(getMethodByName(methodConfig.getOninvoke().getClass(), oninvokeMethod)); + } + + String onreturnMethod = methodConfig.getOnreturnMethod(); + if (StringUtils.isNotEmpty(onreturnMethod)) { + asyncMethodInfo.setOnreturnMethod(getMethodByName(methodConfig.getOnreturn().getClass(), onreturnMethod)); + } + + String onthrowMethod = methodConfig.getOnthrowMethod(); + if (StringUtils.isNotEmpty(onthrowMethod)) { + asyncMethodInfo.setOnthrowMethod(getMethodByName(methodConfig.getOnthrow().getClass(), onthrowMethod)); + } + } catch (Exception e) { + throw new IllegalStateException(e.getMessage(), e); + } + + return asyncMethodInfo; + } + + private static Method getMethodByName(Class clazz, String methodName) { + try { + return ReflectUtils.findMethodByMethodName(clazz, methodName); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + private 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; + } + + private static Object convertPrimitive(Class type, String value) { + 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); + } else 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); + } + return value; + } + + protected static void checkExtension(Class type, String property, String value) { + checkName(property, value); + if (value != null && value.length() > 0 + && !ExtensionLoader.getExtensionLoader(type).hasExtension(value)) { + throw new IllegalStateException("No such extension " + value + " for " + property + "/" + type.getName()); + } + } + + protected static void checkMultiExtension(Class type, String property, String value) { + checkMultiName(property, value); + if (value != null && value.length() > 0) { + String[] values = value.split("\\s*[,]+\\s*"); + for (String v : values) { + if (v.startsWith(Constants.REMOVE_VALUE_PREFIX)) { + v = v.substring(1); + } + if (Constants.DEFAULT_KEY.equals(v)) { + continue; + } + if (!ExtensionLoader.getExtensionLoader(type).hasExtension(v)) { + throw new IllegalStateException("No such extension " + v + " for " + property + "/" + type.getName()); + } + } + } + } + + protected static void checkLength(String property, String value) { + checkProperty(property, value, MAX_LENGTH, null); + } + + protected static void checkPathLength(String property, String value) { + checkProperty(property, value, MAX_PATH_LENGTH, null); + } + + protected static void checkName(String property, String value) { + checkProperty(property, value, MAX_LENGTH, PATTERN_NAME); + } + + protected static void checkNameHasSymbol(String property, String value) { + checkProperty(property, value, MAX_LENGTH, PATTERN_NAME_HAS_SYMBOL); + } + + protected static void checkKey(String property, String value) { + checkProperty(property, value, MAX_LENGTH, PATTERN_KEY); + } + + protected static void checkMultiName(String property, String value) { + checkProperty(property, value, MAX_LENGTH, PATTERN_MULTI_NAME); + } + + protected static void checkPathName(String property, String value) { + checkProperty(property, value, MAX_PATH_LENGTH, PATTERN_PATH); + } + + protected static void checkMethodName(String property, String value) { + checkProperty(property, value, MAX_LENGTH, PATTERN_METHOD_NAME); + } + + protected static void checkParameterName(Map parameters) { + if (parameters == null || parameters.size() == 0) { + return; + } + for (Map.Entry entry : parameters.entrySet()) { + checkNameHasSymbol(entry.getKey(), entry.getValue()); + } + } + + protected static void checkProperty(String property, String value, int maxlength, Pattern pattern) { + if (value == null || value.length() == 0) { + return; + } + if (value.length() > maxlength) { + throw new IllegalStateException("Invalid " + property + "=\"" + value + "\" is longer than " + maxlength); + } + if (pattern != null) { + Matcher matcher = pattern.matcher(value); + if (!matcher.matches()) { + throw new IllegalStateException("Invalid " + property + "=\"" + value + "\" contains illegal " + + "character, only digit, letter, '-', '_' or '.' is legal."); + } + } + } + + @Parameter(excluded = true) + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + protected void appendAnnotation(Class annotationClass, Object annotation) { + Method[] methods = annotationClass.getMethods(); + for (Method method : methods) { + if (method.getDeclaringClass() != Object.class + && method.getReturnType() != void.class + && method.getParameterTypes().length == 0 + && Modifier.isPublic(method.getModifiers()) + && !Modifier.isStatic(method.getModifiers())) { + try { + String property = method.getName(); + if ("interfaceClass".equals(property) || "interfaceName".equals(property)) { + property = "interface"; + } + String setter = "set" + property.substring(0, 1).toUpperCase() + property.substring(1); + Object value = method.invoke(annotation); + if (value != null && !value.equals(method.getDefaultValue())) { + Class parameterType = ReflectUtils.getBoxedClass(method.getReturnType()); + if ("filter".equals(property) || "listener".equals(property)) { + parameterType = String.class; + value = StringUtils.join((String[]) value, ","); + } else if ("parameters".equals(property)) { + parameterType = Map.class; + value = CollectionUtils.toStringMap((String[]) value); + } + try { + Method setterMethod = getClass().getMethod(setter, parameterType); + setterMethod.invoke(this, value); + } catch (NoSuchMethodException e) { + // ignore + } + } + } catch (Throwable e) { + logger.error(e.getMessage(), e); + } + } + } + } + + @Override + public String toString() { + try { + StringBuilder buf = new StringBuilder(); + buf.append(""); + return buf.toString(); + } catch (Throwable t) { + logger.warn(t.getMessage(), t); + return super.toString(); + } + } + +} 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 70ab62e4493a..3ff1cebb9e68 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 @@ -286,7 +286,36 @@ protected void checkInterfaceAndMethods(Class interfaceClass, List interfaceClass) { + void checkMock(Class interfaceClass) { + if (ConfigUtils.isEmpty(mock)) { + return; + } + + String normalizedMock = MockInvoker.normalizeMock(mock); + if (normalizedMock.startsWith(Constants.RETURN_PREFIX)) { + normalizedMock = normalizedMock.substring(Constants.RETURN_PREFIX.length()).trim(); + try { + MockInvoker.parseMockValue(normalizedMock); + } catch (Exception e) { + throw new IllegalStateException("Illegal mock return in "); + } + } else if (normalizedMock.startsWith(Constants.THROW_PREFIX)) { + normalizedMock = normalizedMock.substring(Constants.THROW_PREFIX.length()).trim(); + if (ConfigUtils.isNotEmpty(normalizedMock)) { + try { + MockInvoker.getThrowable(normalizedMock); + } catch (Exception e) { + throw new IllegalStateException("Illegal mock throw in "); + } + } + } else { + MockInvoker.getMockObject(normalizedMock, interfaceClass); + } + } + + void checkStub(Class interfaceClass) { if (ConfigUtils.isNotEmpty(local)) { Class localClass = ConfigUtils.isDefault(local) ? ReflectUtils.forName(interfaceClass.getName() + "Local") : ReflectUtils.forName(local); if (!interfaceClass.isAssignableFrom(localClass)) { @@ -309,26 +338,6 @@ protected void checkStubAndMock(Class interfaceClass) { throw new IllegalStateException("No such constructor \"public " + localClass.getSimpleName() + "(" + interfaceClass.getName() + ")\" in local implementation class " + localClass.getName()); } } - if (ConfigUtils.isNotEmpty(mock)) { - if (mock.startsWith(Constants.RETURN_PREFIX)) { - String value = mock.substring(Constants.RETURN_PREFIX.length()); - try { - MockInvoker.parseMockValue(value); - } catch (Exception e) { - throw new IllegalStateException("Illegal mock json value in "); - } - } else { - Class mockClass = ConfigUtils.isDefault(mock) ? ReflectUtils.forName(interfaceClass.getName() + "Mock") : ReflectUtils.forName(mock); - if (!interfaceClass.isAssignableFrom(mockClass)) { - throw new IllegalStateException("The mock implementation class " + mockClass.getName() + " not implement interface " + interfaceClass.getName()); - } - try { - mockClass.getConstructor(new Class[0]); - } catch (NoSuchMethodException e) { - throw new IllegalStateException("No such empty constructor \"public " + mockClass.getSimpleName() + "()\" in mock implementation class " + mockClass.getName()); - } - } - } } /** @@ -522,4 +531,4 @@ public String getScope() { public void setScope(String scope) { this.scope = scope; } -} \ No newline at end of file +} 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 a4acce86c93d..a2263b8221e5 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 @@ -64,6 +64,19 @@ public abstract class AbstractMethodConfig extends AbstractConfig { // customized parameters protected Map parameters; + /** + * forks for forking cluster + */ + protected Integer forks; + + public Integer getForks() { + return forks; + } + + public void setForks(Integer forks) { + this.forks = forks; + } + public Integer getTimeout() { return timeout; } @@ -127,8 +140,14 @@ public void setMock(Boolean mock) { } public void setMock(String mock) { - if (mock != null && mock.startsWith(Constants.RETURN_PREFIX)) { + if (mock == null) { + return; + } + + if (mock.startsWith(Constants.RETURN_PREFIX) || mock.startsWith(Constants.THROW_PREFIX + " ")) { checkLength("mock", mock); + } else if (mock.startsWith(Constants.FAIL_PREFIX) || mock.startsWith(Constants.FORCE_PREFIX)) { + checkNameHasSymbol("mock", mock); } else { checkName("mock", mock); } @@ -168,4 +187,4 @@ public void setParameters(Map parameters) { this.parameters = parameters; } -} \ No newline at end of file +} 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 3ae33291adc4..75821690a1fa 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 @@ -470,13 +470,4 @@ public void destroy() { ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(name).destroy(); } } - - /** - * Just for compatibility. - * It should be deleted in the next major version, say 2.7.x. - */ - @Deprecated - public static void destroyAll() { - DubboShutdownHook.getDubboShutdownHook().destroyAll(); - } -} \ No newline at end of file +} 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 7e4e4a449cd5..c39f3b67a59c 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 @@ -24,14 +24,12 @@ import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.annotation.Reference; import org.apache.dubbo.config.support.Parameter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; -import org.apache.dubbo.rpc.StaticContext; import org.apache.dubbo.rpc.cluster.Cluster; import org.apache.dubbo.rpc.cluster.directory.StaticDirectory; import org.apache.dubbo.rpc.cluster.support.AvailableCluster; @@ -45,7 +43,6 @@ import java.io.File; import java.io.FileInputStream; import java.io.IOException; -import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -116,39 +113,6 @@ public ReferenceConfig(Reference reference) { appendAnnotation(Reference.class, reference); } - private static void checkAndConvertImplicitConfig(MethodConfig method, Map map, Map attributes) { - //check config conflict - if (Boolean.FALSE.equals(method.isReturn()) && (method.getOnreturn() != null || method.getOnthrow() != null)) { - throw new IllegalStateException("method config error : return attribute must be set true when onreturn or onthrow has been setted."); - } - //convert onreturn methodName to Method - String onReturnMethodKey = StaticContext.getKey(map, method.getName(), Constants.ON_RETURN_METHOD_KEY); - Object onReturnMethod = attributes.get(onReturnMethodKey); - if (onReturnMethod instanceof String) { - attributes.put(onReturnMethodKey, getMethodByName(method.getOnreturn().getClass(), onReturnMethod.toString())); - } - //convert onthrow methodName to Method - String onThrowMethodKey = StaticContext.getKey(map, method.getName(), Constants.ON_THROW_METHOD_KEY); - Object onThrowMethod = attributes.get(onThrowMethodKey); - if (onThrowMethod instanceof String) { - attributes.put(onThrowMethodKey, getMethodByName(method.getOnthrow().getClass(), onThrowMethod.toString())); - } - //convert oninvoke methodName to Method - String onInvokeMethodKey = StaticContext.getKey(map, method.getName(), Constants.ON_INVOKE_METHOD_KEY); - Object onInvokeMethod = attributes.get(onInvokeMethodKey); - if (onInvokeMethod instanceof String) { - attributes.put(onInvokeMethodKey, getMethodByName(method.getOninvoke().getClass(), onInvokeMethod.toString())); - } - } - - private static Method getMethodByName(Class clazz, String methodName) { - try { - return ReflectUtils.findMethodByMethodName(clazz, methodName); - } catch (Exception e) { - throw new IllegalStateException(e); - } - } - public URL toUrl() { return urls.isEmpty() ? null : urls.iterator().next(); } @@ -229,7 +193,9 @@ private void init() { throw new IllegalStateException("Unload " + resolveFile + ", cause: " + e.getMessage(), e); } finally { try { - if (null != fis) fis.close(); + if (null != fis) { + fis.close(); + } } catch (IOException e) { logger.warn(e.getMessage(), e); } @@ -278,10 +244,11 @@ private void init() { } } checkApplication(); - checkStubAndMock(interfaceClass); + checkStub(interfaceClass); + checkMock(interfaceClass); Map map = new HashMap(); resolveAsyncInterface(interfaceClass, map); - Map attributes = new HashMap(); + map.put(Constants.SIDE_KEY, Constants.CONSUMER_SIDE); map.put(Constants.DUBBO_VERSION_KEY, Version.getProtocolVersion()); map.put(Constants.TIMESTAMP_KEY, String.valueOf(System.currentTimeMillis())); @@ -307,19 +274,19 @@ private void init() { appendParameters(map, module); appendParameters(map, consumer, Constants.DEFAULT_KEY); appendParameters(map, this); - String prefix = StringUtils.getServiceKey(map); + Map attributes = null; if (methods != null && !methods.isEmpty()) { - for (MethodConfig method : methods) { - appendParameters(map, method, method.getName()); - String retryKey = method.getName() + ".retry"; + attributes = new HashMap(); + for (MethodConfig methodConfig : methods) { + appendParameters(map, methodConfig, methodConfig.getName()); + String retryKey = methodConfig.getName() + ".retry"; if (map.containsKey(retryKey)) { String retryValue = map.remove(retryKey); if ("false".equals(retryValue)) { - map.put(method.getName() + ".retries", "0"); + map.put(methodConfig.getName() + ".retries", "0"); } } - appendAttributes(attributes, method, prefix + "." + method.getName()); - checkAndConvertImplicitConfig(method, map, attributes); + attributes.put(methodConfig.getName(), convertMethodConfig2AyncInfo(methodConfig)); } } @@ -331,10 +298,9 @@ private void init() { } map.put(Constants.REGISTER_IP_KEY, hostToRegistry); - //attributes are stored by system context. - StaticContext.getSystemContext().putAll(attributes); ref = createProxy(map); - ConsumerModel consumerModel = new ConsumerModel(getUniqueServiceName(), ref, interfaceClass.getMethods()); + + ConsumerModel consumerModel = new ConsumerModel(getUniqueServiceName(), ref, interfaceClass.getMethods(), attributes); ApplicationModel.initConsumerModel(getUniqueServiceName(), consumerModel); } @@ -440,9 +406,13 @@ private void checkDefault() { private void resolveAsyncInterface(Class interfaceClass, Map map) { AsyncFor annotation = interfaceClass.getAnnotation(AsyncFor.class); - if (annotation == null) return; + if (annotation == null) { + return; + } Class target = annotation.value(); - if (!target.isAssignableFrom(interfaceClass)) return; + if (!target.isAssignableFrom(interfaceClass)) { + return; + } this.asyncInterfaceClass = interfaceClass; this.interfaceClass = target; setInterface(this.interfaceClass.getName()); 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 a9a8145e29ba..0c2022b87c8a 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 @@ -162,8 +162,9 @@ public Integer getWait() { @Deprecated public void setWait(Integer wait) { this.wait = wait; - if (wait != null && wait > 0) + if (wait != null && wait > 0) { System.setProperty(Constants.SHUTDOWN_WAIT_KEY, String.valueOf(wait)); + } } public Boolean isCheck() { 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 29d5d11eddc3..66e8d7fc4263 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 @@ -32,7 +32,6 @@ import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; -import org.apache.dubbo.rpc.ServiceClassHolder; import org.apache.dubbo.rpc.cluster.ConfiguratorFactory; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ProviderModel; @@ -310,7 +309,8 @@ protected synchronized void doExport() { checkRegistry(); checkProtocol(); appendProperties(this); - checkStubAndMock(interfaceClass); + checkStub(interfaceClass); + checkMock(interfaceClass); if (path == null || path.length() == 0) { path = interfaceName; } @@ -532,7 +532,6 @@ private void exportLocal(URL url) { .setProtocol(Constants.LOCAL_PROTOCOL) .setHost(LOCALHOST) .setPort(0); - ServiceClassHolder.getInstance().pushServiceClass(getServiceClass(ref)); Exporter exporter = protocol.export( proxyFactory.getInvoker(ref, (Class) interfaceClass, local)); exporters.add(exporter); @@ -819,6 +818,16 @@ public void setGeneric(String generic) { } } + @Override + public void setMock(Boolean mock) { + throw new IllegalArgumentException("mock doesn't support on provider side"); + } + + @Override + public void setMock(String mock) { + throw new IllegalArgumentException("mock doesn't support on provider side"); + } + public List getExportedUrls() { return urls; } 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 d387432cc98d..0ced6174be7c 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 @@ -117,7 +117,9 @@ public T get(ReferenceConfig referenceConfig) { void destroyKey(String key) { ReferenceConfig config = cache.remove(key); - if (config == null) return; + if (config == null) { + return; + } config.destroy(); } 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 ac231cbad724..792bed697404 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 @@ -141,7 +141,7 @@ public void testAppendParameters4() throws Exception { @Test public void testAppendAttributes1() throws Exception { - Map parameters = new HashMap(); + Map parameters = new HashMap(); AbstractConfig.appendAttributes(parameters, new AttributeConfig('l', true, (byte) 0x01), "prefix"); TestCase.assertEquals('l', parameters.get("prefix.let")); TestCase.assertEquals(true, parameters.get("prefix.activate")); @@ -150,7 +150,7 @@ public void testAppendAttributes1() throws Exception { @Test public void testAppendAttributes2() throws Exception { - Map parameters = new HashMap(); + Map parameters = new HashMap(); AbstractConfig.appendAttributes(parameters, new AttributeConfig('l', true, (byte) 0x01)); TestCase.assertEquals('l', parameters.get("let")); TestCase.assertEquals(true, parameters.get("activate")); @@ -198,7 +198,8 @@ public void checkName() throws Exception { @Test public void checkNameHasSymbol() throws Exception { try { - AbstractConfig.checkNameHasSymbol("hello", ":*,/-0123abcdABCD"); + AbstractConfig.checkNameHasSymbol("hello", ":*,/ -0123\tabcdABCD"); + AbstractConfig.checkNameHasSymbol("mock", "force:return world"); } catch (Exception e) { TestCase.fail("the value should be legal."); } 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 2ea6fb4a0ee0..3199eb969a62 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 @@ -185,63 +185,72 @@ public void checkInterfaceAndMethod5() throws Exception { public void checkStubAndMock1() throws Exception { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setLocal(GreetingLocal1.class.getName()); - interfaceConfig.checkStubAndMock(Greeting.class); + interfaceConfig.checkStub(Greeting.class); + interfaceConfig.checkMock(Greeting.class); } @Test(expected = IllegalStateException.class) public void checkStubAndMock2() throws Exception { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setLocal(GreetingLocal2.class.getName()); - interfaceConfig.checkStubAndMock(Greeting.class); + interfaceConfig.checkStub(Greeting.class); + interfaceConfig.checkMock(Greeting.class); } @Test public void checkStubAndMock3() throws Exception { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setLocal(GreetingLocal3.class.getName()); - interfaceConfig.checkStubAndMock(Greeting.class); + interfaceConfig.checkStub(Greeting.class); + interfaceConfig.checkMock(Greeting.class); } @Test(expected = IllegalStateException.class) public void checkStubAndMock4() throws Exception { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setStub(GreetingLocal1.class.getName()); - interfaceConfig.checkStubAndMock(Greeting.class); + interfaceConfig.checkStub(Greeting.class); + interfaceConfig.checkMock(Greeting.class); } @Test(expected = IllegalStateException.class) public void checkStubAndMock5() throws Exception { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setStub(GreetingLocal2.class.getName()); - interfaceConfig.checkStubAndMock(Greeting.class); + interfaceConfig.checkStub(Greeting.class); + interfaceConfig.checkMock(Greeting.class); } @Test public void checkStubAndMock6() throws Exception { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setStub(GreetingLocal3.class.getName()); - interfaceConfig.checkStubAndMock(Greeting.class); + interfaceConfig.checkStub(Greeting.class); + interfaceConfig.checkMock(Greeting.class); } @Test(expected = IllegalStateException.class) public void checkStubAndMock7() throws Exception { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setMock("return {a, b}"); - interfaceConfig.checkStubAndMock(Greeting.class); + interfaceConfig.checkStub(Greeting.class); + interfaceConfig.checkMock(Greeting.class); } @Test(expected = IllegalStateException.class) public void checkStubAndMock8() throws Exception { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setMock(GreetingMock1.class.getName()); - interfaceConfig.checkStubAndMock(Greeting.class); + interfaceConfig.checkStub(Greeting.class); + interfaceConfig.checkMock(Greeting.class); } @Test(expected = IllegalStateException.class) public void checkStubAndMock9() throws Exception { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setMock(GreetingMock2.class.getName()); - interfaceConfig.checkStubAndMock(Greeting.class); + interfaceConfig.checkStub(Greeting.class); + interfaceConfig.checkMock(Greeting.class); } @Test diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractMethodConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractMethodConfigTest.java index 41549e3ef9bc..063a2e3408ad 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractMethodConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractMethodConfigTest.java @@ -35,6 +35,13 @@ public void testTimeout() throws Exception { assertThat(methodConfig.getTimeout(), equalTo(10)); } + @Test + public void testForks() throws Exception { + MethodConfig methodConfig = new MethodConfig(); + methodConfig.setForks(10); + assertThat(methodConfig.getForks(), equalTo(10)); + } + @Test public void testRetries() throws Exception { MethodConfig methodConfig = new MethodConfig(); 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 2ca7ecc8dfdf..8f7e8609ce7e 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 @@ -100,7 +100,7 @@ public void testOnreturn() throws Exception { MethodConfig method = new MethodConfig(); method.setOnreturn("on-return-object"); assertThat(method.getOnreturn(), equalTo((Object) "on-return-object")); - Map attribute = new HashMap(); + Map attribute = new HashMap(); MethodConfig.appendAttributes(attribute, method); assertThat(attribute, hasEntry((Object) Constants.ON_RETURN_INSTANCE_KEY, (Object) "on-return-object")); Map parameters = new HashMap(); @@ -113,7 +113,7 @@ public void testOnreturnMethod() throws Exception { MethodConfig method = new MethodConfig(); method.setOnreturnMethod("on-return-method"); assertThat(method.getOnreturnMethod(), equalTo("on-return-method")); - Map attribute = new HashMap(); + Map attribute = new HashMap(); MethodConfig.appendAttributes(attribute, method); assertThat(attribute, hasEntry((Object) Constants.ON_RETURN_METHOD_KEY, (Object) "on-return-method")); Map parameters = new HashMap(); @@ -126,7 +126,7 @@ public void testOnthrow() throws Exception { MethodConfig method = new MethodConfig(); method.setOnthrow("on-throw-object"); assertThat(method.getOnthrow(), equalTo((Object) "on-throw-object")); - Map attribute = new HashMap(); + Map attribute = new HashMap(); MethodConfig.appendAttributes(attribute, method); assertThat(attribute, hasEntry((Object) Constants.ON_THROW_INSTANCE_KEY, (Object) "on-throw-object")); Map parameters = new HashMap(); @@ -139,7 +139,7 @@ public void testOnthrowMethod() throws Exception { MethodConfig method = new MethodConfig(); method.setOnthrowMethod("on-throw-method"); assertThat(method.getOnthrowMethod(), equalTo("on-throw-method")); - Map attribute = new HashMap(); + Map attribute = new HashMap(); MethodConfig.appendAttributes(attribute, method); assertThat(attribute, hasEntry((Object) Constants.ON_THROW_METHOD_KEY, (Object) "on-throw-method")); Map parameters = new HashMap(); @@ -152,7 +152,7 @@ public void testOninvoke() throws Exception { MethodConfig method = new MethodConfig(); method.setOninvoke("on-invoke-object"); assertThat(method.getOninvoke(), equalTo((Object) "on-invoke-object")); - Map attribute = new HashMap(); + Map attribute = new HashMap(); MethodConfig.appendAttributes(attribute, method); assertThat(attribute, hasEntry((Object) Constants.ON_INVOKE_INSTANCE_KEY, (Object) "on-invoke-object")); Map parameters = new HashMap(); @@ -165,7 +165,7 @@ public void testOninvokeMethod() throws Exception { MethodConfig method = new MethodConfig(); method.setOninvokeMethod("on-invoke-method"); assertThat(method.getOninvokeMethod(), equalTo("on-invoke-method")); - Map attribute = new HashMap(); + Map attribute = new HashMap(); MethodConfig.appendAttributes(attribute, method); assertThat(attribute, hasEntry((Object) Constants.ON_INVOKE_METHOD_KEY, (Object) "on-invoke-method")); Map parameters = new HashMap(); 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 5da2b463543b..74c1c92b7881 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 @@ -194,6 +194,18 @@ public void testGeneric2() throws Exception { service.setGeneric("illegal"); } + @Test(expected = IllegalArgumentException.class) + public void testMock() throws Exception { + ServiceConfig service = new ServiceConfig(); + service.setMock("true"); + } + + @Test(expected = IllegalArgumentException.class) + public void testMock2() throws Exception { + ServiceConfig service = new ServiceConfig(); + service.setMock(true); + } + @Test public void testUniqueServiceName() throws Exception { ServiceConfig service = new ServiceConfig(); diff --git a/dubbo-config/dubbo-config-spring/pom.xml b/dubbo-config/dubbo-config-spring/pom.xml index 995209db45e3..626556cc3243 100644 --- a/dubbo-config/dubbo-config-spring/pom.xml +++ b/dubbo-config/dubbo-config-spring/pom.xml @@ -34,11 +34,6 @@ dubbo-config-api ${project.parent.version} - - org.apache.dubbo - dubbo-bootstrap - ${project.parent.version} - org.springframework spring-beans @@ -157,4 +152,4 @@ --> - \ No newline at end of file + diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/AnnotationBean.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/AnnotationBean.java index 7612c3302a30..012bd79cec70 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/AnnotationBean.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/AnnotationBean.java @@ -28,11 +28,11 @@ import org.apache.dubbo.config.MonitorConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ProviderConfig; -import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.annotation.Reference; import org.apache.dubbo.config.annotation.Service; + import org.springframework.beans.BeansException; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; @@ -111,17 +111,16 @@ public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) @Override public void destroy() { - - // This will only be called for singleton scope bean, and expected to be called by spring shutdown hook when BeanFactory/ApplicationContext destroys. - // We will guarantee dubbo related resources being released with dubbo shutdown hook. - - // for (ServiceConfig serviceConfig : serviceConfigs) { - // try { - // serviceConfig.unexport(); - // } catch (Throwable e) { - // logger.error(e.getMessage(), e); - // } - // } + // no need to destroy here + // see org.apache.dubbo.config.spring.extension.SpringExtensionFactory.ShutdownHookListener + /* + for (ServiceConfig serviceConfig : serviceConfigs) { + try { + serviceConfig.unexport(); + } catch (Throwable e) { + logger.error(e.getMessage(), e); + } + } for (ReferenceConfig referenceConfig : referenceConfigs.values()) { try { @@ -130,6 +129,7 @@ public void destroy() { logger.error(e.getMessage(), e); } } + */ } @Override @@ -242,7 +242,7 @@ public Object postProcessBeforeInitialization(Object bean, String beanName) } } } catch (Throwable e) { - logger.error("Failed to init remote service reference at filed " + field.getName() + " in class " + bean.getClass().getName() + ", cause: " + e.getMessage(), e); + logger.error("Failed to init remote service reference at field " + field.getName() + " in class " + bean.getClass().getName() + ", cause: " + e.getMessage(), e); } } return bean; 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 bd6195ccb265..337b250f775c 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 @@ -25,6 +25,7 @@ import org.apache.dubbo.config.annotation.Reference; import org.apache.dubbo.config.spring.extension.SpringExtensionFactory; import org.apache.dubbo.config.support.Parameter; + import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; 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 1d5ff8e8d309..1abd8e1cc4c4 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 @@ -25,6 +25,7 @@ import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.annotation.Service; import org.apache.dubbo.config.spring.extension.SpringExtensionFactory; + import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.BeanNameAware; @@ -34,13 +35,13 @@ import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; -import org.springframework.context.support.AbstractApplicationContext; -import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Map; +import static org.apache.dubbo.config.spring.util.BeanFactoryUtils.addApplicationListener; + /** * ServiceFactoryBean * @@ -72,23 +73,7 @@ public ServiceBean(Service service) { public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; SpringExtensionFactory.addApplicationContext(applicationContext); - try { - Method method = applicationContext.getClass().getMethod("addApplicationListener", ApplicationListener.class); // backward compatibility to spring 2.0.1 - method.invoke(applicationContext, this); - supportedApplicationListener = true; - } catch (Throwable t) { - if (applicationContext instanceof AbstractApplicationContext) { - try { - Method method = AbstractApplicationContext.class.getDeclaredMethod("addListener", ApplicationListener.class); // backward compatibility to spring 2.0.1 - if (!method.isAccessible()) { - method.setAccessible(true); - } - method.invoke(applicationContext, this); - supportedApplicationListener = true; - } catch (Throwable t2) { - } - } - } + supportedApplicationListener = addApplicationListener(applicationContext, this); } @Override @@ -107,7 +92,7 @@ public Service getService() { @Override public void onApplicationEvent(ContextRefreshedEvent event) { - if (isDelay() && !isExported() && !isUnexported()) { + if (!isExported() && !isUnexported()) { if (logger.isInfoEnabled()) { logger.info("The service ready on spring started. service: " + getInterface()); } @@ -115,15 +100,6 @@ public void onApplicationEvent(ContextRefreshedEvent event) { } } - private boolean isDelay() { - Integer delay = getDelay(); - ProviderConfig provider = getProvider(); - if (delay == null && provider != null) { - delay = provider.getDelay(); - } - return supportedApplicationListener && (delay == null || delay == -1); - } - @Override @SuppressWarnings({"unchecked", "deprecation"}) public void afterPropertiesSet() throws Exception { @@ -251,16 +227,15 @@ && getInterface() != null && getInterface().length() > 0 setPath(beanName); } } - if (!isDelay()) { + if (!supportedApplicationListener) { export(); } } @Override public void destroy() throws Exception { - // This will only be called for singleton scope bean, and expected to be called by spring shutdown hook when BeanFactory/ApplicationContext destroys. - // We will guarantee dubbo related resources being released with dubbo shutdown hook. - //unexport(); + // no need to call unexport() here, see + // org.apache.dubbo.config.spring.extension.SpringExtensionFactory.ShutdownHookListener } // merged from dubbox diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AbstractAnnotationConfigBeanBuilder.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AbstractAnnotationConfigBeanBuilder.java index 431b130e705b..eb99855e72b2 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AbstractAnnotationConfigBeanBuilder.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AbstractAnnotationConfigBeanBuilder.java @@ -21,6 +21,7 @@ import org.apache.dubbo.config.ModuleConfig; import org.apache.dubbo.config.MonitorConfig; import org.apache.dubbo.config.RegistryConfig; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.context.ApplicationContext; diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/DubboConfigBindingBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/DubboConfigBindingBeanPostProcessor.java index a033596fe845..65aadeff359f 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/DubboConfigBindingBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/DubboConfigBindingBeanPostProcessor.java @@ -22,6 +22,7 @@ import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfigBinding; import org.apache.dubbo.config.spring.context.properties.DefaultDubboConfigBinder; import org.apache.dubbo.config.spring.context.properties.DubboConfigBinder; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeansException; @@ -75,7 +76,7 @@ public DubboConfigBindingBeanPostProcessor(String prefix, String beanName) { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { - if (beanName.equals(this.beanName) && bean instanceof AbstractConfig) { + if (beanName != null && beanName.equals(this.beanName) && bean instanceof AbstractConfig) { AbstractConfig dubboConfig = (AbstractConfig) bean; 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 f89378620ffa..e82239588c57 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java @@ -16,8 +16,11 @@ */ package org.apache.dubbo.config.spring.beans.factory.annotation; +import org.apache.dubbo.common.Constants; +import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.annotation.Reference; import org.apache.dubbo.config.spring.ReferenceBean; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeanUtils; @@ -35,15 +38,18 @@ import org.springframework.core.PriorityOrdered; import org.springframework.core.env.Environment; import org.springframework.util.ClassUtils; +import org.springframework.util.ConcurrentReferenceHashMap; +import org.springframework.util.ObjectUtils; import org.springframework.util.ReflectionUtils; -import org.springframework.util.StringUtils; import java.beans.PropertyDescriptor; +import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; +import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; @@ -83,6 +89,9 @@ public class ReferenceAnnotationBeanPostProcessor extends InstantiationAwareBean private final ConcurrentMap> referenceBeansCache = new ConcurrentHashMap>(); + private static final Map, List> annotationMethodsCache = + new ConcurrentReferenceHashMap, List>(256); + @Override public PropertyValues postProcessPropertyValues( PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeanCreationException { @@ -193,7 +202,7 @@ private ReferenceInjectionMetadata buildReferenceMetadata(final Class beanCla private InjectionMetadata findReferenceMetadata(String beanName, Class clazz, PropertyValues pvs) { // Fall back to class name as cache key, for backwards compatibility with custom callers. - String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName()); + String cacheKey = (StringUtils.isNotEmpty(beanName) ? beanName : clazz.getName()); // Quick check on the concurrent map first, with minimal locking. ReferenceInjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey); if (InjectionMetadata.needsRefresh(metadata, clazz)) { @@ -402,11 +411,7 @@ private ReferenceBean buildReferenceBean(Reference reference, Class refere */ private String generateReferenceBeanCacheKey(Reference reference, Class beanClass) { - String interfaceName = resolveInterfaceName(reference, beanClass); - - String key = reference.url() + "/" + interfaceName + - "/" + reference.version() + - "/" + reference.group(); + String key = resolveReferenceKey(annotationValues(reference)); Environment environment = applicationContext.getEnvironment(); @@ -501,5 +506,92 @@ private T getFieldValue(Object object, String fieldName, Class fieldType) } + /** + * Generate a key based on the annotation. + * + * @param annotations annotatoin value + * @return unique key, never null will be returned. + * @since 2.7.0 + */ + private String resolveReferenceKey(Map annotations) { + Iterator> annotationVisitor = annotations.entrySet().iterator(); + StringBuilder builder = new StringBuilder(); + while (annotationVisitor.hasNext()) { + Map.Entry attribute = annotationVisitor.next(); + String attributeValue = null; + if (attribute.getValue() instanceof String[]) { + attributeValue = toPlainString((String[]) attribute.getValue()); + } else { + attributeValue = attribute.getValue() == null ? "" : attribute.getValue().toString(); + } + if (StringUtils.isNotEmpty(attributeValue)) { + if (builder.length() > 0) { + builder.append(Constants.PATH_SEPARATOR); + } + builder.append(attributeValue); + } + } + return builder.toString(); + } + + private Map annotationValues(Annotation annotation) { + Map annotations = new LinkedHashMap<>(); + + for (Method method : getAnnotationMethods(annotation.annotationType())) { + try { + Object attributeValue = method.invoke(annotation); + Object defaultValue = method.getDefaultValue(); + if (nullSafeEquals(attributeValue, defaultValue)) { + continue; + } + annotations.put(method.getName(), attributeValue); + } catch (Throwable e) { + throw new IllegalStateException("Failed to obtain annotation attribute value for " + method, e); + } + } + return annotations; + } + + private static List getAnnotationMethods(Class annotationType) { + List methods = annotationMethodsCache.get(annotationType); + if (methods != null) { + return methods; + } + + methods = new ArrayList(); + for (Method method : annotationType.getDeclaredMethods()) { + if (isAnnotationMethod(method)) { + ReflectionUtils.makeAccessible(method); + methods.add(method); + } + } + + annotationMethodsCache.put(annotationType, methods); + return methods; + } + + private static boolean isAnnotationMethod(Method method) { + return (method != null + && method.getParameterTypes().length == 0 + && method.getReturnType() != void.class); + } + + private static boolean nullSafeEquals(Object first, Object another) { + return ObjectUtils.nullSafeEquals(first, another); + } + + private String toPlainString(String[] array) { + if (array == null || array.length == 0) { + return ""; + } + StringBuilder buffer = new StringBuilder(); + for (int i = 0; i < array.length; i++) { + if (i > 0) { + buffer.append(Constants.COMMA_SEPARATOR); + } + buffer.append(array[i]); + } + return buffer.toString(); + } } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceBeanBuilder.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceBeanBuilder.java index ec3f4e9e7edc..617b5f15ff90 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceBeanBuilder.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceBeanBuilder.java @@ -21,6 +21,7 @@ import org.apache.dubbo.config.spring.ReferenceBean; import org.apache.dubbo.config.spring.convert.converter.StringArrayToMapConverter; import org.apache.dubbo.config.spring.convert.converter.StringArrayToStringConverter; + import org.springframework.context.ApplicationContext; import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.support.DefaultConversionService; 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 389ef217367a..c08cc13e6a79 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 @@ -21,6 +21,7 @@ import org.apache.dubbo.config.annotation.Service; import org.apache.dubbo.config.spring.ServiceBean; import org.apache.dubbo.config.spring.context.annotation.DubboClassPathBeanDefinitionScanner; + import org.springframework.beans.BeansException; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.BeanClassLoaderAware; @@ -261,7 +262,7 @@ private void registerServiceBean(BeanDefinitionHolder beanDefinitionHolder, Bean if (scanner.checkCandidate(beanName, serviceBeanDefinition)) { // check duplicated candidate bean registry.registerBeanDefinition(beanName, serviceBeanDefinition); - if (logger.isInfoEnabled()) { + if (logger.isWarnEnabled()) { logger.warn("The BeanDefinition[" + serviceBeanDefinition + "] of ServiceBean has been registered with name : " + beanName); } @@ -386,7 +387,7 @@ 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", "interfaceName"); propertyValues.addPropertyValues(new AnnotationPropertyValuesAdapter(service, environment, ignoreAttributeNames)); diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScan.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScan.java index a947a02be572..82f16ecbb416 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScan.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScan.java @@ -18,6 +18,7 @@ import org.apache.dubbo.config.annotation.Reference; import org.apache.dubbo.config.annotation.Service; + import org.springframework.context.annotation.Import; import java.lang.annotation.Annotation; diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScanRegistrar.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScanRegistrar.java index 7fda60f5531f..6e14d56247a3 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScanRegistrar.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScanRegistrar.java @@ -20,6 +20,7 @@ import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor; import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationBeanPostProcessor; import org.apache.dubbo.config.spring.util.BeanRegistrar; + import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.AbstractBeanDefinition; diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigBindingRegistrar.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigBindingRegistrar.java index 2440f3446a6d..52ab0e67129f 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigBindingRegistrar.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigBindingRegistrar.java @@ -18,6 +18,7 @@ import org.apache.dubbo.config.AbstractConfig; import org.apache.dubbo.config.spring.beans.factory.annotation.DubboConfigBindingBeanPostProcessor; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.config.BeanDefinition; diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigBindingsRegistrar.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigBindingsRegistrar.java index 9472c1b76d6f..b420fe12ffbf 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigBindingsRegistrar.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigBindingsRegistrar.java @@ -17,6 +17,7 @@ package org.apache.dubbo.config.spring.context.annotation; import org.apache.dubbo.config.AbstractConfig; + import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfiguration.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfiguration.java index b3e98a597967..e9f39da986d2 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfiguration.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfiguration.java @@ -24,6 +24,7 @@ import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ProviderConfig; import org.apache.dubbo.config.RegistryConfig; + import org.springframework.context.annotation.Configuration; /** diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfigurationSelector.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfigurationSelector.java index a5e97b26a232..639ad971b4da 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfigurationSelector.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfigurationSelector.java @@ -17,6 +17,7 @@ package org.apache.dubbo.config.spring.context.annotation; import org.apache.dubbo.config.AbstractConfig; + import org.springframework.context.annotation.ImportSelector; import org.springframework.core.Ordered; import org.springframework.core.annotation.AnnotationAttributes; diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubbo.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubbo.java index 0ce6e27159a4..4535f188e4cd 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubbo.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubbo.java @@ -17,6 +17,7 @@ package org.apache.dubbo.config.spring.context.annotation; import org.apache.dubbo.config.AbstractConfig; + import org.springframework.core.annotation.AliasFor; import java.lang.annotation.Documented; diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfig.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfig.java index 710ed796a1f2..889e39078b06 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfig.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfig.java @@ -23,6 +23,7 @@ import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ProviderConfig; import org.apache.dubbo.config.RegistryConfig; + import org.springframework.context.annotation.Import; import java.lang.annotation.Documented; diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfigBinding.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfigBinding.java index 7bc7008d6a2a..8b50f367286d 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfigBinding.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfigBinding.java @@ -21,6 +21,7 @@ import org.apache.dubbo.config.ModuleConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.spring.beans.factory.annotation.DubboConfigBindingBeanPostProcessor; + import org.springframework.context.annotation.Import; import org.springframework.core.env.PropertySources; diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/properties/DefaultDubboConfigBinder.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/properties/DefaultDubboConfigBinder.java index 670c49e5bc90..e1d44da8f7f2 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/properties/DefaultDubboConfigBinder.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/properties/DefaultDubboConfigBinder.java @@ -17,6 +17,7 @@ package org.apache.dubbo.config.spring.context.properties; import org.apache.dubbo.config.AbstractConfig; + import org.springframework.beans.MutablePropertyValues; import org.springframework.validation.DataBinder; diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/properties/DubboConfigBinder.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/properties/DubboConfigBinder.java index a0052ff95c0e..00d713fac610 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/properties/DubboConfigBinder.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/properties/DubboConfigBinder.java @@ -17,6 +17,7 @@ package org.apache.dubbo.config.spring.context.properties; import org.apache.dubbo.config.AbstractConfig; + import org.springframework.context.EnvironmentAware; /** diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/convert/converter/StringArrayToMapConverter.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/convert/converter/StringArrayToMapConverter.java index b7739d11c454..a2e4790919b5 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/convert/converter/StringArrayToMapConverter.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/convert/converter/StringArrayToMapConverter.java @@ -17,6 +17,7 @@ package org.apache.dubbo.config.spring.convert.converter; import org.apache.dubbo.common.utils.CollectionUtils; + import org.springframework.core.convert.converter.Converter; import org.springframework.util.ObjectUtils; 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 56862f33b4ad..99b538c25e0c 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 @@ -16,15 +16,22 @@ */ package org.apache.dubbo.config.spring.extension; -import java.util.Set; import org.apache.dubbo.common.extension.ExtensionFactory; import org.apache.dubbo.common.extension.SPI; 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.config.DubboShutdownHook; +import org.apache.dubbo.config.spring.util.BeanFactoryUtils; + import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.NoUniqueBeanDefinitionException; import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationEvent; +import org.springframework.context.ApplicationListener; +import org.springframework.context.event.ContextClosedEvent; + +import java.util.Set; /** * SpringExtensionFactory @@ -33,9 +40,11 @@ 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(); public static void addApplicationContext(ApplicationContext context) { contexts.add(context); + BeanFactoryUtils.addApplicationListener(context, shutdownHookListener); } public static void removeApplicationContext(ApplicationContext context) { @@ -69,13 +78,17 @@ public T getExtension(Class type, String name) { } } - logger.warn("No spring extension(bean) named:" + name + ", try to find an extension(bean) of type " + type.getName()); + logger.warn("No spring extension (bean) named:" + name + ", try to find an extension (bean) of type " + type.getName()); + + if (Object.class == type) { + return null; + } for (ApplicationContext context : contexts) { try { return context.getBean(type); } catch (NoUniqueBeanDefinitionException multiBeanExe) { - throw multiBeanExe; + logger.warn("Find more than 1 spring extensions (beans) of type " + type.getName() + ", will stop auto injection. Please make sure you have specified the concrete parameter type and there's only one extension of that type."); } catch (NoSuchBeanDefinitionException noBeanExe) { if (logger.isDebugEnabled()) { logger.debug("Error when get spring extension(bean) for type:" + type.getName(), noBeanExe); @@ -83,9 +96,21 @@ public T getExtension(Class type, String name) { } } - logger.warn("No spring extension(bean) named:" + name + ", type:" + type.getName() + " found, stop get bean."); + logger.warn("No spring extension (bean) named:" + name + ", type:" + type.getName() + " found, stop get bean."); return null; } + private static class ShutdownHookListener implements ApplicationListener { + @Override + public void onApplicationEvent(ApplicationEvent event) { + if (event instanceof ContextClosedEvent) { + // we call it anyway since dubbo shutdown hook make sure its destroyAll() is re-entrant. + // pls. note we should not remove dubbo shutdown hook when spring framework is present, this is because + // its shutdown hook may not be installed. + DubboShutdownHook shutdownHook = DubboShutdownHook.getDubboShutdownHook(); + shutdownHook.destroyAll(); + } + } + } } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/initializer/DubboApplicationContextInitializer.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/initializer/DubboApplicationContextInitializer.java deleted file mode 100644 index 36727e669f4c..000000000000 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/initializer/DubboApplicationContextInitializer.java +++ /dev/null @@ -1,39 +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.initializer; - -import org.springframework.context.ApplicationContextInitializer; -import org.springframework.context.ConfigurableApplicationContext; - -/** - * Automatically register {@link DubboApplicationListener} to Spring context - * A {@link org.springframework.web.context.ContextLoaderListener} class is defined in - * src/main/resources/META-INF/web-fragment.xml - * In the web-fragment.xml, {@link DubboApplicationContextInitializer} is defined in context params. - * This file will be discovered if running under a servlet 3.0+ container. - * Even if user specifies {@link org.springframework.web.context.ContextLoaderListener} in web.xml, - * it will be merged to web.xml. - * If user specifies in web.xml, this will no take effect, - * unless user configures {@link DubboApplicationContextInitializer} explicitly in web.xml. - */ -public class DubboApplicationContextInitializer implements ApplicationContextInitializer { - - @Override - public void initialize(ConfigurableApplicationContext applicationContext) { - applicationContext.addApplicationListener(new DubboApplicationListener()); - } -} diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/initializer/DubboApplicationListener.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/initializer/DubboApplicationListener.java deleted file mode 100644 index 8b6409bd65f9..000000000000 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/initializer/DubboApplicationListener.java +++ /dev/null @@ -1,49 +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.initializer; - -import org.apache.dubbo.bootstrap.DubboBootstrap; -import org.springframework.context.ApplicationEvent; -import org.springframework.context.ApplicationListener; -import org.springframework.context.event.ContextClosedEvent; -import org.springframework.context.event.ContextRefreshedEvent; - -/** - * An application listener that listens the ContextClosedEvent. - * Upon the event, this listener will do the necessary clean up to avoid memory leak. - */ -public class DubboApplicationListener implements ApplicationListener { - - private DubboBootstrap dubboBootstrap; - - public DubboApplicationListener() { - dubboBootstrap = new DubboBootstrap(false); - } - - public DubboApplicationListener(DubboBootstrap dubboBootstrap) { - this.dubboBootstrap = dubboBootstrap; - } - - @Override - public void onApplicationEvent(ApplicationEvent applicationEvent) { - if (applicationEvent instanceof ContextRefreshedEvent) { - dubboBootstrap.start(); - } else if (applicationEvent instanceof ContextClosedEvent) { - dubboBootstrap.stop(); - } - } -} diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/AnnotationBeanDefinitionParser.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/AnnotationBeanDefinitionParser.java index 833f816cd413..918c916f3c83 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/AnnotationBeanDefinitionParser.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/AnnotationBeanDefinitionParser.java @@ -20,6 +20,7 @@ import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor; import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationBeanPostProcessor; import org.apache.dubbo.config.spring.util.BeanRegistrar; + import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; 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 e38d1afeae2e..73c1819af3dc 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 @@ -135,7 +135,8 @@ private static BeanDefinition parse(Element element, ParserContext parserContext && Modifier.isPublic(setter.getModifiers()) && setter.getParameterTypes().length == 1) { Class type = setter.getParameterTypes()[0]; - String property = StringUtils.camelToSplitName(name.substring(3, 4).toLowerCase() + name.substring(4), "-"); + String propertyName = name.substring(3, 4).toLowerCase() + name.substring(4); + String property = StringUtils.camelToSplitName(propertyName, "-"); props.add(property); Method getter = null; try { @@ -223,7 +224,7 @@ private static BeanDefinition parse(Element element, ParserContext parserContext } reference = new RuntimeBeanReference(value); } - beanDefinition.getPropertyValues().addPropertyValue(property, reference); + beanDefinition.getPropertyValues().addPropertyValue(propertyName, reference); } } } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/DubboNamespaceHandler.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/DubboNamespaceHandler.java index 9f16c39cfaec..035c3f925ce8 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/DubboNamespaceHandler.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/DubboNamespaceHandler.java @@ -26,6 +26,7 @@ import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.spring.ReferenceBean; import org.apache.dubbo.config.spring.ServiceBean; + import org.springframework.beans.factory.xml.NamespaceHandlerSupport; /** diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/status/DataSourceStatusChecker.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/status/DataSourceStatusChecker.java index 5a934bed1f4b..5f268065b43f 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/status/DataSourceStatusChecker.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/status/DataSourceStatusChecker.java @@ -22,6 +22,7 @@ import org.apache.dubbo.common.status.Status; import org.apache.dubbo.common.status.StatusChecker; import org.apache.dubbo.config.spring.extension.SpringExtensionFactory; + import org.springframework.context.ApplicationContext; import javax.sql.DataSource; 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 8f4fb6525be3..9a99ec138fd7 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 @@ -22,6 +22,7 @@ import org.apache.dubbo.common.status.Status; import org.apache.dubbo.common.status.StatusChecker; import org.apache.dubbo.config.spring.extension.SpringExtensionFactory; + import org.springframework.context.ApplicationContext; import org.springframework.context.Lifecycle; diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/BeanFactoryUtils.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/BeanFactoryUtils.java index e78739917dc5..e519cdee280f 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/BeanFactoryUtils.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/BeanFactoryUtils.java @@ -17,10 +17,15 @@ package org.apache.dubbo.config.spring.util; import org.apache.dubbo.common.utils.StringUtils; + import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationListener; +import org.springframework.context.support.AbstractApplicationContext; +import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -89,4 +94,27 @@ public static List getBeans(ListableBeanFactory beanFactory, String[] bea } + public static boolean addApplicationListener(ApplicationContext applicationContext, ApplicationListener listener) { + try { + // backward compatibility to spring 2.0.1 + Method method = applicationContext.getClass().getMethod("addApplicationListener", ApplicationListener.class); + method.invoke(applicationContext, listener); + return true; + } catch (Throwable t) { + if (applicationContext instanceof AbstractApplicationContext) { + try { + // backward compatibility to spring 2.0.1 + Method method = AbstractApplicationContext.class.getDeclaredMethod("addListener", ApplicationListener.class); + if (!method.isAccessible()) { + method.setAccessible(true); + } + method.invoke(applicationContext, listener); + return true; + } catch (Throwable t2) { + // ignore + } + } + } + return false; + } } 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 92d7bd27056c..902bae8fb1b6 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 @@ -101,6 +101,11 @@ + + + + + @@ -492,6 +497,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 88fe25fccb1f..9b21ba247d60 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 @@ -101,6 +101,11 @@ + + + + + @@ -486,6 +491,11 @@ + + + + + diff --git a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/web-fragment.xml b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/web-fragment.xml deleted file mode 100644 index c063bdf2f37a..000000000000 --- a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/web-fragment.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - dubbo_fragment - - - - - - - - - contextInitializerClasses - org.apache.dubbo.config.spring.initializer.DubboApplicationContextInitializer - - - - org.springframework.web.context.ContextLoaderListener - - - \ No newline at end of file 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 ca9cc94b6c87..d68a29529686 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 @@ -33,6 +33,7 @@ import org.apache.dubbo.config.spring.annotation.consumer.AnnotationAction; import org.apache.dubbo.config.spring.api.DemoService; import org.apache.dubbo.config.spring.api.HelloService; +import org.apache.dubbo.config.spring.context.annotation.provider.ProviderConfiguration; import org.apache.dubbo.config.spring.filter.MockFilter; import org.apache.dubbo.config.spring.impl.DemoServiceImpl; import org.apache.dubbo.config.spring.impl.HelloServiceImpl; @@ -50,6 +51,7 @@ import org.junit.Ignore; import org.junit.Test; import org.springframework.beans.factory.BeanCreationException; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.Collection; @@ -105,6 +107,23 @@ public void testServiceClass() { } } + @Test + public void testServiceAnnotation() { + AnnotationConfigApplicationContext providerContext = new AnnotationConfigApplicationContext(); + providerContext.register(ProviderConfiguration.class); + + providerContext.refresh(); + + ReferenceConfig reference = new ReferenceConfig(); + reference.setApplication(new ApplicationConfig("consumer")); + reference.setRegistry(new RegistryConfig(RegistryConfig.NO_AVAILABLE)); + reference.setInterface(HelloService.class); + reference.setUrl("dubbo://127.0.0.1:12345"); + String hello = reference.get().sayHello("hello"); + assertEquals("Hello, hello", hello); + + } + @Test @SuppressWarnings("unchecked") public void testProviderNestedService() { @@ -147,6 +166,20 @@ public void testToString() { assertTrue(str.endsWith(" />")); } + @Test + public void testForks() { + ReferenceConfig reference = new ReferenceConfig(); + reference.setApplication(new ApplicationConfig("consumer")); + reference.setRegistry(new RegistryConfig(RegistryConfig.NO_AVAILABLE)); + reference.setInterface(DemoService.class); + reference.setUrl("dubbo://127.0.0.1:20881"); + + int forks = 10; + reference.setForks(forks); + String str = reference.toString(); + assertTrue(str.contains("forks=\"" + forks + "\"")); + } + @Test public void testMultiProtocol() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(ConfigTest.class.getPackage().getName().replace('.', '/') + "/multi-protocol.xml"); diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java index e45b0255632e..959bfa6531f4 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java @@ -106,7 +106,12 @@ public void testGetReferenceBeans() { Collection> referenceBeans = beanPostProcessor.getReferenceBeans(); - Assert.assertEquals(1, referenceBeans.size()); + /** + * 1 -> demoService、demoServiceShouldBeSame + * 1 -> demoServiceShouldNotBeSame + * 1 -> demoServiceWithArray、demoServiceWithArrayShouldBeSame + */ + Assert.assertEquals(3, referenceBeans.size()); ReferenceBean referenceBean = referenceBeans.iterator().next(); @@ -130,7 +135,10 @@ public void testGetInjectedFieldReferenceBeanMap() { Map> referenceBeanMap = beanPostProcessor.getInjectedFieldReferenceBeanMap(); - Assert.assertEquals(1, referenceBeanMap.size()); + /** + * contains 5 fields. + */ + Assert.assertEquals(5, referenceBeanMap.size()); for (Map.Entry> entry : referenceBeanMap.entrySet()) { @@ -197,6 +205,49 @@ public void testModuleInfo() { } } + @Test + public void testReferenceCache() throws Exception { + + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestBean.class); + + TestBean testBean = context.getBean(TestBean.class); + + Assert.assertNotNull(testBean.getDemoServiceFromAncestor()); + Assert.assertNotNull(testBean.getDemoServiceFromParent()); + Assert.assertNotNull(testBean.getDemoService()); + + Assert.assertEquals(testBean.getDemoServiceFromAncestor(), testBean.getDemoServiceFromParent()); + Assert.assertEquals(testBean.getDemoService(), testBean.getDemoServiceFromParent()); + + DemoService demoService = testBean.getDemoService(); + + Assert.assertEquals(demoService, testBean.getDemoServiceShouldBeSame()); + Assert.assertNotEquals(demoService, testBean.getDemoServiceShouldNotBeSame()); + + context.close(); + + } + + @Test + public void testReferenceCacheWithArray() throws Exception { + + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestBean.class); + + TestBean testBean = context.getBean(TestBean.class); + + Assert.assertNotNull(testBean.getDemoServiceFromAncestor()); + Assert.assertNotNull(testBean.getDemoServiceFromParent()); + Assert.assertNotNull(testBean.getDemoService()); + + Assert.assertEquals(testBean.getDemoServiceFromAncestor(), testBean.getDemoServiceFromParent()); + Assert.assertEquals(testBean.getDemoService(), testBean.getDemoServiceFromParent()); + + Assert.assertEquals(testBean.getDemoServiceWithArray(), testBean.getDemoServiceWithArrayShouldBeSame()); + + context.close(); + + } + private static class AncestorBean { @@ -239,6 +290,19 @@ static class TestBean extends ParentBean { private DemoService demoService; + @Reference(version = "1.2", url = "dubbo://127.0.0.1:12345") + private DemoService demoServiceShouldBeSame; + + @Reference(version = "1.2", url = "dubbo://127.0.0.1:12345", async = true) + private DemoService demoServiceShouldNotBeSame; + + + @Reference(version = "1.2", url = "dubbo://127.0.0.1:12345", parameters = { "key1", "value1"}) + private DemoService demoServiceWithArray; + + @Reference(version = "1.2", url = "dubbo://127.0.0.1:12345", parameters = { "key1", "value1"}) + private DemoService demoServiceWithArrayShouldBeSame; + @Autowired private ApplicationContext applicationContext; @@ -250,6 +314,22 @@ public DemoService getDemoService() { public void setDemoService(DemoService demoService) { this.demoService = demoService; } + + public DemoService getDemoServiceShouldNotBeSame() { + return demoServiceShouldNotBeSame; + } + + public DemoService getDemoServiceShouldBeSame() { + return demoServiceShouldBeSame; + } + + public DemoService getDemoServiceWithArray() { + return demoServiceWithArray; + } + + public DemoService getDemoServiceWithArrayShouldBeSame() { + return demoServiceWithArrayShouldBeSame; + } } } \ No newline at end of file diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/HelloServiceImpl.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/HelloServiceImpl.java index 1c4b405a90a9..982e52a3f73e 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/HelloServiceImpl.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/HelloServiceImpl.java @@ -24,7 +24,7 @@ * * @since 2.5.9 */ -@Service +@Service(interfaceName = "org.apache.dubbo.config.spring.api.HelloService") public class HelloServiceImpl implements HelloService { @Override diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/initializer/DubboApplicationContextInitializerTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/initializer/DubboApplicationContextInitializerTest.java deleted file mode 100644 index b5b8f8c9a9b2..000000000000 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/initializer/DubboApplicationContextInitializerTest.java +++ /dev/null @@ -1,87 +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.initializer; - -import org.apache.catalina.core.StandardContext; -import org.apache.catalina.startup.ContextConfig; -import org.apache.catalina.startup.Tomcat; -import org.junit.Assert; -import org.junit.Test; -import org.springframework.web.context.ContextLoaderListener; - - -public class DubboApplicationContextInitializerTest { - - @Test - public void testSpringContextLoaderListenerInWebXml() throws Exception { - Tomcat tomcat = new Tomcat(); - tomcat.setBaseDir("target/test-classes"); - tomcat.setPort(12345); - StandardContext context = new StandardContext(); - context.setName("test"); - context.setDocBase("test"); - context.setPath("/test"); - context.addLifecycleListener(new ContextConfig()); - tomcat.getHost().addChild(context); - tomcat.start(); - // there should be 1 application listener - Assert.assertEquals(1, context.getApplicationLifecycleListeners().length); - // the first one should be Spring's built in ContextLoaderListener. - Assert.assertTrue(context.getApplicationLifecycleListeners()[0] instanceof ContextLoaderListener); - tomcat.stop(); - tomcat.destroy(); - } - - @Test - public void testNoListenerInWebXml() throws Exception { - Tomcat tomcat = new Tomcat(); - tomcat.setBaseDir("target/test-classes"); - tomcat.setPort(12345); - StandardContext context = new StandardContext(); - context.setName("test2"); - context.setDocBase("test2"); - context.setPath("/test2"); - context.addLifecycleListener(new ContextConfig()); - tomcat.getHost().addChild(context); - tomcat.start(); - // there should be 1 application listener - Assert.assertEquals(1, context.getApplicationLifecycleListeners().length); - // the first one should be Spring's built in ContextLoaderListener. - Assert.assertTrue(context.getApplicationLifecycleListeners()[0] instanceof ContextLoaderListener); - tomcat.stop(); - tomcat.destroy(); - } - - @Test - public void testMetadataComplete() throws Exception { - Tomcat tomcat = new Tomcat(); - tomcat.setBaseDir("target/test-classes"); - tomcat.setPort(12345); - StandardContext context = new StandardContext(); - context.setName("test3"); - context.setDocBase("test3"); - context.setPath("/test3"); - context.addLifecycleListener(new ContextConfig()); - tomcat.getHost().addChild(context); - tomcat.start(); - // there should be no application listeners - Assert.assertEquals(0, context.getApplicationLifecycleListeners().length); - tomcat.stop(); - tomcat.destroy(); - } - -} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/initializer/DubboApplicationListenerTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/initializer/DubboApplicationListenerTest.java deleted file mode 100644 index 9b953d5ba701..000000000000 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/initializer/DubboApplicationListenerTest.java +++ /dev/null @@ -1,59 +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.initializer; - -import org.apache.dubbo.config.DubboShutdownHook; -import org.apache.dubbo.bootstrap.DubboBootstrap; -import org.junit.Test; -import org.mockito.Mockito; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -public class DubboApplicationListenerTest { - - @Test - public void testTwoShutdownHook() { - DubboShutdownHook spyHook = Mockito.spy(DubboShutdownHook.getDubboShutdownHook()); - ClassPathXmlApplicationContext applicationContext = getApplicationContext(spyHook, true); - applicationContext.refresh(); - applicationContext.close(); - // shutdown hook can't be verified, because it will executed after main thread has finished. - // so we can only verify it by manually run it. - try { - spyHook.start(); - spyHook.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - Mockito.verify(spyHook, Mockito.times(2)).destroyAll(); - } - - @Test - public void testOneShutdownHook() { - DubboShutdownHook spyHook = Mockito.spy(DubboShutdownHook.getDubboShutdownHook()); - ClassPathXmlApplicationContext applicationContext = getApplicationContext(spyHook, false); - applicationContext.refresh(); - applicationContext.close(); - Mockito.verify(spyHook, Mockito.times(1)).destroyAll(); - } - - private ClassPathXmlApplicationContext getApplicationContext(DubboShutdownHook hook, boolean registerHook) { - DubboBootstrap bootstrap = new DubboBootstrap(registerHook, hook); - ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(); - applicationContext.addApplicationListener(new DubboApplicationListener(bootstrap)); - return applicationContext; - } -} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/status/DataSourceStatusCheckerTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/status/DataSourceStatusCheckerTest.java index 532d97b5473f..c82fd4af6156 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/status/DataSourceStatusCheckerTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/status/DataSourceStatusCheckerTest.java @@ -49,6 +49,7 @@ public class DataSourceStatusCheckerTest { @Before public void setUp() throws Exception { + SpringExtensionFactory.clearContexts(); initMocks(this); this.dataSourceStatusChecker = new DataSourceStatusChecker(); new ServiceBean().setApplicationContext(applicationContext); @@ -56,7 +57,6 @@ public void setUp() throws Exception { @After public void tearDown() throws Exception { - SpringExtensionFactory.clearContexts(); Mockito.reset(applicationContext); } diff --git a/dubbo-container/dubbo-container-spring/pom.xml b/dubbo-container/dubbo-container-spring/pom.xml index cbcc43e51158..987b2c9d2e61 100644 --- a/dubbo-container/dubbo-container-spring/pom.xml +++ b/dubbo-container/dubbo-container-spring/pom.xml @@ -38,10 +38,5 @@ org.springframework spring-context - - org.apache.dubbo - dubbo-config-spring - ${project.parent.version} - - \ No newline at end of file + diff --git a/dubbo-container/dubbo-container-spring/src/main/java/org/apache/dubbo/container/spring/SpringContainer.java b/dubbo-container/dubbo-container-spring/src/main/java/org/apache/dubbo/container/spring/SpringContainer.java index 9aa9ca5c83cd..c6ec47467312 100644 --- a/dubbo-container/dubbo-container-spring/src/main/java/org/apache/dubbo/container/spring/SpringContainer.java +++ b/dubbo-container/dubbo-container-spring/src/main/java/org/apache/dubbo/container/spring/SpringContainer.java @@ -19,7 +19,6 @@ 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.config.spring.initializer.DubboApplicationListener; import org.apache.dubbo.container.Container; import org.springframework.context.support.ClassPathXmlApplicationContext; @@ -44,10 +43,7 @@ public void start() { if (configPath == null || configPath.length() == 0) { configPath = DEFAULT_SPRING_CONFIG; } - context = new ClassPathXmlApplicationContext(configPath.split("[,\\s]+"), false); - context.addApplicationListener(new DubboApplicationListener()); - context.registerShutdownHook(); - context.refresh(); + context = new ClassPathXmlApplicationContext(configPath.split("[,\\s]+")); context.start(); } diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/java/org/apache/dubbo/demo/consumer/Consumer.java b/dubbo-demo/dubbo-demo-consumer/src/main/java/org/apache/dubbo/demo/consumer/Consumer.java index 8ad330e97831..dd2f58519494 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/java/org/apache/dubbo/demo/consumer/Consumer.java +++ b/dubbo-demo/dubbo-demo-consumer/src/main/java/org/apache/dubbo/demo/consumer/Consumer.java @@ -17,6 +17,7 @@ package org.apache.dubbo.demo.consumer; import org.apache.dubbo.demo.DemoService; + import org.springframework.context.support.ClassPathXmlApplicationContext; public class Consumer { diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml index a56a10ee7ea0..b4c1197477de 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml +++ b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml @@ -32,4 +32,4 @@ local regular interface --> - \ No newline at end of file + diff --git a/dubbo-dependencies-bom/pom.xml b/dubbo-dependencies-bom/pom.xml index 8a0738e62608..c95f748a7f26 100644 --- a/dubbo-dependencies-bom/pom.xml +++ b/dubbo-dependencies-bom/pom.xml @@ -98,6 +98,7 @@ 4.0.1 0.42 2.48-jdk-6 + 1.5.9 2.0 3.0.19.Final @@ -160,7 +161,7 @@ org.apache.httpcomponents httpcore - ${httpcore_version} + ${httpcore_version} com.alibaba @@ -267,6 +268,16 @@ fst ${fst_version} + + io.protostuff + protostuff-core + ${protostuff_version} + + + io.protostuff + protostuff-runtime + ${protostuff_version} + javax.ws.rs javax.ws.rs-api @@ -428,4 +439,4 @@ - \ No newline at end of file + diff --git a/dubbo-distribution/pom.xml b/dubbo-distribution/pom.xml index d8d53ecf2e30..c5c6f0a2af63 100644 --- a/dubbo-distribution/pom.xml +++ b/dubbo-distribution/pom.xml @@ -237,17 +237,17 @@ org.apache.dubbo - dubbo + dubbo-serialization-protostuff ${project.version} org.apache.dubbo - dubbo-compatible + dubbo ${project.version} org.apache.dubbo - dubbo-bootstrap + dubbo-compatible ${project.version} @@ -309,4 +309,4 @@ - \ No newline at end of file + 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 62a739d1866d..ee6282659aa7 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 @@ -16,8 +16,6 @@ */ package org.apache.dubbo.cache.filter; -import java.io.Serializable; - import org.apache.dubbo.cache.Cache; import org.apache.dubbo.cache.CacheFactory; import org.apache.dubbo.common.Constants; @@ -31,6 +29,8 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcResult; +import java.io.Serializable; + /** * CacheFilter */ 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 c3cb373bc0db..381a43ada87c 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 @@ -16,9 +16,9 @@ */ package org.apache.dubbo.cache.support.expiring; +import java.util.ArrayList; import java.util.Collection; import java.util.List; -import java.util.ArrayList; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; diff --git a/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/jcache/JCacheFactoryTest.java b/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/jcache/JCacheFactoryTest.java index bd701bd60ce0..6dbd15d6f785 100644 --- a/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/jcache/JCacheFactoryTest.java +++ b/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/jcache/JCacheFactoryTest.java @@ -38,7 +38,7 @@ public void testJCacheFactory() throws Exception { @Test public void testJCacheGetExpired() throws Exception { - URL url = URL.valueOf("test://test:11/test?cache=jacache&.cache.write.expire=1"); + URL url = URL.valueOf("test://test:12/test?cache=jacache&.cache.write.expire=1"); AbstractCacheFactory cacheFactory = getCacheFactory(); Invocation invocation = new RpcInvocation(); Cache cache = cacheFactory.getCache(url, invocation); diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/MetricRegistry.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/MetricRegistry.java index abb467a3195b..567ee4aa7335 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/MetricRegistry.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/MetricRegistry.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metrics; - import java.util.Map; import java.util.Set; 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 5c83ab060561..6c2fbaed91e1 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 @@ -75,13 +75,10 @@ public Invoker refer(Class type, URL url) throws RpcException { @Override public void destroy() { protocol.destroy(); + stopServer(); } private void startQosServer(URL url) { - if (!hasStarted.compareAndSet(false, true)) { - return; - } - try { boolean qosEnable = url.getParameter(QOS_ENABLE,true); if (!qosEnable) { @@ -91,6 +88,10 @@ private void startQosServer(URL url) { return; } + if (!hasStarted.compareAndSet(false, true)) { + return; + } + int port = url.getParameter(QOS_PORT, QosConstants.DEFAULT_PORT); boolean acceptForeignIp = Boolean.parseBoolean(url.getParameter(ACCEPT_FOREIGN_IP,"false")); Server server = Server.getInstance(); diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/Server.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/Server.java index 4051698e0616..b39221dcbf8c 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/Server.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/Server.java @@ -19,6 +19,7 @@ import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.qos.server.handler.QosProcessHandler; + import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/HttpProcessHandler.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/HttpProcessHandler.java index b7fea07aca95..9a36c9758c02 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/HttpProcessHandler.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/HttpProcessHandler.java @@ -23,6 +23,7 @@ import org.apache.dubbo.qos.command.DefaultCommandExecutor; import org.apache.dubbo.qos.command.NoSuchCommandException; import org.apache.dubbo.qos.command.decoder.HttpCommandDecoder; + import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/LocalHostPermitHandler.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/LocalHostPermitHandler.java index 2194b728e062..d93284ae7fb6 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/LocalHostPermitHandler.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/LocalHostPermitHandler.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.qos.server.handler; - import org.apache.dubbo.qos.common.QosConstants; import io.netty.buffer.ByteBuf; diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/TelnetProcessHandler.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/TelnetProcessHandler.java index f1c02094a11b..2faffa04e734 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/TelnetProcessHandler.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/TelnetProcessHandler.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.qos.server.handler; - import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTable.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTable.java index 74372e5c5704..9469f1e6a3ad 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTable.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTable.java @@ -21,13 +21,13 @@ import java.util.List; import java.util.Scanner; +import static java.lang.Math.abs; +import static java.lang.Math.max; +import static java.lang.String.format; import static org.apache.dubbo.common.utils.StringUtils.EMPTY; import static org.apache.dubbo.common.utils.StringUtils.length; import static org.apache.dubbo.common.utils.StringUtils.repeat; import static org.apache.dubbo.common.utils.StringUtils.replace; -import static java.lang.Math.abs; -import static java.lang.Math.max; -import static java.lang.String.format; /** * Table diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTree.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTree.java index 70e14e9588bf..351f87642621 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTree.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTree.java @@ -21,10 +21,10 @@ import java.util.List; import java.util.Scanner; +import static java.lang.System.currentTimeMillis; import static org.apache.dubbo.common.utils.StringUtils.EMPTY; import static org.apache.dubbo.common.utils.StringUtils.length; import static org.apache.dubbo.common.utils.StringUtils.repeat; -import static java.lang.System.currentTimeMillis; /** * tree 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 3a79cac5e2b7..051c29e33c1c 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 @@ -48,7 +48,6 @@ import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; @@ -594,12 +593,6 @@ public List> doList(Invocation invocation) { if (invokers == null) { invokers = localMethodInvokerMap.get(Constants.ANY_VALUE); } - if (invokers == null) { - Iterator>> iterator = localMethodInvokerMap.values().iterator(); - if (iterator.hasNext()) { - invokers = iterator.next(); - } - } } return invokers == null ? new ArrayList>(0) : invokers; } 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 8347d9a687fa..64647f4ba60d 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 @@ -26,8 +26,8 @@ import java.util.Collection; import java.util.Collections; +import java.util.HashMap; import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; /** @@ -44,7 +44,7 @@ public abstract class AbstractRegistryFactory implements RegistryFactory { private static final ReentrantLock LOCK = new ReentrantLock(); // Registry Collection Map - private static final Map REGISTRIES = new ConcurrentHashMap(); + private static final Map REGISTRIES = new HashMap<>(); /** * Get all registries 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 5e50c3114741..7f3ac3a6be0b 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 @@ -21,6 +21,7 @@ import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.registry.NotifyListener; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -180,6 +181,28 @@ public void notify(List urls) { assertEquals(2, count.get()); } + @Test + public void testRecover() throws Exception { + CountDownLatch countDownLatch = new CountDownLatch(4); + final AtomicReference notified = new AtomicReference(false); + NotifyListener listener = new NotifyListener() { + @Override + public void notify(List urls) { + notified.set(Boolean.TRUE); + } + }; + + MockRegistry mockRegistry = new MockRegistry(registryUrl, countDownLatch); + mockRegistry.register(serviceUrl); + mockRegistry.subscribe(serviceUrl, listener); + Assert.assertEquals(1, mockRegistry.getRegistered().size()); + Assert.assertEquals(1, mockRegistry.getSubscribed().size()); + mockRegistry.recover(); + countDownLatch.await(); + Assert.assertEquals(0, mockRegistry.getFailedRegistered().size()); + Assert.assertEquals(null, mockRegistry.getFailedSubscribed().get(registryUrl)); + Assert.assertEquals(countDownLatch.getCount(), 0); + } private static class MockRegistry extends FailbackRegistry { CountDownLatch latch; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/codec/ExchangeCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/codec/ExchangeCodec.java index 4b18cad95dd9..4031688e04e0 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/codec/ExchangeCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/codec/ExchangeCodec.java @@ -139,8 +139,6 @@ protected Object decode(Channel channel, ChannelBuffer buffer, int readable, byt protected Object decodeBody(Channel channel, InputStream is, byte[] header) throws IOException { byte flag = header[2], proto = (byte) (flag & SERIALIZATION_MASK); - Serialization s = CodecSupport.getSerialization(channel.getUrl(), proto); - ObjectInput in = s.deserialize(channel.getUrl(), is); // get request id. long id = Bytes.bytes2long(header, 4); if ((flag & FLAG_REQUEST) == 0) { @@ -152,8 +150,9 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro // get status. byte status = header[3]; res.setStatus(status); - if (status == Response.OK) { - try { + try { + ObjectInput in = CodecSupport.deserialize(channel.getUrl(), is, proto); + if (status == Response.OK) { Object data; if (res.isHeartbeat()) { data = decodeHeartbeatData(channel, in); @@ -163,12 +162,12 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro data = decodeResponseData(channel, in, getRequestData(id)); } res.setResult(data); - } catch (Throwable t) { - res.setStatus(Response.CLIENT_ERROR); - res.setErrorMessage(StringUtils.toString(t)); + } else { + res.setErrorMessage(in.readUTF()); } - } else { - res.setErrorMessage(in.readUTF()); + } catch (Throwable t) { + res.setStatus(Response.CLIENT_ERROR); + res.setErrorMessage(StringUtils.toString(t)); } return res; } else { @@ -180,6 +179,7 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro req.setEvent(Request.HEARTBEAT_EVENT); } try { + ObjectInput in = CodecSupport.deserialize(channel.getUrl(), is, proto); Object data; if (req.isHeartbeat()) { data = decodeHeartbeatData(channel, in); @@ -200,11 +200,13 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro protected Object getRequestData(long id) { DefaultFuture future = DefaultFuture.getFuture(id); - if (future == null) + if (future == null) { return null; + } Request req = future.getRequest(); - if (req == null) + if (req == null) { return null; + } return req.getData(); } @@ -218,8 +220,12 @@ protected void encodeRequest(Channel channel, ChannelBuffer buffer, Request req) // set request and serialization flag. header[2] = (byte) (FLAG_REQUEST | serialization.getContentTypeId()); - if (req.isTwoWay()) header[2] |= FLAG_TWOWAY; - if (req.isEvent()) header[2] |= FLAG_EVENT; + if (req.isTwoWay()) { + header[2] |= FLAG_TWOWAY; + } + if (req.isEvent()) { + header[2] |= FLAG_EVENT; + } // set request id. Bytes.long2bytes(req.getId(), header, 4); @@ -260,7 +266,9 @@ protected void encodeResponse(Channel channel, ChannelBuffer buffer, Response re Bytes.short2bytes(MAGIC, header); // set request and serialization flag. header[2] = serialization.getContentTypeId(); - if (res.isHeartbeat()) header[2] |= FLAG_EVENT; + if (res.isHeartbeat()) { + header[2] |= FLAG_EVENT; + } // set response status. byte status = res.getStatus(); header[3] = status; @@ -277,7 +285,9 @@ protected void encodeResponse(Channel channel, ChannelBuffer buffer, Response re } else { encodeResponseData(channel, out, res.getResult(), res.getVersion()); } - } else out.writeUTF(res.getErrorMessage()); + } else { + out.writeUTF(res.getErrorMessage()); + } out.flushBuffer(); if (out instanceof Cleanable) { ((Cleanable) out).cleanup(); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/AbstractTimerTask.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/AbstractTimerTask.java new file mode 100644 index 000000000000..003af243d860 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/AbstractTimerTask.java @@ -0,0 +1,87 @@ +/* + * 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.header; + +import org.apache.dubbo.common.timer.Timeout; +import org.apache.dubbo.common.timer.Timer; +import org.apache.dubbo.common.timer.TimerTask; +import org.apache.dubbo.remoting.Channel; + +import java.util.Collection; +import java.util.concurrent.TimeUnit; + +/** + * AbstractTimerTask + */ +public abstract class AbstractTimerTask implements TimerTask { + + private final ChannelProvider channelProvider; + + private final Long tick; + + AbstractTimerTask(ChannelProvider channelProvider, Long tick) { + if (channelProvider == null || tick == null) { + throw new IllegalArgumentException(); + } + this.tick = tick; + this.channelProvider = channelProvider; + } + + static Long lastRead(Channel channel) { + return (Long) channel.getAttribute(HeaderExchangeHandler.KEY_READ_TIMESTAMP); + } + + static Long lastWrite(Channel channel) { + return (Long) channel.getAttribute(HeaderExchangeHandler.KEY_WRITE_TIMESTAMP); + } + + static Long now() { + return System.currentTimeMillis(); + } + + private void reput(Timeout timeout, Long tick) { + if (timeout == null || tick == null) { + throw new IllegalArgumentException(); + } + + Timer timer = timeout.timer(); + if (timer.isStop() || timeout.isCancelled()) { + return; + } + + timer.newTimeout(timeout.task(), tick, TimeUnit.MILLISECONDS); + } + + @Override + public void run(Timeout timeout) throws Exception { + Collection c = channelProvider.getChannels(); + for (Channel channel : c) { + if (channel.isClosed()) { + continue; + } + doTask(channel); + } + reput(timeout, tick); + } + + protected abstract void doTask(Channel channel); + + interface ChannelProvider { + Collection getChannels(); + } +} 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 feac1bff7d61..3abbe5b54223 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 @@ -18,10 +18,8 @@ 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.timer.HashedWheelTimer; import org.apache.dubbo.common.utils.NamedThreadFactory; -import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Client; import org.apache.dubbo.remoting.RemotingException; @@ -31,10 +29,7 @@ import org.apache.dubbo.remoting.exchange.ResponseFuture; import java.net.InetSocketAddress; -import java.util.Collection; import java.util.Collections; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** @@ -42,17 +37,14 @@ */ public class HeaderExchangeClient implements ExchangeClient { - private static final Logger logger = LoggerFactory.getLogger(HeaderExchangeClient.class); - - private static final ScheduledThreadPoolExecutor scheduled = new ScheduledThreadPoolExecutor(2, new NamedThreadFactory("dubbo-remoting-client-heartbeat", true)); private final Client client; private final ExchangeChannel channel; - // heartbeat timer - private ScheduledFuture heartbeatTimer; // heartbeat(ms), default value is 0 , won't execute a heartbeat. private int heartbeat; private int heartbeatTimeout; + private HashedWheelTimer heartbeatTimer; + public HeaderExchangeClient(Client client, boolean needHeartbeat) { if (client == null) { throw new IllegalArgumentException("client == null"); @@ -60,12 +52,18 @@ public HeaderExchangeClient(Client client, boolean needHeartbeat) { this.client = client; this.channel = new HeaderExchangeChannel(client); String dubbo = client.getUrl().getParameter(Constants.DUBBO_VERSION_KEY); - this.heartbeat = client.getUrl().getParameter(Constants.HEARTBEAT_KEY, dubbo != null && dubbo.startsWith("1.0.") ? Constants.DEFAULT_HEARTBEAT : 0); + + this.heartbeat = client.getUrl().getParameter(Constants.HEARTBEAT_KEY, dubbo != null && + dubbo.startsWith("1.0.") ? Constants.DEFAULT_HEARTBEAT : 0); this.heartbeatTimeout = client.getUrl().getParameter(Constants.HEARTBEAT_TIMEOUT_KEY, heartbeat * 3); if (heartbeatTimeout < heartbeat * 2) { throw new IllegalStateException("heartbeatTimeout < heartbeatInterval * 2"); } + if (needHeartbeat) { + long tickDuration = calculateLeastDuration(heartbeat); + heartbeatTimer = new HashedWheelTimer(new NamedThreadFactory("dubbo-client-heartbeat", true), tickDuration, + TimeUnit.MILLISECONDS, Constants.TICKS_PER_WHEEL); startHeartbeatTimer(); } } @@ -181,37 +179,40 @@ public boolean hasAttribute(String key) { } private void startHeartbeatTimer() { - stopHeartbeatTimer(); - if (heartbeat > 0) { - heartbeatTimer = scheduled.scheduleWithFixedDelay( - new HeartBeatTask(new HeartBeatTask.ChannelProvider() { - @Override - public Collection getChannels() { - return Collections.singletonList(HeaderExchangeClient.this); - } - }, heartbeat, heartbeatTimeout), - heartbeat, heartbeat, TimeUnit.MILLISECONDS); - } + AbstractTimerTask.ChannelProvider cp = () -> Collections.singletonList(HeaderExchangeClient.this); + + long heartbeatTick = calculateLeastDuration(heartbeat); + long heartbeatTimeoutTick = calculateLeastDuration(heartbeatTimeout); + HeartbeatTimerTask heartBeatTimerTask = new HeartbeatTimerTask(cp, heartbeatTick, heartbeat); + ReconnectTimerTask reconnectTimerTask = new ReconnectTimerTask(cp, heartbeatTimeoutTick, heartbeatTimeout); + + // init task and start timer. + heartbeatTimer.newTimeout(heartBeatTimerTask, heartbeatTick, TimeUnit.MILLISECONDS); + heartbeatTimer.newTimeout(reconnectTimerTask, heartbeatTimeoutTick, TimeUnit.MILLISECONDS); } private void stopHeartbeatTimer() { - if (heartbeatTimer != null && !heartbeatTimer.isCancelled()) { - try { - heartbeatTimer.cancel(true); - scheduled.purge(); - } catch (Throwable e) { - if (logger.isWarnEnabled()) { - logger.warn(e.getMessage(), e); - } - } + if (heartbeatTimer != null) { + heartbeatTimer.stop(); + heartbeatTimer = null; } - heartbeatTimer = null; } private void doClose() { stopHeartbeatTimer(); } + /** + * Each interval cannot be less than 1000ms. + */ + private long calculateLeastDuration(int time) { + if (time / Constants.HEARTBEAT_CHECK_TICK <= 0) { + return Constants.LEAST_HEARTBEAT_DURATION; + } else { + return time / Constants.HEARTBEAT_CHECK_TICK; + } + } + @Override public String toString() { return "HeaderExchangeClient [channel=" + channel + "]"; 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 1be8827a8db7..9e73541a05f8 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 @@ -83,9 +83,13 @@ void handleRequest(final ExchangeChannel channel, Request req) throws RemotingEx Object data = req.getData(); String msg; - if (data == null) msg = null; - else if (data instanceof Throwable) msg = StringUtils.toString((Throwable) data); - else msg = data.toString(); + if (data == null) { + msg = null; + } else if (data instanceof Throwable) { + msg = StringUtils.toString((Throwable) data); + } else { + msg = data.toString(); + } res.setErrorMessage("Fail to decode request due to: " + msg); res.setStatus(Response.BAD_REQUEST); 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 8eceb182e4ba..7f3067d60ccf 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 @@ -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.timer.HashedWheelTimer; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; @@ -33,13 +34,11 @@ import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import static java.util.Collections.unmodifiableCollection; + /** * ExchangeServerImpl */ @@ -47,18 +46,14 @@ public class HeaderExchangeServer implements ExchangeServer { protected final Logger logger = LoggerFactory.getLogger(getClass()); - private final ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1, - new NamedThreadFactory( - "dubbo-remoting-server-heartbeat", - true)); private final Server server; - // heartbeat timer - private ScheduledFuture heartbeatTimer; // heartbeat timeout (ms), default value is 0 , won't execute a heartbeat. private int heartbeat; private int heartbeatTimeout; private AtomicBoolean closed = new AtomicBoolean(false); + private HashedWheelTimer heartbeatTimer; + public HeaderExchangeServer(Server server) { if (server == null) { throw new IllegalArgumentException("server == null"); @@ -69,6 +64,7 @@ public HeaderExchangeServer(Server server) { if (heartbeatTimeout < heartbeat * 2) { throw new IllegalStateException("heartbeatTimeout < heartbeatInterval * 2"); } + startHeartbeatTimer(); } @@ -153,11 +149,6 @@ private void doClose() { return; } stopHeartbeatTimer(); - try { - scheduled.shutdown(); - } catch (Throwable t) { - logger.warn(t.getMessage(), t); - } } @Override @@ -223,6 +214,8 @@ public void reset(URL url) { if (h != heartbeat || t != heartbeatTimeout) { heartbeat = h; heartbeatTimeout = t; + + stopHeartbeatTimer(); startHeartbeatTimer(); } } @@ -240,7 +233,8 @@ public void reset(org.apache.dubbo.common.Parameters parameters) { @Override public void send(Object message) throws RemotingException { if (closed.get()) { - throw new RemotingException(this.getLocalAddress(), null, "Failed to send message " + message + ", cause: The server " + getLocalAddress() + " is closed!"); + throw new RemotingException(this.getLocalAddress(), null, "Failed to send message " + message + + ", cause: The server " + getLocalAddress() + " is closed!"); } server.send(message); } @@ -248,35 +242,43 @@ public void send(Object message) throws RemotingException { @Override public void send(Object message, boolean sent) throws RemotingException { if (closed.get()) { - throw new RemotingException(this.getLocalAddress(), null, "Failed to send message " + message + ", cause: The server " + getLocalAddress() + " is closed!"); + throw new RemotingException(this.getLocalAddress(), null, "Failed to send message " + message + + ", cause: The server " + getLocalAddress() + " is closed!"); } server.send(message, sent); } - private void startHeartbeatTimer() { - stopHeartbeatTimer(); - if (heartbeat > 0) { - heartbeatTimer = scheduled.scheduleWithFixedDelay( - new HeartBeatTask(new HeartBeatTask.ChannelProvider() { - @Override - public Collection getChannels() { - return Collections.unmodifiableCollection( - HeaderExchangeServer.this.getChannels()); - } - }, heartbeat, heartbeatTimeout), - heartbeat, heartbeat, TimeUnit.MILLISECONDS); + /** + * Each interval cannot be less than 1000ms. + */ + private long calculateLeastDuration(int time) { + if (time / Constants.HEARTBEAT_CHECK_TICK <= 0) { + return Constants.LEAST_HEARTBEAT_DURATION; + } else { + return time / Constants.HEARTBEAT_CHECK_TICK; } } + private void startHeartbeatTimer() { + long tickDuration = calculateLeastDuration(heartbeat); + heartbeatTimer = new HashedWheelTimer(new NamedThreadFactory("dubbo-server-heartbeat", true), tickDuration, + TimeUnit.MILLISECONDS, Constants.TICKS_PER_WHEEL); + + AbstractTimerTask.ChannelProvider cp = () -> unmodifiableCollection(HeaderExchangeServer.this.getChannels()); + + long heartbeatTick = calculateLeastDuration(heartbeat); + long heartbeatTimeoutTick = calculateLeastDuration(heartbeatTimeout); + HeartbeatTimerTask heartBeatTimerTask = new HeartbeatTimerTask(cp, heartbeatTick, heartbeat); + ReconnectTimerTask reconnectTimerTask = new ReconnectTimerTask(cp, heartbeatTimeoutTick, heartbeatTimeout); + + // init task and start timer. + heartbeatTimer.newTimeout(heartBeatTimerTask, heartbeatTick, TimeUnit.MILLISECONDS); + heartbeatTimer.newTimeout(reconnectTimerTask, heartbeatTimeoutTick, TimeUnit.MILLISECONDS); + } + private void stopHeartbeatTimer() { - try { - ScheduledFuture timer = heartbeatTimer; - if (timer != null && !timer.isCancelled()) { - timer.cancel(true); - } - } catch (Throwable t) { - logger.warn(t.getMessage(), t); - } finally { + if (heartbeatTimer != null) { + heartbeatTimer.stop(); heartbeatTimer = null; } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartBeatTask.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartBeatTask.java deleted file mode 100644 index 97bb1811ad83..000000000000 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartBeatTask.java +++ /dev/null @@ -1,97 +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.header; - -import org.apache.dubbo.common.Version; -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.exchange.Request; - -import java.util.Collection; - -final class HeartBeatTask implements Runnable { - - private static final Logger logger = LoggerFactory.getLogger(HeartBeatTask.class); - - private ChannelProvider channelProvider; - - private int heartbeat; - - private int heartbeatTimeout; - - HeartBeatTask(ChannelProvider provider, int heartbeat, int heartbeatTimeout) { - this.channelProvider = provider; - this.heartbeat = heartbeat; - this.heartbeatTimeout = heartbeatTimeout; - } - - @Override - public void run() { - try { - long now = System.currentTimeMillis(); - for (Channel channel : channelProvider.getChannels()) { - if (channel.isClosed()) { - continue; - } - try { - Long lastRead = (Long) channel.getAttribute( - HeaderExchangeHandler.KEY_READ_TIMESTAMP); - Long lastWrite = (Long) channel.getAttribute( - HeaderExchangeHandler.KEY_WRITE_TIMESTAMP); - if ((lastRead != null && now - lastRead > heartbeat) - || (lastWrite != null && now - lastWrite > heartbeat)) { - Request req = new Request(); - req.setVersion(Version.getProtocolVersion()); - req.setTwoWay(true); - req.setEvent(Request.HEARTBEAT_EVENT); - channel.send(req); - if (logger.isDebugEnabled()) { - logger.debug("Send heartbeat to remote channel " + channel.getRemoteAddress() - + ", cause: The channel has no data-transmission exceeds a heartbeat period: " + heartbeat + "ms"); - } - } - if (lastRead != null && now - lastRead > heartbeatTimeout) { - logger.warn("Close channel " + channel - + ", because heartbeat read idle time out: " + heartbeatTimeout + "ms"); - if (channel instanceof Client) { - try { - ((Client) channel).reconnect(); - } catch (Exception e) { - //do nothing - } - } else { - channel.close(); - } - } - } catch (Throwable t) { - logger.warn("Exception when heartbeat to remote channel " + channel.getRemoteAddress(), t); - } - } - } catch (Throwable t) { - logger.warn("Unhandled exception when heartbeat, cause: " + t.getMessage(), t); - } - } - - interface ChannelProvider { - Collection getChannels(); - } - -} - diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatTimerTask.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatTimerTask.java new file mode 100644 index 000000000000..cbe01f85063c --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatTimerTask.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.remoting.exchange.support.header; + +import org.apache.dubbo.common.Version; +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.exchange.Request; + +/** + * HeartbeatTimerTask + */ +public class HeartbeatTimerTask extends AbstractTimerTask { + + private static final Logger logger = LoggerFactory.getLogger(HeartbeatTimerTask.class); + + private final int heartbeat; + + HeartbeatTimerTask(ChannelProvider channelProvider, Long heartbeatTick, int heartbeat) { + super(channelProvider, heartbeatTick); + this.heartbeat = heartbeat; + } + + @Override + protected void doTask(Channel channel) { + try { + Long lastRead = lastRead(channel); + Long lastWrite = lastWrite(channel); + if ((lastRead != null && now() - lastRead > heartbeat) + || (lastWrite != null && now() - lastWrite > heartbeat)) { + Request req = new Request(); + req.setVersion(Version.getProtocolVersion()); + req.setTwoWay(true); + req.setEvent(Request.HEARTBEAT_EVENT); + channel.send(req); + if (logger.isDebugEnabled()) { + logger.debug("Send heartbeat to remote channel " + channel.getRemoteAddress() + + ", cause: The channel has no data-transmission exceeds a heartbeat period: " + + heartbeat + "ms"); + } + } + } catch (Throwable t) { + logger.warn("Exception when heartbeat to remote channel " + channel.getRemoteAddress(), t); + } + } +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/ReconnectTimerTask.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/ReconnectTimerTask.java new file mode 100644 index 000000000000..dccbe5332cd6 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/ReconnectTimerTask.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.remoting.exchange.support.header; + +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; + +/** + * ReconnectTimerTask + */ +public class ReconnectTimerTask extends AbstractTimerTask { + + private static final Logger logger = LoggerFactory.getLogger(ReconnectTimerTask.class); + + private final int heartbeatTimeout; + + ReconnectTimerTask(ChannelProvider channelProvider, Long heartbeatTimeoutTick, int heartbeatTimeout1) { + super(channelProvider, heartbeatTimeoutTick); + this.heartbeatTimeout = heartbeatTimeout1; + } + + @Override + protected void doTask(Channel channel) { + try { + Long lastRead = lastRead(channel); + Long now = now(); + if (lastRead != null && now - lastRead > heartbeatTimeout) { + logger.warn("Close channel " + channel + ", because heartbeat read idle time out: " + + heartbeatTimeout + "ms"); + if (channel instanceof Client) { + try { + ((Client) channel).reconnect(); + } catch (Exception e) { + //do nothing + } + } else { + channel.close(); + } + } + } catch (Throwable t) { + logger.warn("Exception when reconnect to remote channel " + channel.getRemoteAddress(), t); + } + } +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/LogTelnetHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/LogTelnetHandler.java index e01aa83af773..121b9d3538e1 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 @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.telnet.support.command; - import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.Level; import org.apache.dubbo.common.logger.LoggerFactory; 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 477fa71f877f..ed913d2a0f7c 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 @@ -199,56 +199,63 @@ public InetSocketAddress getConnectAddress() { @Override public InetSocketAddress getRemoteAddress() { Channel channel = getChannel(); - if (channel == null) + if (channel == null) { return getUrl().toInetSocketAddress(); + } return channel.getRemoteAddress(); } @Override public InetSocketAddress getLocalAddress() { Channel channel = getChannel(); - if (channel == null) + if (channel == null) { return InetSocketAddress.createUnresolved(NetUtils.getLocalHost(), 0); + } return channel.getLocalAddress(); } @Override public boolean isConnected() { Channel channel = getChannel(); - if (channel == null) + if (channel == null) { return false; + } return channel.isConnected(); } @Override public Object getAttribute(String key) { Channel channel = getChannel(); - if (channel == null) + if (channel == null) { return null; + } return channel.getAttribute(key); } @Override public void setAttribute(String key, Object value) { Channel channel = getChannel(); - if (channel == null) + if (channel == null) { return; + } channel.setAttribute(key, value); } @Override public void removeAttribute(String key) { Channel channel = getChannel(); - if (channel == null) + if (channel == null) { return; + } channel.removeAttribute(key); } @Override public boolean hasAttribute(String key) { Channel channel = getChannel(); - if (channel == null) + if (channel == null) { return false; + } return channel.hasAttribute(key); } 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 9ca1c2e05422..07da9a388233 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 @@ -22,9 +22,11 @@ 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 java.io.IOException; +import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -75,4 +77,8 @@ public static Serialization getSerialization(URL url, Byte id) throws IOExceptio return serialization; } + public static ObjectInput deserialize(URL url, InputStream is, byte proto) throws IOException { + Serialization s = getSerialization(url, proto); + return s.deserialize(url, is); + } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelHandlers.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelHandlers.java index d14a1c3d6d04..1ec59617ad27 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelHandlers.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelHandlers.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.transport.dispatcher; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.remoting.ChannelHandler; 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 cde663ded749..5c0d9012c2cc 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 @@ -32,6 +32,7 @@ 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.Assert; import org.junit.Before; import org.junit.Test; @@ -147,6 +148,23 @@ public void test_Decode_Error_Response_Object() throws IOException { Assert.assertEquals(90, obj.getStatus()); } + @Test + public void testInvalidSerializaitonId() throws Exception { + byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, (byte)0x8F, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + Object obj = decode(header); + Assert.assertTrue(obj instanceof Request); + Request request = (Request) obj; + Assert.assertTrue(request.isBroken()); + Assert.assertTrue(request.getData() instanceof IOException); + header = new byte[]{MAGIC_HIGH, MAGIC_LOW, (byte)0x1F, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + + obj = decode(header); + Assert.assertTrue(obj instanceof Response); + Response response = (Response) obj; + Assert.assertEquals(response.getStatus(), Response.CLIENT_ERROR); + Assert.assertTrue(response.getErrorMessage().contains("IOException")); + } + @Test public void test_Decode_Check_Payload() throws IOException { byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; 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 5909a586663a..b302b555f5b3 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,32 +19,30 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.timer.HashedWheelTimer; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.exchange.Request; - import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import java.util.Collection; import java.util.Collections; import java.util.List; +import java.util.concurrent.TimeUnit; public class HeartBeatTaskTest { private URL url = URL.valueOf("dubbo://localhost:20880"); private MockChannel channel; - private HeartBeatTask task; + + private HeartbeatTimerTask heartbeatTimerTask; + private HashedWheelTimer heartbeatTimer; @Before public void setup() throws Exception { - task = new HeartBeatTask(new HeartBeatTask.ChannelProvider() { - - public Collection getChannels() { - return Collections.singletonList(channel); - } - }, 1000, 1000 * 3); + long tickDuration = 1000; + heartbeatTimer = new HashedWheelTimer(tickDuration / Constants.HEARTBEAT_CHECK_TICK, TimeUnit.MILLISECONDS); channel = new MockChannel() { @@ -53,17 +51,24 @@ public URL getUrl() { return url; } }; + + AbstractTimerTask.ChannelProvider cp = () -> Collections.singletonList(channel); + heartbeatTimerTask = new HeartbeatTimerTask(cp, tickDuration / Constants.HEARTBEAT_CHECK_TICK, (int) tickDuration); } @Test public void testHeartBeat() throws Exception { + long now = System.currentTimeMillis(); + url = url.addParameter(Constants.DUBBO_VERSION_KEY, "2.1.1"); channel.setAttribute( - HeaderExchangeHandler.KEY_READ_TIMESTAMP, System.currentTimeMillis()); + HeaderExchangeHandler.KEY_READ_TIMESTAMP, now); channel.setAttribute( - HeaderExchangeHandler.KEY_WRITE_TIMESTAMP, System.currentTimeMillis()); + HeaderExchangeHandler.KEY_WRITE_TIMESTAMP, now); + + heartbeatTimer.newTimeout(heartbeatTimerTask, 250, TimeUnit.MILLISECONDS); + Thread.sleep(2000L); - task.run(); List objects = channel.getSentObjects(); Assert.assertTrue(objects.size() > 0); Object obj = objects.get(0); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/codec/DeprecatedExchangeCodec.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/codec/DeprecatedExchangeCodec.java index 5dc5962ccf24..1dce90c8158b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/codec/DeprecatedExchangeCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/codec/DeprecatedExchangeCodec.java @@ -130,8 +130,6 @@ protected Object decode(Channel channel, InputStream is, int readable, byte[] he protected Object decodeBody(Channel channel, InputStream is, byte[] header) throws IOException { byte flag = header[2], proto = (byte) (flag & SERIALIZATION_MASK); - Serialization s = CodecSupport.getSerialization(channel.getUrl(), proto); - ObjectInput in = s.deserialize(channel.getUrl(), is); // get request id. long id = Bytes.bytes2long(header, 4); if ((flag & FLAG_REQUEST) == 0) { @@ -143,8 +141,9 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro // get status. byte status = header[3]; res.setStatus(status); - if (status == Response.OK) { - try { + try { + ObjectInput in = CodecSupport.deserialize(channel.getUrl(), is, proto); + if (status == Response.OK) { Object data; if (res.isHeartbeat()) { data = decodeHeartbeatData(channel, in); @@ -154,12 +153,12 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro data = decodeResponseData(channel, in, getRequestData(id)); } res.setResult(data); - } catch (Throwable t) { - res.setStatus(Response.CLIENT_ERROR); - res.setErrorMessage(StringUtils.toString(t)); + } else { + res.setErrorMessage(in.readUTF()); } - } else { - res.setErrorMessage(in.readUTF()); + } catch (Throwable t) { + res.setStatus(Response.CLIENT_ERROR); + res.setErrorMessage(StringUtils.toString(t)); } return res; } else { @@ -171,6 +170,7 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro req.setEvent(Request.HEARTBEAT_EVENT); } try { + ObjectInput in = CodecSupport.deserialize(channel.getUrl(), is, proto); Object data; if (req.isHeartbeat()) { data = decodeHeartbeatData(channel, in); 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 7cc96edad355..4732676a082a 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 @@ -168,13 +168,23 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } GrizzlyChannel other = (GrizzlyChannel) obj; if (connection == null) { - if (other.connection != null) return false; - } else if (!connection.equals(other.connection)) return false; + if (other.connection != null) { + return false; + } + } else if (!connection.equals(other.connection)) { + return false; + } return true; } 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 39c01f0585a9..093ce2169403 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 @@ -161,13 +161,23 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } MinaChannel other = (MinaChannel) obj; if (session == null) { - if (other.session != null) return false; - } else if (!session.equals(other.session)) return false; + if (other.session != null) { + return false; + } + } else if (!session.equals(other.session)) { + return false; + } return true; } 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 260bf62b351b..5e60fb2d4902 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 @@ -95,7 +95,9 @@ private class InternalDecoder implements ProtocolDecoder { @Override public void decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception { int readable = in.limit(); - if (readable <= 0) return; + if (readable <= 0) { + return; + } ChannelBuffer frame; 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 0e7bc5dc4292..9a0e107c84f9 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 @@ -177,13 +177,23 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } NettyChannel other = (NettyChannel) obj; if (channel == null) { - if (other.channel != null) return false; - } else if (!channel.equals(other.channel)) return false; + if (other.channel != null) { + return false; + } + } else if (!channel.equals(other.channel)) { + return false; + } return true; } 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 574402f278d2..434fd2a03b06 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 @@ -157,8 +157,9 @@ protected void doClose() throws Throwable { @Override protected org.apache.dubbo.remoting.Channel getChannel() { Channel c = channel; - if (c == null || !c.isConnected()) + if (c == null || !c.isConnected()) { return null; + } return NettyChannel.getOrAddChannel(c, 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 867854a3a168..7db1fb5743d9 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 @@ -29,9 +29,8 @@ 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.Assert; import org.junit.After; +import org.junit.Assert; import org.junit.Test; import java.util.concurrent.CompletableFuture; @@ -66,6 +65,11 @@ public void testServerHeartbeat() throws Exception { FakeChannelHandlers.setTestingChannelHandlers(); 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(Constants.HEARTBEAT_KEY, 600 * 1000); + serverURL = serverURL.addParameter(Constants.RECONNECT_KEY, false); + client = Exchangers.connect(serverURL); Thread.sleep(10000); Assert.assertTrue(handler.disconnectCount > 0); 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 a2cff1dcc2b2..3d4e52d022f7 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,6 +16,7 @@ */ package org.apache.dubbo.remoting.transport.netty; +import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; @@ -29,11 +30,17 @@ public class NettyClientToServerTest extends ClientToServerTest { protected ExchangeServer newServer(int port, Replier receiver) throws RemotingException { - return Exchangers.bind(URL.valueOf("exchange://localhost:" + port + "?server=netty3"), receiver); + // add heartbeat cycle to avoid unstable ut. + URL url = URL.valueOf("exchange://localhost:" + port + "?server=netty3"); + url = url.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000); + return Exchangers.bind(url, receiver); } protected ExchangeChannel newClient(int port) throws RemotingException { - return Exchangers.connect(URL.valueOf("exchange://localhost:" + port + "?client=netty3&timeout=3000")); + // 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); + 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/NettyBackedChannelBuffer.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyBackedChannelBuffer.java index 20ac7a143e5c..143660a3d931 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyBackedChannelBuffer.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyBackedChannelBuffer.java @@ -20,6 +20,7 @@ import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBufferFactory; import org.apache.dubbo.remoting.buffer.ChannelBuffers; + import io.netty.buffer.ByteBuf; import java.io.IOException; 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 19b56aeaf8b6..4ea6fe12c52f 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 @@ -156,8 +156,9 @@ protected void doClose() throws Throwable { @Override protected org.apache.dubbo.remoting.Channel getChannel() { Channel c = channel; - if (c == null || !c.isActive()) + if (c == null || !c.isActive()) { return null; + } return NettyChannel.getOrAddChannel(c, getUrl(), this); } 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 61086e20e35a..2d8981170f34 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 @@ -19,12 +19,12 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.ChannelHandler; +import org.apache.dubbo.remoting.exchange.Request; +import org.apache.dubbo.remoting.exchange.Response; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; -import org.apache.dubbo.remoting.exchange.Request; -import org.apache.dubbo.remoting.exchange.Response; /** * NettyClientHandler 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 ba300623e855..56d4ff69c99e 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 @@ -30,7 +30,7 @@ import java.util.concurrent.ConcurrentHashMap; /** - * NettyClientHandler + * NettyServerHandler */ @io.netty.channel.ChannelHandler.Sharable public class NettyServerHandler extends ChannelDuplexHandler { diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/logging/MessageFormatter.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/logging/MessageFormatter.java index c8a6c2a3bcdc..a138bcf6e60d 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/logging/MessageFormatter.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/logging/MessageFormatter.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.transport.netty4.logging; - import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; 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 af20985e0515..1d3d5132d8a4 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,6 +16,7 @@ */ package org.apache.dubbo.remoting.transport.netty4; +import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeChannel; @@ -29,11 +30,17 @@ public class NettyClientToServerTest extends ClientToServerTest { protected ExchangeServer newServer(int port, Replier receiver) throws RemotingException { - return Exchangers.bind(URL.valueOf("exchange://localhost:" + port + "?server=netty4"), receiver); + // add heartbeat cycle to avoid unstable ut. + URL url = URL.valueOf("exchange://localhost:" + port + "?server=netty4"); + url = url.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000); + return Exchangers.bind(url, receiver); } protected ExchangeChannel newClient(int port) throws RemotingException { - return Exchangers.connect(URL.valueOf("exchange://localhost:" + port + "?client=netty4&timeout=3000")); + // 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); + return Exchangers.connect(url); } } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/test/java/org/apache/dubbo/remoting/p2p/support/FileNetworkerTest.java b/dubbo-remoting/dubbo-remoting-p2p/src/test/java/org/apache/dubbo/remoting/p2p/support/FileNetworkerTest.java index 980718e88687..621e3c4aa6af 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/src/test/java/org/apache/dubbo/remoting/p2p/support/FileNetworkerTest.java +++ b/dubbo-remoting/dubbo-remoting-p2p/src/test/java/org/apache/dubbo/remoting/p2p/support/FileNetworkerTest.java @@ -51,7 +51,7 @@ public void tearDown() throws Exception { @Test public void testJoin() throws RemotingException, InterruptedException, IOException { - final String groupURL = "file://" + folder.newFile(); + final String groupURL = "file:///" + folder.newFile(); FileNetworker networker = new FileNetworker(); Group group = networker.lookup(URL.valueOf(groupURL)); diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/zkclient/ZkClientWrapper.java b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/zkclient/ZkClientWrapper.java index 17aa372da8dc..a22bbe99a13b 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/zkclient/ZkClientWrapper.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/zkclient/ZkClientWrapper.java @@ -16,12 +16,13 @@ */ package org.apache.dubbo.remoting.zookeeper.zkclient; -import org.I0Itec.zkclient.IZkChildListener; -import org.I0Itec.zkclient.IZkStateListener; -import org.I0Itec.zkclient.ZkClient; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.Assert; + +import org.I0Itec.zkclient.IZkChildListener; +import org.I0Itec.zkclient.IZkStateListener; +import org.I0Itec.zkclient.ZkClient; import org.apache.zookeeper.Watcher.Event.KeeperState; import java.util.List; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/service/GenericService.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/service/GenericService.java index e6b3168d6280..b63b60bd3e1e 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/service/GenericService.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/service/GenericService.java @@ -20,6 +20,7 @@ @Deprecated public interface GenericService extends org.apache.dubbo.rpc.service.GenericService { + @Override Object $invoke(String method, String[] parameterTypes, Object[] args) throws com.alibaba.dubbo.rpc.service.GenericException; } 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 064fd9fd90c6..760a9c1a1116 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 @@ -64,6 +64,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/AsyncContextImpl.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncContextImpl.java index 9e4ddaf9ee6f..0142f7391534 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncContextImpl.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncContextImpl.java @@ -71,6 +71,7 @@ public void start() { this.started.set(true); } + @Override public void signalContextSwitch() { RpcContext.restoreContext(storedContext); RpcContext.restoreServerContext(storedServerContext); 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 e9ed9156c03a..81a8c75737d1 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 @@ -162,6 +162,7 @@ public String getAttachment(String key, String defaultValue) { return getRpcResult().getAttachment(key, defaultValue); } + @Override public void setAttachment(String key, String value) { getRpcResult().setAttachment(key, value); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/StaticContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/StaticContext.java deleted file mode 100644 index 30caf571092d..000000000000 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/StaticContext.java +++ /dev/null @@ -1,75 +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 org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.StringUtils; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * System context, for internal use only - */ -public class StaticContext extends ConcurrentHashMap { - private static final long serialVersionUID = 1L; - private static final String SYSTEMNAME = "system"; - private static final ConcurrentMap context_map = new ConcurrentHashMap(); - private String name; - - private StaticContext(String name) { - super(); - this.name = name; - } - - public static StaticContext getSystemContext() { - return getContext(SYSTEMNAME); - } - - public static StaticContext getContext(String name) { - StaticContext appContext = context_map.get(name); - if (appContext == null) { - appContext = context_map.putIfAbsent(name, new StaticContext(name)); - if (appContext == null) { - appContext = context_map.get(name); - } - } - return appContext; - } - - public static StaticContext remove(String name) { - return context_map.remove(name); - } - - public static String getKey(URL url, String methodName, String suffix) { - return getKey(url.getServiceKey(), methodName, suffix); - } - - public static String getKey(Map paras, String methodName, String suffix) { - return getKey(StringUtils.getServiceKey(paras), methodName, suffix); - } - - private static String getKey(String servicekey, String methodName, String suffix) { - StringBuffer sb = new StringBuffer().append(servicekey).append(".").append(methodName).append(".").append(suffix); - return sb.toString(); - } - - public String getName() { - return name; - } -} \ No newline at end of file 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 58965e11966c..89eb070603da 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 @@ -18,7 +18,6 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.extension.Activate; -import com.alibaba.fastjson.JSON; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConcurrentHashSet; @@ -31,6 +30,8 @@ import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; +import com.alibaba.fastjson.JSON; + import java.io.File; import java.io.FileWriter; import java.text.SimpleDateFormat; 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 becdba30477a..5dfa8f0813eb 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 @@ -33,8 +33,9 @@ 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(Constants.$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/model/ApplicationModel.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java index 98d32c10e514..74a52d7c4c7f 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 @@ -18,78 +18,58 @@ 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.rpc.Invoker; import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -import static java.util.stream.Collectors.toSet; - -// adjust project structure in order to fully utilize the methods introduced here. +/** + * Represent a application which is using Dubbo and store basic metadata info for using + * during the processing of RPC invoking. + * + * ApplicationModel includes many ProviderModel which is about published services + * and many Consumer Model which is about subscribed services. + * + * adjust project structure in order to fully utilize the methods introduced here. + */ public class ApplicationModel { - protected static final Logger logger = LoggerFactory.getLogger(ApplicationModel.class); + protected static final Logger LOGGER = LoggerFactory.getLogger(ApplicationModel.class); /** * full qualified class name -> provided service */ - private static final ConcurrentMap> providedServices = new ConcurrentHashMap<>(); + private static final ConcurrentMap providedServices = new ConcurrentHashMap<>(); /** * full qualified class name -> subscribe service */ - private static final ConcurrentMap> consumedServices = new ConcurrentHashMap<>(); - - private static final ConcurrentMap> providedServicesInvoker = new ConcurrentHashMap<>(); + private static final ConcurrentMap consumedServices = new ConcurrentHashMap<>(); public static Collection allConsumerModels() { - return consumedServices.values().stream().flatMap(Collection::stream).collect(toSet()); + return consumedServices.values(); } public static Collection allProviderModels() { - return providedServices.values().stream().flatMap(Collection::stream).collect(toSet()); + return providedServices.values(); } - public static Collection getProviderModel(String serviceName) { + public static ProviderModel getProviderModel(String serviceName) { return providedServices.get(serviceName); } - public static Collection getConsumerModel(String serviceName) { + public static ConsumerModel getConsumerModel(String serviceName) { return consumedServices.get(serviceName); } public static void initConsumerModel(String serviceName, ConsumerModel consumerModel) { - Set consumerModels = consumedServices.computeIfAbsent(serviceName, k -> new HashSet<>()); - if (!consumerModels.add(consumerModel)) { - logger.warn("Already register the same consumer:" + serviceName); + if (consumedServices.putIfAbsent(serviceName, consumerModel) != null) { + LOGGER.warn("Already register the same consumer:" + serviceName); } } public static void initProviderModel(String serviceName, ProviderModel providerModel) { - Set providerModels = providedServices.computeIfAbsent(serviceName, k -> new HashSet<>()); - if (!providerModels.add(providerModel)) { - logger.warn("already register the provider service: " + serviceName); + if (providedServices.putIfAbsent(serviceName, providerModel) != null) { + LOGGER.warn("Already register the same:" + serviceName); } } - - public static void addProviderInvoker(String serviceName,Invoker invoker){ - Set invokers = providedServicesInvoker.get(serviceName); - if (invokers == null){ - providedServicesInvoker.putIfAbsent(serviceName,new ConcurrentHashSet()); - invokers = providedServicesInvoker.get(serviceName); - } - invokers.add(invoker); - } - - public Set getProviderInvoker(String serviceName){ - Set invokers = providedServicesInvoker.get(serviceName); - if (invokers == null){ - return Collections.emptySet(); - } - return invokers; - } } 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 96f55bee4b75..5a871cecc635 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 @@ -19,6 +19,7 @@ import org.apache.dubbo.common.Constants; import java.lang.reflect.Method; +import java.util.Map; public class ConsumerMethodModel { private final Method method; @@ -30,13 +31,22 @@ public class ConsumerMethodModel { private final String methodName; private final boolean generic; - public ConsumerMethodModel(Method method) { + private final AsyncMethodInfo asyncInfo; + + + public ConsumerMethodModel(Method method, Map attributes) { this.method = method; this.parameterClasses = method.getParameterTypes(); this.returnClass = method.getReturnType(); this.parameterTypes = this.createParamSignature(parameterClasses); this.methodName = method.getName(); this.generic = methodName.equals(Constants.$INVOKE) && parameterTypes != null && parameterTypes.length == 3; + + if (attributes != null) { + asyncInfo = (AsyncMethodInfo) attributes.get(methodName); + } else { + asyncInfo = null; + } } public Method getMethod() { @@ -47,6 +57,9 @@ public Class getReturnClass() { return returnClass; } + public AsyncMethodInfo getAsyncInfo() { + return asyncInfo; + } public String getMethodName() { return methodName; @@ -75,4 +88,73 @@ public boolean isGeneric() { public Class[] getParameterClasses() { return parameterClasses; } + + + public static class AsyncMethodInfo { + // callback instance when async-call is invoked + private Object oninvokeInstance; + + // callback method when async-call is invoked + private Method oninvokeMethod; + + // callback instance when async-call is returned + private Object onreturnInstance; + + // callback method when async-call is returned + private Method onreturnMethod; + + // callback instance when async-call has exception thrown + private Object onthrowInstance; + + // callback method when async-call has exception thrown + private Method onthrowMethod; + + public Object getOninvokeInstance() { + return oninvokeInstance; + } + + public void setOninvokeInstance(Object oninvokeInstance) { + this.oninvokeInstance = oninvokeInstance; + } + + public Method getOninvokeMethod() { + return oninvokeMethod; + } + + public void setOninvokeMethod(Method oninvokeMethod) { + this.oninvokeMethod = oninvokeMethod; + } + + public Object getOnreturnInstance() { + return onreturnInstance; + } + + public void setOnreturnInstance(Object onreturnInstance) { + this.onreturnInstance = onreturnInstance; + } + + public Method getOnreturnMethod() { + return onreturnMethod; + } + + public void setOnreturnMethod(Method onreturnMethod) { + this.onreturnMethod = onreturnMethod; + } + + public Object getOnthrowInstance() { + return onthrowInstance; + } + + public void setOnthrowInstance(Object onthrowInstance) { + this.onthrowInstance = onthrowInstance; + } + + public Method getOnthrowMethod() { + return onthrowMethod; + } + + public void setOnthrowMethod(Method onthrowMethod) { + this.onthrowMethod = onthrowMethod; + } + } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ConsumerModel.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ConsumerModel.java index 35ff391e1dd9..398bc91bd21d 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ConsumerModel.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ConsumerModel.java @@ -21,20 +21,24 @@ import java.util.IdentityHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; +/** + * Consumer Model which is about subscribed services. + */ public class ConsumerModel { private final Object proxyObject; private final String serviceName; private final Map methodModels = new IdentityHashMap(); - public ConsumerModel(String serviceName, Object proxyObject, Method[] methods) { + public ConsumerModel(String serviceName, Object proxyObject, Method[] methods, Map attributes) { this.serviceName = serviceName; this.proxyObject = proxyObject; if (proxyObject != null) { for (Method method : methods) { - methodModels.put(method, new ConsumerMethodModel(method)); + methodModels.put(method, new ConsumerMethodModel(method, attributes)); } } } @@ -53,6 +57,17 @@ public ConsumerMethodModel getMethodModel(Method method) { return methodModels.get(method); } + /** + * Return method model for the given method on consumer side + * + * @param method method object + * @return method model + */ + public ConsumerMethodModel getMethodModel(String method) { + Optional> consumerMethodModelEntry = methodModels.entrySet().stream().filter(entry -> entry.getKey().getName().equals(method)).findFirst(); + return consumerMethodModelEntry.map(Map.Entry::getValue).orElse(null); + } + /** * Return all method models for the current service * diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ProviderModel.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ProviderModel.java index b91d0cba0d03..6fb9bebd7ea2 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ProviderModel.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ProviderModel.java @@ -23,6 +23,9 @@ import java.util.List; import java.util.Map; +/** + * ProviderModel which is about published services + */ public class ProviderModel { private final String serviceName; private final Object serviceInstance; @@ -46,6 +49,10 @@ public String getServiceName() { return serviceName; } + public Class getServiceInterfaceClass() { + return serviceInterfaceClass; + } + public Object getServiceInstance() { return serviceInstance; } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractExporter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractExporter.java index 3e7cd609432c..41a47806c9a8 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractExporter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractExporter.java @@ -33,12 +33,15 @@ public abstract class AbstractExporter implements Exporter { private volatile boolean unexported = false; public AbstractExporter(Invoker invoker) { - if (invoker == null) + if (invoker == null) { throw new IllegalStateException("service invoker == null"); - if (invoker.getInterface() == null) + } + if (invoker.getInterface() == null) { throw new IllegalStateException("service type == null"); - if (invoker.getUrl() == null) + } + if (invoker.getUrl() == null) { throw new IllegalStateException("service url == null"); + } this.invoker = invoker; } 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 023635c61bc0..fd0cca6d8ed6 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 @@ -63,10 +63,12 @@ public AbstractInvoker(Class type, URL url, String[] keys) { } public AbstractInvoker(Class type, URL url, Map attachment) { - if (type == null) + if (type == null) { throw new IllegalArgumentException("service type == null"); - if (url == null) + } + if (url == null) { throw new IllegalArgumentException("service url == null"); + } this.type = type; this.url = url; this.attachment = attachment == null ? null : Collections.unmodifiableMap(attachment); @@ -124,10 +126,10 @@ public String toString() { @Override public Result invoke(Invocation inv) throws RpcException { + // if invoker is destroyed due to address refresh from registry, let's allow the current invoke to proceed if (destroyed.get()) { - throw new RpcException("Rpc invoker for service " + this + " on consumer " + NetUtils.getLocalHost() - + " use dubbo version " + Version.getVersion() - + " is DESTROYED, can not be invoked any more!"); + logger.warn("Invoker for service " + this + " on consumer " + NetUtils.getLocalHost() + " is destroyed, " + + ", dubbo version is " + Version.getVersion() + ", this invoker should not be used any longer"); } RpcInvocation invocation = (RpcInvocation) inv; invocation.setInvoker(this); 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 bc4a4c9ba712..c46aada701d3 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,8 +16,6 @@ */ package org.apache.dubbo.rpc.proxy; -import com.alibaba.dubbo.rpc.service.EchoService; - import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.rpc.Invoker; @@ -25,6 +23,8 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.service.GenericService; +import com.alibaba.dubbo.rpc.service.EchoService; + /** * AbstractProxyFactory */ 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 9f71c41f5abc..ef9dac3b89ab 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 @@ -30,6 +30,7 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.RpcResult; + import com.alibaba.fastjson.JSON; import java.lang.reflect.Constructor; @@ -96,26 +97,21 @@ public Result invoke(Invocation invocation) throws RpcException { if (StringUtils.isBlank(mock)) { throw new RpcException(new IllegalAccessException("mock can not be null. url :" + url)); } - mock = normallizeMock(URL.decode(mock)); - if (Constants.RETURN_PREFIX.trim().equalsIgnoreCase(mock.trim())) { - RpcResult result = new RpcResult(); - result.setValue(null); - return result; - } else if (mock.startsWith(Constants.RETURN_PREFIX)) { + mock = normalizeMock(URL.decode(mock)); + if (mock.startsWith(Constants.RETURN_PREFIX)) { mock = mock.substring(Constants.RETURN_PREFIX.length()).trim(); - mock = mock.replace('`', '"'); try { Type[] returnTypes = RpcUtils.getReturnTypes(invocation); Object value = parseMockValue(mock, returnTypes); return new RpcResult(value); } catch (Exception ew) { - throw new RpcException("mock return invoke error. method :" + invocation.getMethodName() + ", mock:" + mock + ", url: " + url, ew); + throw new RpcException("mock return invoke error. method :" + invocation.getMethodName() + + ", mock:" + mock + ", url: " + url, ew); } } else if (mock.startsWith(Constants.THROW_PREFIX)) { mock = mock.substring(Constants.THROW_PREFIX.length()).trim(); - mock = mock.replace('`', '"'); if (StringUtils.isBlank(mock)) { - throw new RpcException(" mocked exception for Service degradation. "); + throw new RpcException("mocked exception for service degradation."); } else { // user customized class Throwable t = getThrowable(mock); throw new RpcException(RpcException.BIZ_EXCEPTION, t); @@ -125,29 +121,29 @@ public Result invoke(Invocation invocation) throws RpcException { Invoker invoker = getInvoker(mock); return invoker.invoke(invocation); } catch (Throwable t) { - throw new RpcException("Failed to create mock implemention class " + mock, t); + throw new RpcException("Failed to create mock implementation class " + mock, t); } } } - private Throwable getThrowable(String throwstr) { - Throwable throwable = (Throwable) throwables.get(throwstr); + public static Throwable getThrowable(String throwstr) { + Throwable throwable = throwables.get(throwstr); if (throwable != null) { return throwable; - } else { - Throwable t = null; - try { - Class bizException = ReflectUtils.forName(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); - } - } catch (Exception e) { - throw new RpcException("mock throw error :" + throwstr + " argument error.", e); + } + + try { + Throwable t; + Class bizException = ReflectUtils.forName(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); } return t; + } catch (Exception e) { + throw new RpcException("mock throw error :" + throwstr + " argument error.", e); } } @@ -156,49 +152,84 @@ private Invoker getInvoker(String mockService) { Invoker invoker = (Invoker) mocks.get(mockService); if (invoker != null) { return invoker; - } else { - Class serviceType = (Class) ReflectUtils.forName(url.getServiceInterface()); - if (ConfigUtils.isDefault(mockService)) { - mockService = serviceType.getName() + "Mock"; - } + } - Class mockClass = ReflectUtils.forName(mockService); - if (!serviceType.isAssignableFrom(mockClass)) { - throw new IllegalArgumentException("The mock implemention class " + mockClass.getName() + " not implement interface " + serviceType.getName()); - } + 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); + } + return invoker; + } - if (!serviceType.isAssignableFrom(mockClass)) { - throw new IllegalArgumentException("The mock implemention class " + mockClass.getName() + " not implement interface " + serviceType.getName()); - } - try { - T mockObject = (T) mockClass.newInstance(); - invoker = proxyFactory.getInvoker(mockObject, (Class) serviceType, url); - if (mocks.size() < 10000) { - mocks.put(mockService, invoker); - } - return invoker; - } catch (InstantiationException e) { - throw new IllegalStateException("No such empty constructor \"public " + mockClass.getSimpleName() + "()\" in mock implemention class " + mockClass.getName(), e); - } catch (IllegalAccessException e) { - throw new IllegalStateException(e); - } + @SuppressWarnings("unchecked") + public static Object getMockObject(String mockService, Class serviceType) { + if (ConfigUtils.isDefault(mockService)) { + mockService = serviceType.getName() + "Mock"; + } + + Class mockClass = ReflectUtils.forName(mockService); + if (!serviceType.isAssignableFrom(mockClass)) { + throw new IllegalStateException("The mock class " + mockClass.getName() + + " not implement interface " + serviceType.getName()); + } + + try { + return mockClass.newInstance(); + } catch (InstantiationException e) { + throw new IllegalStateException("No default constructor from mock class " + mockClass.getName(), e); + } catch (IllegalAccessException e) { + throw new IllegalStateException(e); } } - //mock=fail:throw - //mock=fail:return - //mock=xx.Service - private String normallizeMock(String mock) { - if (mock == null || mock.trim().length() == 0) { + + /** + * Normalize mock string: + * + *
    + *
  1. return => return null
  2. + *
  3. fail => default
  4. + *
  5. force => default
  6. + *
  7. fail:throw/return foo => throw/return foo
  8. + *
  9. force:throw/return foo => throw/return foo
  10. + *
+ * + * @param mock mock string + * @return normalized mock string + */ + public static String normalizeMock(String mock) { + if (mock == null) { return mock; - } else if (ConfigUtils.isDefault(mock) || "fail".equalsIgnoreCase(mock.trim()) || "force".equalsIgnoreCase(mock.trim())) { - mock = url.getServiceInterface() + "Mock"; } + + mock = mock.trim(); + + if (mock.length() == 0) { + return mock; + } + + if (Constants.RETURN_KEY.equalsIgnoreCase(mock)) { + return Constants.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(); - } else if (mock.startsWith(Constants.FORCE_PREFIX)) { + } + + if (mock.startsWith(Constants.FORCE_PREFIX)) { mock = mock.substring(Constants.FORCE_PREFIX.length()).trim(); } + + if (mock.startsWith(Constants.RETURN_PREFIX) || mock.startsWith(Constants.THROW_PREFIX)) { + mock = mock.replace('`', '"'); + } + return mock; } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/StaticContextTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/StaticContextTest.java deleted file mode 100644 index 723b1be1e463..000000000000 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/StaticContextTest.java +++ /dev/null @@ -1,64 +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 org.apache.dubbo.common.Constants; -import org.apache.dubbo.common.URL; -import org.junit.Assert; -import org.junit.Test; - -import java.util.HashMap; -import java.util.Map; - -public class StaticContextTest { - - @Test - public void testGetContext() { - String name = "custom"; - - StaticContext context = StaticContext.getContext(name); - Assert.assertTrue(context != null); - Assert.assertEquals(name, context.getName()); - - StaticContext.remove(name); - - StaticContext sysContext = StaticContext.getSystemContext(); - Assert.assertTrue(sysContext != null); - - } - - @Test - public void testGetKey() { - String interfaceName = "interface"; - String method = "method"; - String group = "group"; - String version = "1.0"; - - String suffix = "suffix"; - - Map para = new HashMap<>(); - para.put(Constants.INTERFACE_KEY, interfaceName); - para.put(Constants.GROUP_KEY, group); - para.put(Constants.VERSION_KEY, version); - - URL url = new URL("dubbo", "localhost", 20880, interfaceName, para); - - Assert.assertEquals(StaticContext.getKey(url, method, suffix), - StaticContext.getKey(para, method, suffix)); - - } -} diff --git a/dubbo-rpc/dubbo-rpc-dubbo/pom.xml b/dubbo-rpc/dubbo-rpc-dubbo/pom.xml index 26915e458de1..2445399f5e03 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/pom.xml +++ b/dubbo-rpc/dubbo-rpc-dubbo/pom.xml @@ -60,6 +60,12 @@ ${project.parent.version} test + + org.apache.dubbo + dubbo-remoting-mina + ${project.parent.version} + test + io.netty netty-all 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 50cdc76a18fb..7c72133e66b9 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 @@ -91,8 +91,9 @@ public Object decode(Channel channel, InputStream input) throws IOException { case DubboCodec.RESPONSE_WITH_EXCEPTION: try { Object obj = in.readObject(); - if (obj instanceof Throwable == false) + if (obj instanceof Throwable == false) { throw new IOException("Response data error, expect Throwable, but get " + obj); + } setException((Throwable) obj); } catch (ClassNotFoundException e) { throw new IOException(StringUtils.toString("Read response data failed.", e)); @@ -119,8 +120,9 @@ public Object decode(Channel channel, InputStream input) throws IOException { case DubboCodec.RESPONSE_WITH_EXCEPTION_WITH_ATTACHMENTS: try { Object obj = in.readObject(); - if (obj instanceof Throwable == false) + if (obj instanceof Throwable == false) { throw new IOException("Response data error, expect Throwable, but get " + obj); + } setException((Throwable) obj); setAttachments((Map) in.readObject(Map.class)); } catch (ClassNotFoundException e) { 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 7523392c1e7c..d6a8e14ed390 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 @@ -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.Version; import org.apache.dubbo.common.io.Bytes; import org.apache.dubbo.common.io.UnsafeByteArrayInputStream; @@ -25,7 +24,6 @@ import org.apache.dubbo.common.logger.LoggerFactory; 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.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; @@ -64,7 +62,6 @@ public class DubboCodec extends ExchangeCodec implements Codec2 { @Override protected Object decodeBody(Channel channel, InputStream is, byte[] header) throws IOException { byte flag = header[2], proto = (byte) (flag & SERIALIZATION_MASK); - Serialization s = CodecSupport.getSerialization(channel.getUrl(), proto); // get request id. long id = Bytes.bytes2long(header, 4); if ((flag & FLAG_REQUEST) == 0) { @@ -76,13 +73,14 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro // get status. byte status = header[3]; res.setStatus(status); - if (status == Response.OK) { - try { + try { + ObjectInput in = CodecSupport.deserialize(channel.getUrl(), is, proto); + if (status == Response.OK) { Object data; if (res.isHeartbeat()) { - data = decodeHeartbeatData(channel, deserialize(s, channel.getUrl(), is)); + data = decodeHeartbeatData(channel, in); } else if (res.isEvent()) { - data = decodeEventData(channel, deserialize(s, channel.getUrl(), is)); + data = decodeEventData(channel, in); } else { DecodeableRpcResult result; if (channel.getUrl().getParameter( @@ -99,15 +97,15 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro data = result; } res.setResult(data); - } catch (Throwable t) { - if (log.isWarnEnabled()) { - log.warn("Decode response failed: " + t.getMessage(), t); - } - res.setStatus(Response.CLIENT_ERROR); - res.setErrorMessage(StringUtils.toString(t)); + } else { + res.setErrorMessage(in.readUTF()); } - } else { - res.setErrorMessage(deserialize(s, channel.getUrl(), is).readUTF()); + } catch (Throwable t) { + if (log.isWarnEnabled()) { + log.warn("Decode response failed: " + t.getMessage(), t); + } + res.setStatus(Response.CLIENT_ERROR); + res.setErrorMessage(StringUtils.toString(t)); } return res; } else { @@ -120,10 +118,11 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro } try { Object data; + ObjectInput in = CodecSupport.deserialize(channel.getUrl(), is, proto); if (req.isHeartbeat()) { - data = decodeHeartbeatData(channel, deserialize(s, channel.getUrl(), is)); + data = decodeHeartbeatData(channel, in); } else if (req.isEvent()) { - data = decodeEventData(channel, deserialize(s, channel.getUrl(), is)); + data = decodeEventData(channel, in); } else { DecodeableRpcInvocation inv; if (channel.getUrl().getParameter( @@ -150,11 +149,6 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro } } - private ObjectInput deserialize(Serialization serialization, URL url, InputStream is) - throws IOException { - return serialization.deserialize(url, is); - } - private byte[] readMessageData(InputStream is) throws IOException { if (is.available() > 0) { byte[] result = new byte[is.available()]; @@ -185,10 +179,11 @@ protected void encodeRequestData(Channel channel, ObjectOutput out, Object data, out.writeUTF(inv.getMethodName()); out.writeUTF(ReflectUtils.getDesc(inv.getParameterTypes())); Object[] args = inv.getArguments(); - if (args != null) + if (args != null) { for (int i = 0; i < args.length; i++) { out.writeObject(encodeInvocationArgument(channel, inv, i)); } + } out.writeObject(RpcUtils.getNecessaryAttachments(inv)); } @@ -196,7 +191,7 @@ protected void encodeRequestData(Channel channel, ObjectOutput out, Object data, protected void encodeResponseData(Channel channel, ObjectOutput out, Object data, String version) throws IOException { Result result = (Result) data; // currently, the version value in Response records the version of Request - boolean attach = Version.isSupportResponseAttatchment(version); + boolean attach = Version.isSupportResponseAttachment(version); Throwable th = result.getException(); if (th == null) { Object ret = result.getValue(); 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 7c574ffb8568..93343c0c26f1 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 @@ -116,8 +116,9 @@ protected Result doInvoke(final Invocation invocation) throws Throwable { @Override public boolean isAvailable() { - if (!super.isAvailable()) + if (!super.isAvailable()) { return false; + } for (ExchangeClient client : clients) { if (client.isConnected() && !client.hasAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY)) { //cannot write == not Available ? 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 d7fe35d3b9cf..334f0fbaba9d 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 @@ -225,8 +225,9 @@ Invoker getInvoker(Channel channel, Invocation inv) throws RemotingException DubboExporter exporter = (DubboExporter) exporterMap.get(serviceKey); - if (exporter == null) + if (exporter == null) { throw new RemotingException(channel, "Not found exported service: " + serviceKey + " in " + exporterMap.keySet() + ", may be version or group mismatch " + ", channel: consumer: " + channel.getRemoteAddress() + " --> provider: " + channel.getLocalAddress() + ", message:" + inv); + } return exporter.getInvoker(); } @@ -297,8 +298,9 @@ private ExchangeServer createServer(URL url) { url = url.addParameterIfAbsent(Constants.HEARTBEAT_KEY, String.valueOf(Constants.DEFAULT_HEARTBEAT)); String str = url.getParameter(Constants.SERVER_KEY, Constants.DEFAULT_REMOTING_SERVER); - if (str != null && str.length() > 0 && !ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str)) + if (str != null && str.length() > 0 && !ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str)) { throw new RpcException("Unsupported server type: " + str + ", url: " + url); + } url = url.addParameter(Constants.CODEC_KEY, DubboCodec.NAME); ExchangeServer server; 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 508b7e7f3924..b5a4057f54dd 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 @@ -62,15 +62,17 @@ public LazyConnectExchangeClient(URL url, ExchangeHandler requestHandler) { private void initClient() throws RemotingException { - if (client != null) + if (client != null) { return; + } if (logger.isInfoEnabled()) { logger.info("Lazy connect to " + url); } connectLock.lock(); try { - if (client != null) + if (client != null) { return; + } this.client = Exchangers.connect(url, requestHandler); } finally { connectLock.unlock(); @@ -162,22 +164,25 @@ public void send(Object message, boolean sent) throws RemotingException { @Override public boolean isClosed() { - if (client != null) + if (client != null) { return client.isClosed(); - else + } else { return true; + } } @Override public void close() { - if (client != null) + if (client != null) { client.close(); + } } @Override public void close(int timeout) { - if (client != null) + if (client != null) { client.close(timeout); + } } @Override 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 4547b85f16f7..f101ed84277b 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 @@ -26,7 +26,9 @@ import org.apache.dubbo.rpc.PostProcessFilter; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.StaticContext; +import org.apache.dubbo.rpc.model.ApplicationModel; +import org.apache.dubbo.rpc.model.ConsumerMethodModel; +import org.apache.dubbo.rpc.model.ConsumerModel; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -79,14 +81,18 @@ private void asyncCallback(final Invoker invoker, final Invocation invocation } private void fireInvokeCallback(final Invoker invoker, final Invocation invocation) { - final Method onInvokeMethod = (Method) StaticContext.getSystemContext().get(StaticContext.getKey(invoker.getUrl(), invocation.getMethodName(), Constants.ON_INVOKE_METHOD_KEY)); - final Object onInvokeInst = StaticContext.getSystemContext().get(StaticContext.getKey(invoker.getUrl(), invocation.getMethodName(), Constants.ON_INVOKE_INSTANCE_KEY)); + final ConsumerMethodModel.AsyncMethodInfo asyncMethodInfo = getAsyncMethodInfo(invoker, invocation); + if (asyncMethodInfo == null) { + return; + } + final Method onInvokeMethod = asyncMethodInfo.getOninvokeMethod(); + final Object onInvokeInst = asyncMethodInfo.getOninvokeInstance(); if (onInvokeMethod == null && onInvokeInst == null) { return; } if (onInvokeMethod == null || onInvokeInst == null) { - throw new IllegalStateException("service:" + invoker.getUrl().getServiceKey() + " has a onreturn callback config , but no such " + (onInvokeMethod == null ? "method" : "instance") + " found. url:" + invoker.getUrl()); + throw new IllegalStateException("service:" + invoker.getUrl().getServiceKey() + " has a oninvoke callback config , but no such " + (onInvokeMethod == null ? "method" : "instance") + " found. url:" + invoker.getUrl()); } if (!onInvokeMethod.isAccessible()) { onInvokeMethod.setAccessible(true); @@ -103,8 +109,13 @@ private void fireInvokeCallback(final Invoker invoker, final Invocation invoc } private void fireReturnCallback(final Invoker invoker, final Invocation invocation, final Object result) { - final Method onReturnMethod = (Method) StaticContext.getSystemContext().get(StaticContext.getKey(invoker.getUrl(), invocation.getMethodName(), Constants.ON_RETURN_METHOD_KEY)); - final Object onReturnInst = StaticContext.getSystemContext().get(StaticContext.getKey(invoker.getUrl(), invocation.getMethodName(), Constants.ON_RETURN_INSTANCE_KEY)); + final ConsumerMethodModel.AsyncMethodInfo asyncMethodInfo = getAsyncMethodInfo(invoker, invocation); + if (asyncMethodInfo == null) { + return; + } + + final Method onReturnMethod = asyncMethodInfo.getOnreturnMethod(); + final Object onReturnInst = asyncMethodInfo.getOnreturnInstance(); //not set onreturn callback if (onReturnMethod == null && onReturnInst == null) { @@ -144,8 +155,13 @@ private void fireReturnCallback(final Invoker invoker, final Invocation invoc } private void fireThrowCallback(final Invoker invoker, final Invocation invocation, final Throwable exception) { - final Method onthrowMethod = (Method) StaticContext.getSystemContext().get(StaticContext.getKey(invoker.getUrl(), invocation.getMethodName(), Constants.ON_THROW_METHOD_KEY)); - final Object onthrowInst = StaticContext.getSystemContext().get(StaticContext.getKey(invoker.getUrl(), invocation.getMethodName(), Constants.ON_THROW_INSTANCE_KEY)); + final ConsumerMethodModel.AsyncMethodInfo asyncMethodInfo = getAsyncMethodInfo(invoker, invocation); + if (asyncMethodInfo == null) { + return; + } + + final Method onthrowMethod = asyncMethodInfo.getOnthrowMethod(); + final Object onthrowInst = asyncMethodInfo.getOnthrowInstance(); //onthrow callback not configured if (onthrowMethod == null && onthrowInst == null) { @@ -184,4 +200,20 @@ private void fireThrowCallback(final Invoker invoker, final Invocation invoca logger.error(invocation.getMethodName() + ".call back method invoke error . callback method :" + onthrowMethod + ", url:" + invoker.getUrl(), exception); } } + + private ConsumerMethodModel.AsyncMethodInfo getAsyncMethodInfo(Invoker invoker, Invocation invocation) { + final ConsumerModel consumerModel = ApplicationModel.getConsumerModel(invoker.getUrl().getServiceKey()); + if (consumerModel == null) { + return null; + } + ConsumerMethodModel methodModel = consumerModel.getMethodModel(invocation.getMethodName()); + if (methodModel == null) { + return null; + } + final ConsumerMethodModel.AsyncMethodInfo asyncMethodInfo = methodModel.getAsyncInfo(); + if (asyncMethodInfo == null) { + return null; + } + return asyncMethodInfo; + } } 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 475c3eef2a61..53ae2bd457ce 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 @@ -28,6 +28,7 @@ import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; + import com.alibaba.fastjson.JSON; import java.util.ArrayList; 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 d149a50e4589..82591ab90c10 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 @@ -28,6 +28,7 @@ import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; + import com.alibaba.fastjson.JSON; import java.lang.reflect.Method; 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 ae8ac964f7b2..ac2379784c1e 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 @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.dubbo.telnet; - import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.Level; import org.apache.dubbo.common.logger.LoggerFactory; 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 7366ed1dd253..ef04a857bda0 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 @@ -26,11 +26,13 @@ import org.apache.dubbo.rpc.protocol.dubbo.support.DemoService; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoServiceImpl; import org.apache.dubbo.rpc.protocol.dubbo.support.NonSerialized; +import org.apache.dubbo.rpc.protocol.dubbo.support.ProtocolUtils; import org.apache.dubbo.rpc.protocol.dubbo.support.RemoteService; import org.apache.dubbo.rpc.protocol.dubbo.support.RemoteServiceImpl; import org.apache.dubbo.rpc.protocol.dubbo.support.Type; import org.apache.dubbo.rpc.service.EchoService; +import org.junit.AfterClass; import org.junit.Assert; import org.junit.Test; @@ -48,6 +50,11 @@ public class DubboProtocolTest { private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + @AfterClass + public static void after() { + ProtocolUtils.closeAll(); + } + @Test public void testDemoProtocol() throws Exception { DemoService service = new DemoServiceImpl(); @@ -89,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:9010/" + DemoService.class.getName()).addParameter(Constants.SERVER_KEY, "mina"))); - service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:9010/" + 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(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); @@ -105,7 +112,7 @@ public void testDubboProtocolWithMina() throws Exception { service.invoke("dubbo://127.0.0.1:9010/" + DemoService.class.getName() + "", "invoke"); } - service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:9010/" + DemoService.class.getName() + "?client=mina").addParameter("timeout", 3000l))); + service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:9011/" + DemoService.class.getName() + "?client=mina").addParameter("timeout", 3000l))); // test netty client StringBuffer buf = new StringBuffer(); for (int i = 0; i < 1024 * 32 + 32; i++) @@ -113,7 +120,7 @@ public void testDubboProtocolWithMina() throws Exception { System.out.println(service.stringLength(buf.toString())); // cast to EchoService - EchoService echo = proxy.getProxy(protocol.refer(EchoService.class, URL.valueOf("dubbo://127.0.0.1:9010/" + DemoService.class.getName() + "?client=mina").addParameter("timeout", 3000l))); + EchoService echo = proxy.getProxy(protocol.refer(EchoService.class, URL.valueOf("dubbo://127.0.0.1:9011/" + DemoService.class.getName() + "?client=mina").addParameter("timeout", 3000l))); for (int i = 0; i < 10; i++) { assertEquals(echo.$echo(buf.toString()), buf.toString()); assertEquals(echo.$echo("test"), "test"); @@ -181,4 +188,4 @@ public void testReturnNonSerialized() throws Exception { Assert.assertTrue(e.getMessage().contains("org.apache.dubbo.rpc.protocol.dubbo.support.NonSerialized must implement java.io.Serializable")); } } -} \ 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 773e72f1ead0..4c5308caf2eb 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 @@ -23,7 +23,9 @@ import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcContext; -import org.apache.dubbo.rpc.StaticContext; +import org.apache.dubbo.rpc.model.ApplicationModel; +import org.apache.dubbo.rpc.model.ConsumerMethodModel; +import org.apache.dubbo.rpc.model.ConsumerModel; import org.apache.dubbo.rpc.protocol.dubbo.support.ProtocolUtils; import org.junit.After; import org.junit.Assert; @@ -72,6 +74,12 @@ public void initOrResetService() { referService(); } + public void initOrResetExService() { + destroyService(); + exportExService(); + referService(); + } + public void destroyService() { demoProxy = null; try { @@ -95,26 +103,36 @@ public void exportExService() { public void initOrResetUrl(boolean isAsync) throws Exception { int port = NetUtils.getAvailablePort(); - consumerUrl = serviceURL = URL.valueOf("dubbo://127.0.0.1:" + port + "/" + IDemoService.class.getName() + "?group=test&async=" + isAsync + "&timeout=100000&reference.filter=future"); - StaticContext.getSystemContext().clear(); + consumerUrl = serviceURL = URL.valueOf("dubbo://127.0.0.1:" + port + "/" + IDemoService.class.getName() + "?group=" + System.nanoTime() + "&async=" + isAsync + "&timeout=100000&reference.filter=future"); } public void initImplicitCallBackURL_onlyOnthrow() throws Exception { - StaticContext.getSystemContext().put(StaticContext.getKey(consumerUrl, "get", Constants.ON_THROW_METHOD_KEY), onThrowMethod); - StaticContext.getSystemContext().put(StaticContext.getKey(consumerUrl, "get", Constants.ON_THROW_INSTANCE_KEY), notify); + Map attitudes = new HashMap<>(); + ConsumerMethodModel.AsyncMethodInfo asyncMethodInfo = new ConsumerMethodModel.AsyncMethodInfo(); + asyncMethodInfo.setOnthrowInstance(notify); + asyncMethodInfo.setOnthrowMethod(onThrowMethod); + attitudes.put("get", asyncMethodInfo); + ApplicationModel.initConsumerModel(consumerUrl.getServiceKey(), new ConsumerModel(consumerUrl.getServiceKey(), demoProxy, IDemoService.class.getMethods(), attitudes)); } //================================================================================================ public void initImplicitCallBackURL_onlyOnreturn() throws Exception { - StaticContext.getSystemContext().put(StaticContext.getKey(consumerUrl, "get", Constants.ON_RETURN_METHOD_KEY), onReturnMethod); - StaticContext.getSystemContext().put(StaticContext.getKey(consumerUrl, "get", Constants.ON_RETURN_INSTANCE_KEY), notify); - + Map attitudes = new HashMap<>(); + ConsumerMethodModel.AsyncMethodInfo asyncMethodInfo = new ConsumerMethodModel.AsyncMethodInfo(); + asyncMethodInfo.setOnreturnInstance(notify); + asyncMethodInfo.setOnreturnMethod(onReturnMethod); + attitudes.put("get", asyncMethodInfo); + ApplicationModel.initConsumerModel(consumerUrl.getServiceKey(), new ConsumerModel(consumerUrl.getServiceKey(), demoProxy, IDemoService.class.getMethods(), attitudes)); } public void initImplicitCallBackURL_onlyOninvoke() throws Exception { - StaticContext.getSystemContext().put(StaticContext.getKey(consumerUrl, "get", Constants.ON_INVOKE_METHOD_KEY), onInvokeMethod); - StaticContext.getSystemContext().put(StaticContext.getKey(consumerUrl, "get", Constants.ON_INVOKE_INSTANCE_KEY), notify); + Map attitudes = new HashMap<>(); + ConsumerMethodModel.AsyncMethodInfo asyncMethodInfo = new ConsumerMethodModel.AsyncMethodInfo(); + asyncMethodInfo.setOninvokeInstance(notify); + asyncMethodInfo.setOninvokeMethod(onInvokeMethod); + attitudes.put("get", asyncMethodInfo); + ApplicationModel.initConsumerModel(consumerUrl.getServiceKey(), new ConsumerModel(consumerUrl.getServiceKey(), demoProxy, IDemoService.class.getMethods(), attitudes)); } @Test @@ -129,8 +147,9 @@ public void test_CloseCallback() throws Exception { @Test public void test_Sync_Onreturn() throws Exception { initOrResetUrl(false); - initImplicitCallBackURL_onlyOnreturn(); initOrResetService(); + initImplicitCallBackURL_onlyOnreturn(); + int requestId = 2; Person ret = demoProxy.get(requestId); Assert.assertEquals(requestId, ret.getId()); @@ -148,11 +167,9 @@ public void test_Sync_Onreturn() throws Exception { @Test public void test_Ex_OnReturn() throws Exception { initOrResetUrl(true); + initOrResetExService(); initImplicitCallBackURL_onlyOnreturn(); - destroyService(); - exportExService(); - referService(); int requestId = 2; Person ret = demoProxy.get(requestId); @@ -171,12 +188,9 @@ public void test_Ex_OnReturn() throws Exception { @Test public void test_Ex_OnInvoke() throws Exception { initOrResetUrl(true); + initOrResetExService(); initImplicitCallBackURL_onlyOninvoke(); - destroyService(); - exportExService(); - referService(); - int requestId = 2; Person ret = demoProxy.get(requestId); Assert.assertEquals(null, ret); @@ -194,12 +208,9 @@ public void test_Ex_OnInvoke() throws Exception { @Test public void test_Ex_Onthrow() throws Exception { initOrResetUrl(true); + initOrResetExService(); initImplicitCallBackURL_onlyOnthrow(); - destroyService(); - exportExService(); - referService(); - int requestId = 2; Person ret = demoProxy.get(requestId); Assert.assertEquals(null, ret); @@ -218,10 +229,8 @@ public void test_Ex_Onthrow() throws Exception { @Test public void test_Sync_NoFuture() throws Exception { initOrResetUrl(false); + initOrResetService(); initImplicitCallBackURL_onlyOnreturn(); - destroyService(); - exportService(); - referService(); int requestId = 2; Person ret = demoProxy.get(requestId); @@ -234,9 +243,7 @@ public void test_Sync_NoFuture() throws Exception { @Test public void test_Async_Future() throws Exception { initOrResetUrl(true); - destroyService(); - exportService(); - referService(); + initOrResetService(); int requestId = 2; Person ret = demoProxy.get(requestId); @@ -250,9 +257,7 @@ public void test_Async_Future() throws Exception { @Test public void test_Async_Future_Multi() throws Exception { initOrResetUrl(true); - destroyService(); - exportService(); - referService(); + initOrResetService(); int requestId1 = 1; Person ret = demoProxy.get(requestId1); @@ -275,9 +280,7 @@ public void test_Async_Future_Multi() throws Exception { public void test_Async_Future_Ex() throws Throwable { try { initOrResetUrl(true); - destroyService(); - exportExService(); - referService(); + initOrResetExService(); int requestId = 2; Person ret = demoProxy.get(requestId); @@ -295,9 +298,7 @@ public void test_Async_Future_Ex() throws Throwable { @Test(expected = RuntimeException.class) public void test_Normal_Ex() throws Exception { initOrResetUrl(false); - destroyService(); - exportExService(); - referService(); + initOrResetExService(); int requestId = 2; Person ret = demoProxy.get(requestId); 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 ea7743ad5240..fb338769b655 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 @@ -26,7 +26,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.dubbo.support.ProtocolUtils; +import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; @@ -52,6 +54,11 @@ public class ReferenceCountExchangeClientTest { public static void setUpBeforeClass() throws Exception { } + @AfterClass + public static void tearDownAfterClass() { + ProtocolUtils.closeAll(); + } + public static Invoker referInvoker(Class type, URL url) { return (Invoker) protocol.refer(type, url); } 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 0cce1045f028..21c566fe0fbd 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 @@ -19,6 +19,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.rpc.RpcContext; + import com.caucho.hessian.client.HessianConnection; import com.caucho.hessian.client.HessianURLConnectionFactory; 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 8a7e0e99bb78..3b9239171a95 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 @@ -24,9 +24,9 @@ import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.protocol.AbstractProxyProtocol; - import org.apache.dubbo.rpc.service.GenericService; import org.apache.dubbo.rpc.support.ProtocolUtils; + import com.caucho.hessian.HessianException; import com.caucho.hessian.client.HessianConnectionException; import com.caucho.hessian.client.HessianConnectionFactory; 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 76130d69eabe..ba4bb4f2433a 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 @@ -26,6 +26,7 @@ import org.apache.dubbo.rpc.protocol.AbstractProxyProtocol; import org.apache.dubbo.rpc.service.GenericService; import org.apache.dubbo.rpc.support.ProtocolUtils; + import org.aopalliance.intercept.MethodInvocation; import org.springframework.remoting.RemoteAccessException; import org.springframework.remoting.httpinvoker.HttpComponentsHttpInvokerRequestExecutor; 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 77179f24562d..c2cf48ac5f0a 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 @@ -20,6 +20,7 @@ import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.RpcContext; + import org.aopalliance.intercept.MethodInvocation; import org.springframework.remoting.support.RemoteInvocation; 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 bd1ea8bcd21e..ba35c298ec48 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 @@ -74,22 +74,30 @@ public Invoker refer(final Class type, final URL url) throws RpcExcept config.setTestOnBorrow(url.getParameter("test.on.borrow", true)); config.setTestOnReturn(url.getParameter("test.on.return", false)); config.setTestWhileIdle(url.getParameter("test.while.idle", false)); - if (url.getParameter("max.idle", 0) > 0) + if (url.getParameter("max.idle", 0) > 0) { config.setMaxIdle(url.getParameter("max.idle", 0)); - if (url.getParameter("min.idle", 0) > 0) + } + if (url.getParameter("min.idle", 0) > 0) { config.setMinIdle(url.getParameter("min.idle", 0)); - if (url.getParameter("max.active", 0) > 0) + } + if (url.getParameter("max.active", 0) > 0) { config.setMaxTotal(url.getParameter("max.active", 0)); - if (url.getParameter("max.total", 0) > 0) + } + if (url.getParameter("max.total", 0) > 0) { config.setMaxTotal(url.getParameter("max.total", 0)); - if (url.getParameter("max.wait", 0) > 0) + } + if (url.getParameter("max.wait", 0) > 0) { config.setMaxWaitMillis(url.getParameter("max.wait", 0)); - if (url.getParameter("num.tests.per.eviction.run", 0) > 0) + } + if (url.getParameter("num.tests.per.eviction.run", 0) > 0) { config.setNumTestsPerEvictionRun(url.getParameter("num.tests.per.eviction.run", 0)); - if (url.getParameter("time.between.eviction.runs.millis", 0) > 0) + } + if (url.getParameter("time.between.eviction.runs.millis", 0) > 0) { config.setTimeBetweenEvictionRunsMillis(url.getParameter("time.between.eviction.runs.millis", 0)); - if (url.getParameter("min.evictable.idle.time.millis", 0) > 0) + } + if (url.getParameter("min.evictable.idle.time.millis", 0) > 0) { 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), StringUtils.isBlank(url.getPassword()) ? null : url.getPassword(), 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 2268b71ac90a..6c24ca575ec7 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 @@ -23,7 +23,7 @@ import org.apache.dubbo.remoting.http.servlet.BootstrapListener; import org.apache.dubbo.remoting.http.servlet.ServletManager; import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.ServiceClassHolder; +import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.protocol.AbstractProxyProtocol; import org.apache.http.HeaderElement; @@ -90,7 +90,7 @@ public int getDefaultPort() { @Override protected Runnable doExport(T impl, Class type, URL url) throws RpcException { String addr = getAddr(url); - Class implClass = ServiceClassHolder.getInstance().popServiceClass(); + Class implClass = ApplicationModel.getProviderModel(url.getServiceKey()).getServiceInterfaceClass(); RestServer server = servers.get(addr); if (server == null) { server = serverFactory.createServer(url.getParameter(Constants.SERVER_KEY, DEFAULT_SERVER)); diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RpcContextFilter.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RpcContextFilter.java index ae9e813ddc23..b99bf1dc4eb6 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RpcContextFilter.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RpcContextFilter.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.RpcContext; + import org.jboss.resteasy.spi.ResteasyProviderFactory; import javax.annotation.Priority; diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerApiListingResource.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerApiListingResource.java index 6fcc8db62052..41b8ff51fd99 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerApiListingResource.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerApiListingResource.java @@ -17,16 +17,17 @@ package org.apache.dubbo.rpc.protocol.rest.integration.swagger; import org.apache.dubbo.config.annotation.Service; + import com.fasterxml.jackson.core.JsonProcessingException; import io.swagger.jaxrs.listing.BaseApiListingResource; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; -import javax.ws.rs.core.Response; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Application; @Service public class DubboSwaggerApiListingResource extends BaseApiListingResource implements DubboSwaggerService { diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerService.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerService.java index bca1b863e7c4..3f6d7630baf7 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerService.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerService.java @@ -25,9 +25,9 @@ import javax.ws.rs.Produces; import javax.ws.rs.core.Application; import javax.ws.rs.core.Context; +import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.UriInfo; 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 a698d0c3e258..215bc410c1c3 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 @@ -27,7 +27,8 @@ import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.ServiceClassHolder; +import org.apache.dubbo.rpc.model.ApplicationModel; +import org.apache.dubbo.rpc.model.ProviderModel; import org.hamcrest.CoreMatchers; import org.junit.After; import org.junit.Test; @@ -48,11 +49,12 @@ public void tearDown() { @Test public void testExport() { - ServiceClassHolder.getInstance().pushServiceClass(DemoService.class); - + IDemoService server = new DemoService(); + ProviderModel providerModel = new ProviderModel(exportUrl.getServiceKey(), server, IDemoService.class); + ApplicationModel.initProviderModel(exportUrl.getServiceKey(), providerModel); RpcContext.getContext().setAttachment("timeout", "200"); - Exporter exporter = protocol.export(proxy.getInvoker(new DemoService(), IDemoService.class, exportUrl)); + Exporter exporter = protocol.export(proxy.getInvoker(server, IDemoService.class, exportUrl)); IDemoService demoService = this.proxy.getProxy(protocol.refer(IDemoService.class, exportUrl)); @@ -64,7 +66,9 @@ public void testExport() { @Test public void testNettyServer() { - ServiceClassHolder.getInstance().pushServiceClass(DemoService.class); + IDemoService server = new DemoService(); + ProviderModel providerModel = new ProviderModel(exportUrl.getServiceKey(), server, IDemoService.class); + ApplicationModel.initProviderModel(exportUrl.getServiceKey(), providerModel); URL nettyUrl = exportUrl.addParameter(Constants.SERVER_KEY, "netty"); Exporter exporter = protocol.export(proxy.getInvoker(new DemoService(), IDemoService.class, nettyUrl)); @@ -79,19 +83,23 @@ public void testNettyServer() { @Test(expected = RpcException.class) public void testServletWithoutWebConfig() { - ServiceClassHolder.getInstance().pushServiceClass(DemoService.class); + IDemoService server = new DemoService(); + ProviderModel providerModel = new ProviderModel(exportUrl.getServiceKey(), server, IDemoService.class); + ApplicationModel.initProviderModel(exportUrl.getServiceKey(), providerModel); URL servletUrl = exportUrl.addParameter(Constants.SERVER_KEY, "servlet"); - protocol.export(proxy.getInvoker(new DemoService(), IDemoService.class, servletUrl)); + protocol.export(proxy.getInvoker(server, IDemoService.class, servletUrl)); } @Test(expected = RpcException.class) public void testErrorHandler() { - ServiceClassHolder.getInstance().pushServiceClass(DemoService.class); + IDemoService server = new DemoService(); + ProviderModel providerModel = new ProviderModel(exportUrl.getServiceKey(), server, IDemoService.class); + ApplicationModel.initProviderModel(exportUrl.getServiceKey(), providerModel); URL nettyUrl = exportUrl.addParameter(Constants.SERVER_KEY, "netty"); - Exporter exporter = protocol.export(proxy.getInvoker(new DemoService(), IDemoService.class, nettyUrl)); + Exporter exporter = protocol.export(proxy.getInvoker(server, IDemoService.class, nettyUrl)); IDemoService demoService = this.proxy.getProxy(protocol.refer(IDemoService.class, nettyUrl)); @@ -100,10 +108,12 @@ public void testErrorHandler() { @Test public void testInvoke() { - ServiceClassHolder.getInstance().pushServiceClass(DemoService.class); + IDemoService server = new DemoService(); + ProviderModel providerModel = new ProviderModel(exportUrl.getServiceKey(), server, IDemoService.class); + ApplicationModel.initProviderModel(exportUrl.getServiceKey(), providerModel); - Exporter exporter = protocol.export(proxy.getInvoker(new DemoService(), IDemoService.class, exportUrl)); + Exporter exporter = protocol.export(proxy.getInvoker(server, IDemoService.class, exportUrl)); RpcInvocation rpcInvocation = new RpcInvocation("hello", new Class[]{Integer.class, Integer.class}, new Integer[]{2, 3}); @@ -113,11 +123,13 @@ public void testInvoke() { @Test public void testFilter() { - ServiceClassHolder.getInstance().pushServiceClass(DemoService.class); + IDemoService server = new DemoService(); + ProviderModel providerModel = new ProviderModel(exportUrl.getServiceKey(), server, IDemoService.class); + ApplicationModel.initProviderModel(exportUrl.getServiceKey(), providerModel); URL nettyUrl = exportUrl.addParameter(Constants.SERVER_KEY, "netty") .addParameter(Constants.EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.support.LoggingFilter"); - Exporter exporter = protocol.export(proxy.getInvoker(new DemoService(), IDemoService.class, nettyUrl)); + Exporter exporter = protocol.export(proxy.getInvoker(server, IDemoService.class, nettyUrl)); IDemoService demoService = this.proxy.getProxy(protocol.refer(IDemoService.class, nettyUrl)); @@ -130,12 +142,14 @@ public void testFilter() { @Test public void testRpcContextFilter() { - ServiceClassHolder.getInstance().pushServiceClass(DemoService.class); + IDemoService server = new DemoService(); + ProviderModel providerModel = new ProviderModel(exportUrl.getServiceKey(), server, IDemoService.class); + ApplicationModel.initProviderModel(exportUrl.getServiceKey(), providerModel); // use RpcContextFilter URL nettyUrl = exportUrl.addParameter(Constants.SERVER_KEY, "netty") .addParameter(Constants.EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.RpcContextFilter"); - Exporter exporter = protocol.export(proxy.getInvoker(new DemoService(), IDemoService.class, nettyUrl)); + Exporter exporter = protocol.export(proxy.getInvoker(server, IDemoService.class, nettyUrl)); IDemoService demoService = this.proxy.getProxy(protocol.refer(IDemoService.class, nettyUrl)); @@ -151,10 +165,12 @@ public void testRpcContextFilter() { @Test(expected = RuntimeException.class) public void testRegFail() { - ServiceClassHolder.getInstance().pushServiceClass(DemoService.class); + IDemoService server = new DemoService(); + ProviderModel providerModel = new ProviderModel(exportUrl.getServiceKey(), server, IDemoService.class); + ApplicationModel.initProviderModel(exportUrl.getServiceKey(), providerModel); URL nettyUrl = exportUrl.addParameter(Constants.EXTENSION_KEY, "com.not.existing.Filter"); - protocol.export(proxy.getInvoker(new DemoService(), IDemoService.class, nettyUrl)); + protocol.export(proxy.getInvoker(server, IDemoService.class, nettyUrl)); } @Test diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protol/rest/RestProtocolTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protol/rest/RestProtocolTest.java index bd2d66a5c41a..ab0da76a890d 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protol/rest/RestProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protol/rest/RestProtocolTest.java @@ -16,10 +16,15 @@ */ package org.apache.dubbo.rpc.protol.rest; +import junit.framework.Assert; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.rpc.*; -import junit.framework.Assert; +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.dubbo.rpc.model.ApplicationModel; +import org.apache.dubbo.rpc.model.ProviderModel; import org.junit.Test; /** @@ -32,12 +37,14 @@ public class RestProtocolTest { @Test public void testRestProtocol() { - ServiceClassHolder.getInstance().pushServiceClass(RestServiceImpl.class); - RestServiceImpl server = new RestServiceImpl(); - Assert.assertFalse(server.isCalled()); URL url = URL.valueOf("rest://127.0.0.1:5342/rest/say1?version=1.0.0"); + RestServiceImpl server = new RestServiceImpl(); + ProviderModel providerModel = new ProviderModel(url.getServiceKey(), server, RestService.class); + ApplicationModel.initProviderModel(url.getServiceKey(), providerModel); + Exporter exporter = protocol.export(proxyFactory.getInvoker(server, RestService.class, url)); - Invoker invoker = protocol.refer(RestService.class, url); + Invoker invoker = protocol.refer(RestService.class, url); Assert.assertFalse(server.isCalled()); + RestService client = proxyFactory.getProxy(invoker); String result = client.sayHello("haha"); Assert.assertTrue(server.isCalled()); @@ -48,10 +55,12 @@ public void testRestProtocol() { @Test public void testRestProtocolWithContextPath() { - ServiceClassHolder.getInstance().pushServiceClass(RestServiceImpl.class); RestServiceImpl server = new RestServiceImpl(); Assert.assertFalse(server.isCalled()); URL url = URL.valueOf("rest://127.0.0.1:5341/a/b/c?version=1.0.0"); + ProviderModel providerModel = new ProviderModel(url.getServiceKey(), server, RestService.class); + ApplicationModel.initProviderModel(url.getServiceKey(), providerModel); + Exporter exporter = protocol.export(proxyFactory.getInvoker(server, RestService.class, url)); url = URL.valueOf("rest://127.0.0.1:5341/a/b/c/?version=1.0.0"); 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 f85afccf61e6..dbbe9d668679 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 @@ -17,6 +17,7 @@ package org.apache.dubbo.rpc.protocol.rmi; import org.apache.dubbo.rpc.RpcContext; + import org.aopalliance.intercept.MethodInvocation; import org.springframework.remoting.support.RemoteInvocation; 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 b693847fb18f..02c0699af2c3 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.ClassHelper; 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 1c50bdf592d2..96f4726f1dfe 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 @@ -201,8 +201,9 @@ private ExchangeServer getServer(URL url) { url = url.addParameterIfAbsent(Constants.CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString()); String str = url.getParameter(Constants.SERVER_KEY, Constants.DEFAULT_REMOTING_SERVER); - if (str != null && str.length() > 0 && !ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str)) + if (str != null && str.length() > 0 && !ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str)) { throw new RpcException("Unsupported server type: " + str + ", url: " + url); + } ExchangeServer server; try { 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 bfdd8c0cd88e..a5d0d119370c 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 @@ -36,8 +36,9 @@ public RandomAccessByteArrayOutputStream() { public RandomAccessByteArrayOutputStream(int size) { - if (size < 0) + if (size < 0) { throw new IllegalArgumentException("Negative initial size: " + size); + } buffer = new byte[size]; } @@ -45,8 +46,9 @@ public RandomAccessByteArrayOutputStream(int size) { public void write(int b) { int newcount = count + 1; - if (newcount > buffer.length) + if (newcount > buffer.length) { buffer = Bytes.copyOf(buffer, Math.max(buffer.length << 1, newcount)); + } buffer[count] = (byte) b; count = newcount; } @@ -54,13 +56,16 @@ public void write(int b) { @Override public void write(byte b[], int off, int len) { - if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) + if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); - if (len == 0) + } + if (len == 0) { return; + } int newcount = count + len; - if (newcount > buffer.length) + if (newcount > buffer.length) { buffer = Bytes.copyOf(buffer, Math.max(buffer.length << 1, newcount)); + } System.arraycopy(b, off, buffer, count, len); count = newcount; } diff --git a/dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonObjectInput.java b/dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonObjectInput.java index bef92db462fa..96824fd58cf1 100644 --- a/dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonObjectInput.java +++ b/dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonObjectInput.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.utils.PojoUtils; + import com.alibaba.fastjson.JSON; import java.io.BufferedReader; @@ -105,7 +106,9 @@ public T readObject(Class cls, Type type) throws IOException, ClassNotFou private String readLine() throws IOException, EOFException { 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; } diff --git a/dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonObjectOutput.java b/dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonObjectOutput.java index 0ec5c010eab2..d0e4ed546e9c 100644 --- a/dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonObjectOutput.java +++ b/dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonObjectOutput.java @@ -17,6 +17,7 @@ package org.apache.dubbo.common.serialize.fastjson; import org.apache.dubbo.common.serialize.ObjectOutput; + import com.alibaba.fastjson.serializer.JSONSerializer; import com.alibaba.fastjson.serializer.SerializeWriter; import com.alibaba.fastjson.serializer.SerializerFeature; diff --git a/dubbo-serialization/dubbo-serialization-fastjson/src/test/java/org/apache/dubbo/common/serialize/fastjson/model/Image.java b/dubbo-serialization/dubbo-serialization-fastjson/src/test/java/org/apache/dubbo/common/serialize/fastjson/model/Image.java deleted file mode 100644 index bb2dc06eb395..000000000000 --- a/dubbo-serialization/dubbo-serialization-fastjson/src/test/java/org/apache/dubbo/common/serialize/fastjson/model/Image.java +++ /dev/null @@ -1,104 +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.serialize.fastjson.model; - -public class Image implements java.io.Serializable { - private static final long serialVersionUID = 1L; - private String uri; - private String title; - private int width; - private int height; - private Size size; - - public Image(String uri, String title, int width, int height, Size size) { - this.height = height; - this.title = title; - this.uri = uri; - this.width = width; - this.size = size; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - Image image = (Image) o; - - if (height != image.height) return false; - if (width != image.width) return false; - if (size != image.size) return false; - if (title != null ? !title.equals(image.title) : image.title != null) return false; - if (uri != null ? !uri.equals(image.uri) : image.uri != null) return false; - - return true; - } - - @Override - public int hashCode() { - int result = uri != null ? uri.hashCode() : 0; - result = 31 * result + (title != null ? title.hashCode() : 0); - result = 31 * result + width; - result = 31 * result + height; - result = 31 * result + (size != null ? size.hashCode() : 0); - return result; - } - - public String getUri() { - return uri; - } - - public void setUri(String uri) { - this.uri = uri; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public int getWidth() { - return width; - } - - public void setWidth(int width) { - this.width = width; - } - - public int getHeight() { - return height; - } - - public void setHeight(int height) { - this.height = height; - } - - public Size getSize() { - return size; - } - - public void setSize(Size size) { - this.size = size; - } - - public enum Size { - SMALL, LARGE - } -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-fastjson/src/test/resources/log4j.xml b/dubbo-serialization/dubbo-serialization-fastjson/src/test/resources/log4j.xml deleted file mode 100644 index d045b92c0de6..000000000000 --- a/dubbo-serialization/dubbo-serialization-fastjson/src/test/resources/log4j.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstFactory.java b/dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstFactory.java index 6329d1ecb7d3..b0830332b529 100644 --- a/dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstFactory.java +++ b/dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstFactory.java @@ -17,6 +17,7 @@ package org.apache.dubbo.common.serialize.fst; import org.apache.dubbo.common.serialize.support.SerializableClassRegistry; + import org.nustaq.serialization.FSTConfiguration; import org.nustaq.serialization.FSTObjectInput; import org.nustaq.serialization.FSTObjectOutput; diff --git a/dubbo-serialization/dubbo-serialization-fst/src/test/java/org/apache/dubbo/common/serialize/fst/model/FullAddress.java b/dubbo-serialization/dubbo-serialization-fst/src/test/java/org/apache/dubbo/common/serialize/fst/model/FullAddress.java deleted file mode 100644 index d3f88a93f906..000000000000 --- a/dubbo-serialization/dubbo-serialization-fst/src/test/java/org/apache/dubbo/common/serialize/fst/model/FullAddress.java +++ /dev/null @@ -1,199 +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.serialize.fst.model; - -import java.io.Serializable; - -public class FullAddress implements Serializable { - - private static final long serialVersionUID = 5163979984269419831L; - - private String countryId; - - private String countryName; - - private String provinceName; - - private String cityId; - - private String cityName; - - private String streetAddress; - - private String zipCode; - - public FullAddress(String countryId, String provinceName, String cityId, String streetAddress, - String zipCode) { - this.countryId = countryId; - this.countryName = countryId; - this.provinceName = provinceName; - this.cityId = cityId; - this.cityName = cityId; - this.streetAddress = streetAddress; - this.zipCode = zipCode; - } - - public FullAddress(String countryId, String countryName, String provinceName, String cityId, - String cityName, String streetAddress, String zipCode) { - this.countryId = countryId; - this.countryName = countryName; - this.provinceName = provinceName; - this.cityId = cityId; - this.cityName = cityName; - this.streetAddress = streetAddress; - this.zipCode = zipCode; - } - - public String getCountryId() { - return countryId; - } - - public void setCountryId(String countryId) { - this.countryId = countryId; - } - - public String getCountryName() { - return countryName; - } - - public void setCountryName(String countryName) { - this.countryName = countryName; - } - - public String getProvinceName() { - return provinceName; - } - - public void setProvinceName(String provinceName) { - this.provinceName = provinceName; - } - - public String getCityId() { - return cityId; - } - - public void setCityId(String cityId) { - this.cityId = cityId; - } - - public String getCityName() { - return cityName; - } - - public void setCityName(String cityName) { - this.cityName = cityName; - } - - public String getStreetAddress() { - return streetAddress; - } - - public void setStreetAddress(String streetAddress) { - this.streetAddress = streetAddress; - } - - public String getZipCode() { - return zipCode; - } - - public void setZipCode(String zipCode) { - this.zipCode = zipCode; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((cityId == null) ? 0 : cityId.hashCode()); - result = prime * result + ((cityName == null) ? 0 : cityName.hashCode()); - result = prime * result + ((countryId == null) ? 0 : countryId.hashCode()); - result = prime * result + ((countryName == null) ? 0 : countryName.hashCode()); - result = prime * result + ((provinceName == null) ? 0 : provinceName.hashCode()); - result = prime * result + ((streetAddress == null) ? 0 : streetAddress.hashCode()); - result = prime * result + ((zipCode == null) ? 0 : zipCode.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - FullAddress other = (FullAddress) obj; - if (cityId == null) { - if (other.cityId != null) - return false; - } else if (!cityId.equals(other.cityId)) - return false; - if (cityName == null) { - if (other.cityName != null) - return false; - } else if (!cityName.equals(other.cityName)) - return false; - if (countryId == null) { - if (other.countryId != null) - return false; - } else if (!countryId.equals(other.countryId)) - return false; - if (countryName == null) { - if (other.countryName != null) - return false; - } else if (!countryName.equals(other.countryName)) - return false; - if (provinceName == null) { - if (other.provinceName != null) - return false; - } else if (!provinceName.equals(other.provinceName)) - return false; - if (streetAddress == null) { - if (other.streetAddress != null) - return false; - } else if (!streetAddress.equals(other.streetAddress)) - return false; - if (zipCode == null) { - if (other.zipCode != null) - return false; - } else if (!zipCode.equals(other.zipCode)) - return false; - return true; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - if (countryName != null && countryName.length() > 0) { - sb.append(countryName); - } - if (provinceName != null && provinceName.length() > 0) { - sb.append(" "); - sb.append(provinceName); - } - if (cityName != null && cityName.length() > 0) { - sb.append(" "); - sb.append(cityName); - } - if (streetAddress != null && streetAddress.length() > 0) { - sb.append(" "); - sb.append(streetAddress); - } - return sb.toString(); - } - -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-fst/src/test/resources/log4j.xml b/dubbo-serialization/dubbo-serialization-fst/src/test/resources/log4j.xml deleted file mode 100644 index d045b92c0de6..000000000000 --- a/dubbo-serialization/dubbo-serialization-fst/src/test/resources/log4j.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ObjectInput.java b/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ObjectInput.java index 4ec97a4c7056..348d04d9913a 100644 --- a/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ObjectInput.java +++ b/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ObjectInput.java @@ -16,9 +16,10 @@ */ package org.apache.dubbo.common.serialize.hessian2; -import com.alibaba.com.caucho.hessian.io.Hessian2Input; import org.apache.dubbo.common.serialize.ObjectInput; +import com.alibaba.com.caucho.hessian.io.Hessian2Input; + import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Type; diff --git a/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ObjectOutput.java b/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ObjectOutput.java index 5d640fdc8d9d..fec356a668ac 100644 --- a/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ObjectOutput.java +++ b/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ObjectOutput.java @@ -16,9 +16,10 @@ */ package org.apache.dubbo.common.serialize.hessian2; -import com.alibaba.com.caucho.hessian.io.Hessian2Output; import org.apache.dubbo.common.serialize.ObjectOutput; +import com.alibaba.com.caucho.hessian.io.Hessian2Output; + import java.io.IOException; import java.io.OutputStream; diff --git a/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/model/BizExceptionNoDefaultConstructor.java b/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/model/BizExceptionNoDefaultConstructor.java deleted file mode 100644 index f1ffadb0234a..000000000000 --- a/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/model/BizExceptionNoDefaultConstructor.java +++ /dev/null @@ -1,26 +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.model; - -public class BizExceptionNoDefaultConstructor extends RuntimeException { - - private static final long serialVersionUID = 1L; - - public BizExceptionNoDefaultConstructor(String message) { - super(message); - } -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/model/SerializablePerson.java b/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/model/SerializablePerson.java deleted file mode 100644 index d78c5928ea85..000000000000 --- a/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/model/SerializablePerson.java +++ /dev/null @@ -1,97 +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.model; - -import java.io.Serializable; -import java.util.Arrays; - -public class SerializablePerson implements Serializable { - private static final long serialVersionUID = 1L; - byte oneByte = 123; - private String name = "name1"; - private int age = 11; - - private String[] value = {"value1", "value2"}; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public byte getOneByte() { - return oneByte; - } - - public void setOneByte(byte b) { - this.oneByte = b; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - - public String[] getValue() { - return value; - } - - public void setValue(String[] value) { - this.value = value; - } - - @Override - public String toString() { - return String.format("Person name(%s) age(%d) byte(%s) [value=%s]", name, age, oneByte, Arrays.toString(value)); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + age; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + Arrays.hashCode(value); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - SerializablePerson other = (SerializablePerson) obj; - if (age != other.age) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (!Arrays.equals(value, other.value)) - return false; - return true; - } -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/model/media/Media.java b/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/model/media/Media.java deleted file mode 100644 index 042a3a5273ac..000000000000 --- a/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/model/media/Media.java +++ /dev/null @@ -1,205 +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.model.media; - -import java.util.List; - -@SuppressWarnings("serial") -public class Media implements java.io.Serializable { - public String uri; - public String title; // Can be unset. - public int width; - public int height; - public String format; - public long duration; - public long size; - public int bitrate; // Can be unset. - public boolean hasBitrate; - public List persons; - public Player player; - public String copyright; // Can be unset. - - public Media() { - } - - public Media(String uri, String title, int width, int height, String format, long duration, long size, int bitrate, boolean hasBitrate, List persons, Player player, String copyright) { - this.uri = uri; - this.title = title; - this.width = width; - this.height = height; - this.format = format; - this.duration = duration; - this.size = size; - this.bitrate = bitrate; - this.hasBitrate = hasBitrate; - this.persons = persons; - this.player = player; - this.copyright = copyright; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - Media media = (Media) o; - - if (bitrate != media.bitrate) return false; - if (duration != media.duration) return false; - if (hasBitrate != media.hasBitrate) return false; - if (height != media.height) return false; - if (size != media.size) return false; - if (width != media.width) return false; - if (copyright != null ? !copyright.equals(media.copyright) : media.copyright != null) return false; - if (format != null ? !format.equals(media.format) : media.format != null) return false; - if (persons != null ? !persons.equals(media.persons) : media.persons != null) return false; - if (player != media.player) return false; - if (title != null ? !title.equals(media.title) : media.title != null) return false; - if (uri != null ? !uri.equals(media.uri) : media.uri != null) return false; - - return true; - } - - @Override - public int hashCode() { - int result = uri != null ? uri.hashCode() : 0; - result = 31 * result + (title != null ? title.hashCode() : 0); - result = 31 * result + width; - result = 31 * result + height; - result = 31 * result + (format != null ? format.hashCode() : 0); - result = 31 * result + (int) (duration ^ (duration >>> 32)); - result = 31 * result + (int) (size ^ (size >>> 32)); - result = 31 * result + bitrate; - result = 31 * result + (hasBitrate ? 1 : 0); - result = 31 * result + (persons != null ? persons.hashCode() : 0); - result = 31 * result + (player != null ? player.hashCode() : 0); - result = 31 * result + (copyright != null ? copyright.hashCode() : 0); - return result; - } - - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("[Media "); - sb.append("uri=").append(uri); - sb.append(", title=").append(title); - sb.append(", width=").append(width); - sb.append(", height=").append(height); - sb.append(", format=").append(format); - sb.append(", duration=").append(duration); - sb.append(", size=").append(size); - sb.append(", hasBitrate=").append(hasBitrate); - sb.append(", bitrate=").append(String.valueOf(bitrate)); - sb.append(", persons=").append(persons); - sb.append(", player=").append(player); - sb.append(", copyright=").append(copyright); - sb.append("]"); - return sb.toString(); - } - - public String getUri() { - return uri; - } - - public void setUri(String uri) { - this.uri = uri; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public int getWidth() { - return width; - } - - public void setWidth(int width) { - this.width = width; - } - - public int getHeight() { - return height; - } - - public void setHeight(int height) { - this.height = height; - } - - public String getFormat() { - return format; - } - - public void setFormat(String format) { - this.format = format; - } - - public long getDuration() { - return duration; - } - - public void setDuration(long duration) { - this.duration = duration; - } - - public long getSize() { - return size; - } - - public void setSize(long size) { - this.size = size; - } - - public int getBitrate() { - return bitrate; - } - - public void setBitrate(int bitrate) { - this.bitrate = bitrate; - this.hasBitrate = true; - } - - public List getPersons() { - return persons; - } - - public void setPersons(List persons) { - this.persons = persons; - } - - public Player getPlayer() { - return player; - } - - public void setPlayer(Player player) { - this.player = player; - } - - public String getCopyright() { - return copyright; - } - - public void setCopyright(String copyright) { - this.copyright = copyright; - } - - public enum Player { - JAVA, FLASH - } -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/model/person/BigPerson.java b/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/model/person/BigPerson.java deleted file mode 100644 index 4ce79008fb4e..000000000000 --- a/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/model/person/BigPerson.java +++ /dev/null @@ -1,151 +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.model.person; - -import java.io.Serializable; - -public class BigPerson implements Serializable { - private static final long serialVersionUID = 1L; - - String personId; - - String loginName; - - PersonStatus status; - - String email; - - String penName; - - PersonInfo infoProfile; - - public BigPerson() { - - } - - public BigPerson(String id) { - this.personId = id; - } - - public String getPersonId() { - return personId; - } - - public void setPersonId(String personId) { - this.personId = personId; - } - - public PersonInfo getInfoProfile() { - return infoProfile; - } - - public void setInfoProfile(PersonInfo infoProfile) { - this.infoProfile = infoProfile; - } - - public String getEmail() { - return this.email; - } - - public void setEmail(String email) { - this.email = email; - } - - public String getLoginName() { - return this.loginName; - } - - public void setLoginName(String loginName) { - this.loginName = loginName; - } - - public PersonStatus getStatus() { - return this.status; - } - - public void setStatus(PersonStatus status) { - this.status = status; - } - - public String getPenName() { - return penName; - } - - public void setPenName(String penName) { - this.penName = penName; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((email == null) ? 0 : email.hashCode()); - result = prime * result + ((infoProfile == null) ? 0 : infoProfile.hashCode()); - result = prime * result + ((loginName == null) ? 0 : loginName.hashCode()); - result = prime * result + ((penName == null) ? 0 : penName.hashCode()); - result = prime * result + ((personId == null) ? 0 : personId.hashCode()); - result = prime * result + ((status == null) ? 0 : status.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - BigPerson other = (BigPerson) obj; - if (email == null) { - if (other.email != null) - return false; - } else if (!email.equals(other.email)) - return false; - if (infoProfile == null) { - if (other.infoProfile != null) - return false; - } else if (!infoProfile.equals(other.infoProfile)) - return false; - if (loginName == null) { - if (other.loginName != null) - return false; - } else if (!loginName.equals(other.loginName)) - return false; - if (penName == null) { - if (other.penName != null) - return false; - } else if (!penName.equals(other.penName)) - return false; - if (personId == null) { - if (other.personId != null) - return false; - } else if (!personId.equals(other.personId)) - return false; - if (status != other.status) - return false; - return true; - } - - @Override - public String toString() { - return "BigPerson [personId=" + personId + ", loginName=" + loginName + ", status=" - + status + ", email=" + email + ", penName=" + penName + ", infoProfile=" - + infoProfile + "]"; - } - -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/model/person/PersonInfo.java b/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/model/person/PersonInfo.java deleted file mode 100644 index 15f1238fe854..000000000000 --- a/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/model/person/PersonInfo.java +++ /dev/null @@ -1,206 +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.model.person; - -import java.io.Serializable; -import java.util.List; - -public class PersonInfo implements Serializable { - private static final long serialVersionUID = 7443011149612231882L; - - List phones; - - Phone fax; - - FullAddress fullAddress; - - String mobileNo; - - String name; - - boolean male; - - boolean female; - - String department; - - String jobTitle; - - String homepageUrl; - - public List getPhones() { - return phones; - } - - public void setPhones(List phones) { - this.phones = phones; - } - - public boolean isMale() { - return male; - } - - public void setMale(boolean male) { - this.male = male; - } - - public boolean isFemale() { - return female; - } - - public void setFemale(boolean female) { - this.female = female; - } - - public String getDepartment() { - return department; - } - - public void setDepartment(String department) { - this.department = department; - } - - public Phone getFax() { - return fax; - } - - public void setFax(Phone fax) { - this.fax = fax; - } - - public FullAddress getFullAddress() { - return fullAddress; - } - - public void setFullAddress(FullAddress fullAddress) { - this.fullAddress = fullAddress; - } - - public String getHomepageUrl() { - return homepageUrl; - } - - public void setHomepageUrl(String homepageUrl) { - this.homepageUrl = homepageUrl; - } - - public String getJobTitle() { - return jobTitle; - } - - public void setJobTitle(String jobTitle) { - this.jobTitle = jobTitle; - } - - public String getMobileNo() { - return mobileNo; - } - - public void setMobileNo(String mobileNo) { - this.mobileNo = mobileNo; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((department == null) ? 0 : department.hashCode()); - result = prime * result + ((fax == null) ? 0 : fax.hashCode()); - result = prime * result + (female ? 1231 : 1237); - result = prime * result + ((fullAddress == null) ? 0 : fullAddress.hashCode()); - result = prime * result + ((homepageUrl == null) ? 0 : homepageUrl.hashCode()); - result = prime * result + ((jobTitle == null) ? 0 : jobTitle.hashCode()); - result = prime * result + (male ? 1231 : 1237); - result = prime * result + ((mobileNo == null) ? 0 : mobileNo.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((phones == null) ? 0 : phones.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - PersonInfo other = (PersonInfo) obj; - if (department == null) { - if (other.department != null) - return false; - } else if (!department.equals(other.department)) - return false; - if (fax == null) { - if (other.fax != null) - return false; - } else if (!fax.equals(other.fax)) - return false; - if (female != other.female) - return false; - if (fullAddress == null) { - if (other.fullAddress != null) - return false; - } else if (!fullAddress.equals(other.fullAddress)) - return false; - if (homepageUrl == null) { - if (other.homepageUrl != null) - return false; - } else if (!homepageUrl.equals(other.homepageUrl)) - return false; - if (jobTitle == null) { - if (other.jobTitle != null) - return false; - } else if (!jobTitle.equals(other.jobTitle)) - return false; - if (male != other.male) - return false; - if (mobileNo == null) { - if (other.mobileNo != null) - return false; - } else if (!mobileNo.equals(other.mobileNo)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (phones == null) { - if (other.phones != null) - return false; - } else if (!phones.equals(other.phones)) - return false; - return true; - } - - @Override - public String toString() { - return "PersonInfo [phones=" + phones + ", fax=" + fax + ", fullAddress=" + fullAddress - + ", mobileNo=" + mobileNo + ", name=" + name + ", male=" + male + ", female=" - + female + ", department=" + department + ", jobTitle=" + jobTitle - + ", homepageUrl=" + homepageUrl + "]"; - } - -} diff --git a/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/model/person/PersonStatus.java b/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/model/person/PersonStatus.java deleted file mode 100644 index 62869c2b80b4..000000000000 --- a/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/model/person/PersonStatus.java +++ /dev/null @@ -1,22 +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.model.person; - -public enum PersonStatus { - ENABLED, - DISABLED -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/model/person/Phone.java b/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/model/person/Phone.java deleted file mode 100644 index 41fd38a92df7..000000000000 --- a/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/model/person/Phone.java +++ /dev/null @@ -1,139 +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.model.person; - -import java.io.Serializable; - -public class Phone implements Serializable { - - private static final long serialVersionUID = 4399060521859707703L; - - private String country; - - private String area; - - private String number; - - private String extensionNumber; - - public Phone() { - } - - public Phone(String country, String area, String number, String extensionNumber) { - this.country = country; - this.area = area; - this.number = number; - this.extensionNumber = extensionNumber; - } - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - public String getArea() { - return area; - } - - public void setArea(String area) { - this.area = area; - } - - public String getNumber() { - return number; - } - - public void setNumber(String number) { - this.number = number; - } - - public String getExtensionNumber() { - return extensionNumber; - } - - public void setExtensionNumber(String extensionNumber) { - this.extensionNumber = extensionNumber; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((area == null) ? 0 : area.hashCode()); - result = prime * result + ((country == null) ? 0 : country.hashCode()); - result = prime * result + ((extensionNumber == null) ? 0 : extensionNumber.hashCode()); - result = prime * result + ((number == null) ? 0 : number.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Phone other = (Phone) obj; - if (area == null) { - if (other.area != null) - return false; - } else if (!area.equals(other.area)) - return false; - if (country == null) { - if (other.country != null) - return false; - } else if (!country.equals(other.country)) - return false; - if (extensionNumber == null) { - if (other.extensionNumber != null) - return false; - } else if (!extensionNumber.equals(other.extensionNumber)) - return false; - if (number == null) { - if (other.number != null) - return false; - } else if (!number.equals(other.number)) - return false; - return true; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - if (country != null && country.length() > 0) { - sb.append(country); - sb.append("-"); - } - if (area != null && area.length() > 0) { - sb.append(area); - sb.append("-"); - } - if (number != null && number.length() > 0) { - sb.append(number); - } - if (extensionNumber != null && extensionNumber.length() > 0) { - sb.append("-"); - sb.append(extensionNumber); - } - return sb.toString(); - } - -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/serialize/serialization/AbstractSerializationPersonFailTest.java b/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/serialize/serialization/AbstractSerializationPersonFailTest.java deleted file mode 100644 index 5d27bb565585..000000000000 --- a/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/serialize/serialization/AbstractSerializationPersonFailTest.java +++ /dev/null @@ -1,137 +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.serialize.serialization; - -import org.apache.dubbo.common.model.Person; -import org.apache.dubbo.common.serialize.ObjectOutput; - -import org.junit.Test; - -import java.io.NotSerializableException; -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 static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; -import static org.junit.matchers.JUnitMatchers.containsString; - -public abstract class AbstractSerializationPersonFailTest extends AbstractSerializationTest { - @Test - public void test_Person() throws Exception { - try { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(new Person()); - fail(); - } catch (NotSerializableException expected) { - } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("Serialized class org.apache.dubbo.common.model.Person must implement java.io.Serializable")); - } - } - - @Test - public void test_PersonList() throws Exception { - List args = new ArrayList(); - args.add(new Person()); - try { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(args); - fail(); - } catch (NotSerializableException expected) { - } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("Serialized class org.apache.dubbo.common.model.Person must implement java.io.Serializable")); - } - } - - @Test - public void test_PersonSet() throws Exception { - Set args = new HashSet(); - args.add(new Person()); - try { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(args); - fail(); - } catch (NotSerializableException expected) { - } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("Serialized class org.apache.dubbo.common.model.Person must implement java.io.Serializable")); - } - } - - @Test - public void test_IntPersonMap() throws Exception { - Map args = new HashMap(); - args.put(1, new Person()); - try { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(args); - fail(); - } catch (NotSerializableException expected) { - } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("Serialized class org.apache.dubbo.common.model.Person must implement java.io.Serializable")); - } - } - - @Test - public void test_StringPersonMap() throws Exception { - Map args = new HashMap(); - args.put("1", new Person()); - try { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(args); - fail(); - } catch (NotSerializableException expected) { - } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("Serialized class org.apache.dubbo.common.model.Person must implement java.io.Serializable")); - } - } - - @Test - public void test_StringPersonListMap() throws Exception { - Map> args = new HashMap>(); - - List sublist = new ArrayList(); - sublist.add(new Person()); - args.put("1", sublist); - try { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(args); - fail(); - } catch (NotSerializableException expected) { - } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("Serialized class org.apache.dubbo.common.model.Person must implement java.io.Serializable")); - } - } - - @Test - public void test_PersonListList() throws Exception { - List> args = new ArrayList>(); - List sublist = new ArrayList(); - sublist.add(new Person()); - args.add(sublist); - try { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(args); - fail(); - } catch (NotSerializableException expected) { - } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("Serialized class org.apache.dubbo.common.model.Person must implement java.io.Serializable")); - } - } -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-hessian2/src/test/resources/log4j.xml b/dubbo-serialization/dubbo-serialization-hessian2/src/test/resources/log4j.xml deleted file mode 100644 index d045b92c0de6..000000000000 --- a/dubbo-serialization/dubbo-serialization-hessian2/src/test/resources/log4j.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaObjectInput.java b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaObjectInput.java index 6a4bbb9b378d..00e712e6e97c 100644 --- a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaObjectInput.java +++ b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaObjectInput.java @@ -40,12 +40,15 @@ public JavaObjectInput(InputStream is, boolean compacted) throws IOException { @Override public byte[] readBytes() throws IOException { int len = getObjectInputStream().readInt(); - if (len < 0) + if (len < 0) { return null; - if (len == 0) + } + if (len == 0) { return new byte[0]; - if (len > MAX_BYTE_ARRAY_LENGTH) + } + if (len > MAX_BYTE_ARRAY_LENGTH) { throw new IOException("Byte array length too large. " + len); + } byte[] b = new byte[len]; getObjectInputStream().readFully(b); @@ -55,8 +58,9 @@ public byte[] readBytes() throws IOException { @Override public String readUTF() throws IOException { int len = getObjectInputStream().readInt(); - if (len < 0) + if (len < 0) { return null; + } return getObjectInputStream().readUTF(); } @@ -64,8 +68,9 @@ public String readUTF() throws IOException { @Override public Object readObject() throws IOException, ClassNotFoundException { byte b = getObjectInputStream().readByte(); - if (b == 0) + if (b == 0) { return null; + } return getObjectInputStream().readObject(); } diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaObjectOutput.java b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaObjectOutput.java index 44308b482817..49a4b45123f3 100644 --- a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaObjectOutput.java +++ b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaObjectOutput.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.serialize.java; - import org.apache.dubbo.common.serialize.nativejava.NativeJavaObjectOutput; import java.io.IOException; diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/AnimalEnum.java b/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/AnimalEnum.java deleted file mode 100644 index 760663fe04cf..000000000000 --- a/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/AnimalEnum.java +++ /dev/null @@ -1,21 +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.model; - -public enum AnimalEnum { - dog, cat, rat, cow, bull, horse; -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/Person.java b/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/Person.java deleted file mode 100644 index 5a551a7f36b9..000000000000 --- a/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/Person.java +++ /dev/null @@ -1,95 +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.model; - -import java.util.Arrays; - -public class Person { - byte oneByte = 123; - private String name = "name1"; - private int age = 11; - - private String[] value = {"value1", "value2"}; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public byte getOneByte() { - return oneByte; - } - - public void setOneByte(byte b) { - this.oneByte = b; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - - public String[] getValue() { - return value; - } - - public void setValue(String[] value) { - this.value = value; - } - - @Override - public String toString() { - return String.format("Person name(%s) age(%d) byte(%s) [value=%s]", name, age, oneByte, Arrays.toString(value)); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + age; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + Arrays.hashCode(value); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Person other = (Person) obj; - if (age != other.age) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (!Arrays.equals(value, other.value)) - return false; - return true; - } -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/SerializablePerson.java b/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/SerializablePerson.java deleted file mode 100644 index d78c5928ea85..000000000000 --- a/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/SerializablePerson.java +++ /dev/null @@ -1,97 +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.model; - -import java.io.Serializable; -import java.util.Arrays; - -public class SerializablePerson implements Serializable { - private static final long serialVersionUID = 1L; - byte oneByte = 123; - private String name = "name1"; - private int age = 11; - - private String[] value = {"value1", "value2"}; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public byte getOneByte() { - return oneByte; - } - - public void setOneByte(byte b) { - this.oneByte = b; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - - public String[] getValue() { - return value; - } - - public void setValue(String[] value) { - this.value = value; - } - - @Override - public String toString() { - return String.format("Person name(%s) age(%d) byte(%s) [value=%s]", name, age, oneByte, Arrays.toString(value)); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + age; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + Arrays.hashCode(value); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - SerializablePerson other = (SerializablePerson) obj; - if (age != other.age) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (!Arrays.equals(value, other.value)) - return false; - return true; - } -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/media/Image.java b/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/media/Image.java deleted file mode 100644 index a59eff35be68..000000000000 --- a/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/media/Image.java +++ /dev/null @@ -1,120 +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.model.media; - - -public class Image implements java.io.Serializable { - private static final long serialVersionUID = 1L; - public String uri; - public String title; // Can be null - public int width; - public int height; - public Size size; - - public Image() { - } - - public Image(String uri, String title, int width, int height, Size size) { - this.height = height; - this.title = title; - this.uri = uri; - this.width = width; - this.size = size; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - Image image = (Image) o; - - if (height != image.height) return false; - if (width != image.width) return false; - if (size != image.size) return false; - if (title != null ? !title.equals(image.title) : image.title != null) return false; - if (uri != null ? !uri.equals(image.uri) : image.uri != null) return false; - - return true; - } - - @Override - public int hashCode() { - int result = uri != null ? uri.hashCode() : 0; - result = 31 * result + (title != null ? title.hashCode() : 0); - result = 31 * result + width; - result = 31 * result + height; - result = 31 * result + (size != null ? size.hashCode() : 0); - return result; - } - - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("[Image "); - sb.append("uri=").append(uri); - sb.append(", title=").append(title); - sb.append(", width=").append(width); - sb.append(", height=").append(height); - sb.append(", size=").append(size); - sb.append("]"); - return sb.toString(); - } - - public String getUri() { - return uri; - } - - public void setUri(String uri) { - this.uri = uri; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public int getWidth() { - return width; - } - - public void setWidth(int width) { - this.width = width; - } - - public int getHeight() { - return height; - } - - public void setHeight(int height) { - this.height = height; - } - - public Size getSize() { - return size; - } - - public void setSize(Size size) { - this.size = size; - } - - public enum Size { - SMALL, LARGE - } -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/media/Media.java b/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/media/Media.java deleted file mode 100644 index 042a3a5273ac..000000000000 --- a/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/media/Media.java +++ /dev/null @@ -1,205 +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.model.media; - -import java.util.List; - -@SuppressWarnings("serial") -public class Media implements java.io.Serializable { - public String uri; - public String title; // Can be unset. - public int width; - public int height; - public String format; - public long duration; - public long size; - public int bitrate; // Can be unset. - public boolean hasBitrate; - public List persons; - public Player player; - public String copyright; // Can be unset. - - public Media() { - } - - public Media(String uri, String title, int width, int height, String format, long duration, long size, int bitrate, boolean hasBitrate, List persons, Player player, String copyright) { - this.uri = uri; - this.title = title; - this.width = width; - this.height = height; - this.format = format; - this.duration = duration; - this.size = size; - this.bitrate = bitrate; - this.hasBitrate = hasBitrate; - this.persons = persons; - this.player = player; - this.copyright = copyright; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - Media media = (Media) o; - - if (bitrate != media.bitrate) return false; - if (duration != media.duration) return false; - if (hasBitrate != media.hasBitrate) return false; - if (height != media.height) return false; - if (size != media.size) return false; - if (width != media.width) return false; - if (copyright != null ? !copyright.equals(media.copyright) : media.copyright != null) return false; - if (format != null ? !format.equals(media.format) : media.format != null) return false; - if (persons != null ? !persons.equals(media.persons) : media.persons != null) return false; - if (player != media.player) return false; - if (title != null ? !title.equals(media.title) : media.title != null) return false; - if (uri != null ? !uri.equals(media.uri) : media.uri != null) return false; - - return true; - } - - @Override - public int hashCode() { - int result = uri != null ? uri.hashCode() : 0; - result = 31 * result + (title != null ? title.hashCode() : 0); - result = 31 * result + width; - result = 31 * result + height; - result = 31 * result + (format != null ? format.hashCode() : 0); - result = 31 * result + (int) (duration ^ (duration >>> 32)); - result = 31 * result + (int) (size ^ (size >>> 32)); - result = 31 * result + bitrate; - result = 31 * result + (hasBitrate ? 1 : 0); - result = 31 * result + (persons != null ? persons.hashCode() : 0); - result = 31 * result + (player != null ? player.hashCode() : 0); - result = 31 * result + (copyright != null ? copyright.hashCode() : 0); - return result; - } - - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("[Media "); - sb.append("uri=").append(uri); - sb.append(", title=").append(title); - sb.append(", width=").append(width); - sb.append(", height=").append(height); - sb.append(", format=").append(format); - sb.append(", duration=").append(duration); - sb.append(", size=").append(size); - sb.append(", hasBitrate=").append(hasBitrate); - sb.append(", bitrate=").append(String.valueOf(bitrate)); - sb.append(", persons=").append(persons); - sb.append(", player=").append(player); - sb.append(", copyright=").append(copyright); - sb.append("]"); - return sb.toString(); - } - - public String getUri() { - return uri; - } - - public void setUri(String uri) { - this.uri = uri; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public int getWidth() { - return width; - } - - public void setWidth(int width) { - this.width = width; - } - - public int getHeight() { - return height; - } - - public void setHeight(int height) { - this.height = height; - } - - public String getFormat() { - return format; - } - - public void setFormat(String format) { - this.format = format; - } - - public long getDuration() { - return duration; - } - - public void setDuration(long duration) { - this.duration = duration; - } - - public long getSize() { - return size; - } - - public void setSize(long size) { - this.size = size; - } - - public int getBitrate() { - return bitrate; - } - - public void setBitrate(int bitrate) { - this.bitrate = bitrate; - this.hasBitrate = true; - } - - public List getPersons() { - return persons; - } - - public void setPersons(List persons) { - this.persons = persons; - } - - public Player getPlayer() { - return player; - } - - public void setPlayer(Player player) { - this.player = player; - } - - public String getCopyright() { - return copyright; - } - - public void setCopyright(String copyright) { - this.copyright = copyright; - } - - public enum Player { - JAVA, FLASH - } -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/media/MediaContent.java b/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/media/MediaContent.java deleted file mode 100644 index 7991f5061012..000000000000 --- a/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/media/MediaContent.java +++ /dev/null @@ -1,78 +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.model.media; - -import java.util.List; - -@SuppressWarnings("serial") -public class MediaContent implements java.io.Serializable { - public Media media; - public List images; - - public MediaContent() { - } - - public MediaContent(Media media, List images) { - this.media = media; - this.images = images; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - MediaContent that = (MediaContent) o; - - if (images != null ? !images.equals(that.images) : that.images != null) return false; - if (media != null ? !media.equals(that.media) : that.media != null) return false; - - return true; - } - - @Override - public int hashCode() { - int result = media != null ? media.hashCode() : 0; - result = 31 * result + (images != null ? images.hashCode() : 0); - return result; - } - - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("[MediaContent: "); - sb.append("media=").append(media); - sb.append(", images=").append(images); - sb.append("]"); - return sb.toString(); - } - - public Media getMedia() { - return media; - } - - public void setMedia(Media media) { - this.media = media; - } - - public List getImages() { - return images; - } - - public void setImages(List images) { - this.images = images; - } -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/person/FullAddress.java b/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/person/FullAddress.java deleted file mode 100644 index 38921670f976..000000000000 --- a/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/person/FullAddress.java +++ /dev/null @@ -1,202 +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.model.person; - -import java.io.Serializable; - -public class FullAddress implements Serializable { - - private static final long serialVersionUID = 5163979984269419831L; - - private String countryId; - - private String countryName; - - private String provinceName; - - private String cityId; - - private String cityName; - - private String streetAddress; - - private String zipCode; - - public FullAddress() { - } - - public FullAddress(String countryId, String provinceName, String cityId, String streetAddress, - String zipCode) { - this.countryId = countryId; - this.countryName = countryId; - this.provinceName = provinceName; - this.cityId = cityId; - this.cityName = cityId; - this.streetAddress = streetAddress; - this.zipCode = zipCode; - } - - public FullAddress(String countryId, String countryName, String provinceName, String cityId, - String cityName, String streetAddress, String zipCode) { - this.countryId = countryId; - this.countryName = countryName; - this.provinceName = provinceName; - this.cityId = cityId; - this.cityName = cityName; - this.streetAddress = streetAddress; - this.zipCode = zipCode; - } - - public String getCountryId() { - return countryId; - } - - public void setCountryId(String countryId) { - this.countryId = countryId; - } - - public String getCountryName() { - return countryName; - } - - public void setCountryName(String countryName) { - this.countryName = countryName; - } - - public String getProvinceName() { - return provinceName; - } - - public void setProvinceName(String provinceName) { - this.provinceName = provinceName; - } - - public String getCityId() { - return cityId; - } - - public void setCityId(String cityId) { - this.cityId = cityId; - } - - public String getCityName() { - return cityName; - } - - public void setCityName(String cityName) { - this.cityName = cityName; - } - - public String getStreetAddress() { - return streetAddress; - } - - public void setStreetAddress(String streetAddress) { - this.streetAddress = streetAddress; - } - - public String getZipCode() { - return zipCode; - } - - public void setZipCode(String zipCode) { - this.zipCode = zipCode; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((cityId == null) ? 0 : cityId.hashCode()); - result = prime * result + ((cityName == null) ? 0 : cityName.hashCode()); - result = prime * result + ((countryId == null) ? 0 : countryId.hashCode()); - result = prime * result + ((countryName == null) ? 0 : countryName.hashCode()); - result = prime * result + ((provinceName == null) ? 0 : provinceName.hashCode()); - result = prime * result + ((streetAddress == null) ? 0 : streetAddress.hashCode()); - result = prime * result + ((zipCode == null) ? 0 : zipCode.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - FullAddress other = (FullAddress) obj; - if (cityId == null) { - if (other.cityId != null) - return false; - } else if (!cityId.equals(other.cityId)) - return false; - if (cityName == null) { - if (other.cityName != null) - return false; - } else if (!cityName.equals(other.cityName)) - return false; - if (countryId == null) { - if (other.countryId != null) - return false; - } else if (!countryId.equals(other.countryId)) - return false; - if (countryName == null) { - if (other.countryName != null) - return false; - } else if (!countryName.equals(other.countryName)) - return false; - if (provinceName == null) { - if (other.provinceName != null) - return false; - } else if (!provinceName.equals(other.provinceName)) - return false; - if (streetAddress == null) { - if (other.streetAddress != null) - return false; - } else if (!streetAddress.equals(other.streetAddress)) - return false; - if (zipCode == null) { - if (other.zipCode != null) - return false; - } else if (!zipCode.equals(other.zipCode)) - return false; - return true; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - if (countryName != null && countryName.length() > 0) { - sb.append(countryName); - } - if (provinceName != null && provinceName.length() > 0) { - sb.append(" "); - sb.append(provinceName); - } - if (cityName != null && cityName.length() > 0) { - sb.append(" "); - sb.append(cityName); - } - if (streetAddress != null && streetAddress.length() > 0) { - sb.append(" "); - sb.append(streetAddress); - } - return sb.toString(); - } - -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/person/PersonStatus.java b/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/person/PersonStatus.java deleted file mode 100644 index 62869c2b80b4..000000000000 --- a/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/person/PersonStatus.java +++ /dev/null @@ -1,22 +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.model.person; - -public enum PersonStatus { - ENABLED, - DISABLED -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/person/Phone.java b/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/person/Phone.java deleted file mode 100644 index 41fd38a92df7..000000000000 --- a/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/person/Phone.java +++ /dev/null @@ -1,139 +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.model.person; - -import java.io.Serializable; - -public class Phone implements Serializable { - - private static final long serialVersionUID = 4399060521859707703L; - - private String country; - - private String area; - - private String number; - - private String extensionNumber; - - public Phone() { - } - - public Phone(String country, String area, String number, String extensionNumber) { - this.country = country; - this.area = area; - this.number = number; - this.extensionNumber = extensionNumber; - } - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - public String getArea() { - return area; - } - - public void setArea(String area) { - this.area = area; - } - - public String getNumber() { - return number; - } - - public void setNumber(String number) { - this.number = number; - } - - public String getExtensionNumber() { - return extensionNumber; - } - - public void setExtensionNumber(String extensionNumber) { - this.extensionNumber = extensionNumber; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((area == null) ? 0 : area.hashCode()); - result = prime * result + ((country == null) ? 0 : country.hashCode()); - result = prime * result + ((extensionNumber == null) ? 0 : extensionNumber.hashCode()); - result = prime * result + ((number == null) ? 0 : number.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Phone other = (Phone) obj; - if (area == null) { - if (other.area != null) - return false; - } else if (!area.equals(other.area)) - return false; - if (country == null) { - if (other.country != null) - return false; - } else if (!country.equals(other.country)) - return false; - if (extensionNumber == null) { - if (other.extensionNumber != null) - return false; - } else if (!extensionNumber.equals(other.extensionNumber)) - return false; - if (number == null) { - if (other.number != null) - return false; - } else if (!number.equals(other.number)) - return false; - return true; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - if (country != null && country.length() > 0) { - sb.append(country); - sb.append("-"); - } - if (area != null && area.length() > 0) { - sb.append(area); - sb.append("-"); - } - if (number != null && number.length() > 0) { - sb.append(number); - } - if (extensionNumber != null && extensionNumber.length() > 0) { - sb.append("-"); - sb.append(extensionNumber); - } - return sb.toString(); - } - -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/serialize/serialization/AbstractSerializationPersonFailTest.java b/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/serialize/serialization/AbstractSerializationPersonFailTest.java deleted file mode 100644 index 5d27bb565585..000000000000 --- a/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/serialize/serialization/AbstractSerializationPersonFailTest.java +++ /dev/null @@ -1,137 +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.serialize.serialization; - -import org.apache.dubbo.common.model.Person; -import org.apache.dubbo.common.serialize.ObjectOutput; - -import org.junit.Test; - -import java.io.NotSerializableException; -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 static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; -import static org.junit.matchers.JUnitMatchers.containsString; - -public abstract class AbstractSerializationPersonFailTest extends AbstractSerializationTest { - @Test - public void test_Person() throws Exception { - try { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(new Person()); - fail(); - } catch (NotSerializableException expected) { - } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("Serialized class org.apache.dubbo.common.model.Person must implement java.io.Serializable")); - } - } - - @Test - public void test_PersonList() throws Exception { - List args = new ArrayList(); - args.add(new Person()); - try { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(args); - fail(); - } catch (NotSerializableException expected) { - } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("Serialized class org.apache.dubbo.common.model.Person must implement java.io.Serializable")); - } - } - - @Test - public void test_PersonSet() throws Exception { - Set args = new HashSet(); - args.add(new Person()); - try { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(args); - fail(); - } catch (NotSerializableException expected) { - } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("Serialized class org.apache.dubbo.common.model.Person must implement java.io.Serializable")); - } - } - - @Test - public void test_IntPersonMap() throws Exception { - Map args = new HashMap(); - args.put(1, new Person()); - try { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(args); - fail(); - } catch (NotSerializableException expected) { - } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("Serialized class org.apache.dubbo.common.model.Person must implement java.io.Serializable")); - } - } - - @Test - public void test_StringPersonMap() throws Exception { - Map args = new HashMap(); - args.put("1", new Person()); - try { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(args); - fail(); - } catch (NotSerializableException expected) { - } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("Serialized class org.apache.dubbo.common.model.Person must implement java.io.Serializable")); - } - } - - @Test - public void test_StringPersonListMap() throws Exception { - Map> args = new HashMap>(); - - List sublist = new ArrayList(); - sublist.add(new Person()); - args.put("1", sublist); - try { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(args); - fail(); - } catch (NotSerializableException expected) { - } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("Serialized class org.apache.dubbo.common.model.Person must implement java.io.Serializable")); - } - } - - @Test - public void test_PersonListList() throws Exception { - List> args = new ArrayList>(); - List sublist = new ArrayList(); - sublist.add(new Person()); - args.add(sublist); - try { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(args); - fail(); - } catch (NotSerializableException expected) { - } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("Serialized class org.apache.dubbo.common.model.Person must implement java.io.Serializable")); - } - } -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/serialize/serialization/AbstractSerializationPersonOkTest.java b/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/serialize/serialization/AbstractSerializationPersonOkTest.java deleted file mode 100644 index 03395cb0cd9e..000000000000 --- a/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/serialize/serialization/AbstractSerializationPersonOkTest.java +++ /dev/null @@ -1,93 +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.serialize.serialization; - -import org.apache.dubbo.common.model.Person; - -import org.junit.Test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -public abstract class AbstractSerializationPersonOkTest extends AbstractSerializationTest { - @Test - public void test_Person() throws Exception { - assertObject(new Person()); - } - - @Test - public void test_Person_withType() throws Exception { - assertObjectWithType(new Person(), Person.class); - } - - @Test - public void test_PersonList() throws Exception { - List args = new ArrayList(); - args.add(new Person()); - - assertObject(args); - } - - @Test - public void test_PersonSet() throws Exception { - Set args = new HashSet(); - args.add(new Person()); - - assertObject(args); - } - - @Test - public void test_IntPersonMap() throws Exception { - Map args = new HashMap(); - args.put(1, new Person()); - - assertObject(args); - } - - @Test - public void test_StringPersonMap() throws Exception { - Map args = new HashMap(); - args.put("1", new Person()); - - assertObject(args); - } - - @Test - public void test_StringPersonListMap() throws Exception { - Map> args = new HashMap>(); - - List sublist = new ArrayList(); - sublist.add(new Person()); - args.put("1", sublist); - - assertObject(args); - } - - @Test - public void test_PersonListList() throws Exception { - List> args = new ArrayList>(); - List sublist = new ArrayList(); - sublist.add(new Person()); - args.add(sublist); - - assertObject(args); - } -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/serialize/serialization/AbstractSerializationTest.java b/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/serialize/serialization/AbstractSerializationTest.java deleted file mode 100644 index a40e37809447..000000000000 --- a/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/serialize/serialization/AbstractSerializationTest.java +++ /dev/null @@ -1,1210 +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.serialize.serialization; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.model.AnimalEnum; -import org.apache.dubbo.common.model.BizException; -import org.apache.dubbo.common.model.BizExceptionNoDefaultConstructor; -import org.apache.dubbo.common.model.SerializablePerson; -import org.apache.dubbo.common.model.media.Image; -import org.apache.dubbo.common.model.media.Image.Size; -import org.apache.dubbo.common.model.media.Media; -import org.apache.dubbo.common.model.media.Media.Player; -import org.apache.dubbo.common.model.media.MediaContent; -import org.apache.dubbo.common.model.person.BigPerson; -import org.apache.dubbo.common.model.person.FullAddress; -import org.apache.dubbo.common.model.person.PersonInfo; -import org.apache.dubbo.common.model.person.PersonStatus; -import org.apache.dubbo.common.model.person.Phone; -import org.apache.dubbo.common.serialize.ObjectInput; -import org.apache.dubbo.common.serialize.ObjectOutput; -import org.apache.dubbo.common.serialize.Serialization; - -import org.junit.Test; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.sql.Time; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.Set; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -public abstract class AbstractSerializationTest { - static Random random = new Random(); - Serialization serialization; - URL url = new URL("protocol", "1.1.1.1", 1234); - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - - // ================ Primitive Type ================ - BigPerson bigPerson; - MediaContent mediaContent; - - { - bigPerson = new BigPerson(); - bigPerson.setPersonId("superman111"); - bigPerson.setLoginName("superman"); - bigPerson.setStatus(PersonStatus.ENABLED); - bigPerson.setEmail("sm@1.com"); - bigPerson.setPenName("pname"); - - ArrayList phones = new ArrayList(); - Phone phone1 = new Phone("86", "0571", "87654321", "001"); - Phone phone2 = new Phone("86", "0571", "87654322", "002"); - phones.add(phone1); - phones.add(phone2); - - PersonInfo pi = new PersonInfo(); - pi.setPhones(phones); - Phone fax = new Phone("86", "0571", "87654321", null); - pi.setFax(fax); - FullAddress addr = new FullAddress("CN", "zj", "3480", "wensanlu", "315000"); - pi.setFullAddress(addr); - pi.setMobileNo("13584652131"); - pi.setMale(true); - pi.setDepartment("b2b"); - pi.setHomepageUrl("www.capcom.com"); - pi.setJobTitle("qa"); - pi.setName("superman"); - - bigPerson.setInfoProfile(pi); - } - - { - Media media = new Media(); - media.setUri("uri://中华人民共和国"); - media.setTitle("title"); - media.setWidth(1239); - media.setHeight(1938); - media.setFormat("format-xxxx"); - media.setDuration(93419235); - media.setSize(3477897); - media.setBitrate(94523); - List persons = new ArrayList(); - persons.add("jerry"); - persons.add("tom"); - persons.add("lucy"); - media.setPersons(persons); - media.setCopyright("1999-2011"); - media.setPlayer(Player.FLASH); - - List images = new ArrayList(); - for (int i = 0; i < 10; ++i) { - Image image = new Image(); - image.setUri("url" + i); - if (i % 2 == 0) image.setTitle("title" + i); - image.setWidth(34 + i); - image.setHeight(2323 + i); - image.setSize((i % 2 == 0) ? Size.SMALL : Size.LARGE); - - images.add(image); - } - - mediaContent = new MediaContent(media, images); - } - - @Test - public void test_Bool() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeBool(false); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertFalse(deserialize.readBool()); - - try { - deserialize.readBool(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_Bool_Multi() throws Exception { - boolean[] array = new boolean[100]; - for (int i = 0; i < array.length; i++) { - array[i] = random.nextBoolean(); - } - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - for (boolean b : array) { - objectOutput.writeBool(b); - } - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - for (boolean b : array) { - assertEquals(b, deserialize.readBool()); - } - - try { - deserialize.readBool(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_Byte() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeByte((byte) 123); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertEquals((byte) 123, deserialize.readByte()); - - try { - deserialize.readByte(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_Byte_Multi() throws Exception { - byte[] array = new byte[100]; - random.nextBytes(array); - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - for (byte b : array) { - objectOutput.writeByte(b); - } - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - for (byte b : array) { - assertEquals(b, deserialize.readByte()); - } - - try { - deserialize.readByte(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_Short() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeShort((short) 123); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertEquals((short) 123, deserialize.readShort()); - - try { - deserialize.readShort(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_Integer() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeInt(1); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - int i = deserialize.readInt(); - assertEquals(1, i); - - try { - deserialize.readInt(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_Long() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeLong(123L); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertEquals(123L, deserialize.readLong()); - - try { - deserialize.readLong(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_Float() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeFloat(1.28F); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertTrue(1.28F == deserialize.readFloat()); - - try { - deserialize.readFloat(); - fail(); - } catch (IOException expected) { - } - } - - // ================== Util methods ================== - - @Test - public void test_Double() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeDouble(1.28); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertTrue(1.28 == deserialize.readDouble()); - - try { - deserialize.readDouble(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_UtfString() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeUTF("123中华人民共和国"); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertEquals("123中华人民共和国", deserialize.readUTF()); - - try { - deserialize.readUTF(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_Bytes() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeBytes("123中华人民共和国".getBytes()); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals("123中华人民共和国".getBytes(), deserialize.readBytes()); - - try { - deserialize.readBytes(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_BytesRange() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeBytes("123中华人民共和国-新疆维吾尔自治区".getBytes(), 1, 9); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - byte[] expectedArray = new byte[9]; - System.arraycopy("123中华人民共和国-新疆维吾尔自治区".getBytes(), 1, expectedArray, 0, expectedArray.length); - assertArrayEquals(expectedArray, deserialize.readBytes()); - - try { - deserialize.readBytes(); - fail(); - } catch (IOException expected) { - } - } - - // ================ Array Type ================ - - void assertObjectArray(T[] data, Class clazz) throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, clazz.cast(deserialize.readObject())); - - try { - deserialize.readObject(); - fail(); - } catch (IOException expected) { - } - } - - void assertObjectArrayWithType(T[] data, Class clazz) throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, clazz.cast(deserialize.readObject(clazz))); - - try { - deserialize.readObject(clazz); - fail(); - } catch (IOException expected) { - } - } - - @SuppressWarnings("unchecked") - void assertObject(T data) throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertEquals(data, (T) deserialize.readObject()); - - try { - deserialize.readObject(); - fail(); - } catch (IOException expected) { - } - } - - void assertObjectWithType(T data, Class clazz) throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertEquals(data, (T) deserialize.readObject(clazz)); - - try { - deserialize.readObject(clazz); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_boolArray() throws Exception { - boolean[] data = new boolean[]{true, false, true}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertTrue(Arrays.equals(data, (boolean[]) deserialize.readObject())); - - try { - deserialize.readObject(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_boolArray_withType() throws Exception { - boolean[] data = new boolean[]{true, false, true}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertTrue(Arrays.equals(data, (boolean[]) deserialize.readObject(boolean[].class))); - - try { - deserialize.readObject(boolean[].class); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_charArray() throws Exception { - char[] data = new char[]{'a', '中', '无'}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, (char[]) deserialize.readObject()); - - try { - deserialize.readObject(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_charArray_withType() throws Exception { - char[] data = new char[]{'a', '中', '无'}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, (char[]) deserialize.readObject(char[].class)); - - try { - deserialize.readObject(char[].class); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_shortArray() throws Exception { - short[] data = new short[]{37, 39, 12}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, (short[]) deserialize.readObject()); - - try { - deserialize.readObject(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_shortArray_withType() throws Exception { - short[] data = new short[]{37, 39, 12}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, (short[]) deserialize.readObject(short[].class)); - - try { - deserialize.readObject(short[].class); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_intArray() throws Exception { - int[] data = new int[]{234, 0, -1}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, (int[]) deserialize.readObject()); - - try { - deserialize.readObject(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_intArray_withType() throws Exception { - int[] data = new int[]{234, 0, -1}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, (int[]) deserialize.readObject(int[].class)); - - try { - deserialize.readObject(int[].class); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_longArray() throws Exception { - long[] data = new long[]{234, 0, -1}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, (long[]) deserialize.readObject()); - - try { - deserialize.readObject(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_longArray_withType() throws Exception { - long[] data = new long[]{234, 0, -1}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, (long[]) deserialize.readObject(long[].class)); - - try { - deserialize.readObject(long[].class); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_floatArray() throws Exception { - float[] data = new float[]{37F, -3.14F, 123456.7F}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, (float[]) deserialize.readObject(), 0.0001F); - - try { - deserialize.readObject(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_floatArray_withType() throws Exception { - float[] data = new float[]{37F, -3.14F, 123456.7F}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, (float[]) deserialize.readObject(float[].class), 0.0001F); - - try { - deserialize.readObject(float[].class); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_doubleArray() throws Exception { - double[] data = new double[]{37D, -3.14D, 123456.7D}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, (double[]) deserialize.readObject(), 0.0001); - - try { - deserialize.readObject(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_doubleArray_withType() throws Exception { - double[] data = new double[]{37D, -3.14D, 123456.7D}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, (double[]) deserialize.readObject(double[].class), 0.0001); - - try { - deserialize.readObject(double[].class); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_StringArray() throws Exception { - assertObjectArray(new String[]{"1", "b"}, String[].class); - } - - @Test - public void test_StringArray_withType() throws Exception { - assertObjectArrayWithType(new String[]{"1", "b"}, String[].class); - } - - // ================ Simple Type ================ - - @Test - public void test_IntegerArray() throws Exception { - assertObjectArray(new Integer[]{234, 0, -1}, Integer[].class); - } - - @Test - public void test_IntegerArray_withType() throws Exception { - assertObjectArrayWithType(new Integer[]{234, 0, -1}, Integer[].class); - } - - @Test - public void test_EnumArray() throws Exception { - assertObjectArray(new AnimalEnum[]{AnimalEnum.bull, AnimalEnum.cat, AnimalEnum.dog, AnimalEnum.horse}, AnimalEnum[].class); - } - - @Test - public void test_EnumArray_withType() throws Exception { - assertObjectArrayWithType(new AnimalEnum[]{AnimalEnum.bull, AnimalEnum.cat, AnimalEnum.dog, AnimalEnum.horse}, AnimalEnum[].class); - } - - @Test - public void test_SPerson() throws Exception { - assertObject(new SerializablePerson()); - } - - @Test - public void test_SPerson_withType() throws Exception { - assertObjectWithType(new SerializablePerson(), SerializablePerson.class); - } - - @Test - public void test_BizException() throws Exception { - BizException e = new BizException("Hello"); - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(e); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - Object read = deserialize.readObject(); - assertEquals("Hello", ((BizException) read).getMessage()); - } - - @Test - public void test_BizException_WithType() throws Exception { - BizException e = new BizException("Hello"); - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(e); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - Object read = deserialize.readObject(BizException.class); - assertEquals("Hello", ((BizException) read).getMessage()); - } - - @Test - public void test_BizExceptionNoDefaultConstructor() throws Exception { - BizExceptionNoDefaultConstructor e = new BizExceptionNoDefaultConstructor("Hello"); - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(e); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - Object read = deserialize.readObject(); - assertEquals("Hello", ((BizExceptionNoDefaultConstructor) read).getMessage()); - } - - @Test - public void test_BizExceptionNoDefaultConstructor_WithType() throws Exception { - BizExceptionNoDefaultConstructor e = new BizExceptionNoDefaultConstructor("Hello"); - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(e); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - Object read = deserialize.readObject(BizExceptionNoDefaultConstructor.class); - assertEquals("Hello", ((BizExceptionNoDefaultConstructor) read).getMessage()); - } - - @Test - public void test_enum() throws Exception { - assertObject(AnimalEnum.dog); - } - - @Test - public void test_enum_withType() throws Exception { - assertObjectWithType(AnimalEnum.dog, AnimalEnum.class); - } - - @Test - public void test_Date() throws Exception { - assertObject(new Date()); - } - - @Test - public void test_Date_withType() throws Exception { - assertObjectWithType(new Date(), Date.class); - } - - @Test - public void test_Time() throws Exception { - assertObject(new Time(System.currentTimeMillis())); - } - - @Test - public void test_Time_withType() throws Exception { - assertObjectWithType(new Time(System.currentTimeMillis()), Time.class); - } - - @Test - public void test_ByteWrap() throws Exception { - assertObject(new Byte((byte) 12)); - } - - @Test - public void test_ByteWrap_withType() throws Exception { - assertObjectWithType(new Byte((byte) 12), Byte.class); - } - - @Test - public void test_LongWrap() throws Exception { - assertObject(new Long(12)); - } - - @Test - public void test_LongWrap_withType() throws Exception { - assertObjectWithType(new Long(12), Long.class); - } - - @Test - public void test_BigInteger() throws Exception { - assertObject(new BigInteger("23423434234234234")); - } - - @Test - public void test_BigInteger_withType() throws Exception { - assertObjectWithType(new BigInteger("23423434234234234"), BigInteger.class); - } - - @Test - public void test_BigDecimal() throws Exception { - assertObject(new BigDecimal("23423434234234234.341274832341234235")); - } - - @Test - public void test_BigDecimal_withType() throws Exception { - assertObjectWithType(new BigDecimal("23423434234234234.341274832341234235"), BigDecimal.class); - } - - @Test - public void test_StringList_asListReturn() throws Exception { - List args = Arrays.asList(new String[]{"1", "b"}); - - assertObject(args); - } - - @Test - public void test_StringArrayList() throws Exception { - List args = new ArrayList(Arrays.asList(new String[]{"1", "b"})); - - assertObject(args); - } - - @Test - public void test_StringSet() throws Exception { - Set args = new HashSet(); - args.add("1"); - - assertObject(args); - } - - @Test - public void test_LinkedHashMap() throws Exception { - LinkedHashMap data = new LinkedHashMap(); - data.put("1", "a"); - data.put("2", "b"); - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - Object read = deserialize.readObject(); - assertTrue(read instanceof LinkedHashMap); - @SuppressWarnings("unchecked") - String key1 = ((LinkedHashMap) read).entrySet().iterator().next().getKey(); - assertEquals("1", key1); - - assertEquals(data, read); - - try { - deserialize.readObject(); - fail(); - } catch (IOException expected) { - } - } - - // ================ Complex Collection Type ================ - - @Test - public void test_SPersonList() throws Exception { - List args = new ArrayList(); - args.add(new SerializablePerson()); - - assertObject(args); - } - - @Test - public void test_SPersonSet() throws Exception { - Set args = new HashSet(); - args.add(new SerializablePerson()); - - assertObject(args); - } - - // ================ complex POJO ============= - - @Test - public void test_IntSPersonMap() throws Exception { - Map args = new HashMap(); - args.put(1, new SerializablePerson()); - - assertObject(args); - } - - @Test - public void test_StringSPersonMap() throws Exception { - Map args = new HashMap(); - args.put("1", new SerializablePerson()); - - assertObject(args); - } - - @Test - public void test_StringSPersonListMap() throws Exception { - Map> args = new HashMap>(); - - List sublist = new ArrayList(); - sublist.add(new SerializablePerson()); - args.put("1", sublist); - - assertObject(args); - } - - @Test - public void test_SPersonListList() throws Exception { - List> args = new ArrayList>(); - List sublist = new ArrayList(); - sublist.add(new SerializablePerson()); - args.add(sublist); - - assertObject(args); - } - - @Test - public void test_BigPerson() throws Exception { - assertObject(bigPerson); - } - - @Test - public void test_BigPerson_WithType() throws Exception { - assertObjectWithType(bigPerson, BigPerson.class); - } - - @Test - public void test_MediaContent() throws Exception { - assertObject(mediaContent); - } - - @Test - public void test_MediaContent_WithType() throws Exception { - assertObjectWithType(mediaContent, MediaContent.class); - } - - @Test - public void test_MultiObject() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeBool(false); - objectOutput.writeObject(bigPerson); - objectOutput.writeByte((byte) 23); - objectOutput.writeObject(mediaContent); - objectOutput.writeInt(-23); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertEquals(false, deserialize.readBool()); - assertEquals(bigPerson, deserialize.readObject()); - assertEquals((byte) 23, deserialize.readByte()); - assertEquals(mediaContent, deserialize.readObject()); - assertEquals(-23, deserialize.readInt()); - - try { - deserialize.readObject(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_MultiObject_WithType() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeBool(false); - objectOutput.writeObject(bigPerson); - objectOutput.writeByte((byte) 23); - objectOutput.writeObject(mediaContent); - objectOutput.writeInt(-23); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertEquals(false, deserialize.readBool()); - assertEquals(bigPerson, deserialize.readObject(BigPerson.class)); - assertEquals((byte) 23, deserialize.readByte()); - assertEquals(mediaContent, deserialize.readObject(MediaContent.class)); - assertEquals(-23, deserialize.readInt()); - - try { - deserialize.readObject(); - fail(); - } catch (IOException expected) { - } - } - - - // abnormal case - - @Test - public void test_MediaContent_badStream() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(mediaContent); - objectOutput.flushBuffer(); - - byte[] byteArray = byteArrayOutputStream.toByteArray(); - for (int i = 0; i < byteArray.length; i++) { - if (i % 3 == 0) { - byteArray[i] = (byte) ~byteArray[i]; - } - } - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray); - - try { - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - @SuppressWarnings("unused") // local variable, convenient for debug - Object read = deserialize.readObject(); - fail(); - } catch (IOException expected) { - System.out.println(expected); - } - } - - @Test - public void test_MediaContent_WithType_badStream() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(mediaContent); - objectOutput.flushBuffer(); - - byte[] byteArray = byteArrayOutputStream.toByteArray(); - for (int i = 0; i < byteArray.length; i++) { - if (i % 3 == 0) { - byteArray[i] = (byte) ~byteArray[i]; - } - } - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray); - - try { - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - @SuppressWarnings("unused") // local variable, convenient for debug - Object read = deserialize.readObject(MediaContent.class); - fail(); - } catch (IOException expected) { - System.out.println(expected); - } - } - - - @Test(timeout = 3000) - public void test_LoopReference() throws Exception { - Map map = new HashMap(); - map.put("k1", "v1"); - map.put("self", map); - - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(map); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - @SuppressWarnings("unchecked") - Map output = (Map) deserialize.readObject(); - - assertEquals("v1", output.get("k1")); - assertSame(output, output.get("self")); - } - - // ================ final field test ================ - - @Test - public void test_URL_mutable_withType() throws Exception { - URL data = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&noValue"); - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - URL actual = (URL) deserialize.readObject(URL.class); - assertEquals(data, actual); - assertEquals(data.getParameters(), actual.getParameters()); - - try { - deserialize.readObject(); - fail(); - } catch (IOException expected) { - } - } -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/test/resources/log4j.xml b/dubbo-serialization/dubbo-serialization-jdk/src/test/resources/log4j.xml deleted file mode 100644 index d045b92c0de6..000000000000 --- a/dubbo-serialization/dubbo-serialization-jdk/src/test/resources/log4j.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/test/resources/org/apache/dubbo/common/serialize/dubbo/SimpleDO.fc b/dubbo-serialization/dubbo-serialization-jdk/src/test/resources/org/apache/dubbo/common/serialize/dubbo/SimpleDO.fc deleted file mode 100644 index c8c083c17eb1..000000000000 --- a/dubbo-serialization/dubbo-serialization-jdk/src/test/resources/org/apache/dubbo/common/serialize/dubbo/SimpleDO.fc +++ /dev/null @@ -1,2 +0,0 @@ -a,d,e,b,c -str3,str2 \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/CompatibleKryo.java b/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/CompatibleKryo.java index ba854e5381b9..69e4b35b16f4 100644 --- a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/CompatibleKryo.java +++ b/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/CompatibleKryo.java @@ -16,13 +16,14 @@ */ package org.apache.dubbo.common.serialize.kryo; -import com.esotericsoftware.kryo.Kryo; -import com.esotericsoftware.kryo.Serializer; -import com.esotericsoftware.kryo.serializers.JavaSerializer; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.kryo.utils.ReflectionUtils; +import com.esotericsoftware.kryo.Kryo; +import com.esotericsoftware.kryo.Serializer; +import com.esotericsoftware.kryo.serializers.JavaSerializer; + public class CompatibleKryo extends Kryo { private static final Logger logger = LoggerFactory.getLogger(CompatibleKryo.class); diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/AbstractKryoFactory.java b/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/AbstractKryoFactory.java index 523b59f7b306..541a5e7dd028 100644 --- a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/AbstractKryoFactory.java +++ b/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/AbstractKryoFactory.java @@ -16,6 +16,9 @@ */ package org.apache.dubbo.common.serialize.kryo.utils; +import org.apache.dubbo.common.serialize.kryo.CompatibleKryo; +import org.apache.dubbo.common.serialize.support.SerializableClassRegistry; + import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.pool.KryoFactory; @@ -29,8 +32,6 @@ import de.javakaffee.kryoserializers.URISerializer; import de.javakaffee.kryoserializers.UUIDSerializer; import de.javakaffee.kryoserializers.UnmodifiableCollectionsSerializer; -import org.apache.dubbo.common.serialize.kryo.CompatibleKryo; -import org.apache.dubbo.common.serialize.support.SerializableClassRegistry; import java.lang.reflect.InvocationHandler; import java.math.BigDecimal; diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/model/AnimalEnum.java b/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/model/AnimalEnum.java deleted file mode 100644 index 760663fe04cf..000000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/model/AnimalEnum.java +++ /dev/null @@ -1,21 +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.model; - -public enum AnimalEnum { - dog, cat, rat, cow, bull, horse; -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/model/BizExceptionNoDefaultConstructor.java b/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/model/BizExceptionNoDefaultConstructor.java deleted file mode 100644 index f1ffadb0234a..000000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/model/BizExceptionNoDefaultConstructor.java +++ /dev/null @@ -1,26 +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.model; - -public class BizExceptionNoDefaultConstructor extends RuntimeException { - - private static final long serialVersionUID = 1L; - - public BizExceptionNoDefaultConstructor(String message) { - super(message); - } -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/model/Person.java b/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/model/Person.java deleted file mode 100644 index 5a551a7f36b9..000000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/model/Person.java +++ /dev/null @@ -1,95 +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.model; - -import java.util.Arrays; - -public class Person { - byte oneByte = 123; - private String name = "name1"; - private int age = 11; - - private String[] value = {"value1", "value2"}; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public byte getOneByte() { - return oneByte; - } - - public void setOneByte(byte b) { - this.oneByte = b; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - - public String[] getValue() { - return value; - } - - public void setValue(String[] value) { - this.value = value; - } - - @Override - public String toString() { - return String.format("Person name(%s) age(%d) byte(%s) [value=%s]", name, age, oneByte, Arrays.toString(value)); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + age; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + Arrays.hashCode(value); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Person other = (Person) obj; - if (age != other.age) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (!Arrays.equals(value, other.value)) - return false; - return true; - } -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/model/media/Image.java b/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/model/media/Image.java deleted file mode 100644 index a59eff35be68..000000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/model/media/Image.java +++ /dev/null @@ -1,120 +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.model.media; - - -public class Image implements java.io.Serializable { - private static final long serialVersionUID = 1L; - public String uri; - public String title; // Can be null - public int width; - public int height; - public Size size; - - public Image() { - } - - public Image(String uri, String title, int width, int height, Size size) { - this.height = height; - this.title = title; - this.uri = uri; - this.width = width; - this.size = size; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - Image image = (Image) o; - - if (height != image.height) return false; - if (width != image.width) return false; - if (size != image.size) return false; - if (title != null ? !title.equals(image.title) : image.title != null) return false; - if (uri != null ? !uri.equals(image.uri) : image.uri != null) return false; - - return true; - } - - @Override - public int hashCode() { - int result = uri != null ? uri.hashCode() : 0; - result = 31 * result + (title != null ? title.hashCode() : 0); - result = 31 * result + width; - result = 31 * result + height; - result = 31 * result + (size != null ? size.hashCode() : 0); - return result; - } - - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("[Image "); - sb.append("uri=").append(uri); - sb.append(", title=").append(title); - sb.append(", width=").append(width); - sb.append(", height=").append(height); - sb.append(", size=").append(size); - sb.append("]"); - return sb.toString(); - } - - public String getUri() { - return uri; - } - - public void setUri(String uri) { - this.uri = uri; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public int getWidth() { - return width; - } - - public void setWidth(int width) { - this.width = width; - } - - public int getHeight() { - return height; - } - - public void setHeight(int height) { - this.height = height; - } - - public Size getSize() { - return size; - } - - public void setSize(Size size) { - this.size = size; - } - - public enum Size { - SMALL, LARGE - } -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/model/media/MediaContent.java b/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/model/media/MediaContent.java deleted file mode 100644 index 7991f5061012..000000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/model/media/MediaContent.java +++ /dev/null @@ -1,78 +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.model.media; - -import java.util.List; - -@SuppressWarnings("serial") -public class MediaContent implements java.io.Serializable { - public Media media; - public List images; - - public MediaContent() { - } - - public MediaContent(Media media, List images) { - this.media = media; - this.images = images; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - MediaContent that = (MediaContent) o; - - if (images != null ? !images.equals(that.images) : that.images != null) return false; - if (media != null ? !media.equals(that.media) : that.media != null) return false; - - return true; - } - - @Override - public int hashCode() { - int result = media != null ? media.hashCode() : 0; - result = 31 * result + (images != null ? images.hashCode() : 0); - return result; - } - - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("[MediaContent: "); - sb.append("media=").append(media); - sb.append(", images=").append(images); - sb.append("]"); - return sb.toString(); - } - - public Media getMedia() { - return media; - } - - public void setMedia(Media media) { - this.media = media; - } - - public List getImages() { - return images; - } - - public void setImages(List images) { - this.images = images; - } -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/model/person/BigPerson.java b/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/model/person/BigPerson.java deleted file mode 100644 index 4ce79008fb4e..000000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/model/person/BigPerson.java +++ /dev/null @@ -1,151 +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.model.person; - -import java.io.Serializable; - -public class BigPerson implements Serializable { - private static final long serialVersionUID = 1L; - - String personId; - - String loginName; - - PersonStatus status; - - String email; - - String penName; - - PersonInfo infoProfile; - - public BigPerson() { - - } - - public BigPerson(String id) { - this.personId = id; - } - - public String getPersonId() { - return personId; - } - - public void setPersonId(String personId) { - this.personId = personId; - } - - public PersonInfo getInfoProfile() { - return infoProfile; - } - - public void setInfoProfile(PersonInfo infoProfile) { - this.infoProfile = infoProfile; - } - - public String getEmail() { - return this.email; - } - - public void setEmail(String email) { - this.email = email; - } - - public String getLoginName() { - return this.loginName; - } - - public void setLoginName(String loginName) { - this.loginName = loginName; - } - - public PersonStatus getStatus() { - return this.status; - } - - public void setStatus(PersonStatus status) { - this.status = status; - } - - public String getPenName() { - return penName; - } - - public void setPenName(String penName) { - this.penName = penName; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((email == null) ? 0 : email.hashCode()); - result = prime * result + ((infoProfile == null) ? 0 : infoProfile.hashCode()); - result = prime * result + ((loginName == null) ? 0 : loginName.hashCode()); - result = prime * result + ((penName == null) ? 0 : penName.hashCode()); - result = prime * result + ((personId == null) ? 0 : personId.hashCode()); - result = prime * result + ((status == null) ? 0 : status.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - BigPerson other = (BigPerson) obj; - if (email == null) { - if (other.email != null) - return false; - } else if (!email.equals(other.email)) - return false; - if (infoProfile == null) { - if (other.infoProfile != null) - return false; - } else if (!infoProfile.equals(other.infoProfile)) - return false; - if (loginName == null) { - if (other.loginName != null) - return false; - } else if (!loginName.equals(other.loginName)) - return false; - if (penName == null) { - if (other.penName != null) - return false; - } else if (!penName.equals(other.penName)) - return false; - if (personId == null) { - if (other.personId != null) - return false; - } else if (!personId.equals(other.personId)) - return false; - if (status != other.status) - return false; - return true; - } - - @Override - public String toString() { - return "BigPerson [personId=" + personId + ", loginName=" + loginName + ", status=" - + status + ", email=" + email + ", penName=" + penName + ", infoProfile=" - + infoProfile + "]"; - } - -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/model/person/FullAddress.java b/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/model/person/FullAddress.java deleted file mode 100644 index 38921670f976..000000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/model/person/FullAddress.java +++ /dev/null @@ -1,202 +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.model.person; - -import java.io.Serializable; - -public class FullAddress implements Serializable { - - private static final long serialVersionUID = 5163979984269419831L; - - private String countryId; - - private String countryName; - - private String provinceName; - - private String cityId; - - private String cityName; - - private String streetAddress; - - private String zipCode; - - public FullAddress() { - } - - public FullAddress(String countryId, String provinceName, String cityId, String streetAddress, - String zipCode) { - this.countryId = countryId; - this.countryName = countryId; - this.provinceName = provinceName; - this.cityId = cityId; - this.cityName = cityId; - this.streetAddress = streetAddress; - this.zipCode = zipCode; - } - - public FullAddress(String countryId, String countryName, String provinceName, String cityId, - String cityName, String streetAddress, String zipCode) { - this.countryId = countryId; - this.countryName = countryName; - this.provinceName = provinceName; - this.cityId = cityId; - this.cityName = cityName; - this.streetAddress = streetAddress; - this.zipCode = zipCode; - } - - public String getCountryId() { - return countryId; - } - - public void setCountryId(String countryId) { - this.countryId = countryId; - } - - public String getCountryName() { - return countryName; - } - - public void setCountryName(String countryName) { - this.countryName = countryName; - } - - public String getProvinceName() { - return provinceName; - } - - public void setProvinceName(String provinceName) { - this.provinceName = provinceName; - } - - public String getCityId() { - return cityId; - } - - public void setCityId(String cityId) { - this.cityId = cityId; - } - - public String getCityName() { - return cityName; - } - - public void setCityName(String cityName) { - this.cityName = cityName; - } - - public String getStreetAddress() { - return streetAddress; - } - - public void setStreetAddress(String streetAddress) { - this.streetAddress = streetAddress; - } - - public String getZipCode() { - return zipCode; - } - - public void setZipCode(String zipCode) { - this.zipCode = zipCode; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((cityId == null) ? 0 : cityId.hashCode()); - result = prime * result + ((cityName == null) ? 0 : cityName.hashCode()); - result = prime * result + ((countryId == null) ? 0 : countryId.hashCode()); - result = prime * result + ((countryName == null) ? 0 : countryName.hashCode()); - result = prime * result + ((provinceName == null) ? 0 : provinceName.hashCode()); - result = prime * result + ((streetAddress == null) ? 0 : streetAddress.hashCode()); - result = prime * result + ((zipCode == null) ? 0 : zipCode.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - FullAddress other = (FullAddress) obj; - if (cityId == null) { - if (other.cityId != null) - return false; - } else if (!cityId.equals(other.cityId)) - return false; - if (cityName == null) { - if (other.cityName != null) - return false; - } else if (!cityName.equals(other.cityName)) - return false; - if (countryId == null) { - if (other.countryId != null) - return false; - } else if (!countryId.equals(other.countryId)) - return false; - if (countryName == null) { - if (other.countryName != null) - return false; - } else if (!countryName.equals(other.countryName)) - return false; - if (provinceName == null) { - if (other.provinceName != null) - return false; - } else if (!provinceName.equals(other.provinceName)) - return false; - if (streetAddress == null) { - if (other.streetAddress != null) - return false; - } else if (!streetAddress.equals(other.streetAddress)) - return false; - if (zipCode == null) { - if (other.zipCode != null) - return false; - } else if (!zipCode.equals(other.zipCode)) - return false; - return true; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - if (countryName != null && countryName.length() > 0) { - sb.append(countryName); - } - if (provinceName != null && provinceName.length() > 0) { - sb.append(" "); - sb.append(provinceName); - } - if (cityName != null && cityName.length() > 0) { - sb.append(" "); - sb.append(cityName); - } - if (streetAddress != null && streetAddress.length() > 0) { - sb.append(" "); - sb.append(streetAddress); - } - return sb.toString(); - } - -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/model/person/PersonInfo.java b/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/model/person/PersonInfo.java deleted file mode 100644 index 15f1238fe854..000000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/model/person/PersonInfo.java +++ /dev/null @@ -1,206 +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.model.person; - -import java.io.Serializable; -import java.util.List; - -public class PersonInfo implements Serializable { - private static final long serialVersionUID = 7443011149612231882L; - - List phones; - - Phone fax; - - FullAddress fullAddress; - - String mobileNo; - - String name; - - boolean male; - - boolean female; - - String department; - - String jobTitle; - - String homepageUrl; - - public List getPhones() { - return phones; - } - - public void setPhones(List phones) { - this.phones = phones; - } - - public boolean isMale() { - return male; - } - - public void setMale(boolean male) { - this.male = male; - } - - public boolean isFemale() { - return female; - } - - public void setFemale(boolean female) { - this.female = female; - } - - public String getDepartment() { - return department; - } - - public void setDepartment(String department) { - this.department = department; - } - - public Phone getFax() { - return fax; - } - - public void setFax(Phone fax) { - this.fax = fax; - } - - public FullAddress getFullAddress() { - return fullAddress; - } - - public void setFullAddress(FullAddress fullAddress) { - this.fullAddress = fullAddress; - } - - public String getHomepageUrl() { - return homepageUrl; - } - - public void setHomepageUrl(String homepageUrl) { - this.homepageUrl = homepageUrl; - } - - public String getJobTitle() { - return jobTitle; - } - - public void setJobTitle(String jobTitle) { - this.jobTitle = jobTitle; - } - - public String getMobileNo() { - return mobileNo; - } - - public void setMobileNo(String mobileNo) { - this.mobileNo = mobileNo; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((department == null) ? 0 : department.hashCode()); - result = prime * result + ((fax == null) ? 0 : fax.hashCode()); - result = prime * result + (female ? 1231 : 1237); - result = prime * result + ((fullAddress == null) ? 0 : fullAddress.hashCode()); - result = prime * result + ((homepageUrl == null) ? 0 : homepageUrl.hashCode()); - result = prime * result + ((jobTitle == null) ? 0 : jobTitle.hashCode()); - result = prime * result + (male ? 1231 : 1237); - result = prime * result + ((mobileNo == null) ? 0 : mobileNo.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((phones == null) ? 0 : phones.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - PersonInfo other = (PersonInfo) obj; - if (department == null) { - if (other.department != null) - return false; - } else if (!department.equals(other.department)) - return false; - if (fax == null) { - if (other.fax != null) - return false; - } else if (!fax.equals(other.fax)) - return false; - if (female != other.female) - return false; - if (fullAddress == null) { - if (other.fullAddress != null) - return false; - } else if (!fullAddress.equals(other.fullAddress)) - return false; - if (homepageUrl == null) { - if (other.homepageUrl != null) - return false; - } else if (!homepageUrl.equals(other.homepageUrl)) - return false; - if (jobTitle == null) { - if (other.jobTitle != null) - return false; - } else if (!jobTitle.equals(other.jobTitle)) - return false; - if (male != other.male) - return false; - if (mobileNo == null) { - if (other.mobileNo != null) - return false; - } else if (!mobileNo.equals(other.mobileNo)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (phones == null) { - if (other.phones != null) - return false; - } else if (!phones.equals(other.phones)) - return false; - return true; - } - - @Override - public String toString() { - return "PersonInfo [phones=" + phones + ", fax=" + fax + ", fullAddress=" + fullAddress - + ", mobileNo=" + mobileNo + ", name=" + name + ", male=" + male + ", female=" - + female + ", department=" + department + ", jobTitle=" + jobTitle - + ", homepageUrl=" + homepageUrl + "]"; - } - -} diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/serialize/serialization/AbstractSerializationPersonOkTest.java b/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/serialize/serialization/AbstractSerializationPersonOkTest.java deleted file mode 100644 index 03395cb0cd9e..000000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/serialize/serialization/AbstractSerializationPersonOkTest.java +++ /dev/null @@ -1,93 +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.serialize.serialization; - -import org.apache.dubbo.common.model.Person; - -import org.junit.Test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -public abstract class AbstractSerializationPersonOkTest extends AbstractSerializationTest { - @Test - public void test_Person() throws Exception { - assertObject(new Person()); - } - - @Test - public void test_Person_withType() throws Exception { - assertObjectWithType(new Person(), Person.class); - } - - @Test - public void test_PersonList() throws Exception { - List args = new ArrayList(); - args.add(new Person()); - - assertObject(args); - } - - @Test - public void test_PersonSet() throws Exception { - Set args = new HashSet(); - args.add(new Person()); - - assertObject(args); - } - - @Test - public void test_IntPersonMap() throws Exception { - Map args = new HashMap(); - args.put(1, new Person()); - - assertObject(args); - } - - @Test - public void test_StringPersonMap() throws Exception { - Map args = new HashMap(); - args.put("1", new Person()); - - assertObject(args); - } - - @Test - public void test_StringPersonListMap() throws Exception { - Map> args = new HashMap>(); - - List sublist = new ArrayList(); - sublist.add(new Person()); - args.put("1", sublist); - - assertObject(args); - } - - @Test - public void test_PersonListList() throws Exception { - List> args = new ArrayList>(); - List sublist = new ArrayList(); - sublist.add(new Person()); - args.add(sublist); - - assertObject(args); - } -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/serialize/serialization/AbstractSerializationTest.java b/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/serialize/serialization/AbstractSerializationTest.java deleted file mode 100644 index 411627f0dd6b..000000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/src/test/java/org/apache/dubbo/common/serialize/serialization/AbstractSerializationTest.java +++ /dev/null @@ -1,1215 +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.serialize.serialization; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.model.AnimalEnum; -import org.apache.dubbo.common.model.BizException; -import org.apache.dubbo.common.model.BizExceptionNoDefaultConstructor; -import org.apache.dubbo.common.model.SerializablePerson; -import org.apache.dubbo.common.model.media.Image; -import org.apache.dubbo.common.model.media.Image.Size; -import org.apache.dubbo.common.model.media.Media; -import org.apache.dubbo.common.model.media.Media.Player; -import org.apache.dubbo.common.model.media.MediaContent; -import org.apache.dubbo.common.model.person.BigPerson; -import org.apache.dubbo.common.model.person.FullAddress; -import org.apache.dubbo.common.model.person.PersonInfo; -import org.apache.dubbo.common.model.person.PersonStatus; -import org.apache.dubbo.common.model.person.Phone; -import org.apache.dubbo.common.serialize.ObjectInput; -import org.apache.dubbo.common.serialize.ObjectOutput; -import org.apache.dubbo.common.serialize.Serialization; -import org.junit.Test; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.sql.Time; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.Set; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -public abstract class AbstractSerializationTest { - static Random random = new Random(); - Serialization serialization; - URL url = new URL("protocol", "1.1.1.1", 1234); - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - - // ================ Primitive Type ================ - BigPerson bigPerson; - MediaContent mediaContent; - - { - bigPerson = new BigPerson(); - bigPerson.setPersonId("superman111"); - bigPerson.setLoginName("superman"); - bigPerson.setStatus(PersonStatus.ENABLED); - bigPerson.setEmail("sm@1.com"); - bigPerson.setPenName("pname"); - - ArrayList phones = new ArrayList(); - Phone phone1 = new Phone("86", "0571", "87654321", "001"); - Phone phone2 = new Phone("86", "0571", "87654322", "002"); - phones.add(phone1); - phones.add(phone2); - - PersonInfo pi = new PersonInfo(); - pi.setPhones(phones); - Phone fax = new Phone("86", "0571", "87654321", null); - pi.setFax(fax); - FullAddress addr = new FullAddress("CN", "zj", "3480", "wensanlu", "315000"); - pi.setFullAddress(addr); - pi.setMobileNo("13584652131"); - pi.setMale(true); - pi.setDepartment("b2b"); - pi.setHomepageUrl("www.capcom.com"); - pi.setJobTitle("qa"); - pi.setName("superman"); - - bigPerson.setInfoProfile(pi); - } - - { - Media media = new Media(); - media.setUri("uri://中华人民共和国"); - media.setTitle("title"); - media.setWidth(1239); - media.setHeight(1938); - media.setFormat("format-xxxx"); - media.setDuration(93419235); - media.setSize(3477897); - media.setBitrate(94523); - List persons = new ArrayList(); - persons.add("jerry"); - persons.add("tom"); - persons.add("lucy"); - media.setPersons(persons); - media.setCopyright("1999-2011"); - media.setPlayer(Player.FLASH); - - List images = new ArrayList(); - for (int i = 0; i < 10; ++i) { - Image image = new Image(); - image.setUri("url" + i); - if (i % 2 == 0) image.setTitle("title" + i); - image.setWidth(34 + i); - image.setHeight(2323 + i); - image.setSize((i % 2 == 0) ? Size.SMALL : Size.LARGE); - - images.add(image); - } - - mediaContent = new MediaContent(media, images); - } - - @Test - public void test_Bool() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeBool(false); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertFalse(deserialize.readBool()); - - try { - deserialize.readBool(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_Bool_Multi() throws Exception { - boolean[] array = new boolean[100]; - for (int i = 0; i < array.length; i++) { - array[i] = random.nextBoolean(); - } - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - for (boolean b : array) { - objectOutput.writeBool(b); - } - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - for (boolean b : array) { - assertEquals(b, deserialize.readBool()); - } - - try { - deserialize.readBool(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_Byte() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeByte((byte) 123); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertEquals((byte) 123, deserialize.readByte()); - - try { - deserialize.readByte(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_Byte_Multi() throws Exception { - byte[] array = new byte[100]; - random.nextBytes(array); - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - for (byte b : array) { - objectOutput.writeByte(b); - } - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - for (byte b : array) { - assertEquals(b, deserialize.readByte()); - } - - try { - deserialize.readByte(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_Short() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeShort((short) 123); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertEquals((short) 123, deserialize.readShort()); - - try { - deserialize.readShort(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_Integer() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeInt(1); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - int i = deserialize.readInt(); - assertEquals(1, i); - - try { - deserialize.readInt(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_Long() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeLong(123L); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertEquals(123L, deserialize.readLong()); - - try { - deserialize.readLong(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_Float() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeFloat(1.28F); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertTrue(1.28F == deserialize.readFloat()); - - try { - deserialize.readFloat(); - fail(); - } catch (IOException expected) { - } - } - - // ================== Util methods ================== - - @Test - public void test_Double() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeDouble(1.28); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertTrue(1.28 == deserialize.readDouble()); - - try { - deserialize.readDouble(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_UtfString() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeUTF("123中华人民共和国"); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertEquals("123中华人民共和国", deserialize.readUTF()); - - try { - deserialize.readUTF(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_Bytes() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeBytes("123中华人民共和国".getBytes()); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals("123中华人民共和国".getBytes(), deserialize.readBytes()); - - try { - deserialize.readBytes(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_BytesRange() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeBytes("123中华人民共和国-新疆维吾尔自治区".getBytes(), 1, 9); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - byte[] expectedArray = new byte[9]; - System.arraycopy("123中华人民共和国-新疆维吾尔自治区".getBytes(), 1, expectedArray, 0, expectedArray.length); - assertArrayEquals(expectedArray, deserialize.readBytes()); - - try { - deserialize.readBytes(); - fail(); - } catch (IOException expected) { - } - } - - // ================ Array Type ================ - - void assertObjectArray(T[] data, Class clazz) throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, clazz.cast(deserialize.readObject())); - - try { - deserialize.readObject(); - fail(); - } catch (IOException expected) { - } - } - - void assertObjectArrayWithType(T[] data, Class clazz) throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, clazz.cast(deserialize.readObject(clazz))); - - try { - deserialize.readObject(clazz); - fail(); - } catch (IOException expected) { - } - } - - @SuppressWarnings("unchecked") - void assertObject(T data) throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertEquals(data, (T) deserialize.readObject()); - - try { - deserialize.readObject(); - fail(); - } catch (IOException expected) { - } - } - - void assertObjectWithType(T data, Class clazz) throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertEquals(data, (T) deserialize.readObject(clazz)); - - try { - deserialize.readObject(clazz); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_boolArray() throws Exception { - boolean[] data = new boolean[]{true, false, true}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertTrue(Arrays.equals(data, (boolean[]) deserialize.readObject())); - - try { - deserialize.readObject(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_boolArray_withType() throws Exception { - boolean[] data = new boolean[]{true, false, true}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertTrue(Arrays.equals(data, (boolean[]) deserialize.readObject(boolean[].class))); - - try { - deserialize.readObject(boolean[].class); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_charArray() throws Exception { - char[] data = new char[]{'a', '中', '无'}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, (char[]) deserialize.readObject()); - - try { - deserialize.readObject(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_charArray_withType() throws Exception { - char[] data = new char[]{'a', '中', '无'}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, (char[]) deserialize.readObject(char[].class)); - - try { - deserialize.readObject(char[].class); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_shortArray() throws Exception { - short[] data = new short[]{37, 39, 12}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, (short[]) deserialize.readObject()); - - try { - deserialize.readObject(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_shortArray_withType() throws Exception { - short[] data = new short[]{37, 39, 12}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, (short[]) deserialize.readObject(short[].class)); - - try { - deserialize.readObject(short[].class); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_intArray() throws Exception { - int[] data = new int[]{234, 0, -1}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, (int[]) deserialize.readObject()); - - try { - deserialize.readObject(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_intArray_withType() throws Exception { - int[] data = new int[]{234, 0, -1}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, (int[]) deserialize.readObject(int[].class)); - - try { - deserialize.readObject(int[].class); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_longArray() throws Exception { - long[] data = new long[]{234, 0, -1}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, (long[]) deserialize.readObject()); - - try { - deserialize.readObject(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_longArray_withType() throws Exception { - long[] data = new long[]{234, 0, -1}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, (long[]) deserialize.readObject(long[].class)); - - try { - deserialize.readObject(long[].class); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_floatArray() throws Exception { - float[] data = new float[]{37F, -3.14F, 123456.7F}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, (float[]) deserialize.readObject(), 0.0001F); - - try { - deserialize.readObject(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_floatArray_withType() throws Exception { - float[] data = new float[]{37F, -3.14F, 123456.7F}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, (float[]) deserialize.readObject(float[].class), 0.0001F); - - try { - deserialize.readObject(float[].class); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_doubleArray() throws Exception { - double[] data = new double[]{37D, -3.14D, 123456.7D}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, (double[]) deserialize.readObject(), 0.0001); - - try { - deserialize.readObject(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_doubleArray_withType() throws Exception { - double[] data = new double[]{37D, -3.14D, 123456.7D}; - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertArrayEquals(data, (double[]) deserialize.readObject(double[].class), 0.0001); - - try { - deserialize.readObject(double[].class); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_StringArray() throws Exception { - assertObjectArray(new String[]{"1", "b"}, String[].class); - } - - @Test - public void test_StringArray_withType() throws Exception { - assertObjectArrayWithType(new String[]{"1", "b"}, String[].class); - } - - // ================ Simple Type ================ - - @Test - public void test_IntegerArray() throws Exception { - assertObjectArray(new Integer[]{234, 0, -1}, Integer[].class); - } - - @Test - public void test_IntegerArray_withType() throws Exception { - assertObjectArrayWithType(new Integer[]{234, 0, -1}, Integer[].class); - } - - @Test - public void test_EnumArray() throws Exception { - assertObjectArray(new AnimalEnum[]{AnimalEnum.bull, AnimalEnum.cat, AnimalEnum.dog, AnimalEnum.horse}, AnimalEnum[].class); - } - - @Test - public void test_EnumArray_withType() throws Exception { - assertObjectArrayWithType(new AnimalEnum[]{AnimalEnum.bull, AnimalEnum.cat, AnimalEnum.dog, AnimalEnum.horse}, AnimalEnum[].class); - } - - @Test - public void test_SPerson() throws Exception { - assertObject(new SerializablePerson()); - } - - @Test - public void test_SPerson_withType() throws Exception { - assertObjectWithType(new SerializablePerson(), SerializablePerson.class); - } - - @Test - public void test_BizException() throws Exception { - BizException e = new BizException("Hello"); - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(e); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - Object read = deserialize.readObject(); - assertEquals("Hello", ((BizException) read).getMessage()); - } - - @Test - public void test_BizException_WithType() throws Exception { - BizException e = new BizException("Hello"); - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(e); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - Object read = deserialize.readObject(BizException.class); - assertEquals("Hello", ((BizException) read).getMessage()); - } - - @Test - public void test_BizExceptionNoDefaultConstructor() throws Exception { - BizExceptionNoDefaultConstructor e = new BizExceptionNoDefaultConstructor("Hello"); - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(e); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - Object read = deserialize.readObject(); - assertEquals("Hello", ((BizExceptionNoDefaultConstructor) read).getMessage()); - } - - @Test - public void test_BizExceptionNoDefaultConstructor_WithType() throws Exception { - BizExceptionNoDefaultConstructor e = new BizExceptionNoDefaultConstructor("Hello"); - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(e); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - Object read = deserialize.readObject(BizExceptionNoDefaultConstructor.class); - assertEquals("Hello", ((BizExceptionNoDefaultConstructor) read).getMessage()); - } - - @Test - public void test_LocalDateTime() throws Exception { - assertObject(LocalDateTime.now()); - } - - @Test - public void test_enum() throws Exception { - assertObject(AnimalEnum.dog); - } - - @Test - public void test_enum_withType() throws Exception { - assertObjectWithType(AnimalEnum.dog, AnimalEnum.class); - } - - @Test - public void test_Date() throws Exception { - assertObject(new Date()); - } - - @Test - public void test_Date_withType() throws Exception { - assertObjectWithType(new Date(), Date.class); - } - - @Test - public void test_Time() throws Exception { - assertObject(new Time(System.currentTimeMillis())); - } - - @Test - public void test_Time_withType() throws Exception { - assertObjectWithType(new Time(System.currentTimeMillis()), Time.class); - } - - @Test - public void test_ByteWrap() throws Exception { - assertObject(new Byte((byte) 12)); - } - - @Test - public void test_ByteWrap_withType() throws Exception { - assertObjectWithType(new Byte((byte) 12), Byte.class); - } - - @Test - public void test_LongWrap() throws Exception { - assertObject(new Long(12)); - } - - @Test - public void test_LongWrap_withType() throws Exception { - assertObjectWithType(new Long(12), Long.class); - } - - @Test - public void test_BigInteger() throws Exception { - assertObject(new BigInteger("23423434234234234")); - } - - @Test - public void test_BigInteger_withType() throws Exception { - assertObjectWithType(new BigInteger("23423434234234234"), BigInteger.class); - } - - @Test - public void test_BigDecimal() throws Exception { - assertObject(new BigDecimal("23423434234234234.341274832341234235")); - } - - @Test - public void test_BigDecimal_withType() throws Exception { - assertObjectWithType(new BigDecimal("23423434234234234.341274832341234235"), BigDecimal.class); - } - - @Test - public void test_StringList_asListReturn() throws Exception { - List args = Arrays.asList(new String[]{"1", "b"}); - - assertObject(args); - } - - @Test - public void test_StringArrayList() throws Exception { - List args = new ArrayList(Arrays.asList(new String[]{"1", "b"})); - - assertObject(args); - } - - @Test - public void test_StringSet() throws Exception { - Set args = new HashSet(); - args.add("1"); - - assertObject(args); - } - - @Test - public void test_LinkedHashMap() throws Exception { - LinkedHashMap data = new LinkedHashMap(); - data.put("1", "a"); - data.put("2", "b"); - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - Object read = deserialize.readObject(); - assertTrue(read instanceof LinkedHashMap); - @SuppressWarnings("unchecked") - String key1 = ((LinkedHashMap) read).entrySet().iterator().next().getKey(); - assertEquals("1", key1); - - assertEquals(data, read); - - try { - deserialize.readObject(); - fail(); - } catch (IOException expected) { - } - } - - // ================ Complex Collection Type ================ - - @Test - public void test_SPersonList() throws Exception { - List args = new ArrayList(); - args.add(new SerializablePerson()); - - assertObject(args); - } - - @Test - public void test_SPersonSet() throws Exception { - Set args = new HashSet(); - args.add(new SerializablePerson()); - - assertObject(args); - } - - // ================ complex POJO ============= - - @Test - public void test_IntSPersonMap() throws Exception { - Map args = new HashMap(); - args.put(1, new SerializablePerson()); - - assertObject(args); - } - - @Test - public void test_StringSPersonMap() throws Exception { - Map args = new HashMap(); - args.put("1", new SerializablePerson()); - - assertObject(args); - } - - @Test - public void test_StringSPersonListMap() throws Exception { - Map> args = new HashMap>(); - - List sublist = new ArrayList(); - sublist.add(new SerializablePerson()); - args.put("1", sublist); - - assertObject(args); - } - - @Test - public void test_SPersonListList() throws Exception { - List> args = new ArrayList>(); - List sublist = new ArrayList(); - sublist.add(new SerializablePerson()); - args.add(sublist); - - assertObject(args); - } - - @Test - public void test_BigPerson() throws Exception { - assertObject(bigPerson); - } - - @Test - public void test_BigPerson_WithType() throws Exception { - assertObjectWithType(bigPerson, BigPerson.class); - } - - @Test - public void test_MediaContent() throws Exception { - assertObject(mediaContent); - } - - @Test - public void test_MediaContent_WithType() throws Exception { - assertObjectWithType(mediaContent, MediaContent.class); - } - - @Test - public void test_MultiObject() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeBool(false); - objectOutput.writeObject(bigPerson); - objectOutput.writeByte((byte) 23); - objectOutput.writeObject(mediaContent); - objectOutput.writeInt(-23); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertEquals(false, deserialize.readBool()); - assertEquals(bigPerson, deserialize.readObject()); - assertEquals((byte) 23, deserialize.readByte()); - assertEquals(mediaContent, deserialize.readObject()); - assertEquals(-23, deserialize.readInt()); - - try { - deserialize.readObject(); - fail(); - } catch (IOException expected) { - } - } - - @Test - public void test_MultiObject_WithType() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeBool(false); - objectOutput.writeObject(bigPerson); - objectOutput.writeByte((byte) 23); - objectOutput.writeObject(mediaContent); - objectOutput.writeInt(-23); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - assertEquals(false, deserialize.readBool()); - assertEquals(bigPerson, deserialize.readObject(BigPerson.class)); - assertEquals((byte) 23, deserialize.readByte()); - assertEquals(mediaContent, deserialize.readObject(MediaContent.class)); - assertEquals(-23, deserialize.readInt()); - - try { - deserialize.readObject(); - fail(); - } catch (IOException expected) { - } - } - - - // abnormal case - - @Test - public void test_MediaContent_badStream() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(mediaContent); - objectOutput.flushBuffer(); - - byte[] byteArray = byteArrayOutputStream.toByteArray(); - for (int i = 0; i < byteArray.length; i++) { - if (i % 3 == 0) { - byteArray[i] = (byte) ~byteArray[i]; - } - } - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray); - - try { - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - @SuppressWarnings("unused") // local variable, convenient for debug - Object read = deserialize.readObject(); - fail(); - } catch (IOException expected) { - System.out.println(expected); - } - } - - @Test - public void test_MediaContent_WithType_badStream() throws Exception { - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(mediaContent); - objectOutput.flushBuffer(); - - byte[] byteArray = byteArrayOutputStream.toByteArray(); - for (int i = 0; i < byteArray.length; i++) { - if (i % 3 == 0) { - byteArray[i] = (byte) ~byteArray[i]; - } - } - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray); - - try { - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - @SuppressWarnings("unused") // local variable, convenient for debug - Object read = deserialize.readObject(MediaContent.class); - fail(); - } catch (IOException expected) { - System.out.println(expected); - } - } - - - @Test(timeout = 3000) - public void test_LoopReference() throws Exception { - Map map = new HashMap(); - map.put("k1", "v1"); - map.put("self", map); - - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(map); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - @SuppressWarnings("unchecked") - Map output = (Map) deserialize.readObject(); - - assertEquals("v1", output.get("k1")); - assertSame(output, output.get("self")); - } - - // ================ final field test ================ - - @Test - public void test_URL_mutable_withType() throws Exception { - URL data = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&noValue"); - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); - ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); - - URL actual = (URL) deserialize.readObject(URL.class); - assertEquals(data, actual); - assertEquals(data.getParameters(), actual.getParameters()); - - try { - deserialize.readObject(); - fail(); - } catch (IOException expected) { - } - } -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/test/resources/log4j.xml b/dubbo-serialization/dubbo-serialization-kryo/src/test/resources/log4j.xml deleted file mode 100644 index d045b92c0de6..000000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/src/test/resources/log4j.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/test/resources/org/apache/dubbo/common/serialize/dubbo/SimpleDO.fc b/dubbo-serialization/dubbo-serialization-kryo/src/test/resources/org/apache/dubbo/common/serialize/dubbo/SimpleDO.fc deleted file mode 100644 index c8c083c17eb1..000000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/src/test/resources/org/apache/dubbo/common/serialize/dubbo/SimpleDO.fc +++ /dev/null @@ -1,2 +0,0 @@ -a,d,e,b,c -str3,str2 \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-protostuff/pom.xml b/dubbo-serialization/dubbo-serialization-protostuff/pom.xml new file mode 100644 index 000000000000..cd1b644000d0 --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-protostuff/pom.xml @@ -0,0 +1,55 @@ + + + + 4.0.0 + + dubbo-serialization + org.apache.dubbo + 2.7.0-SNAPSHOT + + + dubbo-serialization-protostuff + jar + ${project.artifactId} + The protostuff serialization module of dubbo project + + + 1.5.9 + + + + + org.apache.dubbo + dubbo-serialization-api + ${project.parent.version} + + + io.protostuff + protostuff-core + ${protostuff.version} + + + io.protostuff + protostuff-runtime + ${protostuff.version} + + + + diff --git a/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffObjectInput.java b/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffObjectInput.java new file mode 100644 index 000000000000..0202762cfa29 --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffObjectInput.java @@ -0,0 +1,135 @@ +/* + * 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; + +import org.apache.dubbo.common.serialize.ObjectInput; +import org.apache.dubbo.common.serialize.protostuff.utils.WrapperUtils; + +import io.protostuff.ProtobufIOUtil; +import io.protostuff.Schema; +import io.protostuff.runtime.RuntimeSchema; + +import java.io.DataInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Type; + +public class ProtostuffObjectInput implements ObjectInput { + + private DataInputStream dis; + + public ProtostuffObjectInput(InputStream inputStream) { + dis = new DataInputStream(inputStream); + } + + @SuppressWarnings("ResultOfMethodCallIgnored") + @Override + public Object readObject() throws IOException, ClassNotFoundException { + int classNameLength = dis.readInt(); + int bytesLength = dis.readInt(); + + if (classNameLength < 0 || bytesLength < 0) { + throw new IOException(); + } + + byte[] classNameBytes = new byte[classNameLength]; + dis.readFully(classNameBytes, 0, classNameLength); + + byte[] bytes = new byte[bytesLength]; + dis.readFully(bytes, 0, bytesLength); + + String className = new String(classNameBytes); + Class clazz = Class.forName(className); + + Object result; + if (WrapperUtils.needWrapper(clazz)) { + Schema schema = RuntimeSchema.getSchema(Wrapper.class); + Wrapper wrapper = schema.newMessage(); + ProtobufIOUtil.mergeFrom(bytes, wrapper, schema); + result = wrapper.getData(); + } else { + Schema schema = RuntimeSchema.getSchema(clazz); + result = schema.newMessage(); + ProtobufIOUtil.mergeFrom(bytes, result, schema); + } + + return result; + } + + @SuppressWarnings("unchecked") + @Override + public T readObject(Class clazz) throws IOException, ClassNotFoundException { + return (T) readObject(); + } + + @Override + public T readObject(Class cls, Type type) throws IOException, ClassNotFoundException { + return readObject(cls); + } + + @Override + public boolean readBool() throws IOException { + return dis.readBoolean(); + } + + @Override + public byte readByte() throws IOException { + return dis.readByte(); + } + + @Override + public short readShort() throws IOException { + return dis.readShort(); + } + + @Override + public int readInt() throws IOException { + return dis.readInt(); + } + + @Override + public long readLong() throws IOException { + return dis.readLong(); + } + + @Override + public float readFloat() throws IOException { + return dis.readFloat(); + } + + @Override + public double readDouble() throws IOException { + return dis.readDouble(); + } + + @Override + public String readUTF() throws IOException { + int length = dis.readInt(); + byte[] bytes = new byte[length]; + dis.read(bytes, 0, length); + return new String(bytes); + } + + @Override + public byte[] readBytes() throws IOException { + int length = dis.readInt(); + byte[] bytes = new byte[length]; + dis.read(bytes, 0, length); + return bytes; + } +} diff --git a/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffObjectOutput.java b/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffObjectOutput.java new file mode 100644 index 000000000000..2e91d17ef6f3 --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffObjectOutput.java @@ -0,0 +1,129 @@ +/* + * 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; + +import org.apache.dubbo.common.serialize.ObjectOutput; +import org.apache.dubbo.common.serialize.protostuff.utils.WrapperUtils; + +import io.protostuff.LinkedBuffer; +import io.protostuff.ProtobufIOUtil; +import io.protostuff.Schema; +import io.protostuff.runtime.RuntimeSchema; + +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.OutputStream; + +public class ProtostuffObjectOutput implements ObjectOutput { + + private LinkedBuffer buffer = LinkedBuffer.allocate(); + private DataOutputStream dos; + + public ProtostuffObjectOutput(OutputStream outputStream) { + dos = new DataOutputStream(outputStream); + } + + @SuppressWarnings("unchecked") + @Override + public void writeObject(Object obj) throws IOException { + + byte[] bytes; + byte[] classNameBytes; + + try { + if (WrapperUtils.needWrapper(obj)) { + Schema schema = RuntimeSchema.getSchema(Wrapper.class); + Wrapper wrapper = new Wrapper(obj); + bytes = ProtobufIOUtil.toByteArray(wrapper, schema, buffer); + classNameBytes = Wrapper.class.getName().getBytes(); + } else { + Schema schema = RuntimeSchema.getSchema(obj.getClass()); + bytes = ProtobufIOUtil.toByteArray(obj, schema, buffer); + classNameBytes = obj.getClass().getName().getBytes(); + } + } finally { + buffer.clear(); + } + + dos.writeInt(classNameBytes.length); + dos.writeInt(bytes.length); + dos.write(classNameBytes); + dos.write(bytes); + } + + @Override + public void writeBool(boolean v) throws IOException { + dos.writeBoolean(v); + } + + @Override + public void writeByte(byte v) throws IOException { + dos.writeByte(v); + } + + @Override + public void writeShort(short v) throws IOException { + dos.writeShort(v); + } + + @Override + public void writeInt(int v) throws IOException { + dos.writeInt(v); + } + + @Override + public void writeLong(long v) throws IOException { + dos.writeLong(v); + } + + @Override + public void writeFloat(float v) throws IOException { + dos.writeFloat(v); + } + + @Override + public void writeDouble(double v) throws IOException { + dos.writeDouble(v); + } + + @Override + public void writeUTF(String v) throws IOException { + byte[] bytes = v.getBytes(); + dos.writeInt(bytes.length); + dos.write(bytes); + } + + @Override + public void writeBytes(byte[] v) throws IOException { + dos.writeInt(v.length); + dos.write(v); + } + + @Override + public void writeBytes(byte[] v, int off, int len) throws IOException { + dos.writeInt(len); + byte[] bytes = new byte[len]; + System.arraycopy(v, off, bytes, 0, len); + dos.write(bytes); + } + + @Override + public void flushBuffer() throws IOException { + dos.flush(); + } +} 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 new file mode 100644 index 000000000000..aaf5bddc36d5 --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffSerialization.java @@ -0,0 +1,49 @@ +/* + * 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; + +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 ProtostuffSerialization implements Serialization { + @Override + public byte getContentTypeId() { + return 10; + } + + @Override + public String getContentType() { + return "x-application/protostuff"; + } + + @Override + public ObjectOutput serialize(URL url, OutputStream output) throws IOException { + return new ProtostuffObjectOutput(output); + } + + @Override + public ObjectInput deserialize(URL url, InputStream input) throws IOException { + return new ProtostuffObjectInput(input); + } +} diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/BizException.java b/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/Wrapper.java similarity index 73% rename from dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/BizException.java rename to dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/Wrapper.java index 95f4046afa0b..9b56b43fad9a 100644 --- a/dubbo-serialization/dubbo-serialization-jdk/src/test/java/org/apache/dubbo/common/model/BizException.java +++ b/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/Wrapper.java @@ -14,16 +14,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.common.model; -public class BizException extends RuntimeException { +package org.apache.dubbo.common.serialize.protostuff; - private static final long serialVersionUID = 1L; +/** + * Protostuff can only serialize/deserialize POJOs, for those it can't deal with, use this Wrapper. + */ +public class Wrapper { + private T data; - public BizException(String message) { - super(message); + Wrapper(T data) { + this.data = data; } - public BizException() { + Object getData() { + return data; } -} \ No newline at end of file +} diff --git a/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/delegate/TimeDelegate.java b/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/delegate/TimeDelegate.java new file mode 100644 index 000000000000..8cc33c7d0beb --- /dev/null +++ b/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/delegate/TimeDelegate.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.common.serialize.protostuff.delegate; + +import io.protostuff.Input; +import io.protostuff.Output; +import io.protostuff.Pipe; +import io.protostuff.WireFormat; +import io.protostuff.runtime.Delegate; + +import java.io.IOException; +import java.sql.Time; + +public class TimeDelegate implements Delegate