diff --git a/.artifacts b/.artifacts index 3f3d84b604a..69d057be080 100644 --- a/.artifacts +++ b/.artifacts @@ -47,7 +47,6 @@ dubbo-kubernetes dubbo-maven-plugin dubbo-metadata dubbo-metadata-api -dubbo-metadata-rest dubbo-metadata-definition-protobuf dubbo-metadata-processor dubbo-metadata-report-nacos @@ -76,7 +75,6 @@ dubbo-registry-nacos dubbo-registry-zookeeper dubbo-remoting dubbo-remoting-api -dubbo-remoting-http dubbo-remoting-http12 dubbo-remoting-netty dubbo-remoting-netty4 @@ -87,7 +85,6 @@ dubbo-rpc dubbo-rpc-api dubbo-rpc-dubbo dubbo-rpc-injvm -dubbo-rpc-rest dubbo-rpc-triple dubbo-security dubbo-serialization @@ -118,7 +115,6 @@ dubbo-seata-spring-boot-starter dubbo-spring-security dubbo-tracing dubbo-xds -dubbo-plugin-proxy-bytebuddy dubbo-plugin-loom dubbo-rest-jaxrs dubbo-rest-servlet diff --git a/.asf.yaml b/.asf.yaml index cb1d0d10373..cc1dcf46a48 100644 --- a/.asf.yaml +++ b/.asf.yaml @@ -55,3 +55,5 @@ github: - http - grpc - web + collaborators: + - oxsean diff --git a/.gitignore b/.gitignore index 0dffb48ba34..a3061c17008 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,8 @@ target/ .settings/ .project .classpath +.externalToolBuilders +maven-eclipse.xml # idea ignore .idea/ @@ -50,3 +52,6 @@ dubbo-demo/dubbo-demo-triple/build/* .git.exec.error +# log files generated by testcase. +dubbo-rpc/dubbo-rpc-api/custom-access.log* + diff --git a/README.md b/README.md index 520c2b04a13..6b371e8b3b1 100644 --- a/README.md +++ b/README.md @@ -141,9 +141,9 @@ See [CONTRIBUTING](https://github.com/apache/dubbo/blob/master/CONTRIBUTING.md) * Fix bugs reported on [issues](https://github.com/apache/dubbo/issues), and send us a pull request. * Review the existing [pull request](https://github.com/apache/dubbo/pulls). * Improve the [website](https://github.com/apache/dubbo-website), typically we need - * blog post - * translation on documentation - * use cases around the integration of Dubbo in enterprise systems. + * blog post + * translation on documentation + * use cases around the integration of Dubbo in enterprise systems. * Improve the [dubbo-admin/dubbo-monitor](https://github.com/apache/dubbo-admin). * Contribute to the projects listed in [ecosystem](https://github.com/dubbo). * Other forms of contribution not explicitly enumerated above. diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/SingleRouterChain.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/SingleRouterChain.java index c217bdb0d69..5c6dec6efce 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/SingleRouterChain.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/SingleRouterChain.java @@ -212,7 +212,7 @@ private void printRouterSnapshot(URL url, BitList> availableInvokers, public RouterSnapshotNode buildRouterSnapshot( URL url, BitList> availableInvokers, Invocation invocation) { BitList> resultInvokers = availableInvokers.clone(); - RouterSnapshotNode parentNode = new RouterSnapshotNode("Parent", resultInvokers.clone()); + RouterSnapshotNode parentNode = new RouterSnapshotNode<>("Parent", resultInvokers.clone()); parentNode.setNodeOutputInvokers(resultInvokers.clone()); // 1. route state router @@ -227,7 +227,7 @@ public RouterSnapshotNode buildRouterSnapshot( return parentNode; } - RouterSnapshotNode commonRouterNode = new RouterSnapshotNode("CommonRouter", resultInvokers.clone()); + RouterSnapshotNode commonRouterNode = new RouterSnapshotNode<>("CommonRouter", resultInvokers.clone()); parentNode.appendNode(commonRouterNode); List> commonRouterResult = resultInvokers; @@ -237,7 +237,7 @@ public RouterSnapshotNode buildRouterSnapshot( List> inputInvokers = new ArrayList<>(commonRouterResult); RouterSnapshotNode currentNode = - new RouterSnapshotNode(router.getClass().getSimpleName(), inputInvokers); + new RouterSnapshotNode<>(router.getClass().getSimpleName(), inputInvokers); // append to router node chain commonRouterNode.appendNode(currentNode); diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java index a72956054a9..406756ad03d 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java @@ -223,7 +223,7 @@ private boolean isDeprecatedConditionMatch(Set conditionKeys, URL url) { } private Set genConditionKeys() { - Set conditionKeys = new HashSet(); + Set conditionKeys = new HashSet<>(); conditionKeys.add(CATEGORY_KEY); conditionKeys.add(Constants.CHECK_KEY); conditionKeys.add(DYNAMIC_KEY); diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalance.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalance.java index fb777ef03a8..82421e460fe 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalance.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalance.java @@ -46,8 +46,7 @@ public class ConsistentHashLoadBalance extends AbstractLoadBalance { */ public static final String HASH_ARGUMENTS = "hash.arguments"; - private final ConcurrentMap> selectors = - new ConcurrentHashMap>(); + private final ConcurrentMap> selectors = new ConcurrentHashMap<>(); @SuppressWarnings("unchecked") @Override @@ -75,7 +74,7 @@ private static final class ConsistentHashSelector { private final int[] argumentIndex; ConsistentHashSelector(List> invokers, String methodName, int identityHashCode) { - this.virtualInvokers = new TreeMap>(); + this.virtualInvokers = new TreeMap<>(); this.identityHashCode = identityHashCode; URL url = invokers.get(0).getUrl(); this.replicaNumber = url.getMethodParameter(methodName, HASH_NODES, 160); diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/MapMerger.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/MapMerger.java index eaa863ed640..dca9c34b25d 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/MapMerger.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/MapMerger.java @@ -32,7 +32,7 @@ public class MapMerger implements Merger> { if (ArrayUtils.isEmpty(items)) { return Collections.emptyMap(); } - Map result = new HashMap(); + Map result = new HashMap<>(); Stream.of(items).filter(Objects::nonNull).forEach(result::putAll); return result; } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/MergerFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/MergerFactory.java index 3aa07f2ad3b..0ac9949470f 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/MergerFactory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/MergerFactory.java @@ -36,7 +36,7 @@ public class MergerFactory implements ScopeModelAware { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MergerFactory.class); - private ConcurrentMap, Merger> MERGER_CACHE = new ConcurrentHashMap, Merger>(); + private ConcurrentMap, Merger> MERGER_CACHE = new ConcurrentHashMap<>(); private ScopeModel scopeModel; @Override diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/SetMerger.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/SetMerger.java index 5b0dc5e0c3f..5b77177cd0a 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/SetMerger.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/SetMerger.java @@ -32,7 +32,7 @@ public Set merge(Set... items) { if (ArrayUtils.isEmpty(items)) { return Collections.emptySet(); } - Set result = new HashSet(); + Set result = new HashSet<>(); Stream.of(items).filter(Objects::nonNull).forEach(result::addAll); return result; } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouterFactory.java index 06a40e81dfa..c18f674c3ea 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouterFactory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouterFactory.java @@ -30,6 +30,6 @@ public class ConditionStateRouterFactory extends CacheableStateRouterFactory { @Override protected StateRouter createRouter(Class interfaceClass, URL url) { - return new ConditionStateRouter(url); + return new ConditionStateRouter<>(url); } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceStateRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceStateRouterFactory.java index ecc536953b3..d35baf6ee38 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceStateRouterFactory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceStateRouterFactory.java @@ -32,6 +32,6 @@ public class ServiceStateRouterFactory extends CacheableStateRouterFactory { @Override protected StateRouter createRouter(Class interfaceClass, URL url) { - return new ServiceStateRouter(url); + return new ServiceStateRouter<>(url); } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleCache.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleCache.java index 098b9bd4cf0..a53e47280a2 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleCache.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleCache.java @@ -136,7 +136,7 @@ public static MeshRuleCache build( Collections.unmodifiableMap(totalSubsetMap), unmatchedInvokers); } else { - return new MeshRuleCache( + return new MeshRuleCache<>( Collections.emptyList(), Collections.emptyMap(), Collections.emptyMap(), invokers); } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockStateRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockStateRouterFactory.java index 9bff80a573a..d81b578ae3c 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockStateRouterFactory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockStateRouterFactory.java @@ -30,6 +30,6 @@ public class MockStateRouterFactory implements StateRouterFactory { @Override public StateRouter getRouter(Class interfaceClass, URL url) { - return new MockInvokersSelector(url); + return new MockInvokersSelector<>(url); } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/BitList.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/BitList.java index 2c04539b071..013a4010e00 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/BitList.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/BitList.java @@ -93,23 +93,23 @@ public BitList(List originList, BitSet rootSet, List tailList) { } // Provided by BitList only - public List getOriginList() { + public synchronized List getOriginList() { return originList; } - public void addIndex(int index) { + public synchronized void addIndex(int index) { this.rootSet.set(index); } - public int totalSetSize() { + public synchronized int totalSetSize() { return this.originList.size(); } - public boolean indexExist(int index) { + public synchronized boolean indexExist(int index) { return this.rootSet.get(index); } - public E getByIndex(int index) { + public synchronized E getByIndex(int index) { return this.originList.get(index); } @@ -120,7 +120,7 @@ public E getByIndex(int index) { * @param target target bitList * @return this bitList only contains those elements contain in both two list and source bitList's tailList */ - public BitList and(BitList target) { + public synchronized BitList and(BitList target) { rootSet.and(target.rootSet); if (target.getTailList() != null) { target.getTailList().forEach(this::addToTailList); @@ -128,28 +128,28 @@ public BitList and(BitList target) { return this; } - public BitList or(BitList target) { + public synchronized BitList or(BitList target) { BitSet resultSet = (BitSet) rootSet.clone(); resultSet.or(target.rootSet); return new BitList<>(originList, resultSet, tailList); } - public boolean hasMoreElementInTailList() { + public synchronized boolean hasMoreElementInTailList() { return CollectionUtils.isNotEmpty(tailList); } - public List getTailList() { + public synchronized List getTailList() { return tailList; } - public void addToTailList(E e) { + public synchronized void addToTailList(E e) { if (tailList == null) { tailList = new LinkedList<>(); } tailList.add(e); } - public E randomSelectOne() { + public synchronized E randomSelectOne() { int originSize = originList.size(); int tailSize = tailList != null ? tailList.size() : 0; int totalSize = originSize + tailSize; @@ -181,18 +181,18 @@ public static BitList emptyList() { // Provided by JDK List interface @Override - public int size() { + public synchronized int size() { return rootSet.cardinality() + (CollectionUtils.isNotEmpty(tailList) ? tailList.size() : 0); } @Override - public boolean contains(Object o) { + public synchronized boolean contains(Object o) { int idx = originList.indexOf(o); return (idx >= 0 && rootSet.get(idx)) || (CollectionUtils.isNotEmpty(tailList) && tailList.contains(o)); } @Override - public Iterator iterator() { + public synchronized Iterator iterator() { return new BitListIterator<>(this, 0); } @@ -205,7 +205,7 @@ public Iterator iterator() { * Notice: It is not recommended adding duplicated element. */ @Override - public boolean add(E e) { + public synchronized boolean add(E e) { int index = originList.indexOf(e); if (index > -1) { rootSet.set(index); @@ -225,7 +225,7 @@ public boolean add(E e) { * If the element is not contained in originList, try to remove from tailList. */ @Override - public boolean remove(Object o) { + public synchronized boolean remove(Object o) { int idx = originList.indexOf(o); if (idx > -1 && rootSet.get(idx)) { rootSet.set(idx, false); @@ -242,7 +242,7 @@ public boolean remove(Object o) { * This may change the default behaviour when adding new element later. */ @Override - public void clear() { + public synchronized void clear() { rootSet.clear(); // to remove references originList = Collections.emptyList(); @@ -252,7 +252,7 @@ public void clear() { } @Override - public E get(int index) { + public synchronized E get(int index) { int bitIndex = -1; if (index < 0) { throw new IndexOutOfBoundsException(); @@ -272,7 +272,7 @@ public E get(int index) { } @Override - public E remove(int index) { + public synchronized E remove(int index) { int bitIndex = -1; if (index >= rootSet.cardinality()) { if (CollectionUtils.isNotEmpty(tailList)) { @@ -290,7 +290,7 @@ public E remove(int index) { } @Override - public int indexOf(Object o) { + public synchronized int indexOf(Object o) { int bitIndex = -1; for (int i = 0; i < rootSet.cardinality(); i++) { bitIndex = rootSet.nextSetBit(bitIndex + 1); @@ -311,7 +311,7 @@ public int indexOf(Object o) { @Override @SuppressWarnings("unchecked") - public boolean addAll(Collection c) { + public synchronized boolean addAll(Collection c) { if (c instanceof BitList) { rootSet.or(((BitList) c).rootSet); if (((BitList) c).hasMoreElementInTailList()) { @@ -325,7 +325,7 @@ public boolean addAll(Collection c) { } @Override - public int lastIndexOf(Object o) { + public synchronized int lastIndexOf(Object o) { int bitIndex = -1; int index = -1; if (CollectionUtils.isNotEmpty(tailList)) { @@ -344,22 +344,22 @@ public int lastIndexOf(Object o) { } @Override - public boolean isEmpty() { + public synchronized boolean isEmpty() { return this.rootSet.isEmpty() && CollectionUtils.isEmpty(tailList); } @Override - public ListIterator listIterator() { + public synchronized ListIterator listIterator() { return new BitListIterator<>(this, 0); } @Override - public ListIterator listIterator(int index) { + public synchronized ListIterator listIterator(int index) { return new BitListIterator<>(this, index); } @Override - public BitList subList(int fromIndex, int toIndex) { + public synchronized BitList subList(int fromIndex, int toIndex) { BitSet resultSet = (BitSet) rootSet.clone(); List copiedTailList = tailList == null ? null : new LinkedList<>(tailList); if (toIndex < size()) { @@ -414,7 +414,7 @@ public BitListIterator(BitList bitList, int index) { } @Override - public boolean hasNext() { + public synchronized boolean hasNext() { if (isInTailList) { return tailListIterator.hasNext(); } else { @@ -428,7 +428,7 @@ public boolean hasNext() { } @Override - public E next() { + public synchronized E next() { if (isInTailList) { if (tailListIterator.hasNext()) { index += 1; @@ -457,7 +457,7 @@ public E next() { } @Override - public boolean hasPrevious() { + public synchronized boolean hasPrevious() { if (isInTailList) { boolean hasPreviousInTailList = tailListIterator.hasPrevious(); if (hasPreviousInTailList) { @@ -471,7 +471,7 @@ public boolean hasPrevious() { } @Override - public E previous() { + public synchronized E previous() { if (isInTailList) { boolean hasPreviousInTailList = tailListIterator.hasPrevious(); if (hasPreviousInTailList) { @@ -503,17 +503,17 @@ public E previous() { } @Override - public int nextIndex() { + public synchronized int nextIndex() { return hasNext() ? index + 1 : index; } @Override - public int previousIndex() { + public synchronized int previousIndex() { return index; } @Override - public void remove() { + public synchronized void remove() { if (lastReturnedIndex == -1) { throw new IllegalStateException(); } else { @@ -533,17 +533,17 @@ public void remove() { } @Override - public void set(E e) { + public synchronized void set(E e) { throw new UnsupportedOperationException("Set method is not supported in BitListIterator!"); } @Override - public void add(E e) { + public synchronized void add(E e) { throw new UnsupportedOperationException("Add method is not supported in BitListIterator!"); } } - public ArrayList cloneToArrayList() { + public synchronized ArrayList cloneToArrayList() { if (rootSet.cardinality() == originList.size() && (CollectionUtils.isEmpty(tailList))) { return new ArrayList<>(originList); } @@ -553,7 +553,7 @@ public ArrayList cloneToArrayList() { } @Override - public BitList clone() { + public synchronized BitList clone() { return new BitList<>( originList, (BitSet) rootSet.clone(), tailList == null ? null : new LinkedList<>(tailList)); } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouterFactory.java index b05e09e7032..de38ff8f7fd 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouterFactory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouterFactory.java @@ -31,6 +31,6 @@ public class TagStateRouterFactory extends CacheableStateRouterFactory { @Override protected StateRouter createRouter(Class interfaceClass, URL url) { - return new TagStateRouter(url); + return new TagStateRouter<>(url); } } 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 a840773c51c..1fc3cadcc11 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 @@ -63,8 +63,8 @@ public Result doInvoke(Invocation invocation, final List> invokers, L int len = calculateInvokeTimes(methodName); // retry loop. RpcException le = null; // last exception. - List> invoked = new ArrayList>(copyInvokers.size()); // invoked invokers. - Set providers = new HashSet(len); + 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. diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableCluster.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableCluster.java index 9bc030729f6..c219745b38f 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableCluster.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableCluster.java @@ -26,6 +26,6 @@ public class MergeableCluster extends AbstractCluster { @Override public AbstractClusterInvoker doJoin(Directory directory) throws RpcException { - return new MergeableClusterInvoker(directory); + return new MergeableClusterInvoker<>(directory); } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/registry/ZoneAwareCluster.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/registry/ZoneAwareCluster.java index a1cbf14e60f..10a12979838 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/registry/ZoneAwareCluster.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/registry/ZoneAwareCluster.java @@ -27,6 +27,6 @@ public class ZoneAwareCluster extends AbstractCluster { @Override protected AbstractClusterInvoker doJoin(Directory directory) throws RpcException { - return new ZoneAwareClusterInvoker(directory); + return new ZoneAwareClusterInvoker<>(directory); } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterWrapper.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterWrapper.java index 0836e48e258..0a2a2e73881 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterWrapper.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterWrapper.java @@ -35,7 +35,7 @@ public MockClusterWrapper(Cluster cluster) { @Override public Invoker join(Directory directory, boolean buildFilterChain) throws RpcException { - return new MockClusterInvoker(directory, this.cluster.join(directory, buildFilterChain)); + return new MockClusterInvoker<>(directory, this.cluster.join(directory, buildFilterChain)); } public Cluster getCluster() { diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/state/BitListTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/state/BitListTest.java index 9996de577f6..8885f445334 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/state/BitListTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/state/BitListTest.java @@ -22,6 +22,8 @@ import java.util.LinkedList; import java.util.List; import java.util.ListIterator; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -576,4 +578,44 @@ void testClone2() { set.add(new LinkedList<>(Arrays.asList("A", "B", "C", "D", "E", "F", "G"))); Assertions.assertEquals(2, set.size()); } + + @Test + void testConcurrent() throws InterruptedException { + for (int i = 0; i < 100000; i++) { + BitList bitList = new BitList<>(Collections.singletonList("test")); + bitList.remove("test"); + + CountDownLatch countDownLatch = new CountDownLatch(1); + CountDownLatch countDownLatch2 = new CountDownLatch(2); + + Thread thread1 = new Thread(() -> { + try { + countDownLatch.await(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + bitList.add("test"); + countDownLatch2.countDown(); + }); + + AtomicReference> ref = new AtomicReference<>(); + Thread thread2 = new Thread(() -> { + try { + countDownLatch.await(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + ref.set(bitList.clone()); + countDownLatch2.countDown(); + }); + + thread1.start(); + thread2.start(); + + countDownLatch.countDown(); + countDownLatch2.await(); + + Assertions.assertDoesNotThrow(() -> ref.get().iterator().hasNext()); + } + } } 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 0c7bb1e3e86..ca79d6480d1 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 @@ -1295,6 +1295,19 @@ public String getColonSeparatedKey() { return serviceNameBuilder.toString(); } + /** + * The format is "{interface}:[version]" + * + * @return + */ + public String getCompatibleColonSeparatedKey() { + StringBuilder serviceNameBuilder = new StringBuilder(); + serviceNameBuilder.append(this.getServiceInterface()); + compatibleAppend(serviceNameBuilder, VERSION_KEY); + compatibleAppend(serviceNameBuilder, GROUP_KEY); + return serviceNameBuilder.toString(); + } + private void append(StringBuilder target, String parameterName, boolean first) { String parameterValue = this.getParameter(parameterName); if (!isBlank(parameterValue)) { @@ -1307,6 +1320,14 @@ private void append(StringBuilder target, String parameterName, boolean first) { } } + private void compatibleAppend(StringBuilder target, String parameterName) { + String parameterValue = this.getParameter(parameterName); + if (!isBlank(parameterValue)) { + target.append(':'); + target.append(parameterValue); + } + } + /** * The format of return value is '{group}/{interfaceName}:{version}' * @@ -1376,6 +1397,10 @@ public String toServiceString() { return buildString(true, false, true, true); } + public String toServiceString(String... parameters) { + return buildString(true, true, true, true, parameters); + } + @Deprecated public String getServiceName() { return getServiceInterface(); 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 a33be42ddcc..90f2b707045 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 @@ -60,7 +60,7 @@ public final class Version { public static final int LOWEST_VERSION_FOR_RESPONSE_ATTACHMENT = 2000200; // 2.0.2 public static final int HIGHEST_PROTOCOL_VERSION = 2009900; // 2.0.99 - private static final Map VERSION2INT = new HashMap(); + private static final Map VERSION2INT = new HashMap<>(); static { // get dubbo version and last commit id 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 6a3afbde425..0149cc9ee7c 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 @@ -35,7 +35,7 @@ public final class JavaBeanSerializeUtil { private static final Logger logger = LoggerFactory.getLogger(JavaBeanSerializeUtil.class); - private static final Map> TYPES = new HashMap>(); + private static final Map> TYPES = new HashMap<>(); private static final String ARRAY_PREFIX = "["; private static final String REFERENCE_TYPE_PREFIX = "L"; private static final String REFERENCE_TYPE_SUFFIX = ";"; @@ -72,7 +72,7 @@ public static JavaBeanDescriptor serialize(Object obj, JavaBeanAccessor accessor if (obj instanceof JavaBeanDescriptor) { return (JavaBeanDescriptor) obj; } - IdentityHashMap cache = new IdentityHashMap(); + IdentityHashMap cache = new IdentityHashMap<>(); return createDescriptorIfAbsent(obj, accessor, cache); } @@ -209,7 +209,7 @@ public static Object deserialize(JavaBeanDescriptor beanDescriptor, ClassLoader if (beanDescriptor == null) { return null; } - IdentityHashMap cache = new IdentityHashMap(); + IdentityHashMap cache = new IdentityHashMap<>(); Object result = instantiateForDeserialize(beanDescriptor, loader, cache); deserializeInternal(result, beanDescriptor, loader, cache); return result; 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 81cadc0d76a..4a6e37c8839 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 @@ -120,7 +120,7 @@ public static Mixin mixin(Class[] ics, Class[] dcs, ClassLoader cl) { Class neighbor = null; // impl methods. - Set worked = new HashSet(); + Set worked = new HashSet<>(); for (int i = 0; i < ics.length; i++) { if (!Modifier.isPublic(ics[i].getModifiers())) { String npkg = ics[i].getPackage().getName(); 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 b42d5e286fb..b68e1ab5e14 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 @@ -42,8 +42,8 @@ * Wrapper. */ public abstract class Wrapper { - private static final ConcurrentMap, Wrapper> WRAPPER_MAP = - new ConcurrentHashMap, Wrapper>(); // class wrapper map + // class wrapper map + private static final ConcurrentMap, Wrapper> WRAPPER_MAP = new ConcurrentHashMap<>(); private static final String[] EMPTY_STRING_ARRAY = new String[0]; private static final String[] OBJECT_METHODS = new String[] {"getClass", "hashCode", "toString", "equals"}; private static final Wrapper OBJECT_WRAPPER = new Wrapper() { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/ClassUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/ClassUtils.java index d2c39053d60..aba14f4cea5 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/ClassUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/ClassUtils.java @@ -392,7 +392,7 @@ public static String getInitCode(Class type) { } public static Map toMap(Map.Entry[] entries) { - Map map = new HashMap(); + Map map = new HashMap<>(); if (entries != null && entries.length > 0) { for (Map.Entry entry : entries) { map.put(entry.getKey(), entry.getValue()); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java index 0302f318ea0..0b7732ec8b2 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java @@ -142,4 +142,11 @@ public interface RegistryConstants { boolean DEFAULT_ENABLE_EMPTY_PROTECTION = false; String REGISTER_CONSUMER_URL_KEY = "register-consumer-url"; String REGISTRY_PROTOCOL_TYPE = "registry-protocol-type"; + + /** + * export noting suffix servicename + * by default, dubbo export servicename is "${interface}:${version}:", this servicename with ':' suffix + * for compatible, we should export noting suffix servicename, eg: ${interface}:${version} + */ + String NACOE_REGISTER_COMPATIBLE = "nacos.register-compatible"; } 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 35c190b5f8a..a9a529a8ca1 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 @@ -75,6 +75,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.locks.ReentrantLock; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -120,6 +121,7 @@ public class ExtensionLoader { private final ConcurrentMap, String> cachedNames = new ConcurrentHashMap<>(); + private final ReentrantLock loadExtensionClassesLock = new ReentrantLock(); private final Holder>> cachedClasses = new Holder<>(); private final Map cachedActivates = Collections.synchronizedMap(new LinkedHashMap<>()); @@ -951,7 +953,8 @@ private Class getExtensionClass(String name) { private Map> getExtensionClasses() { Map> classes = cachedClasses.get(); if (classes == null) { - synchronized (cachedClasses) { + loadExtensionClassesLock.lock(); + try { classes = cachedClasses.get(); if (classes == null) { try { @@ -968,6 +971,8 @@ private Map> getExtensionClasses() { } cachedClasses.set(classes); } + } finally { + loadExtensionClassesLock.unlock(); } } return classes; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalThreadLocalMap.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalThreadLocalMap.java index 58b269a4f3e..88a4fc74f40 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalThreadLocalMap.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalThreadLocalMap.java @@ -28,7 +28,7 @@ public final class InternalThreadLocalMap { private Object[] indexedVariables; - private static ThreadLocal slowThreadLocalMap = new ThreadLocal(); + private static ThreadLocal slowThreadLocalMap = new ThreadLocal<>(); private static final AtomicInteger NEXT_INDEX = new 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 29207a1b3ee..8b6d57589ca 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 @@ -428,7 +428,7 @@ private static void reportTooManyInstances() { } private final class Worker implements Runnable { - private final Set unprocessedTimeouts = new HashSet(); + private final Set unprocessedTimeouts = new HashSet<>(); private long tick; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CIDRUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CIDRUtils.java index 5d9dc8bcbdf..5f3632af7af 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CIDRUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CIDRUtils.java @@ -98,7 +98,7 @@ private void calculate() throws UnknownHostException { private byte[] toBytes(byte[] array, int targetSize) { int counter = 0; - List newArr = new ArrayList(); + List newArr = new ArrayList<>(); while (counter < targetSize && (array.length - 1 - counter >= 0)) { newArr.add(0, array[array.length - 1 - counter]); counter++; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassLoaderResourceLoader.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassLoaderResourceLoader.java index 8c743c214f1..c62966fc444 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassLoaderResourceLoader.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassLoaderResourceLoader.java @@ -16,14 +16,12 @@ */ package org.apache.dubbo.common.utils; -import org.apache.dubbo.common.aot.NativeDetector; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.resource.GlobalResourcesRepository; import java.io.IOException; import java.lang.ref.SoftReference; -import java.lang.reflect.Field; import java.net.URL; import java.util.Collection; import java.util.Collections; @@ -32,7 +30,6 @@ import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; -import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; @@ -81,15 +78,9 @@ public static Set loadResources(String fileName, ClassLoader currentClassLo Enumeration urls; try { urls = currentClassLoader.getResources(fileName); - boolean isNative = NativeDetector.inNativeImage(); if (urls != null) { while (urls.hasMoreElements()) { URL url = urls.nextElement(); - if (isNative) { - // In native mode, the address of each URL is the same instead of different paths, so it is - // necessary to set the ref to make it different - setRef(url); - } set.add(url); } } @@ -113,15 +104,6 @@ public static void destroy() { } } - private static void setRef(URL url) { - try { - Field field = URL.class.getDeclaredField("ref"); - field.setAccessible(true); - field.set(url, UUID.randomUUID().toString()); - } catch (Throwable ignore) { - } - } - // for test protected static SoftReference>>> getClassLoaderResourcesCache() { return classLoaderResourcesCache; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConfigUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConfigUtils.java index f6754ad0649..8c12944ef38 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConfigUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConfigUtils.java @@ -87,7 +87,7 @@ public static boolean isDefault(String value) { */ public static List mergeValues( ExtensionDirector extensionDirector, Class type, String cfg, List def) { - List defaults = new ArrayList(); + List defaults = new ArrayList<>(); if (def != null) { for (String name : def) { if (extensionDirector.getExtensionLoader(type).hasExtension(name)) { @@ -96,7 +96,7 @@ public static List mergeValues( } } - List names = new ArrayList(); + List names = new ArrayList<>(); // add initial values String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : COMMA_SPLIT_PATTERN.split(cfg); 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 0578feed909..c2ee5587b3b 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 @@ -179,7 +179,7 @@ public static String[] readLines(File file) throws IOException { * @throws IOException If an I/O error occurs */ public static String[] readLines(InputStream is) throws IOException { - List lines = new ArrayList(); + List lines = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) { String line; while ((line = reader.readLine()) != null) { 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 13e7ae4e7d4..38f274d98f8 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 @@ -26,7 +26,7 @@ public class Stack { private int mSize = 0; - private final List mElements = new ArrayList(); + private final List mElements = new ArrayList<>(); public Stack() {} 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 2b86d0e256f..74786e8a2e1 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 @@ -878,7 +878,7 @@ public static String join(final Object[] array, final char delimiter, final int */ private static Map parseKeyValuePair(String str, String itemSeparator) { String[] tmp = str.split(itemSeparator); - Map map = new HashMap(tmp.length); + Map map = new HashMap<>(tmp.length); for (int i = 0; i < tmp.length; i++) { Matcher matcher = KVP_PATTERN.matcher(tmp[i]); if (!matcher.matches()) { @@ -902,7 +902,7 @@ public static String getQueryStringValue(String qs, String key) { */ public static Map parseQueryString(String qs) { if (isEmpty(qs)) { - return new HashMap(); + return new HashMap<>(); } return parseKeyValuePair(qs, "\\&"); } 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 ec1745e431f..89e6b52b8d6 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 @@ -181,7 +181,7 @@ public static List parseURLs(String address, Map defaults) throw new IllegalArgumentException( "Addresses is not allowed to be empty, please re-enter."); // here won't be empty } - List registries = new ArrayList(); + List registries = new ArrayList<>(); for (String addr : addresses) { registries.add(parseURL(addr, defaults)); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java index 78b85744c7e..368f8f56ecb 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java @@ -221,7 +221,7 @@ public AbstractInterfaceConfig(ModuleModel moduleModel) { /** * The url of the reference service */ - protected final transient List urls = new ArrayList(); + protected final transient List urls = new ArrayList<>(); @Transient public List getExportedUrls() { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/ModuleConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/ModuleConfig.java index af6d99cf323..7126d64ef4b 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/ModuleConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/ModuleConfig.java @@ -186,7 +186,7 @@ public RegistryConfig getRegistry() { } public void setRegistry(RegistryConfig registry) { - List registries = new ArrayList(1); + List registries = new ArrayList<>(1); registries.add(registry); this.registries = registries; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/RegistryConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/RegistryConfig.java index 933d0c38617..d2dac66dba3 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/RegistryConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/RegistryConfig.java @@ -28,7 +28,6 @@ import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.ENABLE_EMPTY_PROTECTION_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_MODE_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_CLUSTER_KEY; import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; import static org.apache.dubbo.common.utils.PojoUtils.updatePropertyIfAbsent; @@ -241,7 +240,6 @@ public RegistryConfig(ApplicationModel applicationModel, String address, String } @Override - @Parameter(key = REGISTRY_CLUSTER_KEY) public String getId() { return super.getId(); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/util/ClassUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/util/ClassUtils.java index 1115c451b20..b7441b76b06 100755 --- a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/util/ClassUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/util/ClassUtils.java @@ -96,7 +96,7 @@ public static List getNonStaticFields(final Class clazz) { * @return methods list */ public static List getPublicNonStaticMethods(final Class clazz) { - List result = new ArrayList(); + List result = new ArrayList<>(); Method[] methods = clazz.getMethods(); for (Method method : methods) { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ProviderModel.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ProviderModel.java index bb1f0ed8a00..a509506ec51 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ProviderModel.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ProviderModel.java @@ -135,7 +135,7 @@ public void setRegistryUrl(URL registryUrl) { } public List getAllMethodModels() { - List result = new ArrayList(); + List result = new ArrayList<>(); for (List models : methods.values()) { result.addAll(models); } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/URLTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/URLTest.java index 9c3583a1f94..475375ae543 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/URLTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/URLTest.java @@ -1133,4 +1133,22 @@ void testIPV6() { assertEquals(20881, url.getPort()); assertEquals("apache", url.getParameter("name")); } + + @Test + void testToServiceString() { + URL url = URL.valueOf( + "zookeeper://10.20.130.230:4444/org.apache.dubbo.metadata.report.MetadataReport?version=1.0.0&application=vic&group=aaa"); + assertEquals( + "zookeeper://10.20.130.230:4444/aaa/org.apache.dubbo.metadata.report.MetadataReport:1.0.0", + url.toServiceString()); + } + + @Test + void testToServiceStringWithParameters() { + URL url = URL.valueOf( + "zookeeper://10.20.130.230:4444/org.apache.dubbo.metadata.report.MetadataReport?version=1.0.0&application=vic&group=aaa&namespace=test"); + assertEquals( + "zookeeper://10.20.130.230:4444/aaa/org.apache.dubbo.metadata.report.MetadataReport:1.0.0?namespace=test", + url.toServiceString("namespace")); + } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/ClassGeneratorTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/ClassGeneratorTest.java index 9d760b6d907..02a1e9fd251 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/ClassGeneratorTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/ClassGeneratorTest.java @@ -22,6 +22,7 @@ import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; +import java.util.UUID; import java.util.concurrent.CountDownLatch; import javassist.ClassPool; @@ -56,7 +57,8 @@ void test() throws Exception { ClassGenerator cg = ClassGenerator.newInstance(); // add className, interface, superClass - String className = BaseClass.class.getPackage().getName() + ".TestClass"; + String className = BaseClass.class.getPackage().getName() + ".TestClass" + + UUID.randomUUID().toString().replace("-", ""); cg.setClassName(className); cg.addInterface(BaseInterface.class); cg.setSuperClass(BaseClass.class); @@ -184,7 +186,7 @@ void testMain() throws Exception { fname.setAccessible(true); ClassGenerator cg = ClassGenerator.newInstance(); - cg.setClassName(Bean.class.getName() + "$Builder"); + cg.setClassName(Bean.class.getName() + "$Builder" + UUID.randomUUID().toString()); cg.addInterface(Builder.class); cg.addField("public static java.lang.reflect.Field FNAME;"); @@ -211,7 +213,7 @@ void testMain0() throws Exception { fname.setAccessible(true); ClassGenerator cg = ClassGenerator.newInstance(); - cg.setClassName(Bean.class.getName() + "$Builder2"); + cg.setClassName(Bean.class.getName() + "$Builder2" + UUID.randomUUID().toString()); cg.addInterface(Builder.class); cg.addField("FNAME", Modifier.PUBLIC | Modifier.STATIC, java.lang.reflect.Field.class); diff --git a/dubbo-compatible/pom.xml b/dubbo-compatible/pom.xml index 656bfed56f0..f6948de37a0 100644 --- a/dubbo-compatible/pom.xml +++ b/dubbo-compatible/pom.xml @@ -48,11 +48,6 @@ dubbo-remoting-zookeeper ${project.parent.version} - - org.apache.dubbo - dubbo-rpc-rest - ${project.parent.version} - org.apache.dubbo dubbo-filter-cache @@ -63,6 +58,17 @@ dubbo-filter-validation ${project.parent.version} + + javax.servlet + javax.servlet-api + provided + + + + javax.ws.rs + javax.ws.rs-api + provided + log4j log4j diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/cache/support/AbstractCacheFactory.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/cache/support/AbstractCacheFactory.java index 05a9c25d52d..eba2fa5613a 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/cache/support/AbstractCacheFactory.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/cache/support/AbstractCacheFactory.java @@ -30,7 +30,7 @@ @Deprecated public abstract class AbstractCacheFactory implements CacheFactory { - private final ConcurrentMap caches = new ConcurrentHashMap(); + private final ConcurrentMap caches = new ConcurrentHashMap<>(); @Override public Cache getCache(URL url, Invocation invocation) { diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java index 9579e26d67f..724b9f5da46 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java @@ -41,7 +41,6 @@ public class Constants org.apache.dubbo.common.serialize.Constants, org.apache.dubbo.common.config.configcenter.Constants, org.apache.dubbo.metadata.report.support.Constants, - org.apache.dubbo.rpc.protocol.rest.Constants, org.apache.dubbo.registry.Constants { public static final String PROVIDER = "provider"; diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java index fbd752f3582..58ad1e779ce 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java @@ -86,7 +86,7 @@ private static List convertProviderToProtocol(List protocols = new ArrayList(providers.size()); + List protocols = new ArrayList<>(providers.size()); for (ProviderConfig provider : providers) { protocols.add(convertProviderToProtocol(provider)); } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/Page.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/Page.java index 24042939a80..387723e82fe 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/Page.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/Page.java @@ -57,8 +57,8 @@ public Page(String navigation, String title, List columns, List> stringToList(String str) { - List> rows = new ArrayList>(); - List row = new ArrayList(); + List> rows = new ArrayList<>(); + List row = new ArrayList<>(); row.add(str); rows.add(row); return rows; diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/PageServlet.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/PageServlet.java index 25486c07edb..f9cf0fb3fa7 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/PageServlet.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/PageServlet.java @@ -49,8 +49,8 @@ public class PageServlet extends HttpServlet { private static final long serialVersionUID = -8370312705453328501L; private static PageServlet INSTANCE; protected final Random random = new Random(); - protected final Map pages = new ConcurrentHashMap(); - protected final List menus = new ArrayList(); + protected final Map pages = new ConcurrentHashMap<>(); + protected final List menus = new ArrayList<>(); public static PageServlet getInstance() { return INSTANCE; diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/ResourceFilter.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/ResourceFilter.java index 62f3da3d8e4..981508e4aeb 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/ResourceFilter.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/ResourceFilter.java @@ -46,7 +46,7 @@ public class ResourceFilter implements Filter { private final long start = System.currentTimeMillis(); - private final List resources = new ArrayList(); + private final List resources = new ArrayList<>(); public void init(FilterConfig filterConfig) throws ServletException { String config = filterConfig.getInitParameter("resources"); diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/HomePageHandler.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/HomePageHandler.java index 306706c22cc..0556a55a55b 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/HomePageHandler.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/HomePageHandler.java @@ -35,11 +35,11 @@ public class HomePageHandler implements PageHandler { @Override public Page handle(URL url) { - List> rows = new ArrayList>(); + List> rows = new ArrayList<>(); for (PageHandler handler : PageServlet.getInstance().getMenus()) { String uri = ExtensionLoader.getExtensionLoader(PageHandler.class).getExtensionName(handler); Menu menu = handler.getClass().getAnnotation(Menu.class); - List row = new ArrayList(); + List row = new ArrayList<>(); row.add("" + menu.name() + ""); row.add(menu.desc()); rows.add(row); diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/LogPageHandler.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/LogPageHandler.java index ee9f3670d53..cc5a5b3ec0c 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/LogPageHandler.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/LogPageHandler.java @@ -97,8 +97,8 @@ public Page handle(URL url) { } } Level level = LogManager.getRootLogger().getLevel(); - List> rows = new ArrayList>(); - List row = new ArrayList(); + List> rows = new ArrayList<>(); + List row = new ArrayList<>(); row.add(content); rows.add(row); return new Page( diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/StatusPageHandler.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/StatusPageHandler.java index f0fdb34a2ad..7a6b762309b 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/StatusPageHandler.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/StatusPageHandler.java @@ -40,14 +40,14 @@ public class StatusPageHandler implements PageHandler { @Override public Page handle(URL url) { - List> rows = new ArrayList>(); + List> rows = new ArrayList<>(); Set names = ExtensionLoader.getExtensionLoader(StatusChecker.class).getSupportedExtensions(); - Map statuses = new HashMap(); + Map statuses = new HashMap<>(); for (String name : names) { StatusChecker checker = ExtensionLoader.getExtensionLoader(StatusChecker.class).getExtension(name); - List row = new ArrayList(); + List row = new ArrayList<>(); row.add(name); Status status = checker.check(); if (status != null && !Status.Level.UNKNOWN.equals(status.getLevel())) { @@ -61,7 +61,7 @@ public Page handle(URL url) { if ("status".equals(url.getPath())) { return new Page("", "", "", status.getLevel().toString()); } else { - List row = new ArrayList(); + List row = new ArrayList<>(); row.add("summary"); row.add(getLevelHtml(status.getLevel())); row.add("summary"); diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/SystemPageHandler.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/SystemPageHandler.java index 84c3e9439a2..2eebd49702e 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/SystemPageHandler.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/SystemPageHandler.java @@ -46,27 +46,27 @@ public class SystemPageHandler implements PageHandler { @Override public Page handle(URL url) { - List> rows = new ArrayList>(); + List> rows = new ArrayList<>(); List row; - row = new ArrayList(); + row = new ArrayList<>(); row.add("Version"); row.add(Version.getVersion(SystemPageHandler.class, "2.0.0")); rows.add(row); - row = new ArrayList(); + row = new ArrayList<>(); row.add("Host"); String address = NetUtils.getLocalHost(); row.add(NetUtils.getHostName(address) + "/" + address); rows.add(row); - row = new ArrayList(); + row = new ArrayList<>(); row.add("OS"); row.add(SystemPropertyConfigUtils.getSystemProperty(CommonConstants.SystemProperty.SYSTEM_OS_NAME) + " " + SystemPropertyConfigUtils.getSystemProperty(CommonConstants.SystemProperty.SYSTEM_OS_VERSION)); rows.add(row); - row = new ArrayList(); + row = new ArrayList<>(); row.add("JVM"); row.add(SystemPropertyConfigUtils.getSystemProperty(CommonConstants.SystemProperty.JAVA_RUNTIME_NAME) + " " + SystemPropertyConfigUtils.getSystemProperty(CommonConstants.SystemProperty.JAVA_RUNTIME_VERSION) @@ -76,24 +76,24 @@ public Page handle(URL url) { + SystemPropertyConfigUtils.getSystemProperty(CommonConstants.SystemProperty.JAVA_VM_INFO, "")); rows.add(row); - row = new ArrayList(); + row = new ArrayList<>(); row.add("CPU"); row.add(SystemPropertyConfigUtils.getSystemProperty(CommonConstants.SystemProperty.OS_ARCH, "") + ", " + String.valueOf(Runtime.getRuntime().availableProcessors()) + " cores"); rows.add(row); - row = new ArrayList(); + row = new ArrayList<>(); row.add("Locale"); row.add(Locale.getDefault().toString() + "/" + SystemPropertyConfigUtils.getSystemProperty(CommonConstants.SystemProperty.SYSTEM_FILE_ENCODING)); rows.add(row); - row = new ArrayList(); + row = new ArrayList<>(); row.add("Uptime"); row.add(formatUptime(ManagementFactory.getRuntimeMXBean().getUptime())); rows.add(row); - row = new ArrayList(); + row = new ArrayList<>(); row.add("Time"); row.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS Z").format(new Date())); rows.add(row); diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/http/HttpBinder.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/http/HttpBinder.java deleted file mode 100644 index c0982a08454..00000000000 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/http/HttpBinder.java +++ /dev/null @@ -1,20 +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 com.alibaba.dubbo.remoting.http; - -@Deprecated -public interface HttpBinder extends org.apache.dubbo.remoting.http.HttpBinder {} diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java index 6f1b383e629..0f19232bca9 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java @@ -353,7 +353,7 @@ public Future asyncCall(Callable callable) { final T o = callable.call(); // local invoke will return directly if (o != null) { - FutureTask f = new FutureTask(new Callable() { + FutureTask f = new FutureTask<>(new Callable() { @Override public T call() throws Exception { return o; diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcInvocation.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcInvocation.java index d9bc2dd6627..2a741489d09 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcInvocation.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcInvocation.java @@ -162,14 +162,14 @@ public void setAttachments(Map attachments) { public void setAttachment(String key, String value) { if (attachments == null) { - attachments = new HashMap(); + attachments = new HashMap<>(); } attachments.put(key, value); } public void setAttachmentIfAbsent(String key, String value) { if (attachments == null) { - attachments = new HashMap(); + attachments = new HashMap<>(); } if (!attachments.containsKey(key)) { attachments.put(key, value); @@ -181,7 +181,7 @@ public void addAttachments(Map attachments) { return; } if (this.attachments == null) { - this.attachments = new HashMap(); + this.attachments = new HashMap<>(); } this.attachments.putAll(attachments); } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/support/ContentType.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/support/ContentType.java deleted file mode 100644 index ad2508fa6fa..00000000000 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/support/ContentType.java +++ /dev/null @@ -1,20 +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 com.alibaba.dubbo.rpc.protocol.rest.support; - -@Deprecated -public class ContentType extends org.apache.dubbo.rpc.protocol.rest.support.ContentType {} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/rest/AnnotatedMethodParameterProcessorTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/rest/AnnotatedMethodParameterProcessorTest.java deleted file mode 100644 index 6db0efb5b5a..00000000000 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/rest/AnnotatedMethodParameterProcessorTest.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.metadata.annotation.processing.rest; - -import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - -/** - * The abstract class for {@link AnnotatedMethodParameterProcessor}'s test cases - * - * @since 2.7.6 - */ -public abstract class AnnotatedMethodParameterProcessorTest extends AbstractAnnotationProcessingTest { - - protected AnnotatedMethodParameterProcessor processor; - - protected RestMethodMetadata restMethodMetadata; - - protected abstract AnnotatedMethodParameterProcessor createTestInstance(); - - @BeforeEach - public final void prepare() { - this.processor = createTestInstance(); - this.restMethodMetadata = createRestMethodMetadata(); - } - - protected RestMethodMetadata createRestMethodMetadata() { - return new RestMethodMetadata(); - } - - protected abstract String getExpectedAnnotationType(); - - @Test - void testGetAnnotationType() { - String expectedAnnotationType = getExpectedAnnotationType(); - assertNull(processor.getAnnotationType()); - assertEquals(expectedAnnotationType, processor.getAnnotationType()); - } -} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtilsTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtilsTest.java index 18814dc2732..3dfa820a1f6 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtilsTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtilsTest.java @@ -18,14 +18,12 @@ import org.apache.dubbo.config.annotation.Service; import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; -import org.apache.dubbo.metadata.rest.SpringRestService; import org.apache.dubbo.metadata.tools.TestService; import org.apache.dubbo.metadata.tools.TestServiceImpl; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; -import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror; import javax.ws.rs.Path; @@ -35,7 +33,6 @@ import java.util.Set; import org.junit.jupiter.api.Test; -import org.springframework.web.bind.annotation.GetMapping; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.findAnnotation; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.findMetaAnnotation; @@ -45,9 +42,7 @@ import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getAttribute; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getValue; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.isAnnotationPresent; -import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.findMethod; import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getAllDeclaredMethods; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -241,13 +236,6 @@ void testGetAttribute() { assertNull(getAttribute(findAnnotation(testType, Path.class), null)); assertNull(getAttribute(findAnnotation(testType, (Class) null), null)); - - ExecutableElement method = findMethod(getType(SpringRestService.class), "param", String.class); - - AnnotationMirror annotation = findAnnotation(method, GetMapping.class); - - assertArrayEquals(new String[] {"/param"}, (String[]) getAttribute(annotation, "value")); - assertNull(getAttribute(annotation, "path")); } @Test diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/DefaultRestServiceTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/DefaultRestServiceTest.java deleted file mode 100644 index 9b020d2ca4d..00000000000 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/DefaultRestServiceTest.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.tools; - -import org.apache.dubbo.metadata.rest.DefaultRestService; -import org.apache.dubbo.metadata.rest.RestService; -import org.apache.dubbo.metadata.rest.SpringRestService; -import org.apache.dubbo.metadata.rest.StandardRestService; -import org.apache.dubbo.metadata.rest.User; - -import java.io.IOException; - -import org.junit.jupiter.api.Test; - -/** - * The test case for {@link DefaultRestService} - * - * @since 2.7.6 - */ -class DefaultRestServiceTest { - - @Test - void test() throws IOException { - Compiler compiler = new Compiler(); - compiler.compile( - User.class, - RestService.class, - DefaultRestService.class, - SpringRestService.class, - StandardRestService.class); - } -} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/RestServiceTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/RestServiceTest.java deleted file mode 100644 index b8ea68c957f..00000000000 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/RestServiceTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.tools; - -import org.apache.dubbo.metadata.rest.RestService; -import org.apache.dubbo.metadata.rest.SpringRestService; -import org.apache.dubbo.metadata.rest.StandardRestService; -import org.apache.dubbo.metadata.rest.User; - -import java.io.IOException; - -import org.junit.jupiter.api.Test; - -/** - * {@link RestService} Test - * - * @since 2.7.6 - */ -class RestServiceTest { - - @Test - void test() throws IOException { - Compiler compiler = new Compiler(); - compiler.compile(User.class, RestService.class, StandardRestService.class, SpringRestService.class); - } -} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/SpringRestServiceTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/SpringRestServiceTest.java deleted file mode 100644 index 5871c21fefe..00000000000 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/SpringRestServiceTest.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.metadata.tools; - -import org.apache.dubbo.metadata.rest.RestService; -import org.apache.dubbo.metadata.rest.SpringRestService; -import org.apache.dubbo.metadata.rest.User; - -import java.io.IOException; - -import org.junit.jupiter.api.Test; - -/** - * {@link SpringRestService} Test - * - * @since 2.7.6 - */ -class SpringRestServiceTest { - - @Test - void test() throws IOException { - Compiler compiler = new Compiler(); - compiler.compile(User.class, RestService.class, SpringRestService.class); - } -} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/StandardRestServiceTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/StandardRestServiceTest.java deleted file mode 100644 index 84c8199dc7d..00000000000 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/StandardRestServiceTest.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.metadata.tools; - -import org.apache.dubbo.metadata.rest.RestService; -import org.apache.dubbo.metadata.rest.StandardRestService; -import org.apache.dubbo.metadata.rest.User; - -import java.io.IOException; - -import org.junit.jupiter.api.Test; - -/** - * The test case for {@link StandardRestService} - * - * @since 2.7.6 - */ -class StandardRestServiceTest { - - @Test - void test() throws IOException { - Compiler compiler = new Compiler(); - compiler.compile(User.class, RestService.class, StandardRestService.class); - } -} diff --git a/dubbo-config/dubbo-config-api/pom.xml b/dubbo-config/dubbo-config-api/pom.xml index a7fa622c770..bd7b28ed350 100644 --- a/dubbo-config/dubbo-config-api/pom.xml +++ b/dubbo-config/dubbo-config-api/pom.xml @@ -108,13 +108,6 @@ test - - org.apache.dubbo - dubbo-rpc-rest - ${project.parent.version} - test - - org.apache.dubbo dubbo-remoting-netty4 @@ -242,7 +235,7 @@ org.testcontainers testcontainers - 1.19.6 + 1.19.7 test 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 cca118bbfa6..c0aad1a209a 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 @@ -64,6 +64,7 @@ import java.util.Optional; import java.util.Set; import java.util.TreeSet; +import java.util.concurrent.locks.ReentrantLock; import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_DOMAIN; @@ -162,6 +163,8 @@ public class ReferenceConfig extends ReferenceConfigBase { */ private String services; + protected final transient ReentrantLock lock = new ReentrantLock(); + public ReferenceConfig() { super(); } @@ -291,102 +294,113 @@ private void logAndCleanup(Throwable t) { } @Override - public synchronized void destroy() { - super.destroy(); - if (destroyed) { - return; - } - destroyed = true; + public void destroy() { + lock.lock(); try { - if (invoker != null) { - invoker.destroy(); + super.destroy(); + if (destroyed) { + return; } - } catch (Throwable t) { - logger.warn( - CONFIG_FAILED_DESTROY_INVOKER, - "", - "", - "Unexpected error occurred when destroy invoker of ReferenceConfig(" + url + ").", - t); - } - invoker = null; - ref = null; - if (consumerModel != null) { - ModuleServiceRepository repository = getScopeModel().getServiceRepository(); - repository.unregisterConsumer(consumerModel); + destroyed = true; + try { + if (invoker != null) { + invoker.destroy(); + } + } catch (Throwable t) { + logger.warn( + CONFIG_FAILED_DESTROY_INVOKER, + "", + "", + "Unexpected error occurred when destroy invoker of ReferenceConfig(" + url + ").", + t); + } + invoker = null; + ref = null; + if (consumerModel != null) { + ModuleServiceRepository repository = getScopeModel().getServiceRepository(); + repository.unregisterConsumer(consumerModel); + } + } finally { + lock.unlock(); } } - protected synchronized void init() { + protected void init() { init(true); } - protected synchronized void init(boolean check) { - if (initialized && ref != null) { - return; - } + protected void init(boolean check) { + lock.lock(); try { - if (!this.isRefreshed()) { - this.refresh(); - } - // auto detect proxy type - String proxyType = getProxy(); - if (StringUtils.isBlank(proxyType) && DubboStub.class.isAssignableFrom(interfaceClass)) { - setProxy(CommonConstants.NATIVE_STUB); + if (initialized && ref != null) { + return; } + try { + if (!this.isRefreshed()) { + this.refresh(); + } + // auto detect proxy type + String proxyType = getProxy(); + if (StringUtils.isBlank(proxyType) && DubboStub.class.isAssignableFrom(interfaceClass)) { + setProxy(CommonConstants.NATIVE_STUB); + } - // init serviceMetadata - initServiceMetadata(consumer); + // init serviceMetadata + initServiceMetadata(consumer); - serviceMetadata.setServiceType(getServiceInterfaceClass()); - // TODO, uncomment this line once service key is unified - serviceMetadata.generateServiceKey(); + serviceMetadata.setServiceType(getServiceInterfaceClass()); + // TODO, uncomment this line once service key is unified + serviceMetadata.generateServiceKey(); - Map referenceParameters = appendConfig(); + Map referenceParameters = appendConfig(); - ModuleServiceRepository repository = getScopeModel().getServiceRepository(); - ServiceDescriptor serviceDescriptor; - if (CommonConstants.NATIVE_STUB.equals(getProxy())) { - serviceDescriptor = StubSuppliers.getServiceDescriptor(interfaceName); - repository.registerService(serviceDescriptor); - } else { - serviceDescriptor = repository.registerService(interfaceClass); - } - consumerModel = new ConsumerModel( - serviceMetadata.getServiceKey(), - proxy, - serviceDescriptor, - getScopeModel(), - serviceMetadata, - createAsyncMethodInfo(), - interfaceClassLoader); + ModuleServiceRepository repository = getScopeModel().getServiceRepository(); + ServiceDescriptor serviceDescriptor; + if (CommonConstants.NATIVE_STUB.equals(getProxy())) { + serviceDescriptor = StubSuppliers.getServiceDescriptor(interfaceName); + repository.registerService(serviceDescriptor); + setInterface(serviceDescriptor.getInterfaceName()); + } else { + serviceDescriptor = repository.registerService(interfaceClass); + } + consumerModel = new ConsumerModel( + serviceMetadata.getServiceKey(), + proxy, + serviceDescriptor, + getScopeModel(), + serviceMetadata, + createAsyncMethodInfo(), + interfaceClassLoader); - // Compatible with dependencies on ServiceModel#getReferenceConfig() , and will be removed in a future - // version. - consumerModel.setConfig(this); + // Compatible with dependencies on ServiceModel#getReferenceConfig() , and will be removed in a future + // version. + consumerModel.setConfig(this); - repository.registerConsumer(consumerModel); + repository.registerConsumer(consumerModel); - serviceMetadata.getAttachments().putAll(referenceParameters); + serviceMetadata.getAttachments().putAll(referenceParameters); - ref = createProxy(referenceParameters); + ref = createProxy(referenceParameters); - serviceMetadata.setTarget(ref); - serviceMetadata.addAttribute(PROXY_CLASS_REF, ref); + serviceMetadata.setTarget(ref); + serviceMetadata.addAttribute(PROXY_CLASS_REF, ref); - consumerModel.setDestroyRunner(getDestroyRunner()); - consumerModel.setProxyObject(ref); - consumerModel.initMethodModels(); + consumerModel.setDestroyRunner(getDestroyRunner()); + consumerModel.setProxyObject(ref); + consumerModel.initMethodModels(); - if (check) { - checkInvokerAvailable(0); - } - } catch (Throwable t) { - logAndCleanup(t); + if (check) { + checkInvokerAvailable(0); + } + } catch (Throwable t) { + logAndCleanup(t); - throw t; + throw t; + } + initialized = true; + } finally { + lock.unlock(); } - initialized = true; } /** 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 4b13e2dcfca..53bf3c84e95 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 @@ -131,7 +131,7 @@ public class ServiceConfig extends ServiceConfigBase { /** * A random port cache, the different protocols who have no port specified have different random port */ - private static final Map RANDOM_PORT_MAP = new HashMap(); + private static final Map RANDOM_PORT_MAP = new HashMap<>(); private Protocol protocolSPI; @@ -671,7 +671,7 @@ private void processServiceExecutor(URL url) { private Map buildAttributes(ProtocolConfig protocolConfig) { - Map map = new HashMap(); + Map map = new HashMap<>(); map.put(SIDE_KEY, PROVIDER_SIDE); // append params with basic configs, diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java index e4b37d2ad4e..5d7a0c5b997 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java @@ -336,7 +336,7 @@ private void startMetadataCenter() { } } metadataReportInstance.init(validMetadataReportConfigs); - if (!metadataReportInstance.inited()) { + if (!metadataReportInstance.isInitialized()) { throw new IllegalStateException(String.format( "%s MetadataConfigs found, but none of them is valid.", metadataReportConfigs.size())); } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/ConfigValidationUtils.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/ConfigValidationUtils.java index 810e862cd34..3152942f8c6 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/ConfigValidationUtils.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/ConfigValidationUtils.java @@ -82,6 +82,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.CONFIG_NAMESPACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL; import static org.apache.dubbo.common.constants.CommonConstants.DubboProperty.DUBBO_IP_TO_REGISTRY; @@ -108,6 +109,7 @@ import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTER_MODE_INTERFACE; import static org.apache.dubbo.common.constants.RegistryConstants.DUBBO_REGISTER_MODE_DEFAULT_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_MODE_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_CLUSTER_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL_TYPE; @@ -210,7 +212,7 @@ public static List loadRegistries(AbstractInterfaceConfig interfaceConfig, address = ANYHOST_VALUE; } if (!RegistryConfig.NO_AVAILABLE.equalsIgnoreCase(address)) { - Map map = new HashMap(); + Map map = new HashMap<>(); AbstractConfig.appendParameters(map, application); AbstractConfig.appendParameters(map, config); map.put(PATH_KEY, RegistryService.class.getName()); @@ -218,6 +220,14 @@ public static List loadRegistries(AbstractInterfaceConfig interfaceConfig, if (!map.containsKey(PROTOCOL_KEY)) { map.put(PROTOCOL_KEY, DUBBO_PROTOCOL); } + String registryCluster = config.getId(); + if (isEmpty(registryCluster)) { + registryCluster = DEFAULT_KEY; + } + if (map.containsKey(CONFIG_NAMESPACE_KEY)) { + registryCluster += ":" + map.get(CONFIG_NAMESPACE_KEY); + } + map.put(REGISTRY_CLUSTER_KEY, registryCluster); List urls = UrlUtils.parseURLs(address, map); for (URL url : urls) { @@ -313,7 +323,7 @@ private static boolean registryNotExists(URL registryURL, List registryList } public static URL loadMonitor(AbstractInterfaceConfig interfaceConfig, URL registryURL) { - Map map = new HashMap(); + Map map = new HashMap<>(); map.put(INTERFACE_KEY, MonitorService.class.getName()); AbstractInterfaceConfig.appendRuntimeParameters(map); // set ip diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboBootstrapTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboBootstrapTest.java index c107e9b4311..79aeb132ae2 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboBootstrapTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboBootstrapTest.java @@ -38,6 +38,8 @@ import org.apache.dubbo.config.provider.impl.DemoServiceImpl; import org.apache.dubbo.config.utils.ConfigValidationUtils; import org.apache.dubbo.metadata.MetadataService; +import org.apache.dubbo.metadata.report.MetadataReport; +import org.apache.dubbo.metadata.report.MetadataReportInstance; import org.apache.dubbo.monitor.MonitorService; import org.apache.dubbo.registry.RegistryService; import org.apache.dubbo.rpc.Exporter; @@ -51,10 +53,14 @@ import java.io.IOException; import java.io.OutputStream; import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Properties; +import java.util.stream.Collectors; +import com.google.common.collect.Maps; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; @@ -62,10 +68,15 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import static org.apache.dubbo.common.constants.CommonConstants.CONFIG_NAMESPACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_MONITOR_ADDRESS; import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_METADATA_STORAGE_TYPE; import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_SECONDS_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_CLUSTER_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY; +import static org.apache.dubbo.metadata.MetadataConstants.REPORT_CONSUMER_URL_KEY; import static org.hamcrest.CoreMatchers.anything; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasEntry; @@ -142,13 +153,29 @@ void compatibleApplicationShutdown() { @Test void testLoadRegistries() { - SysProps.setProperty("dubbo.registry.address", "addr1"); - ServiceConfig serviceConfig = new ServiceConfig(); serviceConfig.setInterface(DemoService.class); serviceConfig.setRef(new DemoServiceImpl()); serviceConfig.setApplication(new ApplicationConfig("testLoadRegistries")); + String registryId = "nacosRegistry"; + String namespace1 = "test"; + RegistryConfig registryConfig = new RegistryConfig(); + registryConfig.setId(registryId); + registryConfig.setAddress("nacos://addr1:8848"); + Map registryParamMap = Maps.newHashMap(); + registryParamMap.put(CONFIG_NAMESPACE_KEY, namespace1); + registryConfig.setParameters(registryParamMap); + + String namespace2 = "test2"; + RegistryConfig registryConfig2 = new RegistryConfig(); + registryConfig2.setAddress("polaris://addr1:9999"); + Map registryParamMap2 = Maps.newHashMap(); + registryParamMap2.put(CONFIG_NAMESPACE_KEY, namespace2); + registryConfig2.setParameters(registryParamMap2); + + serviceConfig.setRegistries(Arrays.asList(registryConfig, registryConfig2)); + // load configs from props DubboBootstrap.getInstance().initialize(); @@ -157,11 +184,28 @@ void testLoadRegistries() { // ApplicationModel.defaultModel().getEnvironment().setDynamicConfiguration(new // CompositeDynamicConfiguration()); List urls = ConfigValidationUtils.loadRegistries(serviceConfig, true); - Assertions.assertEquals(2, urls.size()); - for (URL url : urls) { + Assertions.assertEquals(4, urls.size()); + + Map> urlsMap = + urls.stream().collect(Collectors.groupingBy(url -> url.getParameter(REGISTRY_KEY))); + Assertions.assertEquals(2, urlsMap.get("nacos").size()); + for (URL url : urlsMap.get("nacos")) { + Assertions.assertTrue(url.getProtocol().contains("registry")); + Assertions.assertEquals("addr1:8848", url.getAddress()); + Assertions.assertEquals(RegistryService.class.getName(), url.getPath()); + Assertions.assertEquals(registryId + ":" + namespace1, url.getParameter(REGISTRY_CLUSTER_KEY)); + Assertions.assertTrue(url.getParameters().containsKey("timestamp")); + Assertions.assertTrue(url.getParameters().containsKey("pid")); + Assertions.assertTrue(url.getParameters().containsKey("registry")); + Assertions.assertTrue(url.getParameters().containsKey("dubbo")); + } + + Assertions.assertEquals(2, urlsMap.get("polaris").size()); + for (URL url : urlsMap.get("polaris")) { Assertions.assertTrue(url.getProtocol().contains("registry")); - Assertions.assertEquals("addr1:9090", url.getAddress()); + Assertions.assertEquals("addr1:9999", url.getAddress()); Assertions.assertEquals(RegistryService.class.getName(), url.getPath()); + Assertions.assertEquals(DEFAULT_KEY + ":" + namespace2, url.getParameter(REGISTRY_CLUSTER_KEY)); Assertions.assertTrue(url.getParameters().containsKey("timestamp")); Assertions.assertTrue(url.getParameters().containsKey("pid")); Assertions.assertTrue(url.getParameters().containsKey("registry")); @@ -169,6 +213,77 @@ void testLoadRegistries() { } } + @Test + void testRegistryWithMetadataReport() { + ServiceConfig serviceConfig = new ServiceConfig(); + serviceConfig.setInterface(DemoService.class); + serviceConfig.setRef(new DemoServiceImpl()); + + List registryConfigs = new ArrayList<>(); + List metadataReportConfigs = new ArrayList<>(); + + String registryId = "nacosRegistry"; + String namespace1 = "test"; + RegistryConfig registryConfig = new RegistryConfig(); + registryConfig.setId(registryId); + registryConfig.setAddress(zkServerAddress); + Map registryParamMap = Maps.newHashMap(); + registryParamMap.put(CONFIG_NAMESPACE_KEY, namespace1); + registryConfig.setParameters(registryParamMap); + registryConfigs.add(registryConfig); + + MetadataReportConfig metadataReportConfig = new MetadataReportConfig(); + metadataReportConfig.setRegistry(registryId); + metadataReportConfig.setAddress(registryConfig.getAddress()); + Map metadataParamMap = Maps.newHashMap(); + metadataParamMap.put(CONFIG_NAMESPACE_KEY, namespace1); + metadataParamMap.put(REPORT_CONSUMER_URL_KEY, Boolean.TRUE.toString()); + metadataReportConfig.setParameters(metadataParamMap); + metadataReportConfig.setReportMetadata(true); + metadataReportConfigs.add(metadataReportConfig); + + String namespace2 = "test2"; + RegistryConfig registryConfig2 = new RegistryConfig(); + registryConfig2.setAddress(zkServerAddress); + Map registryParamMap2 = Maps.newHashMap(); + registryParamMap2.put(CONFIG_NAMESPACE_KEY, namespace2); + registryConfig2.setParameters(registryParamMap2); + registryConfigs.add(registryConfig2); + + MetadataReportConfig metadataReportConfig2 = new MetadataReportConfig(); + metadataReportConfig2.setAddress(registryConfig2.getAddress()); + Map metadataParamMap2 = Maps.newHashMap(); + metadataParamMap2.put(CONFIG_NAMESPACE_KEY, namespace2); + metadataParamMap2.put(REPORT_CONSUMER_URL_KEY, Boolean.TRUE.toString()); + metadataReportConfig2.setParameters(metadataParamMap2); + metadataReportConfig2.setReportMetadata(true); + metadataReportConfigs.add(metadataReportConfig2); + + serviceConfig.setRegistries(registryConfigs); + + DubboBootstrap.getInstance() + .application(new ApplicationConfig("testRegistryWithMetadataReport")) + .registries(registryConfigs) + .metadataReports(metadataReportConfigs) + .service(serviceConfig) + .protocol(new ProtocolConfig(CommonConstants.DUBBO_PROTOCOL, -1)) + .start(); + + ApplicationModel applicationModel = DubboBootstrap.getInstance().getApplicationModel(); + MetadataReportInstance metadataReportInstance = + applicationModel.getBeanFactory().getBean(MetadataReportInstance.class); + + Map metadataReports = metadataReportInstance.getMetadataReports(true); + Assertions.assertEquals(2, metadataReports.size()); + + List urls = ConfigValidationUtils.loadRegistries(serviceConfig, true); + Assertions.assertEquals(4, urls.size()); + + for (URL url : urls) { + Assertions.assertTrue(metadataReports.containsKey(url.getParameter(REGISTRY_CLUSTER_KEY))); + } + } + @Test void testLoadUserMonitor_address_only() { // -Ddubbo.monitor.address=monitor-addr:12080 diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboServiceConsumerBootstrap.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboServiceConsumerBootstrap.java deleted file mode 100644 index 1c3f5fd96c9..00000000000 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboServiceConsumerBootstrap.java +++ /dev/null @@ -1,53 +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.bootstrap; - -import org.apache.dubbo.config.MetadataReportConfig; -import org.apache.dubbo.config.bootstrap.rest.UserService; -import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; - -/** - * Dubbo Provider Bootstrap - * - * @since 2.7.5 - */ -public class DubboServiceConsumerBootstrap { - - public static void main(String[] args) throws Exception { - - DubboBootstrap bootstrap = DubboBootstrap.getInstance() - .application("dubbo-consumer-demo") - .protocol(builder -> builder.port(20887).name("dubbo")) - .registry( - "zookeeper", - builder -> builder.address(ZookeeperRegistryCenterConfig.getConnectionAddress() - + "?registry-type=service&subscribed-services=dubbo-provider-demo")) - .metadataReport(new MetadataReportConfig(ZookeeperRegistryCenterConfig.getConnectionAddress())) - .reference("echo", builder -> builder.interfaceClass(EchoService.class) - .protocol("dubbo")) - .reference("user", builder -> builder.interfaceClass(UserService.class) - .protocol("rest")) - .start(); - - EchoService echoService = bootstrap.getCache().get(EchoService.class); - - for (int i = 0; i < 500; i++) { - Thread.sleep(2000L); - System.out.println(echoService.echo("Hello,World")); - } - } -} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboServiceProviderBootstrap.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboServiceProviderBootstrap.java deleted file mode 100644 index 2fef821a9b5..00000000000 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboServiceProviderBootstrap.java +++ /dev/null @@ -1,82 +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.bootstrap; - -import org.apache.dubbo.config.ApplicationConfig; -import org.apache.dubbo.config.MetadataReportConfig; -import org.apache.dubbo.config.ProtocolConfig; -import org.apache.dubbo.config.RegistryConfig; -import org.apache.dubbo.config.ServiceConfig; -import org.apache.dubbo.config.bootstrap.rest.UserService; -import org.apache.dubbo.config.bootstrap.rest.UserServiceImpl; -import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; - -import java.util.Arrays; - -/** - * Dubbo Provider Bootstrap - * - * @since 2.7.5 - */ -public class DubboServiceProviderBootstrap { - - public static void main(String[] args) { - multipleRegistries(); - } - - private static void multipleRegistries() { - ProtocolConfig restProtocol = new ProtocolConfig(); - restProtocol.setName("rest"); - restProtocol.setId("rest"); - restProtocol.setPort(-1); - - RegistryConfig interfaceRegistry = new RegistryConfig(); - interfaceRegistry.setId("interfaceRegistry"); - interfaceRegistry.setAddress(ZookeeperRegistryCenterConfig.getConnectionAddress()); - - RegistryConfig serviceRegistry = new RegistryConfig(); - serviceRegistry.setId("serviceRegistry"); - serviceRegistry.setAddress(ZookeeperRegistryCenterConfig.getConnectionAddress() + "?registry-type=service"); - - ServiceConfig echoService = new ServiceConfig<>(); - echoService.setInterface(EchoService.class.getName()); - echoService.setRef(new EchoServiceImpl()); - - ServiceConfig userService = new ServiceConfig<>(); - userService.setInterface(UserService.class.getName()); - userService.setRef(new UserServiceImpl()); - userService.setProtocol(restProtocol); - - ApplicationConfig applicationConfig = new ApplicationConfig("dubbo-provider-demo"); - applicationConfig.setMetadataType("remote"); - DubboBootstrap.getInstance() - .application(applicationConfig) - .registries(Arrays.asList(interfaceRegistry, serviceRegistry)) - .protocol(builder -> builder.port(-1).name("dubbo")) - .metadataReport(new MetadataReportConfig(ZookeeperRegistryCenterConfig.getConnectionAddress())) - .service(echoService) - .service(userService) - .start() - .await(); - } - - private static void testSCCallDubbo() {} - - private static void testDubboCallSC() {} - - private static void testDubboTansormation() {} -} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboServiceProviderMinimumBootstrap.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboServiceProviderMinimumBootstrap.java deleted file mode 100644 index f291f5a821c..00000000000 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboServiceProviderMinimumBootstrap.java +++ /dev/null @@ -1,41 +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.bootstrap; - -import org.apache.dubbo.config.bootstrap.rest.UserService; -import org.apache.dubbo.config.bootstrap.rest.UserServiceImpl; -import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; - -/** - * TODO - */ -public class DubboServiceProviderMinimumBootstrap { - - public static void main(String[] args) { - DubboBootstrap.getInstance() - .application("dubbo-provider-demo") - .registry(builder -> builder.address( - ZookeeperRegistryCenterConfig.getConnectionAddress() + "?registry-type=service")) - .protocol(builder -> builder.port(-1).name("dubbo")) - .service("echo", builder -> builder.interfaceClass(EchoService.class) - .ref(new EchoServiceImpl())) - .service("user", builder -> builder.interfaceClass(UserService.class) - .ref(new UserServiceImpl())) - .start() - .await(); - } -} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/NacosDubboServiceConsumerBootstrap.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/NacosDubboServiceConsumerBootstrap.java deleted file mode 100644 index 98603b8d479..00000000000 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/NacosDubboServiceConsumerBootstrap.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.config.bootstrap; - -import org.apache.dubbo.config.ApplicationConfig; -import org.apache.dubbo.config.bootstrap.rest.UserService; - -import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_METADATA_STORAGE_TYPE; - -/** - * Dubbo Provider Bootstrap - * - * @since 2.7.5 - */ -public class NacosDubboServiceConsumerBootstrap { - - public static void main(String[] args) throws Exception { - - ApplicationConfig applicationConfig = new ApplicationConfig("dubbo-nacos-consumer-demo"); - applicationConfig.setMetadataType(REMOTE_METADATA_STORAGE_TYPE); - DubboBootstrap bootstrap = DubboBootstrap.getInstance() - .application(applicationConfig) - // Nacos in service registry type - .registry("nacos", builder -> builder.address("nacos://127.0.0.1:8848?registry-type=service") - .useAsConfigCenter(true) - .useAsMetadataCenter(true)) - // Nacos in traditional registry type - // .registry("nacos-traditional", builder -> builder.address("nacos://127.0.0.1:8848")) - .reference("echo", builder -> builder.interfaceClass(EchoService.class) - .protocol("dubbo")) - .reference("user", builder -> builder.interfaceClass(UserService.class) - .protocol("rest")) - .start(); - - EchoService echoService = bootstrap.getCache().get(EchoService.class); - UserService userService = bootstrap.getCache().get(UserService.class); - - for (int i = 0; i < 5; i++) { - Thread.sleep(2000L); - System.out.println(echoService.echo("Hello,World")); - System.out.println(userService.getUser(i * 1L)); - } - } -} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/NacosDubboServiceProviderBootstrap.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/NacosDubboServiceProviderBootstrap.java deleted file mode 100644 index ad5911c1822..00000000000 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/NacosDubboServiceProviderBootstrap.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.config.bootstrap; - -import org.apache.dubbo.config.ApplicationConfig; -import org.apache.dubbo.config.bootstrap.rest.UserService; -import org.apache.dubbo.config.bootstrap.rest.UserServiceImpl; - -import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_METADATA_STORAGE_TYPE; -import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_TYPE_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_TYPE; - -/** - * Dubbo Provider Bootstrap - * - * @since 2.7.5 - */ -public class NacosDubboServiceProviderBootstrap { - - public static void main(String[] args) { - ApplicationConfig applicationConfig = new ApplicationConfig("dubbo-nacos-provider-demo"); - applicationConfig.setMetadataType(REMOTE_METADATA_STORAGE_TYPE); - DubboBootstrap.getInstance() - .application(applicationConfig) - // Nacos in service registry type - .registry("nacos", builder -> builder.address("nacos://127.0.0.1:8848?username=nacos&password=nacos") - .parameter(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE)) - // Nacos in traditional registry type - // .registry("nacos-traditional", builder -> builder.address("nacos://127.0.0.1:8848")) - .protocol("dubbo", builder -> builder.port(20885).name("dubbo")) - .protocol("rest", builder -> builder.port(9090).name("rest")) - .service(builder -> builder.id("echo") - .interfaceClass(EchoService.class) - .ref(new EchoServiceImpl()) - .protocolIds("dubbo")) - .service(builder -> builder.id("user") - .interfaceClass(UserService.class) - .ref(new UserServiceImpl()) - .protocolIds("rest")) - .start() - .await(); - } -} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/ZookeeperDubboServiceConsumerBootstrap.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/ZookeeperDubboServiceConsumerBootstrap.java deleted file mode 100644 index 657120a2114..00000000000 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/ZookeeperDubboServiceConsumerBootstrap.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.bootstrap; - -import org.apache.dubbo.config.bootstrap.rest.UserService; -import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; - -import static org.apache.dubbo.common.constants.CommonConstants.COMPOSITE_METADATA_STORAGE_TYPE; -import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_TYPE_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_TYPE; - -/** - * Dubbo Provider Bootstrap - * - * @since 2.7.5 - */ -public class ZookeeperDubboServiceConsumerBootstrap { - - public static void main(String[] args) throws Exception { - - DubboBootstrap bootstrap = DubboBootstrap.getInstance() - .application("zookeeper-dubbo-consumer", app -> app.metadata(COMPOSITE_METADATA_STORAGE_TYPE)) - .registry("zookeeper", builder -> builder.address(ZookeeperRegistryCenterConfig.getConnectionAddress()) - .parameter(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE) - .useAsConfigCenter(true) - .useAsMetadataCenter(true)) - .reference("echo", builder -> builder.interfaceClass(EchoService.class) - .protocol("dubbo") - .services("zookeeper-dubbo-provider")) - .reference("user", builder -> builder.interfaceClass(UserService.class) - .protocol("rest")) - .start(); - - EchoService echoService = bootstrap.getCache().get(EchoService.class); - UserService userService = bootstrap.getCache().get(UserService.class); - - for (int i = 0; i < 5; i++) { - Thread.sleep(2000L); - System.out.println(echoService.echo("Hello,World")); - System.out.println(userService.getUser(i * 1L)); - } - - bootstrap.stop(); - } -} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/ZookeeperDubboServiceProviderBootstrap.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/ZookeeperDubboServiceProviderBootstrap.java deleted file mode 100644 index 927716f8130..00000000000 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/ZookeeperDubboServiceProviderBootstrap.java +++ /dev/null @@ -1,48 +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.bootstrap; - -import org.apache.dubbo.config.bootstrap.rest.UserService; -import org.apache.dubbo.config.bootstrap.rest.UserServiceImpl; - -import static org.apache.dubbo.common.constants.CommonConstants.COMPOSITE_METADATA_STORAGE_TYPE; -import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_TYPE_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_TYPE; - -/** - * TODO - */ -public class ZookeeperDubboServiceProviderBootstrap { - - public static void main(String[] args) { - DubboBootstrap.getInstance() - .application("zookeeper-dubbo-provider", app -> app.metadata(COMPOSITE_METADATA_STORAGE_TYPE)) - .registry(builder -> builder.address("127.0.0.1:2181") - .protocol("zookeeper") - .parameter(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE)) - .protocol("dubbo", builder -> builder.port(-1).name("dubbo")) - .protocol("rest", builder -> builder.port(8081).name("rest")) - .service("echo", builder -> builder.interfaceClass(EchoService.class) - .ref(new EchoServiceImpl()) - .protocolIds("dubbo")) - .service("user", builder -> builder.interfaceClass(UserService.class) - .ref(new UserServiceImpl()) - .protocolIds("rest")) - .start() - .await(); - } -} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/compatible/DubboInterfaceConsumerBootstrap.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/compatible/DubboInterfaceConsumerBootstrap.java deleted file mode 100644 index 1a0e141f441..00000000000 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/compatible/DubboInterfaceConsumerBootstrap.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.config.bootstrap.compatible; - -import org.apache.dubbo.config.RegistryConfig; -import org.apache.dubbo.config.bootstrap.DubboBootstrap; -import org.apache.dubbo.config.bootstrap.EchoService; -import org.apache.dubbo.config.bootstrap.rest.UserService; -import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; - -/** - * Dubbo Provider Bootstrap - * - * @since 2.7.5 - */ -public class DubboInterfaceConsumerBootstrap { - - public static void main(String[] args) throws Exception { - RegistryConfig interfaceRegistry = new RegistryConfig(); - interfaceRegistry.setId("interfaceRegistry"); - interfaceRegistry.setAddress(ZookeeperRegistryCenterConfig.getConnectionAddress()); - - DubboBootstrap bootstrap = DubboBootstrap.getInstance() - .application("dubbo-consumer-demo") - // Zookeeper - .registry(interfaceRegistry) - .reference("echo", builder -> builder.interfaceClass(EchoService.class) - .protocol("dubbo")) - .reference("user", builder -> builder.interfaceClass(UserService.class) - .protocol("rest")) - .start() - .await(); - - EchoService echoService = bootstrap.getCache().get(EchoService.class); - UserService userService = bootstrap.getCache().get(UserService.class); - - for (int i = 0; i < 500; i++) { - Thread.sleep(2000L); - System.out.println(echoService.echo("Hello,World")); - System.out.println(userService.getUser(1L)); - } - } -} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/rest/User.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/rest/User.java deleted file mode 100644 index a1586f9955a..00000000000 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/rest/User.java +++ /dev/null @@ -1,72 +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.bootstrap.rest; - -import javax.validation.constraints.Min; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import java.io.Serializable; - -import org.codehaus.jackson.annotate.JsonProperty; - -@XmlRootElement -@XmlAccessorType(XmlAccessType.FIELD) -public class User implements Serializable { - - @NotNull - @Min(1L) - private Long id; - - @JsonProperty("username") - @XmlElement(name = "username") - @NotNull - @Size(min = 6, max = 50) - private String name; - - public User() {} - - public User(Long id, String name) { - this.id = id; - this.name = name; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public String toString() { - return "User (" + "id=" + id + ", name='" + name + '\'' + ')'; - } -} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/rest/UserService.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/rest/UserService.java deleted file mode 100644 index 53400f292ed..00000000000 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/rest/UserService.java +++ /dev/null @@ -1,42 +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.bootstrap.rest; - -import org.apache.dubbo.rpc.protocol.rest.support.ContentType; - -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; - -@Path("users") -@Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) -@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8}) -@Api(value = "UserService") -public interface UserService { - - @GET - @Path("{id : \\d+}") - @ApiOperation(value = "getUser") - User getUser(@ApiParam(value = "id") @PathParam("id") Long id); -} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/rest/UserServiceImpl.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/rest/UserServiceImpl.java deleted file mode 100644 index 6d24d6206df..00000000000 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/rest/UserServiceImpl.java +++ /dev/null @@ -1,29 +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.bootstrap.rest; - -import java.util.concurrent.atomic.AtomicLong; - -public class UserServiceImpl implements UserService { - - private final AtomicLong idGen = new AtomicLong(); - - @Override - public User getUser(Long id) { - return new User(id, "username" + id); - } -} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportmetadata/MultipleRegistryCenterExportMetadataIntegrationTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportmetadata/MultipleRegistryCenterExportMetadataIntegrationTest.java index 0cc1e25b6df..e530a2eb6c9 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportmetadata/MultipleRegistryCenterExportMetadataIntegrationTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportmetadata/MultipleRegistryCenterExportMetadataIntegrationTest.java @@ -168,7 +168,6 @@ private void afterExport() { @AfterEach public void tearDown() throws IOException { DubboBootstrap.reset(); - PROVIDER_APPLICATION_NAME = null; serviceConfig = null; // The exported service has been unexported Assertions.assertTrue(serviceListener.getExportedServices().isEmpty()); diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderIntegrationTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderIntegrationTest.java index 10395824f57..21ffd61150a 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderIntegrationTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderIntegrationTest.java @@ -239,7 +239,6 @@ private void afterInvoke() { @AfterEach public void tearDown() throws IOException { DubboBootstrap.reset(); - PROVIDER_APPLICATION_NAME = null; serviceConfig = null; // The exported service has been unexported Assertions.assertTrue(serviceListener.getExportedServices().isEmpty()); diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/injvm/MultipleRegistryCenterInjvmIntegrationTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/injvm/MultipleRegistryCenterInjvmIntegrationTest.java index 3d7315a456f..f0bd1ba6375 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/injvm/MultipleRegistryCenterInjvmIntegrationTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/injvm/MultipleRegistryCenterInjvmIntegrationTest.java @@ -185,7 +185,6 @@ private void afterInvoke() { @AfterEach public void tearDown() throws IOException { DubboBootstrap.reset(); - PROVIDER_APPLICATION_NAME = null; serviceConfig = null; // The exported service has been unexported Assertions.assertTrue(serviceListener.getExportedServices().isEmpty()); diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/MultipleRegistryCenterServiceDiscoveryRegistryIntegrationTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/MultipleRegistryCenterServiceDiscoveryRegistryIntegrationTest.java index 1f89b88cc33..1816277cf80 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/MultipleRegistryCenterServiceDiscoveryRegistryIntegrationTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/MultipleRegistryCenterServiceDiscoveryRegistryIntegrationTest.java @@ -201,7 +201,6 @@ private void afterInvoke() {} @AfterEach public void tearDown() throws IOException { DubboBootstrap.reset(); - PROVIDER_APPLICATION_NAME = null; serviceConfig = null; // TODO: we need to check whether this scenario is normal // TODO: the Exporter and ServiceDiscoveryRegistry are same in multiple registry center diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportmetadata/SingleRegistryCenterExportMetadataIntegrationTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportmetadata/SingleRegistryCenterExportMetadataIntegrationTest.java index 96536d0a62f..db5193e45da 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportmetadata/SingleRegistryCenterExportMetadataIntegrationTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportmetadata/SingleRegistryCenterExportMetadataIntegrationTest.java @@ -165,7 +165,6 @@ private void afterExport() { @AfterEach public void tearDown() throws IOException { DubboBootstrap.reset(); - PROVIDER_APPLICATION_NAME = null; serviceConfig = null; // The exported service has been unexported Assertions.assertTrue(serviceListener.getExportedServices().isEmpty()); diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportprovider/SingleRegistryCenterExportProviderIntegrationTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportprovider/SingleRegistryCenterExportProviderIntegrationTest.java index d866f40d6e1..b411670349a 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportprovider/SingleRegistryCenterExportProviderIntegrationTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportprovider/SingleRegistryCenterExportProviderIntegrationTest.java @@ -240,7 +240,6 @@ private void afterInvoke() { @AfterEach public void tearDown() throws IOException { DubboBootstrap.reset(); - PROVIDER_APPLICATION_NAME = null; serviceConfig = null; // The exported service has been unexported Assertions.assertTrue(serviceListener.getExportedServices().isEmpty()); diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/injvm/SingleRegistryCenterInjvmIntegrationTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/injvm/SingleRegistryCenterInjvmIntegrationTest.java index 95090fd8ff0..fd68e3367e1 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/injvm/SingleRegistryCenterInjvmIntegrationTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/injvm/SingleRegistryCenterInjvmIntegrationTest.java @@ -185,7 +185,6 @@ private void afterInvoke() { @AfterEach public void tearDown() throws IOException { DubboBootstrap.reset(); - PROVIDER_APPLICATION_NAME = null; serviceConfig = null; // The exported service has been unexported Assertions.assertTrue(serviceListener.getExportedServices().isEmpty()); diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/ReferenceCacheTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/ReferenceCacheTest.java index c231d892bc6..c324c53e06e 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/ReferenceCacheTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/ReferenceCacheTest.java @@ -35,6 +35,7 @@ class ReferenceCacheTest { public void setUp() throws Exception { DubboBootstrap.reset(); MockReferenceConfig.setCounter(0); + XxxMockReferenceConfig.setCounter(0); SimpleReferenceCache.CACHE_HOLDER.clear(); } diff --git a/dubbo-config/dubbo-config-spring/pom.xml b/dubbo-config/dubbo-config-spring/pom.xml index 78316e62437..b49df8dc0c9 100644 --- a/dubbo-config/dubbo-config-spring/pom.xml +++ b/dubbo-config/dubbo-config-spring/pom.xml @@ -74,7 +74,7 @@ org.aspectj aspectjweaver - 1.9.21.1 + 1.9.22 test @@ -95,12 +95,6 @@ ${project.parent.version} test - - org.apache.dubbo - dubbo-rpc-rest - ${project.parent.version} - test - org.apache.dubbo dubbo-remoting-netty4 diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AbstractAnnotationBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AbstractAnnotationBeanPostProcessor.java index 37594fffe23..554473f5675 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AbstractAnnotationBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AbstractAnnotationBeanPostProcessor.java @@ -78,8 +78,7 @@ public abstract class AbstractAnnotationBeanPostProcessor private final Class[] annotationTypes; private final ConcurrentMap - injectionMetadataCache = new ConcurrentHashMap< - String, AbstractAnnotationBeanPostProcessor.AnnotatedInjectionMetadata>(CACHE_SIZE); + injectionMetadataCache = new ConcurrentHashMap<>(CACHE_SIZE); private ConfigurableListableBeanFactory beanFactory; @@ -98,7 +97,7 @@ public AbstractAnnotationBeanPostProcessor(Class... annota } private static Collection combine(Collection... elements) { - List allElements = new ArrayList(); + List allElements = new ArrayList<>(); for (Collection e : elements) { allElements.addAll(e); } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/AnnotationUtils.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/AnnotationUtils.java index 713a1918356..35c1bfa9327 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/AnnotationUtils.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/AnnotationUtils.java @@ -87,7 +87,7 @@ public static Map getAttributes( Set ignoreAttributeNamesSet = new HashSet<>(Arrays.asList(ignoreAttributeNames)); - Map actualAttributes = new LinkedHashMap(); + Map actualAttributes = new LinkedHashMap<>(); for (Map.Entry annotationAttribute : annotationAttributes.entrySet()) { @@ -143,7 +143,7 @@ public static Map getAttributes( if (ignoreDefaultValue && !isEmpty(annotationAttributes)) { - List attributeNamesToIgnore = new LinkedList(asList(ignoreAttributeNames)); + List attributeNamesToIgnore = new LinkedList<>(asList(ignoreAttributeNames)); for (Map.Entry annotationAttribute : annotationAttributes.entrySet()) { String attributeName = annotationAttribute.getKey(); @@ -444,21 +444,11 @@ public static Annotation tryGetMergedAnnotation( (_k) -> ClassUtils.isPresent(ANNOTATED_ELEMENT_UTILS_CLASS_NAME, classLoader))) { Class annotatedElementUtilsClass = resolveClassName(ANNOTATED_ELEMENT_UTILS_CLASS_NAME, classLoader); // getMergedAnnotation method appears in the Spring Framework 4.2 - Method getMergedAnnotationMethod = findMethod( - annotatedElementUtilsClass, - "getMergedAnnotation", - AnnotatedElement.class, - Class.class, - boolean.class, - boolean.class); + Method getMergedAnnotationMethod = + findMethod(annotatedElementUtilsClass, "getMergedAnnotation", AnnotatedElement.class, Class.class); if (getMergedAnnotationMethod != null) { - mergedAnnotation = (Annotation) invokeMethod( - getMergedAnnotationMethod, - null, - annotatedElement, - annotationType, - classValuesAsString, - nestedAnnotationsAsMap); + mergedAnnotation = + (Annotation) invokeMethod(getMergedAnnotationMethod, null, annotatedElement, annotationType); } } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/PropertySourcesUtils.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/PropertySourcesUtils.java index 15e164b5eee..8a5eff73e5e 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/PropertySourcesUtils.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/PropertySourcesUtils.java @@ -103,7 +103,7 @@ public static Map getSubProperties(PropertySources propertySourc public static Map getSubProperties( PropertySources propertySources, PropertyResolver propertyResolver, String prefix) { - Map subProperties = new LinkedHashMap(); + Map subProperties = new LinkedHashMap<>(); String normalizedPrefix = normalizePrefix(prefix); diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ControllerServiceConfigTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ControllerServiceConfigTest.java index 2d2de09b8da..3ecb212b13a 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ControllerServiceConfigTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ControllerServiceConfigTest.java @@ -21,8 +21,10 @@ import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.spring.api.SpringControllerService; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +@Disabled public class ControllerServiceConfigTest { @Test @@ -32,7 +34,7 @@ void testServiceConfig() { ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setName("dubbo"); serviceServiceConfig.setApplication(applicationConfig); - serviceServiceConfig.setProtocol(new ProtocolConfig("rest", 8080)); + serviceServiceConfig.setProtocol(new ProtocolConfig("dubbo", 8080)); serviceServiceConfig.setRef(new SpringControllerService()); serviceServiceConfig.setInterface(SpringControllerService.class.getName()); serviceServiceConfig.export(); diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml b/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml index 4d8eb91d364..991a961c5ff 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml +++ b/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml @@ -1,19 +1,19 @@ 4.0.0 diff --git a/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-consumer/pom.xml b/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-consumer/pom.xml index b66dadc983b..85b651833c1 100644 --- a/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-consumer/pom.xml +++ b/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-consumer/pom.xml @@ -1,21 +1,19 @@ 4.0.0 diff --git a/dubbo-demo/dubbo-demo-annotation/pom.xml b/dubbo-demo/dubbo-demo-annotation/pom.xml index d881d55fdce..8e82740451a 100644 --- a/dubbo-demo/dubbo-demo-annotation/pom.xml +++ b/dubbo-demo/dubbo-demo-annotation/pom.xml @@ -1,21 +1,19 @@ 4.0.0 diff --git a/dubbo-demo/dubbo-demo-api/dubbo-demo-api-consumer/pom.xml b/dubbo-demo/dubbo-demo-api/dubbo-demo-api-consumer/pom.xml index ff2b42a3fea..ce9ef312488 100644 --- a/dubbo-demo/dubbo-demo-api/dubbo-demo-api-consumer/pom.xml +++ b/dubbo-demo/dubbo-demo-api/dubbo-demo-api-consumer/pom.xml @@ -1,21 +1,19 @@ 4.0.0 @@ -98,11 +96,6 @@ dubbo-serialization-fastjson2 ${project.version} - - org.apache.dubbo - dubbo-plugin-cluster-mergeable - ${project.version} - org.apache.logging.log4j log4j-slf4j-impl diff --git a/dubbo-demo/dubbo-demo-api/pom.xml b/dubbo-demo/dubbo-demo-api/pom.xml index deaf2b0dbd8..33ed7504dbd 100644 --- a/dubbo-demo/dubbo-demo-api/pom.xml +++ b/dubbo-demo/dubbo-demo-api/pom.xml @@ -1,21 +1,19 @@ 4.0.0 diff --git a/dubbo-demo/dubbo-demo-generic-call/pom.xml b/dubbo-demo/dubbo-demo-generic-call/pom.xml index 85e74c5f3ae..47d82bcc454 100644 --- a/dubbo-demo/dubbo-demo-generic-call/pom.xml +++ b/dubbo-demo/dubbo-demo-generic-call/pom.xml @@ -1,21 +1,19 @@ 4.0.0 diff --git a/dubbo-demo/dubbo-demo-interface/pom.xml b/dubbo-demo/dubbo-demo-interface/pom.xml index c01cd37eb7d..0c06266cb1b 100644 --- a/dubbo-demo/dubbo-demo-interface/pom.xml +++ b/dubbo-demo/dubbo-demo-interface/pom.xml @@ -33,12 +33,11 @@ + - org.apache.dubbo - dubbo-rpc-rest - ${project.version} + javax.ws.rs + javax.ws.rs-api - org.springframework @@ -55,5 +54,16 @@ org.apache.logging.log4j log4j-slf4j-impl + + + io.swagger + swagger-jaxrs + + + javax.ws.rs + jsr311-api + + + diff --git a/dubbo-demo/dubbo-demo-native/dubbo-demo-native-consumer/pom.xml b/dubbo-demo/dubbo-demo-native/dubbo-demo-native-consumer/pom.xml index daa9dbb49d7..ab13f35f2d3 100644 --- a/dubbo-demo/dubbo-demo-native/dubbo-demo-native-consumer/pom.xml +++ b/dubbo-demo/dubbo-demo-native/dubbo-demo-native-consumer/pom.xml @@ -30,7 +30,7 @@ true 5.1.0 - 3.8.3 + 3.8.4 @@ -133,11 +133,6 @@ dubbo-filter-validation ${project.version} - - org.apache.dubbo - dubbo-remoting-http - ${project.version} - com.alibaba @@ -157,7 +152,7 @@ ch.qos.logback logback-core - 1.5.2 + 1.5.6 compile @@ -189,7 +184,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.12.1 + 3.13.0 1.8 1.8 diff --git a/dubbo-demo/dubbo-demo-native/dubbo-demo-native-provider/pom.xml b/dubbo-demo/dubbo-demo-native/dubbo-demo-native-provider/pom.xml index 7602af35811..39471b6dbd2 100644 --- a/dubbo-demo/dubbo-demo-native/dubbo-demo-native-provider/pom.xml +++ b/dubbo-demo/dubbo-demo-native/dubbo-demo-native-provider/pom.xml @@ -30,7 +30,7 @@ true 5.1.0 - 3.8.3 + 3.8.4 @@ -133,12 +133,6 @@ dubbo-filter-validation ${project.version} - - org.apache.dubbo - dubbo-remoting-http - ${project.version} - - com.alibaba fastjson @@ -157,7 +151,7 @@ ch.qos.logback logback-core - 1.5.2 + 1.5.6 compile @@ -189,7 +183,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.12.1 + 3.13.0 1.8 1.8 diff --git a/dubbo-demo/dubbo-demo-spring-boot/pom.xml b/dubbo-demo/dubbo-demo-spring-boot/pom.xml index 2e8d4893018..9e43674d89e 100644 --- a/dubbo-demo/dubbo-demo-spring-boot/pom.xml +++ b/dubbo-demo/dubbo-demo-spring-boot/pom.xml @@ -35,7 +35,7 @@ true 2.7.18 2.7.18 - 1.12.3 + 1.12.5 diff --git a/dubbo-demo/dubbo-demo-triple/pom.xml b/dubbo-demo/dubbo-demo-triple/pom.xml index 1a519c084d1..9889eb8a2ed 100644 --- a/dubbo-demo/dubbo-demo-triple/pom.xml +++ b/dubbo-demo/dubbo-demo-triple/pom.xml @@ -1,21 +1,19 @@ 4.0.0 @@ -32,7 +30,7 @@ true 1.8 1.8 - 3.12.1 + 3.13.0 diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/pom.xml b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/pom.xml deleted file mode 100644 index e3d58536b82..00000000000 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/pom.xml +++ /dev/null @@ -1,156 +0,0 @@ - - - - 4.0.0 - - org.apache.dubbo - dubbo-demo-xml - ${revision} - ../pom.xml - - - dubbo-demo-jaxrs-rest-consumer - - jar - ${project.artifactId} - Dubbo JAXRS Rest Consumer Demo - - - true - - - - - org.springframework - spring-context - - - org.springframework - spring-web - - - - org.apache.dubbo - dubbo-registry-multicast - ${project.version} - - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-registry-nacos - ${project.version} - - - com.alibaba.nacos - nacos-client - - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-nacos - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-nacos - ${project.version} - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - - - org.apache.dubbo - dubbo-config-spring - ${project.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-jdk - ${project.version} - - - - org.springframework - spring-test - test - - - - org.apache.dubbo - dubbo-demo-interface - ${project.version} - - - org.apache.logging.log4j - log4j-slf4j-impl - - - - - - - javax.annotation - - [1.11,) - - - - javax.annotation - javax.annotation-api - 1.3.2 - - - - - - diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/RestConsumer.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/RestConsumer.java deleted file mode 100644 index 4b3b306d33b..00000000000 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/RestConsumer.java +++ /dev/null @@ -1,117 +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.demo.rest.api; - -import org.apache.dubbo.demo.rest.api.annotation.DubboServiceAnnotationServiceConsumer; - -import java.util.Arrays; - -import org.jboss.resteasy.specimpl.MultivaluedMapImpl; -import org.springframework.context.support.ClassPathXmlApplicationContext; -import po.User; - -public class RestConsumer { - - public static void main(String[] args) { - consumerService(); - } - - public static void consumerService() { - ClassPathXmlApplicationContext context = - new ClassPathXmlApplicationContext(new String[] {"spring/rest-consumer.xml"}); - context.start(); - System.out.println("rest consumer start"); - testExceptionMapperService(context); - testHttpMethodService(context); - httpRPCContextTest(context); - jaxRsRestDemoServiceTest(context); - annotationTest(context); - System.out.println("rest consumer test success"); - } - - private static void annotationTest(ClassPathXmlApplicationContext context) { - DubboServiceAnnotationServiceConsumer bean = context.getBean(DubboServiceAnnotationServiceConsumer.class); - bean.invokeAnnotationService(); - } - - private static void jaxRsRestDemoServiceTest(ClassPathXmlApplicationContext context) { - JaxRsRestDemoService jaxRsRestDemoService = context.getBean("jaxRsRestDemoService", JaxRsRestDemoService.class); - String hello = jaxRsRestDemoService.sayHello("hello"); - assertEquals("Hello, hello", hello); - Integer result = jaxRsRestDemoService.primitiveInt(1, 2); - Long resultLong = jaxRsRestDemoService.primitiveLong(1, 2l); - long resultByte = jaxRsRestDemoService.primitiveByte((byte) 1, 2l); - long resultShort = jaxRsRestDemoService.primitiveShort((short) 1, 2l, 1); - - assertEquals(result, 3); - assertEquals(resultShort, 3l); - assertEquals(resultLong, 3l); - assertEquals(resultByte, 3l); - - assertEquals(Long.valueOf(1l), jaxRsRestDemoService.testFormBody(1l)); - - MultivaluedMapImpl forms = new MultivaluedMapImpl<>(); - forms.put("form", Arrays.asList("F1")); - - assertEquals(Arrays.asList("F1"), jaxRsRestDemoService.testMapForm(forms)); - assertEquals(User.getInstance(), jaxRsRestDemoService.testJavaBeanBody(User.getInstance())); - } - - private static void testExceptionMapperService(ClassPathXmlApplicationContext context) { - String returnStr = "exception"; - String paramStr = "exception"; - ExceptionMapperService exceptionMapperService = - context.getBean("exceptionMapperService", ExceptionMapperService.class); - assertEquals(returnStr, exceptionMapperService.exception(paramStr)); - } - - private static void httpRPCContextTest(ClassPathXmlApplicationContext context) { - - HttpRequestAndResponseRPCContextService requestAndResponseRPCContextService = context.getBean( - "httpRequestAndResponseRPCContextService", HttpRequestAndResponseRPCContextService.class); - String returnStr = "hello"; - String paramStr = "hello"; - assertEquals(returnStr, requestAndResponseRPCContextService.httpRequestHeader(paramStr)); - assertEquals(returnStr, requestAndResponseRPCContextService.httpRequestParam(paramStr)); - assertEquals( - returnStr, - requestAndResponseRPCContextService.httpResponseHeader(paramStr).get(0)); - } - - private static void testHttpMethodService(ClassPathXmlApplicationContext context) { - HttpMethodService httpMethodService = context.getBean("httpMethodService", HttpMethodService.class); - String returnStr = "hello"; - String paramStr = "hello"; - // assertEquals(null, httpMethodService.sayHelloHead(paramStr)); - assertEquals(returnStr, httpMethodService.sayHelloGet(paramStr)); - assertEquals(returnStr, httpMethodService.sayHelloDelete(paramStr)); - assertEquals(returnStr, httpMethodService.sayHelloPut(paramStr)); - assertEquals(returnStr, httpMethodService.sayHelloOptions(paramStr)); - // Assert.assertEquals(returnStr, httpMethodService.sayHelloPatch(paramStr)); - assertEquals(returnStr, httpMethodService.sayHelloPost(paramStr)); - } - - private static void assertEquals(Object returnStr, Object exception) { - boolean equal = returnStr != null && returnStr.equals(exception); - - if (equal) { - return; - } else { - throw new RuntimeException(); - } - } -} diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/annotation/DubboServiceAnnotationServiceConsumer.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/annotation/DubboServiceAnnotationServiceConsumer.java deleted file mode 100644 index dc8f6a5e69d..00000000000 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/annotation/DubboServiceAnnotationServiceConsumer.java +++ /dev/null @@ -1,34 +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.demo.rest.api.annotation; - -import org.apache.dubbo.config.annotation.DubboReference; -import org.apache.dubbo.demo.rest.api.DubboServiceAnnotationService; - -import org.springframework.stereotype.Component; - -@Component -public class DubboServiceAnnotationServiceConsumer { - - @DubboReference(interfaceClass = DubboServiceAnnotationService.class) - DubboServiceAnnotationService dubboServiceAnnotationService; - - public void invokeAnnotationService() { - String annotation = dubboServiceAnnotationService.annotation(); - System.out.println(annotation); - } -} diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/config/DubboConfig.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/config/DubboConfig.java deleted file mode 100644 index 0d9eab4ecb0..00000000000 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/config/DubboConfig.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.demo.rest.api.config; - -import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan; - -@DubboComponentScan("org.apache.dubbo.demo.rest") -public class DubboConfig {} diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/resources/log4j2.xml b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/resources/log4j2.xml deleted file mode 100644 index 69e1321d220..00000000000 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/resources/log4j2.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/resources/spring/rest-consumer.xml b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/resources/spring/rest-consumer.xml deleted file mode 100644 index ea6a63b04f5..00000000000 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/resources/spring/rest-consumer.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/pom.xml b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/pom.xml deleted file mode 100644 index afd7d330bf5..00000000000 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/pom.xml +++ /dev/null @@ -1,156 +0,0 @@ - - - - 4.0.0 - - org.apache.dubbo - dubbo-demo-xml - ${revision} - ../pom.xml - - - dubbo-demo-jaxrs-rest-provider - - jar - ${project.artifactId} - Dubbo JAXRS Rest Provider Demo - - - true - - - - - org.springframework - spring-context - - - org.springframework - spring-web - - - - org.apache.dubbo - dubbo-registry-multicast - ${project.version} - - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-registry-nacos - ${project.version} - - - com.alibaba.nacos - nacos-client - - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-nacos - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-nacos - ${project.version} - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - - - org.apache.dubbo - dubbo-config-spring - ${project.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-jdk - ${project.version} - - - - org.springframework - spring-test - test - - - - org.apache.dubbo - dubbo-demo-interface - ${project.version} - - - org.apache.logging.log4j - log4j-slf4j-impl - - - - - - - javax.annotation - - [1.11,) - - - - javax.annotation - javax.annotation-api - 1.3.2 - - - - - - diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/RestProvider.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/RestProvider.java deleted file mode 100644 index d4cdbe038bf..00000000000 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/RestProvider.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.demo.rest.api; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -public class RestProvider { - - public static void main(String[] args) throws Exception { - ClassPathXmlApplicationContext context = - new ClassPathXmlApplicationContext(new String[] {"spring/rest-provider.xml"}); - - context.refresh(); - - // SpringControllerService springControllerService = context.getBean(SpringControllerService.class); - // ServiceConfig serviceConfig = new ServiceConfig<>(); - // serviceConfig.setInterface(SpringControllerService.class); - // serviceConfig.setProtocol(new ProtocolConfig("rest", 8888)); - // serviceConfig.setRef(springControllerService); - // serviceConfig.export(); - - System.out.println("dubbo service started"); - - System.in.read(); - } -} diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/config/DubboConfig.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/config/DubboConfig.java deleted file mode 100644 index 0d9eab4ecb0..00000000000 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/config/DubboConfig.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.demo.rest.api.config; - -import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan; - -@DubboComponentScan("org.apache.dubbo.demo.rest") -public class DubboConfig {} diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/extension/ExceptionMapperForTest.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/extension/ExceptionMapperForTest.java deleted file mode 100644 index 2fe7fe3641a..00000000000 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/extension/ExceptionMapperForTest.java +++ /dev/null @@ -1,27 +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.demo.rest.api.extension; - -import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionHandler; - -public class ExceptionMapperForTest implements ExceptionHandler { - - @Override - public Object result(RuntimeException exception) { - return exception.getMessage(); - } -} diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/CurlServiceImpl.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/CurlServiceImpl.java deleted file mode 100644 index dcb3b535583..00000000000 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/CurlServiceImpl.java +++ /dev/null @@ -1,29 +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.demo.rest.api.impl; - -import org.apache.dubbo.config.annotation.DubboService; -import org.apache.dubbo.demo.rest.api.CurlService; - -@DubboService(interfaceClass = CurlService.class, protocol = "rest") -public class CurlServiceImpl implements CurlService { - - @Override - public String curl() { - return "hello,dubbo rest curl request"; - } -} diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/DubboServiceAnnotationServiceImpl.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/DubboServiceAnnotationServiceImpl.java deleted file mode 100644 index 823af088f7e..00000000000 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/DubboServiceAnnotationServiceImpl.java +++ /dev/null @@ -1,28 +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.demo.rest.api.impl; - -import org.apache.dubbo.config.annotation.DubboService; -import org.apache.dubbo.demo.rest.api.DubboServiceAnnotationService; - -@DubboService(protocol = "rest") -public class DubboServiceAnnotationServiceImpl implements DubboServiceAnnotationService { - @Override - public String annotation() { - return "Dubbo Service Annotation service demo!"; - } -} diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/ExceptionMapperServiceImpl.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/ExceptionMapperServiceImpl.java deleted file mode 100644 index d8a84cc9324..00000000000 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/ExceptionMapperServiceImpl.java +++ /dev/null @@ -1,31 +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.demo.rest.api.impl; - -import org.apache.dubbo.demo.rest.api.ExceptionMapperService; - -import org.springframework.stereotype.Service; - -@Service("exceptionMapperService") -public class ExceptionMapperServiceImpl implements ExceptionMapperService { - - @Override - public String exception(String message) { - - throw new RuntimeException(message); - } -} diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/HttpMethodServiceImpl.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/HttpMethodServiceImpl.java deleted file mode 100644 index 24fc704becd..00000000000 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/HttpMethodServiceImpl.java +++ /dev/null @@ -1,60 +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.demo.rest.api.impl; - -import org.apache.dubbo.demo.rest.api.HttpMethodService; - -import org.springframework.stereotype.Service; - -@Service("httpMethodService") -public class HttpMethodServiceImpl implements HttpMethodService { - - @Override - public String sayHelloPost(String hello) { - return hello; - } - - @Override - public String sayHelloDelete(String hello) { - return hello; - } - - @Override - public String sayHelloHead(String hello) { - return hello; - } - - @Override - public String sayHelloGet(String hello) { - return hello; - } - - @Override - public String sayHelloPut(String hello) { - return hello; - } - - @Override - public String sayHelloPatch(String hello) { - return hello; - } - - @Override - public String sayHelloOptions(String hello) { - return hello; - } -} diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/HttpRequestAndResponseRPCContextServiceImpl.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/HttpRequestAndResponseRPCContextServiceImpl.java deleted file mode 100644 index 8c12038cf44..00000000000 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/HttpRequestAndResponseRPCContextServiceImpl.java +++ /dev/null @@ -1,53 +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.demo.rest.api.impl; - -import org.apache.dubbo.demo.rest.api.HttpRequestAndResponseRPCContextService; -import org.apache.dubbo.rpc.RpcContext; -import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; -import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import org.springframework.stereotype.Service; - -@Service("httpRequestAndResponseRPCContextService") -public class HttpRequestAndResponseRPCContextServiceImpl implements HttpRequestAndResponseRPCContextService { - @Override - public String httpRequestParam(String hello) { - Object request = RpcContext.getServerAttachment().getRequest(); - return ((RequestFacade) request).getParameter("name"); - } - - @Override - public String httpRequestHeader(String hello) { - Object request = RpcContext.getServerAttachment().getRequest(); - return ((RequestFacade) request).getHeader("header"); - } - - @Override - public List httpResponseHeader(String hello) { - Object response = RpcContext.getServerAttachment().getResponse(); - Map> outputHeaders = ((NettyHttpResponse) response).getOutputHeaders(); - String responseKey = "response"; - outputHeaders.put(responseKey, Arrays.asList(hello)); - - return outputHeaders.get(responseKey); - } -} diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/JaxRsRestDemoServiceImpl.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/JaxRsRestDemoServiceImpl.java deleted file mode 100644 index 06ec4fdbb9a..00000000000 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/JaxRsRestDemoServiceImpl.java +++ /dev/null @@ -1,101 +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.demo.rest.api.impl; - -import org.apache.dubbo.demo.rest.api.JaxRsRestDemoService; - -import javax.ws.rs.core.MultivaluedMap; - -import java.util.List; -import java.util.Map; - -import org.springframework.stereotype.Service; -import po.User; - -@Service("jaxRsRestDemoService") -public class JaxRsRestDemoServiceImpl implements JaxRsRestDemoService { - - @Override - public String sayHello(String name) { - return "Hello, " + name; - } - - @Override - public Long testFormBody(Long number) { - return number; - } - - @Override - public User testJavaBeanBody(User user) { - return user; - } - - @Override - public int primitiveInt(int a, int b) { - return a + b; - } - - @Override - public long primitiveLong(long a, Long b) { - return a + b; - } - - @Override - public long primitiveByte(byte a, Long b) { - return a + b; - } - - @Override - public long primitiveShort(short a, Long b, int c) { - return a + b; - } - - @Override - public String testMapParam(Map params) { - return params.get("param"); - } - - @Override - public String testMapHeader(Map headers) { - return headers.get("header"); - } - - @Override - public List testMapForm(MultivaluedMap params) { - return params.get("form"); - } - - @Override - public String header(String header) { - return header; - } - - @Override - public int headerInt(int header) { - return header; - } - - @Override - public Integer hello(Integer a, Integer b) { - return a + b; - } - - @Override - public String error() { - throw new RuntimeException("test error"); - } -} diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/resources/log4j2.xml b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/resources/log4j2.xml deleted file mode 100644 index 69e1321d220..00000000000 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/resources/log4j2.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/resources/spring/rest-provider.xml b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/resources/spring/rest-provider.xml deleted file mode 100644 index f0471d1dc7c..00000000000 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/resources/spring/rest-provider.xml +++ /dev/null @@ -1,58 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/pom.xml b/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/pom.xml index dc750c333de..e0c96b82fe2 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/pom.xml +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/pom.xml @@ -88,11 +88,6 @@ dubbo-rpc-dubbo ${project.version} - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - org.apache.dubbo dubbo-config-spring diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/pom.xml b/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/pom.xml index 80d5cc72be9..b9320cc5040 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/pom.xml +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/pom.xml @@ -88,11 +88,6 @@ dubbo-rpc-dubbo ${project.version} - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - org.apache.dubbo dubbo-config-spring diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/pom.xml b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/pom.xml index b3402d30bc0..16a2a5a6a07 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/pom.xml +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/pom.xml @@ -82,11 +82,6 @@ dubbo-rpc-dubbo ${project.version} - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - org.apache.dubbo dubbo-config-spring diff --git a/dubbo-demo/dubbo-demo-xml/pom.xml b/dubbo-demo/dubbo-demo-xml/pom.xml index 4a061ac4e8b..960f93e9e59 100644 --- a/dubbo-demo/dubbo-demo-xml/pom.xml +++ b/dubbo-demo/dubbo-demo-xml/pom.xml @@ -32,8 +32,6 @@ dubbo-demo-xml-provider dubbo-demo-xml-consumer - dubbo-demo-jaxrs-rest-consumer - dubbo-demo-jaxrs-rest-provider dubbo-demo-spring-mvc-rest-consumer dubbo-demo-spring-mvc-rest-provider diff --git a/dubbo-dependencies-bom/pom.xml b/dubbo-dependencies-bom/pom.xml index 9cf94d697fe..d50b16f3cc7 100644 --- a/dubbo-dependencies-bom/pom.xml +++ b/dubbo-dependencies-bom/pom.xml @@ -90,16 +90,16 @@ - 5.3.25 - 5.8.10 + 5.3.34 + 5.8.12 3.30.2-GA - 1.14.12 + 1.14.14 3.2.10.Final - 4.1.107.Final + 4.1.109.Final 4.5.14 4.4.16 1.2.83 - 2.0.47 + 2.0.49 3.7.2 5.1.0 2.12.0 @@ -119,39 +119,39 @@ 2.2 3.14.0 0.1.35 - 1.12.3 + 1.12.5 1.26.0 2.16.4 - 1.2.3 + 1.2.5 3.3 0.16.0 1.0.4 - 3.6.2 + 3.6.5 2.2.21 3.14.9 2.1.1 3.15.6.Final 1.9.13 - 8.5.99 - 2.3.1 + 8.5.100 + 2.3.2 1.8.6 1.6.1 - 1.62.2 + 1.63.0 0.8.1 1.2.2 0.9.10 1.7.36 - 1.3.0 + 1.3.1 1.2.17 1.2.13 - 2.23.0 - 2.15.1 + 2.23.1 + 2.16.1 1.16.0 - 0.13.0 + 1.1.0 1.0.11 @@ -166,25 +166,25 @@ 2.2.7 1.2.0 - 1.19.6 + 1.19.7 3.2.13 - 1.6.13 + 1.6.14 1.1.10.5 1.70 5.4.3 2.0.6 2.10.1 - 2.16.1 + 2.17.1 6.1.26 2.0 1.6.0 - 1.26.0 + 1.26.1 2.43.0 check 1.0.0 2.38.0 - 3.3.0-beta.2-SNAPSHOT + 3.3.0-beta.3-SNAPSHOT 3.1.5 4.0.1 2.3.3-b02 diff --git a/dubbo-dependencies/dubbo-dependencies-zookeeper-curator5/pom.xml b/dubbo-dependencies/dubbo-dependencies-zookeeper-curator5/pom.xml index fab9f50a097..6281d635d5f 100644 --- a/dubbo-dependencies/dubbo-dependencies-zookeeper-curator5/pom.xml +++ b/dubbo-dependencies/dubbo-dependencies-zookeeper-curator5/pom.xml @@ -1,19 +1,19 @@ 4.0.0 @@ -31,11 +31,11 @@ pom - 3.3.0-beta.2-SNAPSHOT + 3.3.0-beta.3-SNAPSHOT 1.6.0 1.7.36 5.1.0 - 3.8.3 + 3.8.4 2.43.0 check 1.0.0 diff --git a/dubbo-dependencies/dubbo-dependencies-zookeeper/pom.xml b/dubbo-dependencies/dubbo-dependencies-zookeeper/pom.xml index 0bab7fa215f..c077c86ac2e 100644 --- a/dubbo-dependencies/dubbo-dependencies-zookeeper/pom.xml +++ b/dubbo-dependencies/dubbo-dependencies-zookeeper/pom.xml @@ -1,19 +1,19 @@ 4.0.0 @@ -31,7 +31,7 @@ pom - 3.3.0-beta.2-SNAPSHOT + 3.3.0-beta.3-SNAPSHOT 1.6.0 1.7.36 4.3.0 diff --git a/dubbo-distribution/dubbo-all-shaded/pom.xml b/dubbo-distribution/dubbo-all-shaded/pom.xml index b172ba4324f..a27f148cef6 100644 --- a/dubbo-distribution/dubbo-all-shaded/pom.xml +++ b/dubbo-distribution/dubbo-all-shaded/pom.xml @@ -134,15 +134,6 @@ true - - - org.apache.dubbo - dubbo-kubernetes - ${project.version} - compile - true - - org.apache.dubbo @@ -372,13 +363,6 @@ compile true - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - compile - true - org.apache.dubbo @@ -418,15 +402,6 @@ true - - - org.apache.dubbo - dubbo-xds - ${project.version} - compile - true - - io.netty @@ -525,7 +500,6 @@ org.apache.dubbo:dubbo-rpc-api org.apache.dubbo:dubbo-rpc-dubbo org.apache.dubbo:dubbo-rpc-injvm - org.apache.dubbo:dubbo-rpc-rest org.apache.dubbo:dubbo-rpc-triple org.apache.dubbo:dubbo-rest-jaxrs org.apache.dubbo:dubbo-rest-servlet @@ -534,8 +508,6 @@ org.apache.dubbo:dubbo-serialization-hessian2 org.apache.dubbo:dubbo-serialization-fastjson2 org.apache.dubbo:dubbo-serialization-jdk - org.apache.dubbo:dubbo-kubernetes - org.apache.dubbo:dubbo-xds io.netty:* @@ -651,24 +623,12 @@ META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.builder.TypeBuilder - - META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor - - - META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.rest.ServiceRestMetadataResolver - META-INF/dubbo/internal/org.apache.dubbo.metadata.definition.builder.TypeBuilder META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory - - META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor - - - META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.ServiceRestMetadataReader - META-INF/dubbo/internal/org.apache.dubbo.monitor.MonitorFactory @@ -728,33 +688,6 @@ META-INF/dubbo/internal/org.apache.dubbo.registry.integration.RegistryProtocolListener - - META-INF/dubbo/internal/org.apache.dubbo.registry.xds.XdsCertificateSigner - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.filter.RestResponseInterceptor - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.filter.RestRequestFilter - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.filter.RestResponseFilter - - - META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.NoAnnotatedParameterRequestTagProcessor - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodec - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionPreBuildIntercept - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer.BaseConsumerParamParser - - - META-INF/dubbo/internal/org.apache.dubbo.remoting.http.factory.RestClientFactory - META-INF/dubbo/internal/org.apache.dubbo.remoting.ChannelHandler @@ -786,7 +719,16 @@ META-INF/dubbo/internal/org.apache.dubbo.remoting.exchange.Exchanger - META-INF/dubbo/internal/org.apache.dubbo.remoting.http.HttpBinder + META-INF/dubbo/internal/org.apache.dubbo.remoting.http12.message.HttpMessageEncoderFactory + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.http12.message.HttpMessageDecoderFactory + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.http12.h2.Http2ServerTransportListenerFactory + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.http12.h1.Http1ServerTransportListenerFactory META-INF/dubbo/internal/org.apache.dubbo.remoting.telnet.TelnetHandler @@ -932,24 +874,44 @@ META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.router.mesh.util.TracingContextProvider - - META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.ServiceRestMetadataResolver - META-INF/dubbo/internal/org.apache.dubbo.rpc.executor.IsolationExecutorSupportFactory META-INF/dubbo/internal/org.apache.dubbo.metrics.collector.MetricsCollector + META-INF/dubbo/internal/org.apache.dubbo.spring.security.jackson.ObjectMapperCodecCustomer + - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider.BaseProviderParamParser + META-INF/dubbo/internal/org.apache.dubbo.rpc.model.PackableMethodFactory - META-INF/dubbo/internal/org.apache.dubbo.rpc.model.PackableMethodFactory + META-INF/dubbo/internal/org.apache.dubbo.aot.api.ReflectionTypeDescriberRegistrar + + + + META-INF/dubbo/internal/org.apache.dubbo.aot.api.ProxyDescriberRegistrar + + + + META-INF/dubbo/internal/org.apache.dubbo.aot.api.ResourceDescriberRegistrar + + + + META-INF/dubbo/internal/org.apache.dubbo.common.json.JsonUtil + + + + META-INF/dubbo/internal/org.apache.dubbo.config.CommonConfigPostProcessor + + + META-INF/dubbo/internal/org.apache.dubbo.registry.integration.ServiceURLCustomizer + + diff --git a/dubbo-distribution/dubbo-all/pom.xml b/dubbo-distribution/dubbo-all/pom.xml index ee749b16724..efe16c5cbf4 100644 --- a/dubbo-distribution/dubbo-all/pom.xml +++ b/dubbo-distribution/dubbo-all/pom.xml @@ -128,13 +128,6 @@ compile true - - org.apache.dubbo - dubbo-metadata-rest - ${project.version} - compile - true - org.apache.dubbo dubbo-metadata-report-zookeeper @@ -276,14 +269,6 @@ true - - org.apache.dubbo - dubbo-plugin-proxy-bytebuddy - ${project.version} - compile - true - - org.apache.dubbo dubbo-rest-jaxrs @@ -351,13 +336,6 @@ compile true - - org.apache.dubbo - dubbo-remoting-http - ${project.version} - compile - true - org.apache.dubbo dubbo-remoting-http12 @@ -423,13 +401,6 @@ compile true - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - compile - true - org.apache.dubbo @@ -536,7 +507,6 @@ org.apache.dubbo:dubbo-filter-cache org.apache.dubbo:dubbo-filter-validation org.apache.dubbo:dubbo-metadata-api - org.apache.dubbo:dubbo-metadata-rest org.apache.dubbo:dubbo-metadata-definition-protobuf org.apache.dubbo:dubbo-metadata-report-nacos org.apache.dubbo:dubbo-metadata-report-redis @@ -555,14 +525,12 @@ org.apache.dubbo:dubbo-security org.apache.dubbo:dubbo-reactive org.apache.dubbo:dubbo-spring-security - org.apache.dubbo:dubbo-plugin-proxy-bytebuddy org.apache.dubbo:dubbo-registry-api org.apache.dubbo:dubbo-registry-multicast org.apache.dubbo:dubbo-registry-multiple org.apache.dubbo:dubbo-registry-nacos org.apache.dubbo:dubbo-registry-zookeeper org.apache.dubbo:dubbo-remoting-api - org.apache.dubbo:dubbo-remoting-http org.apache.dubbo:dubbo-remoting-http12 org.apache.dubbo:dubbo-remoting-netty4 org.apache.dubbo:dubbo-remoting-netty @@ -572,7 +540,6 @@ org.apache.dubbo:dubbo-rpc-api org.apache.dubbo:dubbo-rpc-dubbo org.apache.dubbo:dubbo-rpc-injvm - org.apache.dubbo:dubbo-rpc-rest org.apache.dubbo:dubbo-rpc-triple org.apache.dubbo:dubbo-rest-jaxrs org.apache.dubbo:dubbo-rest-servlet @@ -695,24 +662,12 @@ META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.builder.TypeBuilder - - META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor - - - META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.rest.ServiceRestMetadataResolver - META-INF/dubbo/internal/org.apache.dubbo.metadata.definition.builder.TypeBuilder META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory - - META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor - - - META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.ServiceRestMetadataReader - META-INF/dubbo/internal/org.apache.dubbo.monitor.MonitorFactory @@ -772,30 +727,6 @@ META-INF/dubbo/internal/org.apache.dubbo.registry.integration.RegistryProtocolListener - - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.filter.RestResponseInterceptor - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.filter.RestRequestFilter - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.filter.RestResponseFilter - - - META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.NoAnnotatedParameterRequestTagProcessor - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodec - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionPreBuildIntercept - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer.BaseConsumerParamParser - - - META-INF/dubbo/internal/org.apache.dubbo.remoting.http.factory.RestClientFactory - META-INF/dubbo/internal/org.apache.dubbo.remoting.ChannelHandler @@ -826,9 +757,6 @@ META-INF/dubbo/internal/org.apache.dubbo.remoting.exchange.Exchanger - - META-INF/dubbo/internal/org.apache.dubbo.remoting.http.HttpBinder - META-INF/dubbo/internal/org.apache.dubbo.remoting.http12.message.HttpMessageEncoderFactory @@ -985,9 +913,6 @@ META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.router.mesh.util.TracingContextProvider - - META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.ServiceRestMetadataResolver - META-INF/dubbo/internal/org.apache.dubbo.rpc.executor.IsolationExecutorSupportFactory @@ -999,10 +924,6 @@ META-INF/dubbo/internal/org.apache.dubbo.spring.security.jackson.ObjectMapperCodecCustomer - - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider.BaseProviderParamParser - - META-INF/dubbo/internal/org.apache.dubbo.rpc.model.PackableMethodFactory diff --git a/dubbo-distribution/dubbo-apache-release/pom.xml b/dubbo-distribution/dubbo-apache-release/pom.xml index ec914ff07ea..59fd7374580 100644 --- a/dubbo-distribution/dubbo-apache-release/pom.xml +++ b/dubbo-distribution/dubbo-apache-release/pom.xml @@ -52,7 +52,7 @@ maven-assembly-plugin - 3.6.0 + 3.7.1 bin diff --git a/dubbo-distribution/dubbo-bom/pom.xml b/dubbo-distribution/dubbo-bom/pom.xml index 4b0d3220c8a..7e535f3421d 100644 --- a/dubbo-distribution/dubbo-bom/pom.xml +++ b/dubbo-distribution/dubbo-bom/pom.xml @@ -329,11 +329,6 @@ ${project.version} - - org.apache.dubbo - dubbo-plugin-proxy-bytebuddy - ${project.version} - org.apache.dubbo dubbo-rest-jaxrs diff --git a/dubbo-distribution/dubbo-core-spi/pom.xml b/dubbo-distribution/dubbo-core-spi/pom.xml index 8da62e1e038..cdcd0bc429b 100644 --- a/dubbo-distribution/dubbo-core-spi/pom.xml +++ b/dubbo-distribution/dubbo-core-spi/pom.xml @@ -247,24 +247,12 @@ META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.builder.TypeBuilder - - META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor - - - META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.rest.ServiceRestMetadataResolver - META-INF/dubbo/internal/org.apache.dubbo.metadata.definition.builder.TypeBuilder META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory - - META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor - - - META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.ServiceRestMetadataReader - META-INF/dubbo/internal/org.apache.dubbo.monitor.MonitorFactory @@ -280,6 +268,14 @@ META-INF/dubbo/internal/org.apache.dubbo.qos.probe.StartupProbe + + META-INF/dubbo/internal/org.apache.dubbo.qos.permission.PermissionChecker + + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.PenetrateAttachmentSelector + + META-INF/dubbo/internal/org.apache.dubbo.registry.AddressListener @@ -295,9 +291,6 @@ META-INF/dubbo/internal/org.apache.dubbo.registry.client.RegistryClusterIdentifier - - META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscovery - META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscoveryFactory @@ -308,7 +301,7 @@ META-INF/dubbo/internal/org.apache.dubbo.registry.client.metadata.MetadataServiceURLBuilder - META-INF/dubbo/internal/org.apache.dubbo.registry.client.metadata.SubscribedURLsSynthesizer + META-INF/dubbo/internal/org.apache.dubbo.common.ssl.CertProvider META-INF/dubbo/internal/org.apache.dubbo.registry.client.migration.MigrationAddressComparator @@ -334,6 +327,12 @@ META-INF/dubbo/internal/org.apache.dubbo.remoting.Transporter + + META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.dubbo.ByteAccessor + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.api.pu.PortUnificationTransporter + META-INF/dubbo/internal/org.apache.dubbo.remoting.api.connection.ConnectionManager @@ -344,7 +343,16 @@ META-INF/dubbo/internal/org.apache.dubbo.remoting.exchange.Exchanger - META-INF/dubbo/internal/org.apache.dubbo.remoting.http.HttpBinder + META-INF/dubbo/internal/org.apache.dubbo.remoting.http12.message.HttpMessageEncoderFactory + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.http12.message.HttpMessageDecoderFactory + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.http12.h2.Http2ServerTransportListenerFactory + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.http12.h1.Http1ServerTransportListenerFactory META-INF/dubbo/internal/org.apache.dubbo.remoting.telnet.TelnetHandler @@ -418,6 +426,12 @@ META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.router.condition.matcher.pattern.ValuePattern + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.router.condition.matcher.ConditionMatcherFactory + META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ApplicationInitListener @@ -428,33 +442,96 @@ META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.grpc.interceptors.ClientInterceptor + META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.injvm.ParamDeepCopyUtil - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.grpc.interceptors.GrpcConfigurator + META-INF/dubbo/internal/org.apache.dubbo.rpc.PathResolver - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.grpc.interceptors.ServerInterceptor + META-INF/dubbo/internal/org.apache.dubbo.validation.Validation - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.grpc.interceptors.ServerTransportFilter + META-INF/dubbo/internal/org.apache.dubbo.registry.client.metadata.ServiceInstanceNotificationCustomizer - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.injvm.ParamDeepCopyUtil + META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.tri.compressor.Compressor - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.tri.Compressor + META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.tri.compressor.DeCompressor - META-INF/dubbo/internal/org.apache.dubbo.rpc.PathResolver + META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.tri.rest.argument.ArgumentConverter - META-INF/dubbo/internal/org.apache.dubbo.validation.Validation + META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.tri.rest.argument.ArgumentResolver + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.tri.rest.filter.RestExtension + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.tri.rest.filter.RestExtensionAdapter + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.tri.rest.mapping.RequestMappingResolver + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.tri.route.RequestHandlerMapping + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.http12.message.HttpMessageAdapterFactory + + + META-INF/dubbo/internal/org.apache.dubbo.metrics.service.MetricsService + + + META-INF/dubbo/internal/org.apache.dubbo.metrics.service.MetricsServiceExporter + + + META-INF/dubbo/internal/org.apache.dubbo.metrics.report.MetricsReporterFactory + + + META-INF/dubbo/internal/org.apache.dubbo.common.threadpool.event.ThreadPoolExhaustedListener + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.api.pu.PortUnificationTransporter + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.router.mesh.util.TracingContextProvider + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.executor.IsolationExecutorSupportFactory + + + META-INF/dubbo/internal/org.apache.dubbo.metrics.collector.MetricsCollector + + + + META-INF/dubbo/internal/org.apache.dubbo.spring.security.jackson.ObjectMapperCodecCustomer + + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.model.PackableMethodFactory + + + META-INF/dubbo/internal/org.apache.dubbo.aot.api.ReflectionTypeDescriberRegistrar + + META-INF/dubbo/internal/org.apache.dubbo.aot.api.ProxyDescriberRegistrar + + + + META-INF/dubbo/internal/org.apache.dubbo.aot.api.ResourceDescriberRegistrar + + + META-INF/dubbo/internal/org.apache.dubbo.common.json.JsonUtil + META-INF/dubbo/internal/org.apache.dubbo.config.CommonConfigPostProcessor + + META-INF/dubbo/internal/org.apache.dubbo.registry.integration.ServiceURLCustomizer + diff --git a/dubbo-maven-plugin/pom.xml b/dubbo-maven-plugin/pom.xml index 6453eea5f41..5965bab27c6 100644 --- a/dubbo-maven-plugin/pom.xml +++ b/dubbo-maven-plugin/pom.xml @@ -49,7 +49,7 @@ org.apache.maven.plugin-tools maven-plugin-annotations - 3.11.0 + 3.13.0 provided @@ -68,7 +68,7 @@ commons-io commons-io - 2.15.1 + 2.16.1 @@ -102,8 +102,12 @@ + org.apache.maven.plugins maven-plugin-plugin - 3.10.2 + 3.13.0 + + dubbo + default-addPluginArtifactMetadata diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java index e2c58e69eb0..91fce3cef42 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java @@ -25,11 +25,12 @@ import org.apache.dubbo.rpc.model.ScopeModelUtil; import org.apache.dubbo.rpc.service.Destroyable; -import java.util.Arrays; import java.util.Set; import java.util.TreeSet; import static java.util.Collections.emptySet; +import static java.util.stream.Collectors.toSet; +import static java.util.stream.Stream.of; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR; import static org.apache.dubbo.common.extension.ExtensionScope.APPLICATION; @@ -88,7 +89,10 @@ static Set getAppNames(String content) { if (StringUtils.isBlank(content)) { return emptySet(); } - return new TreeSet<>(Arrays.asList(content.split(COMMA_SEPARATOR))); + return new TreeSet<>(of(content.split(COMMA_SEPARATOR)) + .map(String::trim) + .filter(StringUtils::isNotEmpty) + .collect(toSet())); } static Set getMappingByUrl(URL consumerURL) { diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportInstance.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportInstance.java index ded589b4711..59d2dcb874e 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportInstance.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportInstance.java @@ -54,7 +54,7 @@ */ public class MetadataReportInstance implements Disposable { - private AtomicBoolean init = new AtomicBoolean(false); + private final AtomicBoolean initialized = new AtomicBoolean(false); private String metadataType; // mapping of registry id to metadata report instance, registry instances will use this mapping to find related @@ -69,7 +69,7 @@ public MetadataReportInstance(ApplicationModel applicationModel) { } public void init(List metadataReportConfigs) { - if (!init.compareAndSet(false, true)) { + if (!initialized.compareAndSet(false, true)) { return; } @@ -114,9 +114,10 @@ private void init(MetadataReportConfig config, MetadataReportFactory metadataRep } private String getRelatedRegistryId(MetadataReportConfig config, URL url) { - String relatedRegistryId = isEmpty(config.getRegistry()) - ? (isEmpty(config.getId()) ? DEFAULT_KEY : config.getId()) - : config.getRegistry(); + String relatedRegistryId = config.getRegistry(); + if (isEmpty(relatedRegistryId)) { + relatedRegistryId = DEFAULT_KEY; + } String namespace = url.getParameter(NAMESPACE_KEY); if (!StringUtils.isEmpty(namespace)) { relatedRegistryId += ":" + namespace; @@ -144,15 +145,13 @@ public String getMetadataType() { return metadataType; } - public boolean inited() { - return init.get(); + public boolean isInitialized() { + return initialized.get(); } @Override public void destroy() { - metadataReports.forEach((_k, reporter) -> { - reporter.destroy(); - }); + metadataReports.forEach((k, reporter) -> reporter.destroy()); metadataReports.clear(); } } diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactory.java index 7f1770291f1..ecc34f1047a 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactory.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactory.java @@ -29,6 +29,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_FAILED_EXPORT_SERVICE; +import static org.apache.dubbo.metadata.MetadataConstants.NAMESPACE_KEY; public abstract class AbstractMetadataReportFactory implements MetadataReportFactory { @@ -50,7 +51,7 @@ public abstract class AbstractMetadataReportFactory implements MetadataReportFac @Override public MetadataReport getMetadataReport(URL url) { url = url.setPath(MetadataReport.class.getName()).removeParameters(EXPORT_KEY, REFER_KEY); - String key = toMetadataReportKey(url); + String key = url.toServiceString(NAMESPACE_KEY); MetadataReport metadataReport = serviceStoreMap.get(key); if (metadataReport != null) { @@ -88,10 +89,6 @@ public MetadataReport getMetadataReport(URL url) { } } - protected String toMetadataReportKey(URL url) { - return url.toServiceString(); - } - @Override public void destroy() { lock.lock(); diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactoryTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactoryTest.java index f8c3dae0d9a..d321a4ba926 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactoryTest.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactoryTest.java @@ -145,4 +145,26 @@ void testGetForDiffGroup() { MetadataReport metadataReport2 = metadataReportFactory.getMetadataReport(url2); Assertions.assertNotEquals(metadataReport1, metadataReport2); } + + @Test + void testGetForSameNamespace() { + URL url1 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + + ":4444/org.apache.dubbo.TestService1?version=1.0.0&application=vic&namespace=test"); + URL url2 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + + ":4444/org.apache.dubbo.TestService2?version=1.0.0&application=vic&namespace=test"); + MetadataReport metadataReport1 = metadataReportFactory.getMetadataReport(url1); + MetadataReport metadataReport2 = metadataReportFactory.getMetadataReport(url2); + Assertions.assertEquals(metadataReport1, metadataReport2); + } + + @Test + void testGetForDiffNamespace() { + URL url1 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic&namespace=test"); + URL url2 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic&namespace=dev"); + MetadataReport metadataReport1 = metadataReportFactory.getMetadataReport(url1); + MetadataReport metadataReport2 = metadataReportFactory.getMetadataReport(url2); + Assertions.assertNotEquals(metadataReport1, metadataReport2); + } } diff --git a/dubbo-metadata/dubbo-metadata-processor/pom.xml b/dubbo-metadata/dubbo-metadata-processor/pom.xml index 33e6d6ea69e..bf8b63c8dbf 100644 --- a/dubbo-metadata/dubbo-metadata-processor/pom.xml +++ b/dubbo-metadata/dubbo-metadata-processor/pom.xml @@ -1,19 +1,19 @@ 4.0.0 @@ -30,21 +30,6 @@ The metadata processor module of Dubbo project - - org.apache.dubbo - dubbo-metadata-rest - ${project.parent.version} - - - org.apache.dubbo - dubbo-rpc-api - - - org.apache.dubbo - dubbo-cluster - - - org.apache.dubbo @@ -77,10 +62,6 @@ - - org.apache.dubbo - dubbo-metadata-api - org.apache.dubbo dubbo-remoting-api diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/AbstractAnnotatedMethodParameterProcessor.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/AbstractAnnotatedMethodParameterProcessor.java deleted file mode 100644 index 142429e0f3d..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/AbstractAnnotatedMethodParameterProcessor.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.annotation.processing.rest; - -import org.apache.dubbo.metadata.rest.RestMethodMetadata; - -import javax.lang.model.element.AnnotationMirror; -import javax.lang.model.element.ExecutableElement; -import javax.lang.model.element.VariableElement; - -import static org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor.buildDefaultValue; -import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getValue; - -/** - * The abstract {@link AnnotatedMethodParameterProcessor} implementation - * - * @since 2.7.6 - */ -public abstract class AbstractAnnotatedMethodParameterProcessor implements AnnotatedMethodParameterProcessor { - - @Override - public final void process( - AnnotationMirror annotation, - VariableElement parameter, - int parameterIndex, - ExecutableElement method, - RestMethodMetadata restMethodMetadata) { - String annotationValue = getAnnotationValue(annotation, parameter, parameterIndex); - String defaultValue = getDefaultValue(annotation, parameter, parameterIndex); - process(annotationValue, defaultValue, annotation, parameter, parameterIndex, method, restMethodMetadata); - } - - protected abstract void process( - String annotationValue, - String defaultValue, - AnnotationMirror annotation, - VariableElement parameter, - int parameterIndex, - ExecutableElement method, - RestMethodMetadata restMethodMetadata); - - protected String getAnnotationValue(AnnotationMirror annotation, VariableElement parameter, int parameterIndex) { - return getValue(annotation); - } - - protected String getDefaultValue(AnnotationMirror annotation, VariableElement parameter, int parameterIndex) { - return buildDefaultValue(parameterIndex); - } -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/AbstractServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/AbstractServiceRestMetadataResolver.java deleted file mode 100644 index a2a388d34da..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/AbstractServiceRestMetadataResolver.java +++ /dev/null @@ -1,317 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.annotation.processing.rest; - -import org.apache.dubbo.metadata.annotation.processing.util.ExecutableElementComparator; -import org.apache.dubbo.metadata.definition.model.MethodDefinition; -import org.apache.dubbo.metadata.rest.RequestMetadata; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; -import org.apache.dubbo.metadata.rest.ServiceRestMetadata; -import org.apache.dubbo.rpc.model.ApplicationModel; - -import javax.annotation.processing.ProcessingEnvironment; -import javax.lang.model.element.AnnotationMirror; -import javax.lang.model.element.ExecutableElement; -import javax.lang.model.element.TypeElement; -import javax.lang.model.element.VariableElement; -import javax.lang.model.util.Elements; - -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.function.Function; -import java.util.stream.Collectors; - -import static java.lang.ThreadLocal.withInitial; -import static java.util.Collections.emptyList; -import static java.util.Collections.sort; -import static java.util.Optional.empty; -import static java.util.Optional.of; -import static org.apache.dubbo.metadata.annotation.processing.builder.MethodDefinitionBuilder.build; -import static org.apache.dubbo.metadata.annotation.processing.util.LoggerUtils.info; -import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getOverrideMethod; -import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getPublicNonStaticMethods; -import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.getAnnotation; -import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.getGroup; -import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.getVersion; -import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.resolveServiceInterfaceName; - -/** - * Abstract {@link ServiceRestMetadataResolver} implementation - * - * @since 2.7.6 - */ -public abstract class AbstractServiceRestMetadataResolver implements ServiceRestMetadataResolver { - - private static final ThreadLocal> threadLocalCache = withInitial(HashMap::new); - - private static final Map> parameterProcessorsMap = - loadAnnotatedMethodParameterProcessors(); - - private final String processorName = getClass().getSimpleName(); - - @Override - public final ServiceRestMetadata resolve( - ProcessingEnvironment processingEnv, TypeElement serviceType, Set annotations) { - - info( - "%s is processing the service type[%s] with annotations[%s]", - processorName, - serviceType, - annotations.stream().map(t -> "@" + t.toString()).collect(Collectors.joining(","))); - - ServiceRestMetadata serviceRestMetadata = new ServiceRestMetadata(); - - Elements elements = processingEnv.getElementUtils(); - - try { - AnnotationMirror serviceAnnotation = getAnnotation(serviceType); - String serviceInterfaceName = resolveServiceInterfaceName(serviceType, serviceAnnotation); - serviceRestMetadata.setServiceInterface(serviceInterfaceName); - serviceRestMetadata.setGroup(getGroup(serviceAnnotation)); - serviceRestMetadata.setVersion(getVersion(serviceAnnotation)); - - TypeElement serviceInterfaceType = elements.getTypeElement(serviceInterfaceName); - - List serviceMethods = - new LinkedList<>(getPublicNonStaticMethods(serviceInterfaceType, Object.class)); - - // Sorts - sort(serviceMethods, ExecutableElementComparator.INSTANCE); - - serviceMethods.forEach(serviceMethod -> { - resolveRestMethodMetadata( - processingEnv, serviceType, serviceInterfaceType, serviceMethod, serviceRestMetadata) - .ifPresent(serviceRestMetadata.getMeta()::add); - }); - - } finally { - clearCache(); - } - - info("The %s's process result : %s", processorName, serviceRestMetadata); - - return serviceRestMetadata; - } - - protected Optional resolveRestMethodMetadata( - ProcessingEnvironment processingEnv, - TypeElement serviceType, - TypeElement serviceInterfaceType, - ExecutableElement serviceMethod, - ServiceRestMetadata serviceRestMetadata) { - - ExecutableElement restCapableMethod = - findRestCapableMethod(processingEnv, serviceType, serviceInterfaceType, serviceMethod); - - if (restCapableMethod == null) { // if can't be found - return empty(); - } - - String requestPath = - resolveRequestPath(processingEnv, serviceType, restCapableMethod); // requestPath is required - - if (requestPath == null) { - return empty(); - } - - String requestMethod = - resolveRequestMethod(processingEnv, serviceType, restCapableMethod); // requestMethod is required - - if (requestMethod == null) { - return empty(); - } - - RestMethodMetadata metadata = new RestMethodMetadata(); - - MethodDefinition methodDefinition = resolveMethodDefinition(processingEnv, serviceType, restCapableMethod); - // Set MethodDefinition - metadata.setMethod(methodDefinition); - - // process the annotated method parameters - processAnnotatedMethodParameters(restCapableMethod, serviceType, metadata); - - // process produces - Set produces = new LinkedHashSet<>(); - processProduces(processingEnv, serviceType, restCapableMethod, produces); - - // process consumes - Set consumes = new LinkedHashSet<>(); - processConsumes(processingEnv, serviceType, restCapableMethod, consumes); - - // Initialize RequestMetadata - RequestMetadata request = metadata.getRequest(); - request.setPath(requestPath); - request.appendContextPathFromUrl(serviceRestMetadata.getContextPathFromUrl()); - - request.setMethod(requestMethod); - request.setProduces(produces); - request.setConsumes(consumes); - - // Post-Process - postProcessRestMethodMetadata(processingEnv, serviceType, serviceMethod, metadata); - - return of(metadata); - } - - /** - * Find the method with the capable for REST from the specified service method and its override method - * - * @param processingEnv {@link ProcessingEnvironment} - * @param serviceType - * @param serviceInterfaceType - * @param serviceMethod - * @return null if can't be found - */ - private ExecutableElement findRestCapableMethod( - ProcessingEnvironment processingEnv, - TypeElement serviceType, - TypeElement serviceInterfaceType, - ExecutableElement serviceMethod) { - // try to judge the override first - ExecutableElement overrideMethod = getOverrideMethod(processingEnv, serviceType, serviceMethod); - if (supports(processingEnv, serviceType, serviceInterfaceType, overrideMethod)) { - return overrideMethod; - } - // or, try to judge the declared method - return supports(processingEnv, serviceType, serviceInterfaceType, serviceMethod) ? serviceMethod : null; - } - - /** - * Does the specified method support REST or not ? - * - * @param processingEnv {@link ProcessingEnvironment} - * @param method the method may be declared on the interface or class - * @return if supports, return true, or false - */ - protected abstract boolean supports( - ProcessingEnvironment processingEnv, - TypeElement serviceType, - TypeElement serviceInterfaceType, - ExecutableElement method); - - /** - * Post-Process for {@link RestMethodMetadata}, sub-type could override this method for further works - * - * @param processingEnv {@link ProcessingEnvironment} - * @param serviceType The type that @Service annotated - * @param method The public method of serviceType - * @param metadata {@link RestMethodMetadata} maybe updated - */ - protected void postProcessRestMethodMetadata( - ProcessingEnvironment processingEnv, - TypeElement serviceType, - ExecutableElement method, - RestMethodMetadata metadata) {} - - protected abstract String resolveRequestPath( - ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method); - - protected abstract String resolveRequestMethod( - ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method); - - protected MethodDefinition resolveMethodDefinition( - ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method) { - return build(processingEnv, method, new HashMap<>()); - } - - protected void processAnnotatedMethodParameters( - ExecutableElement method, TypeElement type, RestMethodMetadata metadata) { - List methodParameters = method.getParameters(); - int size = methodParameters.size(); - for (int i = 0; i < size; i++) { - VariableElement parameter = methodParameters.get(i); - // Add indexed parameter name - metadata.addIndexToName(i, parameter.getSimpleName().toString()); - processAnnotatedMethodParameter(parameter, i, method, type, metadata); - } - } - - protected void processAnnotatedMethodParameter( - VariableElement parameter, - int parameterIndex, - ExecutableElement method, - TypeElement serviceType, - RestMethodMetadata metadata) { - - parameter.getAnnotationMirrors().forEach(annotation -> { - String annotationType = annotation.getAnnotationType().toString(); - parameterProcessorsMap.getOrDefault(annotationType, emptyList()).forEach(parameterProcessor -> { - parameterProcessor.process(annotation, parameter, parameterIndex, method, metadata); - }); - }); - } - - protected abstract void processProduces( - ProcessingEnvironment processingEnv, - TypeElement serviceType, - ExecutableElement method, - Set produces); - - protected abstract void processConsumes( - ProcessingEnvironment processingEnv, - TypeElement serviceType, - ExecutableElement method, - Set consumes); - - protected static final void put(String name, Object value) { - Map cache = getCache(); - cache.put(name, value); - } - - protected static final T get(String name) throws ClassCastException { - Map cache = getCache(); - return (T) cache.get(name); - } - - protected static final V computeIfAbsent(String name, Function mappingFunction) { - return (V) getCache().computeIfAbsent(name, mappingFunction); - } - - private static Map> loadAnnotatedMethodParameterProcessors() { - Map> parameterProcessorsMap = new LinkedHashMap<>(); - - // load(AnnotatedMethodParameterProcessor.class, - // AnnotatedMethodParameterProcessor.class.getClassLoader()) - - ApplicationModel.defaultModel() - .getExtensionLoader(AnnotatedMethodParameterProcessor.class) - .getSupportedExtensionInstances() - .forEach(processor -> { - List processors = parameterProcessorsMap.computeIfAbsent( - processor.getAnnotationType(), k -> new LinkedList<>()); - processors.add(processor); - }); - - return parameterProcessorsMap; - } - - private static Map getCache() { - return threadLocalCache.get(); - } - - private static void clearCache() { - Map cache = getCache(); - cache.clear(); - threadLocalCache.remove(); - } -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/AnnotatedMethodParameterProcessor.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/AnnotatedMethodParameterProcessor.java deleted file mode 100644 index dd97c2dbd35..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/AnnotatedMethodParameterProcessor.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.annotation.processing.rest; - -import org.apache.dubbo.common.extension.SPI; -import org.apache.dubbo.common.lang.Prioritized; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; - -import javax.lang.model.element.AnnotationMirror; -import javax.lang.model.element.ExecutableElement; -import javax.lang.model.element.VariableElement; - -/** - * The interface to process the parameter of method that was annotated - * - * @since 2.7.6 - */ -@SPI -public interface AnnotatedMethodParameterProcessor extends Prioritized { - - /** - * The string presenting the annotation type - * - * @return non-null - */ - String getAnnotationType(); - - /** - * Process the specified method {@link VariableElement parameter} - * - * @param annotation {@link AnnotationMirror the target annotation} whose type is {@link #getAnnotationType()} - * @param parameter {@link VariableElement method parameter} - * @param parameterIndex the index of parameter in the method - * @param method {@link ExecutableElement method that parameter belongs to} - * @param restMethodMetadata {@link RestMethodMetadata the metadata is used to update} - */ - void process( - AnnotationMirror annotation, - VariableElement parameter, - int parameterIndex, - ExecutableElement method, - RestMethodMetadata restMethodMetadata); - - /** - * Build the default value - * - * @param parameterIndex the index of parameter - * @return the placeholder - */ - static String buildDefaultValue(int parameterIndex) { - return "{" + parameterIndex + "}"; - } -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/DefaultServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/DefaultServiceRestMetadataResolver.java deleted file mode 100644 index 24875726827..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/DefaultServiceRestMetadataResolver.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.metadata.annotation.processing.rest; - -import org.apache.dubbo.common.convert.Converter; -import org.apache.dubbo.common.convert.ConverterUtil; -import org.apache.dubbo.metadata.annotation.processing.rest.jaxrs.JAXRSServiceRestMetadataResolver; -import org.apache.dubbo.metadata.annotation.processing.rest.springmvc.SpringMvcServiceRestMetadataResolver; -import org.apache.dubbo.rpc.model.FrameworkModel; - -import javax.annotation.processing.ProcessingEnvironment; -import javax.lang.model.element.AnnotationMirror; -import javax.lang.model.element.ExecutableElement; -import javax.lang.model.element.TypeElement; -import javax.lang.model.element.VariableElement; -import javax.lang.model.type.TypeMirror; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import static java.lang.String.valueOf; -import static java.util.Arrays.asList; -import static org.apache.dubbo.common.utils.ClassUtils.forName; -import static org.apache.dubbo.common.utils.StringUtils.SLASH_CHAR; -import static org.apache.dubbo.metadata.annotation.processing.util.LoggerUtils.warn; -import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.getAnnotation; -import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.resolveServiceInterfaceName; -import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.findInterface; - -/** - * The default implementation of {@link ServiceRestMetadataResolver} - * - * @since 2.7.6 - */ -public class DefaultServiceRestMetadataResolver extends AbstractServiceRestMetadataResolver { - - private static final char PACKAGE_SEPARATOR = '.'; - - private static final char PATH_SEPARATOR = SLASH_CHAR; - - private static final String HTTP_REQUEST_METHOD = "POST"; - - private static final List MEDIA_TYPES = asList( - "application/json;", - "application/*+json", - "application/xml;charset=UTF-8", - "text/xml;charset=UTF-8", - "application/*+xml;charset=UTF-8"); - - private final Set hasComplexParameterTypeMethods = new HashSet<>(); - - @Override - public boolean supports(ProcessingEnvironment processingEnvironment, TypeElement serviceType) { - return !JAXRSServiceRestMetadataResolver.supports(serviceType) - && !SpringMvcServiceRestMetadataResolver.supports(serviceType); - } - - @Override - protected boolean supports( - ProcessingEnvironment processingEnv, - TypeElement serviceType, - TypeElement serviceInterfaceType, - ExecutableElement method) { - // TODO add some criterion - return true; - } - - @Override - protected String resolveRequestPath( - ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method) { - - AnnotationMirror serviceAnnotation = getAnnotation(serviceType); - - String serviceInterfaceName = resolveServiceInterfaceName(serviceType, serviceAnnotation); - - TypeMirror serviceInterface = findInterface(serviceType.asType(), serviceInterfaceName); - - StringBuilder requestPathBuilder = new StringBuilder(); - // the name of service type as the root path - String rootPath = buildRootPath(serviceInterface); - // the method name as the sub path - String subPath = buildSubPath(method); - - requestPathBuilder.append(rootPath).append(subPath); - // the methods' parameters as the the path variables - List parameters = method.getParameters(); - - for (int i = 0; i < parameters.size(); i++) { - VariableElement parameter = parameters.get(i); - TypeMirror parameterType = parameter.asType(); - if (isComplexType(parameterType)) { - if (addComplexParameterType(method)) { - continue; - } else { - // The count of complex types must be only one, or return immediately - warn( - "The method[%s] contains more than one complex parameter type, " - + "thus it will not be chosen as the REST service", - method.toString()); - } - } - String parameterName = parameter.getSimpleName().toString(); - // If "-parameters" option is enabled, take the parameter name as the path variable name, - // or use the index of parameter - String pathVariableName = isEnabledParametersCompilerOption(parameterName) ? parameterName : valueOf(i); - requestPathBuilder - .append(PATH_SEPARATOR) - .append('{') - .append(pathVariableName) - .append('}'); - } - - return requestPathBuilder.toString(); - } - - private String buildRootPath(TypeMirror serviceInterface) { - return PATH_SEPARATOR + serviceInterface.toString().replace(PACKAGE_SEPARATOR, PATH_SEPARATOR); - } - - private String buildSubPath(ExecutableElement method) { - return PATH_SEPARATOR + method.getSimpleName().toString(); - } - - private boolean isEnabledParametersCompilerOption(String parameterName) { - return !parameterName.startsWith("arg"); - } - - private boolean isComplexType(TypeMirror parameterType) { - return !supportsPathVariableType(parameterType); - } - - /** - * Supports the type of parameter or not, based by {@link Converter}'s conversion feature - * - * @param parameterType the type of parameter - * @return if supports, this method will return true, or false - */ - private boolean supportsPathVariableType(TypeMirror parameterType) { - String className = parameterType.toString(); - ClassLoader classLoader = getClass().getClassLoader(); - boolean supported; - try { - Class targetType = forName(className, classLoader); - supported = FrameworkModel.defaultModel() - .getBeanFactory() - .getBean(ConverterUtil.class) - .getConverter(String.class, targetType) - != null; - } catch (ClassNotFoundException e) { - supported = false; - } - return supported; - } - - @Override - protected String resolveRequestMethod( - ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method) { - return HTTP_REQUEST_METHOD; - } - - @Override - protected void processProduces( - ProcessingEnvironment processingEnv, - TypeElement serviceType, - ExecutableElement method, - Set produces) { - TypeMirror returnType = method.getReturnType(); - if (isComplexType(returnType)) { - produces.addAll(MEDIA_TYPES); - } - } - - @Override - protected void processConsumes( - ProcessingEnvironment processingEnv, - TypeElement serviceType, - ExecutableElement method, - Set consumes) { - if (hasComplexParameterType(method)) { - consumes.addAll(MEDIA_TYPES); - } - } - - private boolean addComplexParameterType(ExecutableElement method) { - return hasComplexParameterTypeMethods.add(method); - } - - private boolean hasComplexParameterType(ExecutableElement method) { - return hasComplexParameterTypeMethods.remove(method); - } -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/ServiceRestMetadataAnnotationProcessor.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/ServiceRestMetadataAnnotationProcessor.java deleted file mode 100644 index e9f0c8bed51..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/ServiceRestMetadataAnnotationProcessor.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.annotation.processing.rest; - -import org.apache.dubbo.metadata.annotation.processing.AbstractServiceAnnotationProcessor; -import org.apache.dubbo.metadata.rest.ServiceRestMetadata; -import org.apache.dubbo.rpc.model.ApplicationModel; - -import javax.annotation.processing.ProcessingEnvironment; -import javax.annotation.processing.Processor; -import javax.annotation.processing.RoundEnvironment; -import javax.lang.model.element.TypeElement; - -import java.io.IOException; -import java.util.LinkedHashSet; -import java.util.Set; - -import static javax.lang.model.util.ElementFilter.typesIn; -import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.isServiceAnnotationPresent; - -/** - * The {@link Processor} class to generate the metadata of REST from the classes that are annotated by Dubbo's - * - * @Service - * @see Processor - * @since 2.7.6 - */ -public class ServiceRestMetadataAnnotationProcessor extends AbstractServiceAnnotationProcessor { - - private Set metadataProcessors; - - private ServiceRestMetadataStorage serviceRestMetadataWriter; - - private Set serviceRestMetadata = new LinkedHashSet<>(); - - @Override - public synchronized void init(ProcessingEnvironment processingEnv) { - super.init(processingEnv); - this.metadataProcessors = ApplicationModel.defaultModel() - .getExtensionLoader(ServiceRestMetadataResolver.class) - .getSupportedExtensionInstances(); - this.serviceRestMetadataWriter = new ServiceRestMetadataStorage(processingEnv); - } - - @Override - public boolean process(Set annotations, RoundEnvironment roundEnv) { - - typesIn(roundEnv.getRootElements()).forEach(serviceType -> process(processingEnv, serviceType, annotations)); - - if (roundEnv.processingOver()) { - try { - serviceRestMetadataWriter.append(serviceRestMetadata); - } catch (IOException e) { - throw new IllegalStateException(e); - } - } - - return false; - } - - private void process( - ProcessingEnvironment processingEnv, TypeElement serviceType, Set annotations) { - metadataProcessors.stream() - .filter(processor -> supports(processor, processingEnv, serviceType)) - .map(processor -> processor.resolve(processingEnv, serviceType, annotations)) - .forEach(serviceRestMetadata::add); - } - - private boolean supports( - ServiceRestMetadataResolver processor, ProcessingEnvironment processingEnv, TypeElement serviceType) { - // @Service must be present in service type - return isServiceAnnotationPresent(serviceType) && processor.supports(processingEnv, serviceType); - } -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/ServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/ServiceRestMetadataResolver.java deleted file mode 100644 index ed29a2d909d..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/ServiceRestMetadataResolver.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.annotation.processing.rest; - -import org.apache.dubbo.common.extension.SPI; -import org.apache.dubbo.common.lang.Prioritized; -import org.apache.dubbo.metadata.rest.ServiceRestMetadata; - -import javax.annotation.processing.ProcessingEnvironment; -import javax.lang.model.element.TypeElement; - -import java.util.Set; - -/** - * The class to resolve {@link ServiceRestMetadata} based on Annotation Processor Tool - * - * @since 2.7.6 - */ -@SPI("default") -public interface ServiceRestMetadataResolver extends Prioritized { - - /** - * Supports or not to the specified service type - * - * @param processingEnvironment {@link ProcessingEnvironment} - * @param serviceType Dubbo service type or interface - * @return if supports, return true, or false - */ - boolean supports(ProcessingEnvironment processingEnvironment, TypeElement serviceType); - - /** - * Resolve the {@link ServiceRestMetadata} from given service type - * - * @param processingEnvironment {@link ProcessingEnvironment} - * @param serviceType Dubbo service type or interface - * @param annotations - * @return non-null - */ - ServiceRestMetadata resolve( - ProcessingEnvironment processingEnvironment, - TypeElement serviceType, - Set annotations); -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/ServiceRestMetadataStorage.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/ServiceRestMetadataStorage.java deleted file mode 100644 index 14a14c24eb8..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/ServiceRestMetadataStorage.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.annotation.processing.rest; - -import org.apache.dubbo.common.utils.JsonUtils; -import org.apache.dubbo.metadata.annotation.processing.ClassPathMetadataStorage; -import org.apache.dubbo.metadata.rest.ServiceRestMetadata; - -import javax.annotation.processing.ProcessingEnvironment; - -import java.io.IOException; -import java.util.Set; - -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SERVICE_REST_METADATA_RESOURCE_PATH; - -/** - * The storage for {@link ServiceRestMetadata} - */ -public class ServiceRestMetadataStorage { - - private final ClassPathMetadataStorage storage; - - public ServiceRestMetadataStorage(ProcessingEnvironment processingEnv) { - this.storage = new ClassPathMetadataStorage(processingEnv); - } - - public void append(Set serviceRestMetadata) throws IOException { - // Add all existed ServiceRestMetadata - storage.read(SERVICE_REST_METADATA_RESOURCE_PATH, reader -> { - try { - StringBuilder stringBuilder = new StringBuilder(); - char[] buf = new char[1024]; - int len; - while ((len = reader.read(buf)) != -1) { - stringBuilder.append(buf, 0, len); - } - return JsonUtils.toJavaList(stringBuilder.toString(), ServiceRestMetadata.class); - } catch (IOException e) { - return null; - } - }) - .ifPresent(serviceRestMetadata::addAll); - write(serviceRestMetadata); - } - - public void write(Set serviceRestMetadata) throws IOException { - if (serviceRestMetadata.isEmpty()) { - return; - } - storage.write(() -> JsonUtils.toJson(serviceRestMetadata), SERVICE_REST_METADATA_RESOURCE_PATH); - } -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/DefaultValueParameterProcessor.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/DefaultValueParameterProcessor.java deleted file mode 100644 index 213d2647b40..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/DefaultValueParameterProcessor.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.annotation.processing.rest.jaxrs; - -import org.apache.dubbo.metadata.annotation.processing.rest.AbstractAnnotatedMethodParameterProcessor; -import org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor; -import org.apache.dubbo.metadata.rest.RequestMetadata; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; - -import javax.lang.model.element.AnnotationMirror; -import javax.lang.model.element.ExecutableElement; -import javax.lang.model.element.VariableElement; - -import java.util.List; -import java.util.Map; - -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.DEFAULT_VALUE_ANNOTATION_CLASS_NAME; - -/** - * The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @DefaultValue - * * - * - * @since 2.7.6 - */ -public class DefaultValueParameterProcessor extends AbstractAnnotatedMethodParameterProcessor { - - @Override - public String getAnnotationType() { - return DEFAULT_VALUE_ANNOTATION_CLASS_NAME; - } - - @Override - protected void process( - String annotationValue, - String defaultValue, - AnnotationMirror annotation, - VariableElement parameter, - int parameterIndex, - ExecutableElement method, - RestMethodMetadata restMethodMetadata) { - RequestMetadata requestMetadata = restMethodMetadata.getRequest(); - - // process the request parameters - setDefaultValue(requestMetadata.getParams(), defaultValue, annotationValue); - // process the request headers - setDefaultValue(requestMetadata.getHeaders(), defaultValue, annotationValue); - } - - private void setDefaultValue(Map> source, String placeholderValue, String defaultValue) { - OUTTER: - for (Map.Entry> entry : source.entrySet()) { - List values = entry.getValue(); - int size = values.size(); - for (int i = 0; i < size; i++) { - String value = values.get(i); - if (placeholderValue.equals(value)) { - values.set(i, defaultValue); - break OUTTER; - } - } - } - } - - @Override - public int getPriority() { - return MIN_PRIORITY; - } -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/FormParamParameterProcessor.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/FormParamParameterProcessor.java deleted file mode 100644 index 01e57db7a06..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/FormParamParameterProcessor.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.annotation.processing.rest.jaxrs; - -import org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor; - -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.FORM_PARAM_ANNOTATION_CLASS_NAME; - -/** - * The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @FormParam - * - * @since 2.7.6 - */ -public class FormParamParameterProcessor extends ParamAnnotationParameterProcessor { - - @Override - public String getAnnotationType() { - return FORM_PARAM_ANNOTATION_CLASS_NAME; - } -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/HeaderParamParameterProcessor.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/HeaderParamParameterProcessor.java deleted file mode 100644 index 5579904e702..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/HeaderParamParameterProcessor.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.annotation.processing.rest.jaxrs; - -import org.apache.dubbo.metadata.annotation.processing.rest.AbstractAnnotatedMethodParameterProcessor; -import org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor; -import org.apache.dubbo.metadata.rest.RequestMetadata; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; - -import javax.lang.model.element.AnnotationMirror; -import javax.lang.model.element.ExecutableElement; -import javax.lang.model.element.VariableElement; - -import static org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor.buildDefaultValue; -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.HEADER_PARAM_ANNOTATION_CLASS_NAME; - -/** - * The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @HeaderParam - * - * @since 2.7.6 - */ -public class HeaderParamParameterProcessor extends AbstractAnnotatedMethodParameterProcessor { - - @Override - public String getAnnotationType() { - return HEADER_PARAM_ANNOTATION_CLASS_NAME; - } - - @Override - protected void process( - String headerName, - String defaultValue, - AnnotationMirror annotation, - VariableElement parameter, - int parameterIndex, - ExecutableElement method, - RestMethodMetadata restMethodMetadata) { - RequestMetadata requestMetadata = restMethodMetadata.getRequest(); - // Add the placeholder as header value - requestMetadata.addHeader(headerName, buildDefaultValue(parameterIndex)); - } -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/JAXRSServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/JAXRSServiceRestMetadataResolver.java deleted file mode 100644 index fcfc9f341fb..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/JAXRSServiceRestMetadataResolver.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.annotation.processing.rest.jaxrs; - -import org.apache.dubbo.metadata.annotation.processing.rest.AbstractServiceRestMetadataResolver; -import org.apache.dubbo.metadata.annotation.processing.rest.ServiceRestMetadataResolver; - -import javax.annotation.processing.ProcessingEnvironment; -import javax.lang.model.AnnotatedConstruct; -import javax.lang.model.element.AnnotationMirror; -import javax.lang.model.element.Element; -import javax.lang.model.element.ExecutableElement; -import javax.lang.model.element.TypeElement; - -import java.util.Set; -import java.util.stream.Stream; - -import static org.apache.dubbo.common.utils.PathUtils.buildPath; -import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.findAnnotation; -import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.findMetaAnnotation; -import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getAnnotation; -import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getValue; -import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.isAnnotationPresent; -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.CONSUMES_ANNOTATION_CLASS_NAME; -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.HTTP_METHOD_ANNOTATION_CLASS_NAME; -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.PATH_ANNOTATION_CLASS_NAME; -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.PRODUCES_ANNOTATION_CLASS_NAME; - -/** - * {@link ServiceRestMetadataResolver} implementation for JAX-RS 2 and 1 - * - * @since 2.7.6 - */ -public class JAXRSServiceRestMetadataResolver extends AbstractServiceRestMetadataResolver { - - @Override - public boolean supports(ProcessingEnvironment processingEnvironment, TypeElement serviceType) { - return supports(serviceType); - } - - public static boolean supports(TypeElement serviceType) { - return isAnnotationPresent(serviceType, PATH_ANNOTATION_CLASS_NAME); - } - - @Override - protected boolean supports( - ProcessingEnvironment processingEnv, - TypeElement serviceType, - TypeElement serviceInterfaceType, - ExecutableElement method) { - return isAnnotationPresent(method, PATH_ANNOTATION_CLASS_NAME) - || isAnnotationPresent(method, HTTP_METHOD_ANNOTATION_CLASS_NAME); - } - - @Override - protected String resolveRequestPath( - ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method) { - String pathFromType = getPathValue(processingEnv, serviceType); - String pathFromMethod = getPathValue(method); - return buildPath(pathFromType, pathFromMethod); - } - - @Override - protected String resolveRequestMethod( - ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method) { - AnnotationMirror annotation = findMetaAnnotation(method, HTTP_METHOD_ANNOTATION_CLASS_NAME); - return getValue(annotation); - } - - @Override - protected void processProduces( - ProcessingEnvironment processingEnv, - TypeElement serviceType, - ExecutableElement method, - Set produces) { - addAnnotationValues(method, PRODUCES_ANNOTATION_CLASS_NAME, produces); - } - - @Override - protected void processConsumes( - ProcessingEnvironment processingEnv, - TypeElement serviceType, - ExecutableElement method, - Set consumes) { - addAnnotationValues(method, CONSUMES_ANNOTATION_CLASS_NAME, consumes); - } - - private void addAnnotationValues(Element element, String annotationAttributeName, Set result) { - AnnotationMirror annotation = findAnnotation(element, annotationAttributeName); - String[] value = getValue(annotation); - if (value != null) { - Stream.of(value).forEach(result::add); - } - } - - private String getPathValue(ProcessingEnvironment processingEnv, TypeElement serviceType) { - AnnotationMirror annotation = findAnnotation(serviceType, PATH_ANNOTATION_CLASS_NAME); - return getValue(annotation); - } - - private String getPathValue(AnnotatedConstruct annotatedConstruct) { - AnnotationMirror annotation = getAnnotation(annotatedConstruct, PATH_ANNOTATION_CLASS_NAME); - return getValue(annotation); - } -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/MatrixParamParameterProcessor.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/MatrixParamParameterProcessor.java deleted file mode 100644 index cf1d96d9aa7..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/MatrixParamParameterProcessor.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.annotation.processing.rest.jaxrs; - -import org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor; - -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.MATRIX_PARAM_ANNOTATION_CLASS_NAME; - -/** - * The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @MatrixParam - * - * @since 2.7.6 - */ -public class MatrixParamParameterProcessor extends ParamAnnotationParameterProcessor { - - @Override - public String getAnnotationType() { - return MATRIX_PARAM_ANNOTATION_CLASS_NAME; - } -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/ParamAnnotationParameterProcessor.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/ParamAnnotationParameterProcessor.java deleted file mode 100644 index 8052fc91237..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/ParamAnnotationParameterProcessor.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.annotation.processing.rest.jaxrs; - -import org.apache.dubbo.metadata.annotation.processing.rest.AbstractAnnotatedMethodParameterProcessor; -import org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor; -import org.apache.dubbo.metadata.rest.RequestMetadata; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; - -import javax.lang.model.element.AnnotationMirror; -import javax.lang.model.element.ExecutableElement; -import javax.lang.model.element.VariableElement; - -/** - * The abstract {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @*Param - */ -public abstract class ParamAnnotationParameterProcessor extends AbstractAnnotatedMethodParameterProcessor { - - protected void process( - String name, - String defaultValue, - AnnotationMirror annotation, - VariableElement parameter, - int parameterIndex, - ExecutableElement method, - RestMethodMetadata restMethodMetadata) { - RequestMetadata requestMetadata = restMethodMetadata.getRequest(); - requestMetadata.addParam(name, defaultValue); - } -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/QueryParamParameterProcessor.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/QueryParamParameterProcessor.java deleted file mode 100644 index 71ba378f9f8..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/QueryParamParameterProcessor.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.annotation.processing.rest.jaxrs; - -import org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor; - -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.QUERY_PARAM_ANNOTATION_CLASS_NAME; - -/** - * The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @QueryParam - * - * @since 2.7.6 - */ -public class QueryParamParameterProcessor extends ParamAnnotationParameterProcessor { - - @Override - public String getAnnotationType() { - return QUERY_PARAM_ANNOTATION_CLASS_NAME; - } -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/AbstractRequestAnnotationParameterProcessor.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/AbstractRequestAnnotationParameterProcessor.java deleted file mode 100644 index 2d9cf8dfb51..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/AbstractRequestAnnotationParameterProcessor.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.annotation.processing.rest.springmvc; - -import org.apache.dubbo.metadata.annotation.processing.rest.AbstractAnnotatedMethodParameterProcessor; -import org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; - -import javax.lang.model.element.AnnotationMirror; -import javax.lang.model.element.ExecutableElement; -import javax.lang.model.element.VariableElement; - -import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getAttribute; - -/** - * The abstract {@link AnnotatedMethodParameterProcessor} implementation for Spring Web MVC's @Request* - */ -public abstract class AbstractRequestAnnotationParameterProcessor extends AbstractAnnotatedMethodParameterProcessor { - - protected abstract void process( - String name, - String defaultValue, - AnnotationMirror annotation, - VariableElement parameter, - int parameterIndex, - ExecutableElement method, - RestMethodMetadata restMethodMetadata); - - @Override - protected String getAnnotationValue(AnnotationMirror annotation, VariableElement parameter, int parameterIndex) { - // try to get "value" attribute first - String name = super.getAnnotationValue(annotation, parameter, parameterIndex); - - // try to get "name" attribute if required - if (isEmpty(name)) { - name = getAttribute(annotation, "name"); - } - - // finally , try to the name of parameter - if (isEmpty(name)) { - name = parameter.getSimpleName().toString(); - } - - return name; - } - - protected String getDefaultValue(AnnotationMirror annotation, VariableElement parameter, int parameterIndex) { - String defaultValue = getAttribute(annotation, "defaultValue"); - if (isEmpty(defaultValue)) { - defaultValue = super.getDefaultValue(annotation, parameter, parameterIndex); - } - return defaultValue; - } - - protected boolean isEmpty(String str) { - return str == null || str.isEmpty(); - } -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/RequestHeaderParameterProcessor.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/RequestHeaderParameterProcessor.java deleted file mode 100644 index 49a5f747e8f..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/RequestHeaderParameterProcessor.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.metadata.annotation.processing.rest.springmvc; - -import org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; - -import javax.lang.model.element.AnnotationMirror; -import javax.lang.model.element.ExecutableElement; -import javax.lang.model.element.VariableElement; - -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SPRING_MVC.REQUEST_HEADER_ANNOTATION_CLASS_NAME; - -/** - * The {@link AnnotatedMethodParameterProcessor} implementation for Spring Web MVC's @RequestHeader - */ -public class RequestHeaderParameterProcessor extends AbstractRequestAnnotationParameterProcessor { - - @Override - public String getAnnotationType() { - return REQUEST_HEADER_ANNOTATION_CLASS_NAME; - } - - @Override - protected void process( - String name, - String defaultValue, - AnnotationMirror annotation, - VariableElement parameter, - int parameterIndex, - ExecutableElement method, - RestMethodMetadata restMethodMetadata) { - restMethodMetadata.getRequest().addHeader(name, defaultValue); - } -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/RequestParamParameterProcessor.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/RequestParamParameterProcessor.java deleted file mode 100644 index f881f1ca12b..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/RequestParamParameterProcessor.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.metadata.annotation.processing.rest.springmvc; - -import org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; - -import javax.lang.model.element.AnnotationMirror; -import javax.lang.model.element.ExecutableElement; -import javax.lang.model.element.VariableElement; - -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SPRING_MVC.REQUEST_PARAM_ANNOTATION_CLASS_NAME; - -/** - * The {@link AnnotatedMethodParameterProcessor} implementation for Spring Web MVC's @RequestParam - */ -public class RequestParamParameterProcessor extends AbstractRequestAnnotationParameterProcessor { - - @Override - public String getAnnotationType() { - return REQUEST_PARAM_ANNOTATION_CLASS_NAME; - } - - @Override - protected void process( - String name, - String defaultValue, - AnnotationMirror annotation, - VariableElement parameter, - int parameterIndex, - ExecutableElement method, - RestMethodMetadata restMethodMetadata) { - restMethodMetadata.getRequest().addParam(name, defaultValue); - } -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/SpringMvcServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/SpringMvcServiceRestMetadataResolver.java deleted file mode 100644 index bcf1d6edd79..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/SpringMvcServiceRestMetadataResolver.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.annotation.processing.rest.springmvc; - -import org.apache.dubbo.metadata.annotation.processing.rest.AbstractServiceRestMetadataResolver; -import org.apache.dubbo.metadata.annotation.processing.rest.ServiceRestMetadataResolver; - -import javax.annotation.processing.ProcessingEnvironment; -import javax.lang.model.element.AnnotationMirror; -import javax.lang.model.element.Element; -import javax.lang.model.element.ExecutableElement; -import javax.lang.model.element.TypeElement; -import javax.lang.model.type.DeclaredType; - -import java.lang.reflect.Array; -import java.util.Set; - -import static java.lang.String.valueOf; -import static java.lang.reflect.Array.getLength; -import static java.util.stream.Stream.of; -import static org.apache.dubbo.common.function.Streams.filterFirst; -import static org.apache.dubbo.common.utils.ArrayUtils.isEmpty; -import static org.apache.dubbo.common.utils.ArrayUtils.isNotEmpty; -import static org.apache.dubbo.common.utils.PathUtils.buildPath; -import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.findAnnotation; -import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.findMetaAnnotation; -import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getAllAnnotations; -import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getAttribute; -import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.isAnnotationPresent; -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SPRING_MVC.CONTROLLER_ANNOTATION_CLASS_NAME; -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SPRING_MVC.REQUEST_MAPPING_ANNOTATION_CLASS_NAME; - -/** - * {@link ServiceRestMetadataResolver} - * - * @since 2.7.6 - */ -public class SpringMvcServiceRestMetadataResolver extends AbstractServiceRestMetadataResolver { - - private static final int FIRST_ELEMENT_INDEX = 0; - - @Override - public boolean supports(ProcessingEnvironment processingEnvironment, TypeElement serviceType) { - return supports(serviceType); - } - - @Override - protected boolean supports( - ProcessingEnvironment processingEnv, - TypeElement serviceType, - TypeElement serviceInterfaceType, - ExecutableElement method) { - return isAnnotationPresent(method, REQUEST_MAPPING_ANNOTATION_CLASS_NAME); - } - - public static boolean supports(TypeElement serviceType) { - // class @Controller or @RequestMapping - return isAnnotationPresent(serviceType, CONTROLLER_ANNOTATION_CLASS_NAME) - || isAnnotationPresent(serviceType, REQUEST_MAPPING_ANNOTATION_CLASS_NAME); - } - - @Override - protected String resolveRequestPath( - ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method) { - - String requestPathFromType = getRequestPath(serviceType); - - String requestPathFromMethod = getRequestPath(method); - - return buildPath(requestPathFromType, requestPathFromMethod); - } - - @Override - protected String resolveRequestMethod( - ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method) { - - AnnotationMirror requestMapping = getRequestMapping(method); - - // httpMethod is an array of RequestMethod - Object httpMethod = getAttribute(requestMapping, "method"); - - if (httpMethod == null || getLength(httpMethod) < 1) { - return null; - } - - // TODO Is is required to support more request methods? - return valueOf(Array.get(httpMethod, FIRST_ELEMENT_INDEX)); - } - - private AnnotationMirror getRequestMapping(Element element) { - // try "@RequestMapping" first - AnnotationMirror requestMapping = findAnnotation(element, REQUEST_MAPPING_ANNOTATION_CLASS_NAME); - // try the annotation meta-annotated later - if (requestMapping == null) { - requestMapping = findMetaAnnotation(element, REQUEST_MAPPING_ANNOTATION_CLASS_NAME); - } - return requestMapping; - } - - @Override - protected void processProduces( - ProcessingEnvironment processingEnv, - TypeElement serviceType, - ExecutableElement method, - Set produces) { - addMediaTypes(method, "produces", produces); - } - - @Override - protected void processConsumes( - ProcessingEnvironment processingEnv, - TypeElement serviceType, - ExecutableElement method, - Set consumes) { - addMediaTypes(method, "consumes", consumes); - } - - private void addMediaTypes(ExecutableElement method, String annotationAttributeName, Set mediaTypesSet) { - - AnnotationMirror mappingAnnotation = getMappingAnnotation(method); - - String[] mediaTypes = getAttribute(mappingAnnotation, annotationAttributeName); - - if (isNotEmpty(mediaTypes)) { - of(mediaTypes).forEach(mediaTypesSet::add); - } - } - - private AnnotationMirror getMappingAnnotation(Element element) { - return computeIfAbsent( - valueOf(element), - key -> filterFirst(getAllAnnotations(element), annotation -> { - DeclaredType annotationType = annotation.getAnnotationType(); - // try "@RequestMapping" first - if (REQUEST_MAPPING_ANNOTATION_CLASS_NAME.equals(annotationType.toString())) { - return true; - } - // try meta annotation - return isAnnotationPresent(annotationType.asElement(), REQUEST_MAPPING_ANNOTATION_CLASS_NAME); - })); - } - - private String getRequestPath(Element element) { - AnnotationMirror mappingAnnotation = getMappingAnnotation(element); - return getRequestPath(mappingAnnotation); - } - - private String getRequestPath(AnnotationMirror mappingAnnotation) { - // try "value" first - String[] value = getAttribute(mappingAnnotation, "value"); - - if (isEmpty(value)) { // try "path" later - value = getAttribute(mappingAnnotation, "path"); - } - - if (isEmpty(value)) { - return ""; - } - // TODO Is is required to support more request paths? - return value[FIRST_ELEMENT_INDEX]; - } -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor b/dubbo-metadata/dubbo-metadata-processor/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor deleted file mode 100644 index 985daed606c..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor +++ /dev/null @@ -1,10 +0,0 @@ -# JAX-RS's implementations -jax-rs.query-param = org.apache.dubbo.metadata.annotation.processing.rest.jaxrs.QueryParamParameterProcessor -jax-rs.form-param = org.apache.dubbo.metadata.annotation.processing.rest.jaxrs.FormParamParameterProcessor -jax-rs.matrix-param = org.apache.dubbo.metadata.annotation.processing.rest.jaxrs.MatrixParamParameterProcessor -jax-rs.header-param = org.apache.dubbo.metadata.annotation.processing.rest.jaxrs.HeaderParamParameterProcessor -jax-rs.default-value-param = org.apache.dubbo.metadata.annotation.processing.rest.jaxrs.DefaultValueParameterProcessor - -# Spring Web MVC's implementations -spring-webmvc.request-param = org.apache.dubbo.metadata.annotation.processing.rest.springmvc.RequestParamParameterProcessor -spring-webmvc.request-header = org.apache.dubbo.metadata.annotation.processing.rest.springmvc.RequestHeaderParameterProcessor \ No newline at end of file diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.rest.ServiceRestMetadataResolver b/dubbo-metadata/dubbo-metadata-processor/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.rest.ServiceRestMetadataResolver deleted file mode 100644 index 9737e7d6f2a..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.rest.ServiceRestMetadataResolver +++ /dev/null @@ -1,3 +0,0 @@ -default = org.apache.dubbo.metadata.annotation.processing.rest.DefaultServiceRestMetadataResolver -jax-rs = org.apache.dubbo.metadata.annotation.processing.rest.jaxrs.JAXRSServiceRestMetadataResolver -spring-webmvc = org.apache.dubbo.metadata.annotation.processing.rest.springmvc.SpringMvcServiceRestMetadataResolver \ No newline at end of file diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/resources/META-INF/services/javax.annotation.processing.Processor b/dubbo-metadata/dubbo-metadata-processor/src/main/resources/META-INF/services/javax.annotation.processing.Processor index 6c5909c26ff..7d46e9fa68a 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/resources/META-INF/services/javax.annotation.processing.Processor +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/resources/META-INF/services/javax.annotation.processing.Processor @@ -1,2 +1 @@ org.apache.dubbo.metadata.annotation.processing.ServiceDefinitionMetadataAnnotationProcessor -org.apache.dubbo.metadata.annotation.processing.rest.ServiceRestMetadataAnnotationProcessor diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/rest/AnnotatedMethodParameterProcessorTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/rest/AnnotatedMethodParameterProcessorTest.java deleted file mode 100644 index 6db0efb5b5a..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/rest/AnnotatedMethodParameterProcessorTest.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.metadata.annotation.processing.rest; - -import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - -/** - * The abstract class for {@link AnnotatedMethodParameterProcessor}'s test cases - * - * @since 2.7.6 - */ -public abstract class AnnotatedMethodParameterProcessorTest extends AbstractAnnotationProcessingTest { - - protected AnnotatedMethodParameterProcessor processor; - - protected RestMethodMetadata restMethodMetadata; - - protected abstract AnnotatedMethodParameterProcessor createTestInstance(); - - @BeforeEach - public final void prepare() { - this.processor = createTestInstance(); - this.restMethodMetadata = createRestMethodMetadata(); - } - - protected RestMethodMetadata createRestMethodMetadata() { - return new RestMethodMetadata(); - } - - protected abstract String getExpectedAnnotationType(); - - @Test - void testGetAnnotationType() { - String expectedAnnotationType = getExpectedAnnotationType(); - assertNull(processor.getAnnotationType()); - assertEquals(expectedAnnotationType, processor.getAnnotationType()); - } -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtilsTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtilsTest.java index 1bb202d91d4..b07df32017e 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtilsTest.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtilsTest.java @@ -18,14 +18,12 @@ import org.apache.dubbo.config.annotation.Service; import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; -import org.apache.dubbo.metadata.rest.SpringRestService; import org.apache.dubbo.metadata.tools.TestService; import org.apache.dubbo.metadata.tools.TestServiceImpl; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; -import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror; import javax.ws.rs.Path; @@ -35,7 +33,6 @@ import java.util.Set; import org.junit.jupiter.api.Test; -import org.springframework.web.bind.annotation.GetMapping; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.findAnnotation; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.findMetaAnnotation; @@ -45,9 +42,7 @@ import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getAttribute; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getValue; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.isAnnotationPresent; -import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.findMethod; import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getAllDeclaredMethods; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -237,13 +232,6 @@ void testGetAttribute() { assertNull(getAttribute(findAnnotation(testType, Path.class), null)); assertNull(getAttribute(findAnnotation(testType, (Class) null), null)); - - ExecutableElement method = findMethod(getType(SpringRestService.class), "param", String.class); - - AnnotationMirror annotation = findAnnotation(method, GetMapping.class); - - assertArrayEquals(new String[] {"/param"}, (String[]) getAttribute(annotation, "value")); - assertNull(getAttribute(annotation, "path")); } @Test diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/DefaultRestService.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/DefaultRestService.java deleted file mode 100644 index 844fe840f37..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/DefaultRestService.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest; - -import org.apache.dubbo.config.annotation.DubboService; - -import java.util.Map; - -/** - * The default implementation of {@link RestService} - * - * @since 2.7.6 - */ -@DubboService(version = "1.0.0", group = "default") -public class DefaultRestService implements RestService { - - @Override - public String param(String param) { - return null; - } - - @Override - public String params(int a, String b) { - return null; - } - - @Override - public String headers(String header, String header2, Integer param) { - return null; - } - - @Override - public String pathVariables(String path1, String path2, String param) { - return null; - } - - @Override - public String form(String form) { - return null; - } - - @Override - public User requestBodyMap(Map data, String param) { - return null; - } - - @Override - public Map requestBodyUser(User user) { - return null; - } - - public User user(User user) { - return user; - } -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/RestService.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/RestService.java deleted file mode 100644 index 7b6883780da..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/RestService.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest; - -import java.util.Map; - -/** - * An interface for REST service - * - * @since 2.7.6 - */ -public interface RestService { - - String param(String param); - - String params(int a, String b); - - String headers(String header, String header2, Integer param); - - String pathVariables(String path1, String path2, String param); - - String form(String form); - - User requestBodyMap(Map data, String param); - - Map requestBodyUser(User user); -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java deleted file mode 100644 index b475bd53da8..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest; - -import org.apache.dubbo.config.annotation.DubboService; - -import java.util.HashMap; -import java.util.Map; - -import org.springframework.http.MediaType; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -/** - * Spring MVC {@link RestService} - * - * @since 2.7.6 - */ -@DubboService(version = "2.0.0", group = "spring") -@RestController -public class SpringRestService implements RestService { - - @Override - @GetMapping(value = "/param") - public String param(@RequestParam(defaultValue = "value-param") String param) { - return null; - } - - @Override - @PostMapping("/params") - public String params( - @RequestParam(defaultValue = "value-a") int a, @RequestParam(defaultValue = "value-b") String b) { - return null; - } - - @Override - @GetMapping("/headers") - public String headers( - @RequestHeader(name = "h", defaultValue = "value-h") String header, - @RequestHeader(name = "h2", defaultValue = "value-h2") String header2, - @RequestParam(value = "v", defaultValue = "1") Integer param) { - return null; - } - - @Override - @GetMapping("/path-variables/{p1}/{p2}") - public String pathVariables( - @PathVariable("p1") String path1, @PathVariable("p2") String path2, @RequestParam("v") String param) { - return null; - } - - @Override - @PostMapping("/form") - public String form(@RequestParam("f") String form) { - return String.valueOf(form); - } - - @Override - @PostMapping(value = "/request/body/map", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - public User requestBodyMap(@RequestBody Map data, @RequestParam("param") String param) { - User user = new User(); - user.setId(((Integer) data.get("id")).longValue()); - user.setName((String) data.get("name")); - user.setAge((Integer) data.get("age")); - return user; - } - - @PostMapping(value = "/request/body/user", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) - @Override - public Map requestBodyUser(@RequestBody User user) { - Map map = new HashMap<>(); - map.put("id", user.getId()); - map.put("name", user.getName()); - map.put("age", user.getAge()); - return map; - } -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java deleted file mode 100644 index 2f7d57e557b..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest; - -import org.apache.dubbo.config.annotation.DubboService; - -import javax.ws.rs.Consumes; -import javax.ws.rs.FormParam; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; - -import java.util.HashMap; -import java.util.Map; - -/** - * JAX-RS {@link RestService} - */ -@DubboService( - version = "3.0.0", - protocol = {"dubbo", "rest"}, - group = "standard") -@Path("/") -public class StandardRestService implements RestService { - - @Override - @Path("param") - @GET - public String param(@QueryParam("param") String param) { - return param; - } - - @Override - @Path("params") - @POST - public String params(@QueryParam("a") int a, @QueryParam("b") String b) { - return a + b; - } - - @Override - @Path("headers") - @GET - public String headers( - @HeaderParam("h") String header, @HeaderParam("h2") String header2, @QueryParam("v") Integer param) { - String result = header + " , " + header2 + " , " + param; - return result; - } - - @Override - @Path("path-variables/{p1}/{p2}") - @GET - public String pathVariables( - @PathParam("p1") String path1, @PathParam("p2") String path2, @QueryParam("v") String param) { - String result = path1 + " , " + path2 + " , " + param; - return result; - } - - // @CookieParam does not support : https://github.com/OpenFeign/feign/issues/913 - // @CookieValue also does not support - - @Override - @Path("form") - @POST - public String form(@FormParam("f") String form) { - return String.valueOf(form); - } - - @Override - @Path("request/body/map") - @POST - @Produces("application/json;charset=UTF-8") - public User requestBodyMap(Map data, @QueryParam("param") String param) { - User user = new User(); - user.setId(((Integer) data.get("id")).longValue()); - user.setName((String) data.get("name")); - user.setAge((Integer) data.get("age")); - return user; - } - - @Path("request/body/user") - @POST - @Override - @Consumes("application/json;charset=UTF-8") - public Map requestBodyUser(User user) { - Map map = new HashMap<>(); - map.put("id", user.getId()); - map.put("name", user.getName()); - map.put("age", user.getAge()); - return map; - } -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/User.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/User.java deleted file mode 100644 index 2b6c4a21baa..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/User.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest; - -import java.io.Serializable; - -/** - * User Entity - * - * @since 2.7.6 - */ -public class User implements Serializable { - - private Long id; - - private String name; - - private Integer age; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Integer getAge() { - return age; - } - - public void setAge(Integer age) { - this.age = age; - } - - @Override - public String toString() { - return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; - } -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/DefaultRestServiceTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/DefaultRestServiceTest.java deleted file mode 100644 index 9b020d2ca4d..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/DefaultRestServiceTest.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.tools; - -import org.apache.dubbo.metadata.rest.DefaultRestService; -import org.apache.dubbo.metadata.rest.RestService; -import org.apache.dubbo.metadata.rest.SpringRestService; -import org.apache.dubbo.metadata.rest.StandardRestService; -import org.apache.dubbo.metadata.rest.User; - -import java.io.IOException; - -import org.junit.jupiter.api.Test; - -/** - * The test case for {@link DefaultRestService} - * - * @since 2.7.6 - */ -class DefaultRestServiceTest { - - @Test - void test() throws IOException { - Compiler compiler = new Compiler(); - compiler.compile( - User.class, - RestService.class, - DefaultRestService.class, - SpringRestService.class, - StandardRestService.class); - } -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/RestServiceTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/RestServiceTest.java deleted file mode 100644 index b8ea68c957f..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/RestServiceTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.tools; - -import org.apache.dubbo.metadata.rest.RestService; -import org.apache.dubbo.metadata.rest.SpringRestService; -import org.apache.dubbo.metadata.rest.StandardRestService; -import org.apache.dubbo.metadata.rest.User; - -import java.io.IOException; - -import org.junit.jupiter.api.Test; - -/** - * {@link RestService} Test - * - * @since 2.7.6 - */ -class RestServiceTest { - - @Test - void test() throws IOException { - Compiler compiler = new Compiler(); - compiler.compile(User.class, RestService.class, StandardRestService.class, SpringRestService.class); - } -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/SpringRestServiceTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/SpringRestServiceTest.java deleted file mode 100644 index 5871c21fefe..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/SpringRestServiceTest.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.metadata.tools; - -import org.apache.dubbo.metadata.rest.RestService; -import org.apache.dubbo.metadata.rest.SpringRestService; -import org.apache.dubbo.metadata.rest.User; - -import java.io.IOException; - -import org.junit.jupiter.api.Test; - -/** - * {@link SpringRestService} Test - * - * @since 2.7.6 - */ -class SpringRestServiceTest { - - @Test - void test() throws IOException { - Compiler compiler = new Compiler(); - compiler.compile(User.class, RestService.class, SpringRestService.class); - } -} diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/StandardRestServiceTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/StandardRestServiceTest.java deleted file mode 100644 index 84c8199dc7d..00000000000 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/StandardRestServiceTest.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.metadata.tools; - -import org.apache.dubbo.metadata.rest.RestService; -import org.apache.dubbo.metadata.rest.StandardRestService; -import org.apache.dubbo.metadata.rest.User; - -import java.io.IOException; - -import org.junit.jupiter.api.Test; - -/** - * The test case for {@link StandardRestService} - * - * @since 2.7.6 - */ -class StandardRestServiceTest { - - @Test - void test() throws IOException { - Compiler compiler = new Compiler(); - compiler.compile(User.class, RestService.class, StandardRestService.class); - } -} diff --git a/dubbo-metadata/dubbo-metadata-report-nacos/pom.xml b/dubbo-metadata/dubbo-metadata-report-nacos/pom.xml index 9b716b33adf..11e7913a39e 100644 --- a/dubbo-metadata/dubbo-metadata-report-nacos/pom.xml +++ b/dubbo-metadata/dubbo-metadata-report-nacos/pom.xml @@ -1,19 +1,19 @@ 4.0.0 diff --git a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java b/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java index bdd5e83006b..d6dac4355ee 100644 --- a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java @@ -258,7 +258,7 @@ protected List doGetExportedURLs(ServiceMetadataIdentifier metadataIdent if (StringUtils.isEmpty(content)) { return Collections.emptyList(); } - return new ArrayList(Arrays.asList(URL.decode(content))); + return new ArrayList<>(Arrays.asList(URL.decode(content))); } @Override diff --git a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java index 338b4067b7d..a858a0a1b1b 100644 --- a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java +++ b/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java @@ -17,12 +17,9 @@ package org.apache.dubbo.metadata.store.nacos; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.metadata.report.MetadataReport; import org.apache.dubbo.metadata.report.support.AbstractMetadataReportFactory; -import static org.apache.dubbo.metadata.MetadataConstants.NAMESPACE_KEY; - /** * metadata report factory impl for nacos */ @@ -31,15 +28,4 @@ public class NacosMetadataReportFactory extends AbstractMetadataReportFactory { protected MetadataReport createMetadataReport(URL url) { return new NacosMetadataReport(url); } - - @Override - protected String toMetadataReportKey(URL url) { - String namespace = url.getParameter(NAMESPACE_KEY); - if (!StringUtils.isEmpty(namespace)) { - return URL.valueOf(url.toServiceString()) - .addParameter(NAMESPACE_KEY, namespace) - .toString(); - } - return super.toMetadataReportKey(url); - } } diff --git a/dubbo-metadata/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java b/dubbo-metadata/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java index 77646498a86..9777bae9a32 100644 --- a/dubbo-metadata/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java +++ b/dubbo-metadata/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java @@ -259,7 +259,8 @@ void testWrongAuthRedisMetadata() throws ClassNotFoundException { if (e.getCause() instanceof JedisConnectionException && e.getCause().getCause() instanceof JedisDataException) { Assertions.assertEquals( - "ERR invalid password", e.getCause().getCause().getMessage()); + "WRONGPASS invalid username-password pair or user is disabled.", + e.getCause().getCause().getMessage()); } else { Assertions.fail("no invalid password exception!"); } diff --git a/dubbo-metadata/dubbo-metadata-rest/pom.xml b/dubbo-metadata/dubbo-metadata-rest/pom.xml deleted file mode 100644 index 8df334033a4..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/pom.xml +++ /dev/null @@ -1,101 +0,0 @@ - - - - 4.0.0 - - org.apache.dubbo - dubbo-metadata - ${revision} - ../pom.xml - - - dubbo-metadata-rest - jar - - dubbo-metadata-rest - The rest metadata module of Dubbo project - - - 2.7.17 - - - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - org.springframework.boot - spring-boot-starter - ${spring-boot.version} - - - org.springframework.boot - spring-boot-starter-logging - - - - - - - - - org.apache.dubbo - dubbo-metadata-api - ${project.parent.version} - - - - - javax.ws.rs - javax.ws.rs-api - test - - - - - org.springframework - spring-web - test - - - - - org.springframework - spring-context - test - - - - org.springframework.cloud - spring-cloud-openfeign-core - test - - - - org.springframework.boot - spring-boot-starter-log4j2 - test - - - - diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AbstractAnnotatedMethodParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AbstractAnnotatedMethodParameterProcessor.java deleted file mode 100644 index d7f9a32bc39..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AbstractAnnotatedMethodParameterProcessor.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.lang.reflect.Parameter; - -import static org.apache.dubbo.common.utils.AnnotationUtils.getValue; -import static org.apache.dubbo.common.utils.ClassUtils.getClassLoader; -import static org.apache.dubbo.common.utils.ClassUtils.resolveClass; - -/** - * The abstract {@link AnnotatedMethodParameterProcessor} implementation - * - * @since 2.7.6 - */ -public abstract class AbstractAnnotatedMethodParameterProcessor implements AnnotatedMethodParameterProcessor { - - @Override - public void process( - Annotation annotation, - Parameter parameter, - int parameterIndex, - Method method, - Class serviceType, - Class serviceInterfaceClass, - RestMethodMetadata restMethodMetadata) { - - String annotationValue = getAnnotationValue(annotation, parameter, parameterIndex); - String defaultValue = getDefaultValue(annotation, parameter, parameterIndex); - addArgInfo(parameter, parameterIndex, restMethodMetadata, annotationValue, defaultValue); - process(annotationValue, defaultValue, annotation, parameter, parameterIndex, method, restMethodMetadata); - } - - protected void process( - String annotationValue, - String defaultValue, - Annotation annotation, - Parameter parameter, - int parameterIndex, - Method method, - RestMethodMetadata restMethodMetadata) {} - - @Override - public Class getAnnotationClass() { - return resolveClass(getAnnotationName(), getClassLoader()); - } - - protected void addArgInfo( - Parameter parameter, - int parameterIndex, - RestMethodMetadata restMethodMetadata, - String annotationValue, - Object defaultValue) { - ArgInfo argInfo = ArgInfo.build(parameterIndex, parameter) - .setParamAnnotationType(getAnnotationClass()) - .setAnnotationNameAttribute(annotationValue) - .setDefaultValue(defaultValue); - restMethodMetadata.addArgInfo(argInfo); - } - - protected String getAnnotationValue(Annotation annotation, Parameter parameter, int parameterIndex) { - return getValue(annotation); - } - - protected String getDefaultValue(Annotation annotation, Parameter parameter, int parameterIndex) { - return AnnotatedMethodParameterProcessor.buildDefaultValue(parameterIndex); - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AbstractNoAnnotatedParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AbstractNoAnnotatedParameterProcessor.java deleted file mode 100644 index 23cdd4cbf3f..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AbstractNoAnnotatedParameterProcessor.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.metadata.rest; - -import org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver; -import org.apache.dubbo.metadata.rest.media.MediaType; - -import java.lang.reflect.Parameter; -import java.util.Set; - -import static org.apache.dubbo.common.utils.ClassUtils.getClassLoader; -import static org.apache.dubbo.common.utils.ClassUtils.resolveClass; - -public abstract class AbstractNoAnnotatedParameterProcessor implements NoAnnotatedParameterRequestTagProcessor { - - public boolean process(Parameter parameter, int parameterIndex, RestMethodMetadata restMethodMetadata) { - MediaType mediaType = consumerContentType(); - if (!contentTypeSupport(restMethodMetadata, mediaType, parameter.getType())) { - return false; - } - boolean isFormBody = isFormContentType(restMethodMetadata); - addArgInfo(parameter, parameterIndex, restMethodMetadata, isFormBody); - return true; - } - - private boolean contentTypeSupport(RestMethodMetadata restMethodMetadata, MediaType mediaType, Class paramType) { - - // @RequestParam String,number param - if (mediaType.equals(MediaType.ALL_VALUE)) { - // jaxrs no annotation param is from http body - if (JAXRSServiceRestMetadataResolver.class.equals(restMethodMetadata.getCodeStyle())) { - return true; - } - - // spring mvc no annotation param only is used by text data(string,number) - if (String.class == paramType || paramType.isPrimitive() || Number.class.isAssignableFrom(paramType)) { - return true; - } - } - - Set consumes = restMethodMetadata.getRequest().getConsumes(); - for (String consume : consumes) { - if (consume.contains(mediaType.value)) { - return true; - } - } - - return false; - } - - protected boolean isFormContentType(RestMethodMetadata restMethodMetadata) { - - return false; - } - - protected void addArgInfo( - Parameter parameter, int parameterIndex, RestMethodMetadata restMethodMetadata, boolean isFormBody) { - ArgInfo argInfo = ArgInfo.build(parameterIndex, parameter) - .setParamAnnotationType(resolveClass(defaultAnnotationClassName(restMethodMetadata), getClassLoader())) - .setAnnotationNameAttribute(parameter.getName()) - .setFormContentType(isFormBody); - restMethodMetadata.addArgInfo(argInfo); - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AbstractServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AbstractServiceRestMetadataResolver.java deleted file mode 100644 index d3e1d537000..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AbstractServiceRestMetadataResolver.java +++ /dev/null @@ -1,487 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest; - -import org.apache.dubbo.common.compact.Dubbo2CompactUtils; -import org.apache.dubbo.common.utils.MethodComparator; -import org.apache.dubbo.common.utils.ServiceAnnotationResolver; -import org.apache.dubbo.config.annotation.DubboService; -import org.apache.dubbo.config.annotation.Service; -import org.apache.dubbo.metadata.definition.MethodDefinitionBuilder; -import org.apache.dubbo.metadata.definition.model.MethodDefinition; -import org.apache.dubbo.rpc.model.ApplicationModel; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.lang.reflect.Parameter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Consumer; - -import static java.util.Collections.emptyList; -import static java.util.Collections.sort; -import static java.util.Collections.unmodifiableMap; -import static org.apache.dubbo.common.function.ThrowableFunction.execute; -import static org.apache.dubbo.common.utils.AnnotationUtils.isAnnotationPresent; -import static org.apache.dubbo.common.utils.AnnotationUtils.isAnyAnnotationPresent; -import static org.apache.dubbo.common.utils.ClassUtils.forName; -import static org.apache.dubbo.common.utils.ClassUtils.getAllInterfaces; -import static org.apache.dubbo.common.utils.MemberUtils.isPrivate; -import static org.apache.dubbo.common.utils.MemberUtils.isStatic; -import static org.apache.dubbo.common.utils.MethodUtils.excludedDeclaredClass; -import static org.apache.dubbo.common.utils.MethodUtils.getAllMethods; -import static org.apache.dubbo.common.utils.MethodUtils.overrides; - -/** - * The abstract {@link ServiceRestMetadataResolver} class to provider some template methods assemble the instance of - * {@link ServiceRestMetadata} will extended by the sub-classes. - * - * @since 2.7.6 - */ -public abstract class AbstractServiceRestMetadataResolver implements ServiceRestMetadataResolver { - - private final Map> parameterProcessorsMap; - private final Set noAnnotatedParameterRequestTagProcessors; - - public AbstractServiceRestMetadataResolver(ApplicationModel applicationModel) { - this.parameterProcessorsMap = loadAnnotatedMethodParameterProcessors(applicationModel); - this.noAnnotatedParameterRequestTagProcessors = loadNoAnnotatedMethodParameterProcessors(applicationModel); - } - - @Override - public final boolean supports(Class serviceType) { - return supports(serviceType, false); - } - - @Override - public final boolean supports(Class serviceType, boolean consumer) { - - if (serviceType == null) { - return false; - } - - // for consumer - // it is possible serviceType is impl - // for provider - // for xml config bean && isServiceAnnotationPresent(serviceType) - // isImplementedInterface(serviceType) SpringController - return supports0(serviceType); - } - - protected final boolean isImplementedInterface(Class serviceType) { - return !getAllInterfaces(serviceType).isEmpty(); - } - - protected final boolean isServiceAnnotationPresent(Class serviceType) { - if (Dubbo2CompactUtils.isEnabled() && Dubbo2CompactUtils.isServiceClassLoaded()) { - return isAnyAnnotationPresent( - serviceType, DubboService.class, Service.class, Dubbo2CompactUtils.getServiceClass()); - } else { - return isAnyAnnotationPresent(serviceType, DubboService.class, Service.class); - } - } - - /** - * internal support method - * - * @param serviceType Dubbo Service interface or type - * @return If supports, return true, or false - */ - protected abstract boolean supports0(Class serviceType); - - @Override - public final ServiceRestMetadata resolve(Class serviceType) { - ServiceRestMetadata serviceRestMetadata = new ServiceRestMetadata(); - - // Process ServiceRestMetadata - processServiceRestMetadata(serviceRestMetadata, serviceType); - - return resolve(serviceType, serviceRestMetadata); - } - - @Override - public final ServiceRestMetadata resolve(Class serviceType, ServiceRestMetadata serviceRestMetadata) { - serviceRestMetadata.setCodeStyle(this.getClass()); - // Process RestMethodMetadata - processAllRestMethodMetadata(serviceRestMetadata, serviceType); - - return serviceRestMetadata; - } - - /** - * Process the service type including the sub-routines: - *
    - *
  • {@link ServiceRestMetadata#setServiceInterface(String)}
  • - *
  • {@link ServiceRestMetadata#setVersion(String)}
  • - *
  • {@link ServiceRestMetadata#setGroup(String)}
  • - *
- * - * @param serviceRestMetadata {@link ServiceRestMetadata} - * @param serviceType Dubbo Service interface or type - */ - protected void processServiceRestMetadata(ServiceRestMetadata serviceRestMetadata, Class serviceType) { - ServiceAnnotationResolver resolver = new ServiceAnnotationResolver(serviceType); - serviceRestMetadata.setServiceInterface(resolver.resolveInterfaceClassName()); - serviceRestMetadata.setVersion(resolver.resolveVersion()); - serviceRestMetadata.setGroup(resolver.resolveGroup()); - } - - /** - * Process all {@link RestMethodMetadata} - * - * @param serviceRestMetadata {@link ServiceRestMetadata} - * @param serviceType Dubbo Service interface or type - */ - protected void processAllRestMethodMetadata(ServiceRestMetadata serviceRestMetadata, Class serviceType) { - Class serviceInterfaceClass = resolveServiceInterfaceClass(serviceRestMetadata, serviceType); - Map serviceMethodsMap = resolveServiceMethodsMap(serviceType, serviceInterfaceClass); - for (Map.Entry entry : serviceMethodsMap.entrySet()) { - // try the overrider method first - Method serviceMethod = entry.getKey(); - // If failed, it indicates the overrider method does not contain metadata , then try the declared method - if (!processRestMethodMetadata( - serviceMethod, - serviceType, - serviceInterfaceClass, - serviceRestMetadata::addRestMethodMetadata, - serviceRestMetadata)) { - Method declaredServiceMethod = entry.getValue(); - processRestMethodMetadata( - declaredServiceMethod, - serviceType, - serviceInterfaceClass, - serviceRestMetadata::addRestMethodMetadata, - serviceRestMetadata); - } - } - } - - /** - * Resolve a map of all public services methods from the specified service type and its interface class, whose key is the - * declared method, and the value is the overrider method - * - * @param serviceType the service interface implementation class - * @param serviceInterfaceClass the service interface class - * @return non-null read-only {@link Map} - */ - protected Map resolveServiceMethodsMap(Class serviceType, Class serviceInterfaceClass) { - Map serviceMethodsMap = new LinkedHashMap<>(); - // exclude the public methods declared in java.lang.Object.class - List declaredServiceMethods = - new ArrayList<>(getAllMethods(serviceInterfaceClass, excludedDeclaredClass(Object.class))); - - // controller class - if (serviceType.equals(serviceInterfaceClass)) { - putServiceMethodToMap(serviceMethodsMap, declaredServiceMethods); - return unmodifiableMap(serviceMethodsMap); - } - - // for interface , such as consumer interface - if (serviceType.isInterface()) { - putServiceMethodToMap(serviceMethodsMap, declaredServiceMethods); - return unmodifiableMap(serviceMethodsMap); - } - - List serviceMethods = new ArrayList<>(getAllMethods(serviceType, excludedDeclaredClass(Object.class))); - - // sort methods - sort(declaredServiceMethods, MethodComparator.INSTANCE); - sort(serviceMethods, MethodComparator.INSTANCE); - - // prevent from repeat method (impl proxy) & leaving out method(interface proxy) - HashSet methodComparators = new HashSet<>(); - - // TODO Map key: method desc & value: Set for accelerate loop speed - for (Method declaredServiceMethod : declaredServiceMethods) { - for (Method serviceMethod : serviceMethods) { - - if (!overrides(serviceMethod, declaredServiceMethod)) { - continue; - } - - String methodDesc = getMethodDesc(serviceMethod); - - if (!methodComparators.add(methodDesc)) { - continue; - } - - serviceMethodsMap.put(serviceMethod, declaredServiceMethod); - } - } - - // make them to be read-only - return unmodifiableMap(serviceMethodsMap); - } - - /** - * For simple method desc - * - * @param serviceMethod - * @return - */ - private String getMethodDesc(Method serviceMethod) { - return serviceMethod.getName() + Arrays.toString(serviceMethod.getParameterTypes()); - } - - private void putServiceMethodToMap(Map serviceMethodsMap, List declaredServiceMethods) { - declaredServiceMethods.stream().forEach(method -> { - - // filter static private default - if (isStatic(method) || isPrivate(method) || method.isDefault()) { - return; - } - serviceMethodsMap.put(method, method); - }); - } - - /** - * Resolve the class of Dubbo Service interface - * - * @param serviceRestMetadata {@link ServiceRestMetadata} - * @param serviceType Dubbo Service interface or type - * @return non-null - * @throws RuntimeException If the class is not found, the {@link RuntimeException} wraps the cause will be thrown - */ - protected Class resolveServiceInterfaceClass(ServiceRestMetadata serviceRestMetadata, Class serviceType) { - return execute(serviceType.getClassLoader(), classLoader -> { - String serviceInterface = serviceRestMetadata.getServiceInterface(); - return forName(serviceInterface, classLoader); - }); - } - - /** - * Process the single {@link RestMethodMetadata} by the specified {@link Consumer} if present - * - * @param serviceMethod Dubbo Service method - * @param serviceType Dubbo Service interface or type - * @param serviceInterfaceClass The type of Dubbo Service interface - * @param metadataToProcess {@link RestMethodMetadata} to process if present - * @return if processed successfully, return true, or false - */ - protected boolean processRestMethodMetadata( - Method serviceMethod, - Class serviceType, - Class serviceInterfaceClass, - Consumer metadataToProcess, - ServiceRestMetadata serviceRestMetadata) { - - if (!isRestCapableMethod(serviceMethod, serviceType, serviceInterfaceClass)) { - return false; - } - - String requestPath = - resolveRequestPath(serviceMethod, serviceType, serviceInterfaceClass); // requestPath is required - - if (requestPath == null) { - return false; - } - - String requestMethod = - resolveRequestMethod(serviceMethod, serviceType, serviceInterfaceClass); // requestMethod is required - - if (requestMethod == null) { - return false; - } - - RestMethodMetadata metadata = new RestMethodMetadata(); - - metadata.setCodeStyle(this.getClass()); - - // to consumer service map - metadata.setReflectMethod(serviceMethod); - - MethodDefinition methodDefinition = resolveMethodDefinition(serviceMethod, serviceType, serviceInterfaceClass); - // Set MethodDefinition - metadata.setMethod(methodDefinition); - - // process produces - Set produces = new LinkedHashSet<>(); - processProduces(serviceMethod, serviceType, serviceInterfaceClass, produces); - - // process consumes - Set consumes = new LinkedHashSet<>(); - processConsumes(serviceMethod, serviceType, serviceInterfaceClass, consumes); - - // Initialize RequestMetadata - RequestMetadata request = metadata.getRequest(); - request.setPath(requestPath); - request.appendContextPathFromUrl(serviceRestMetadata.getContextPathFromUrl()); - request.setMethod(requestMethod); - request.setProduces(produces); - request.setConsumes(consumes); - - // process the annotated method parameters - processAnnotatedMethodParameters(serviceMethod, serviceType, serviceInterfaceClass, metadata); - - // Post-Process - postResolveRestMethodMetadata(serviceMethod, serviceType, serviceInterfaceClass, metadata); - - // Accept RestMethodMetadata - metadataToProcess.accept(metadata); - - return true; - } - - /** - * Test the service method is capable of REST or not? - * - * @param serviceMethod Dubbo Service method - * @param serviceType Dubbo Service interface or type - * @param serviceInterfaceClass The type of Dubbo Service interface - * @return If capable, return true - */ - protected abstract boolean isRestCapableMethod( - Method serviceMethod, Class serviceType, Class serviceInterfaceClass); - - /** - * Resolve the request method - * - * @param serviceMethod Dubbo Service method - * @param serviceType Dubbo Service interface or type - * @param serviceInterfaceClass The type of Dubbo Service interface - * @return if can't be resolve, return null - */ - protected abstract String resolveRequestMethod( - Method serviceMethod, Class serviceType, Class serviceInterfaceClass); - - /** - * Resolve the request path - * - * @param serviceMethod Dubbo Service method - * @param serviceType Dubbo Service interface or type - * @param serviceInterfaceClass The type of Dubbo Service interface - * @return if can't be resolve, return null - */ - protected abstract String resolveRequestPath( - Method serviceMethod, Class serviceType, Class serviceInterfaceClass); - - /** - * Resolve the {@link MethodDefinition} - * - * @param serviceMethod Dubbo Service method - * @param serviceType Dubbo Service interface or type - * @param serviceInterfaceClass The type of Dubbo Service interface - * @return if can't be resolve, return null - * @see MethodDefinitionBuilder - */ - protected MethodDefinition resolveMethodDefinition( - Method serviceMethod, Class serviceType, Class serviceInterfaceClass) { - MethodDefinitionBuilder builder = new MethodDefinitionBuilder(); - return builder.build(serviceMethod); - } - - private void processAnnotatedMethodParameters( - Method serviceMethod, Class serviceType, Class serviceInterfaceClass, RestMethodMetadata metadata) { - int paramCount = serviceMethod.getParameterCount(); - Parameter[] parameters = serviceMethod.getParameters(); - for (int i = 0; i < paramCount; i++) { - Parameter parameter = parameters[i]; - // Add indexed parameter name - metadata.addIndexToName(i, parameter.getName()); - processAnnotatedMethodParameter(parameter, i, serviceMethod, serviceType, serviceInterfaceClass, metadata); - } - } - - protected void processAnnotatedMethodParameter( - Parameter parameter, - int parameterIndex, - Method serviceMethod, - Class serviceType, - Class serviceInterfaceClass, - RestMethodMetadata metadata) { - Annotation[] annotations = parameter.getAnnotations(); - - if (annotations == null || annotations.length == 0) { - - for (NoAnnotatedParameterRequestTagProcessor processor : noAnnotatedParameterRequestTagProcessors) { - // no annotation only one default annotationType - if (processor.process(parameter, parameterIndex, metadata)) { - return; - } - } - } - - for (Annotation annotation : annotations) { - String annotationType = annotation.annotationType().getName(); - parameterProcessorsMap.getOrDefault(annotationType, emptyList()).forEach(processor -> { - processor.process( - annotation, - parameter, - parameterIndex, - serviceMethod, - serviceType, - serviceInterfaceClass, - metadata); - }); - } - } - - protected abstract void processProduces( - Method serviceMethod, Class serviceType, Class serviceInterfaceClass, Set produces); - - protected abstract void processConsumes( - Method serviceMethod, Class serviceType, Class serviceInterfaceClass, Set consumes); - - protected void postResolveRestMethodMetadata( - Method serviceMethod, Class serviceType, Class serviceInterfaceClass, RestMethodMetadata metadata) { - - // parse pathVariable index from url by annotation info - PathUtil.setArgInfoSplitIndex(metadata.getRequest().getPath(), metadata.getArgInfos()); - } - - private static Map> loadAnnotatedMethodParameterProcessors( - ApplicationModel applicationModel) { - Map> parameterProcessorsMap = new LinkedHashMap<>(); - applicationModel - .getExtensionLoader(AnnotatedMethodParameterProcessor.class) - .getSupportedExtensionInstances() - .forEach(processor -> { - List processors = parameterProcessorsMap.computeIfAbsent( - processor.getAnnotationName(), k -> new LinkedList<>()); - processors.add(processor); - }); - return parameterProcessorsMap; - } - - private static Set loadNoAnnotatedMethodParameterProcessors( - ApplicationModel applicationModel) { - Set supportedExtensionInstances = applicationModel - .getExtensionLoader(NoAnnotatedParameterRequestTagProcessor.class) - .getSupportedExtensionInstances(); - - return supportedExtensionInstances; - } - - public static boolean isServiceMethodAnnotationPresent(Class serviceImpl, String annotationClass) { - List allMethods = getAllMethods(serviceImpl, excludedDeclaredClass(Object.class)); - - for (Method method : allMethods) { - if (isAnnotationPresent(method, annotationClass)) { - return true; - } - } - - return false; - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AnnotatedMethodParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AnnotatedMethodParameterProcessor.java deleted file mode 100644 index b05bd4b48e2..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AnnotatedMethodParameterProcessor.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest; - -import org.apache.dubbo.common.extension.ExtensionScope; -import org.apache.dubbo.common.extension.SPI; -import org.apache.dubbo.common.lang.Prioritized; - -import javax.lang.model.element.VariableElement; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.lang.reflect.Parameter; - -/** - * The interface to process the annotated method parameter - * - * @since 2.7.6 - */ -@SPI(scope = ExtensionScope.FRAMEWORK) -public interface AnnotatedMethodParameterProcessor extends Prioritized { - - /** - * The string presenting the annotation name - * - * @return non-null - */ - String getAnnotationName(); - - /** - * The string presenting the annotation type - * - * @return non-null - */ - Class getAnnotationClass(); - - /** - * Process the specified method {@link VariableElement parameter} - * - * @param annotation {@link Annotation the target annotation} whose type is {@link #getAnnotationName()} - * @param parameter the method parameter - * @param parameterIndex the index of method parameter - * @param method {@link Method method that parameter belongs to} - * @param serviceType Dubbo Service interface or type - * @param serviceInterfaceClass The type of Dubbo Service interface - * @param restMethodMetadata {@link RestMethodMetadata the metadata is used to update} - */ - void process( - Annotation annotation, - Parameter parameter, - int parameterIndex, - Method method, - Class serviceType, - Class serviceInterfaceClass, - RestMethodMetadata restMethodMetadata); - - /** - * Build the default value - * - * @param parameterIndex the index of parameter - * @return the placeholder - */ - static String buildDefaultValue(int parameterIndex) { - return "{" + parameterIndex + "}"; - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ArgInfo.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ArgInfo.java deleted file mode 100644 index dc2f7001f8a..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ArgInfo.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest; - -import java.lang.reflect.Parameter; -import java.lang.reflect.Type; - -/** - * description of service method args info - */ -public class ArgInfo { - /** - * method arg index 0,1,2,3 - */ - private int index; - /** - * method annotation name or name - */ - private String annotationNameAttribute; - - /** - * param annotation type - */ - private Class paramAnnotationType; - - /** - * param Type - */ - private Class paramType; - - /** - * param actual Type(collection,map,array) - */ - private Type actualType; - - /** - * param name - */ - private String paramName; - - /** - * url split("/") String[n] index - */ - private int urlSplitIndex; - - private Object defaultValue; - - private boolean formContentType; - - public ArgInfo(int index, String name, Class paramType) { - this.index = index; - this.paramName = name; - this.paramType = paramType; - } - - public ArgInfo(int index, Parameter parameter) { - this(index, parameter.getName(), parameter.getType()); - this.actualType = parameter.getParameterizedType(); - } - - public ArgInfo() {} - - public int getIndex() { - return index; - } - - public ArgInfo setIndex(int index) { - this.index = index; - return this; - } - - public String getAnnotationNameAttribute() { - if (annotationNameAttribute == null) { - // such as String param no annotation - return paramName; - } - return annotationNameAttribute; - } - - public ArgInfo setAnnotationNameAttribute(String annotationNameAttribute) { - this.annotationNameAttribute = annotationNameAttribute; - return this; - } - - public Class getParamAnnotationType() { - return paramAnnotationType; - } - - public ArgInfo setParamAnnotationType(Class paramAnnotationType) { - this.paramAnnotationType = paramAnnotationType; - return this; - } - - public Class getParamType() { - return paramType; - } - - public void setParamType(Class paramType) { - this.paramType = paramType; - } - - public int getUrlSplitIndex() { - return urlSplitIndex; - } - - public void setUrlSplitIndex(int urlSplitIndex) { - this.urlSplitIndex = urlSplitIndex; - } - - public static ArgInfo build() { - return new ArgInfo(); - } - - public static ArgInfo build(int index, Parameter parameter) { - return new ArgInfo(index, parameter); - } - - public String getParamName() { - return paramName; - } - - public ArgInfo setParamName(String paramName) { - this.paramName = paramName; - return this; - } - - public Object getDefaultValue() { - return defaultValue; - } - - public ArgInfo setDefaultValue(Object defaultValue) { - this.defaultValue = defaultValue; - return this; - } - - public boolean isFormContentType() { - return formContentType; - } - - public ArgInfo setFormContentType(boolean isFormContentType) { - this.formContentType = isFormContentType; - return this; - } - - public Type actualReflectType() { - return actualType; - } - - @Override - public String toString() { - return "ArgInfo{" + "index=" - + index + ", annotationNameAttribute='" - + annotationNameAttribute + '\'' + ", paramAnnotationType=" - + paramAnnotationType + ", paramType=" - + paramType + ", paramName='" - + paramName + '\'' + ", urlSplitIndex=" - + urlSplitIndex + ", defaultValue=" - + defaultValue + ", formContentType=" - + formContentType + '}'; - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ClassPathServiceRestMetadataReader.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ClassPathServiceRestMetadataReader.java deleted file mode 100644 index 102f37ad03e..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ClassPathServiceRestMetadataReader.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest; - -import org.apache.dubbo.common.utils.IOUtils; -import org.apache.dubbo.common.utils.JsonUtils; - -import java.io.InputStream; -import java.net.URL; -import java.util.Enumeration; -import java.util.LinkedList; -import java.util.List; - -import static java.util.Collections.unmodifiableList; -import static org.apache.dubbo.common.function.ThrowableAction.execute; -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.METADATA_ENCODING; -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SERVICE_REST_METADATA_RESOURCE_PATH; - -/** - * Class-Path based {@link ServiceRestMetadataReader} implementation - * - * @see ServiceRestMetadataReader - * @since 2.7.6 - */ -public class ClassPathServiceRestMetadataReader implements ServiceRestMetadataReader { - - private final String serviceRestMetadataJsonResourcePath; - - public ClassPathServiceRestMetadataReader() { - this(SERVICE_REST_METADATA_RESOURCE_PATH); - } - - public ClassPathServiceRestMetadataReader(String serviceRestMetadataJsonResourcePath) { - this.serviceRestMetadataJsonResourcePath = serviceRestMetadataJsonResourcePath; - } - - @Override - public List read() { - - List serviceRestMetadataList = new LinkedList<>(); - - ClassLoader classLoader = getClass().getClassLoader(); - - execute(() -> { - Enumeration resources = classLoader.getResources(serviceRestMetadataJsonResourcePath); - while (resources.hasMoreElements()) { - URL resource = resources.nextElement(); - InputStream inputStream = resource.openStream(); - String json = IOUtils.read(inputStream, METADATA_ENCODING); - serviceRestMetadataList.addAll(JsonUtils.toJavaList(json, ServiceRestMetadata.class)); - } - }); - - return unmodifiableList(serviceRestMetadataList); - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/DefaultServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/DefaultServiceRestMetadataResolver.java deleted file mode 100644 index 41a4e1bec99..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/DefaultServiceRestMetadataResolver.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest; - -import org.apache.dubbo.rpc.model.ApplicationModel; - -import java.lang.reflect.Method; -import java.util.Set; - -/** - * The default implementation {@link ServiceRestMetadataResolver} - * - * @since 2.7.6 - */ -public class DefaultServiceRestMetadataResolver extends AbstractServiceRestMetadataResolver { - public DefaultServiceRestMetadataResolver(ApplicationModel applicationModel) { - super(applicationModel); - } - - @Override - protected boolean supports0(Class serviceType) { - return false; - } - - @Override - protected boolean isRestCapableMethod(Method serviceMethod, Class serviceType, Class serviceInterfaceClass) { - return false; - } - - @Override - protected String resolveRequestMethod(Method serviceMethod, Class serviceType, Class serviceInterfaceClass) { - return null; - } - - @Override - protected String resolveRequestPath(Method serviceMethod, Class serviceType, Class serviceInterfaceClass) { - return null; - } - - @Override - protected void processProduces( - Method serviceMethod, Class serviceType, Class serviceInterfaceClass, Set produces) {} - - @Override - protected void processConsumes( - Method serviceMethod, Class serviceType, Class serviceInterfaceClass, Set consumes) {} -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/JAXRSClassConstants.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/JAXRSClassConstants.java deleted file mode 100644 index 47c9149ff40..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/JAXRSClassConstants.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest; - -import static org.apache.dubbo.common.utils.ClassUtils.getClassLoader; -import static org.apache.dubbo.common.utils.ClassUtils.resolveClass; - -public interface JAXRSClassConstants extends RestMetadataConstants.JAX_RS { - /** - * The annotation class of @Path - */ - Class PATH_ANNOTATION_CLASS = resolveClass(PATH_ANNOTATION_CLASS_NAME, getClassLoader()); - - /** - * The annotation class of @FormParam - */ - Class FORM_PARAM_ANNOTATION_CLASS = resolveClass(FORM_PARAM_ANNOTATION_CLASS_NAME, getClassLoader()); - - /** - * The annotation class of @Form - */ - Class FORM_BODY_ANNOTATION_CLASS = resolveClass(REST_EASY_FORM_BODY_ANNOTATION_CLASS_NAME, getClassLoader()); - - /** - * The annotation class of @HeaderParam - */ - Class HEADER_PARAM_ANNOTATION_CLASS = resolveClass(HEADER_PARAM_ANNOTATION_CLASS_NAME, getClassLoader()); - - /** - * The annotation class of @MatrixParam - */ - Class MATRIX_PARAM_ANNOTATION_CLASS = resolveClass(MATRIX_PARAM_ANNOTATION_CLASS_NAME, getClassLoader()); - - /** - * The annotation class of @QueryParam - */ - Class QUERY_PARAM_ANNOTATION_CLASS = resolveClass(QUERY_PARAM_ANNOTATION_CLASS_NAME, getClassLoader()); - - /** - * The annotation class of @Body - */ - Class REST_EASY_BODY_ANNOTATION_CLASS = resolveClass(REST_EASY_BODY_ANNOTATION_CLASS_NAME, getClassLoader()); - - /** - * The annotation class of @PathParam - */ - Class PATH_PARAM_ANNOTATION_CLASS = resolveClass(PATH_PARAM_ANNOTATION_CLASS_NAME, getClassLoader()); -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/NoAnnotatedParameterRequestTagProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/NoAnnotatedParameterRequestTagProcessor.java deleted file mode 100644 index 376e2245240..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/NoAnnotatedParameterRequestTagProcessor.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest; - -import org.apache.dubbo.common.extension.ExtensionScope; -import org.apache.dubbo.common.extension.SPI; -import org.apache.dubbo.metadata.rest.media.MediaType; - -import java.lang.reflect.Parameter; - -@SPI(scope = ExtensionScope.FRAMEWORK) -public interface NoAnnotatedParameterRequestTagProcessor { - MediaType consumerContentType(); - - String defaultAnnotationClassName(RestMethodMetadata restMethodMetadata); - - boolean process(Parameter parameter, int parameterIndex, RestMethodMetadata restMethodMetadata); -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ParamType.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ParamType.java deleted file mode 100644 index 23ac6a840e9..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ParamType.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.metadata.rest; - -import org.apache.dubbo.metadata.rest.tag.BodyTag; -import org.apache.dubbo.metadata.rest.tag.NoAnnotationTag; -import org.apache.dubbo.metadata.rest.tag.ParamTag; - -import java.util.ArrayList; -import java.util.List; - -public enum ParamType { - HEADER(addSupportTypes( - JAXRSClassConstants.HEADER_PARAM_ANNOTATION_CLASS, - SpringMvcClassConstants.REQUEST_HEADER_ANNOTATION_CLASS)), - - PARAM(addSupportTypes( - JAXRSClassConstants.QUERY_PARAM_ANNOTATION_CLASS, - SpringMvcClassConstants.REQUEST_PARAM_ANNOTATION_CLASS, - ParamTag.class)), - - BODY(addSupportTypes( - JAXRSClassConstants.REST_EASY_BODY_ANNOTATION_CLASS, - SpringMvcClassConstants.REQUEST_BODY_ANNOTATION_CLASS, - BodyTag.class)), - - PATH(addSupportTypes( - JAXRSClassConstants.PATH_PARAM_ANNOTATION_CLASS, SpringMvcClassConstants.PATH_VARIABLE_ANNOTATION_CLASS)), - - FORM(addSupportTypes( - JAXRSClassConstants.FORM_PARAM_ANNOTATION_CLASS, - JAXRSClassConstants.FORM_BODY_ANNOTATION_CLASS, - SpringMvcClassConstants.REQUEST_BODY_ANNOTATION_CLASS)), - - PROVIDER_BODY(addSupportTypes( - JAXRSClassConstants.REST_EASY_BODY_ANNOTATION_CLASS, - JAXRSClassConstants.FORM_PARAM_ANNOTATION_CLASS, - SpringMvcClassConstants.REQUEST_BODY_ANNOTATION_CLASS, - BodyTag.class, - JAXRSClassConstants.FORM_BODY_ANNOTATION_CLASS)), - - PROVIDER_NO_ANNOTATION(addSupportTypes(NoAnnotationTag.class)), - - EMPTY(addSupportTypes()); - private List annotationClasses; - - ParamType(List annotationClasses) { - this.annotationClasses = annotationClasses; - } - - public boolean supportAnno(Class anno) { - if (anno == null) { - return false; - } - return this.annotationClasses.contains(anno); - } - - /** - * exclude null types - * - * @param classes - * @return - */ - private static List addSupportTypes(Class... classes) { - - ArrayList types = new ArrayList<>(); - - for (Class clazz : classes) { - - if (clazz == null) { - continue; - } - - types.add(clazz); - } - - return types; - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/PathMatcher.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/PathMatcher.java deleted file mode 100644 index 2e526d19a64..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/PathMatcher.java +++ /dev/null @@ -1,284 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest; - -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.Objects; - -/** - * for http request path match - */ -public class PathMatcher { - private static final String SEPARATOR = "/"; - private String path; - private String version; // service version - private String group; // service group - private Integer port; // service port - private String[] pathSplits; - private boolean hasPathVariable; - private String contextPath; - private String httpMethod; - // for provider http method compare,http 405 - private boolean needCompareHttpMethod = true; - // compare method directly (for get Invoker by method) - private boolean needCompareServiceMethod = false; - - // service method - private Method method; - - public PathMatcher(String path) { - this(path, null, null, null); - } - - public PathMatcher(String path, String version, String group, Integer port) { - this.path = path; - dealPathVariable(path); - this.version = version; - this.group = group; - this.port = (port == null || port == -1 || port == 0) ? null : port; - } - - public PathMatcher(String path, String version, String group, Integer port, String httpMethod) { - this(path, version, group, port); - setHttpMethod(httpMethod); - } - - public PathMatcher(Method method) { - this.method = method; - } - - private void dealPathVariable(String path) { - if (path == null) { - return; - } - this.pathSplits = path.split(SEPARATOR); - - for (String pathSplit : pathSplits) { - - if (isPlaceHold(pathSplit)) { - hasPathVariable = true; - break; - } - } - } - - private void setPath(String path) { - this.path = path; - } - - public void setVersion(String version) { - this.version = version; - } - - public void setGroup(String group) { - this.group = group; - } - - public void setPort(Integer port) { - this.port = port; - } - - public void setContextPath(String contextPath) { - - contextPath = contextPathFormat(contextPath); - - this.contextPath = contextPath; - - setPath(contextPath + path); - - dealPathVariable(path); - } - - public static PathMatcher getInvokeCreatePathMatcher( - String path, String version, String group, Integer port, String method) { - return new PathMatcher(path, version, group, port, method).compareHttpMethod(false); - } - - public static PathMatcher getInvokeCreatePathMatcher(Method serviceMethod) { - return new PathMatcher(serviceMethod).setNeedCompareServiceMethod(true); - } - - public static PathMatcher convertPathMatcher(PathMatcher pathMatcher) { - return getInvokeCreatePathMatcher( - pathMatcher.path, pathMatcher.version, pathMatcher.group, pathMatcher.port, pathMatcher.httpMethod); - } - - public boolean hasPathVariable() { - return hasPathVariable; - } - - public Integer getPort() { - return port; - } - - public String getHttpMethod() { - return httpMethod; - } - - public PathMatcher setHttpMethod(String httpMethod) { - this.httpMethod = httpMethod; - return this; - } - - public PathMatcher compareHttpMethod(boolean needCompareHttpMethod) { - this.needCompareHttpMethod = needCompareHttpMethod; - return this; - } - - public Method getMethod() { - return method; - } - - public void setMethod(Method method) { - this.method = method; - } - - private PathMatcher setNeedCompareServiceMethod(boolean needCompareServiceMethod) { - this.needCompareServiceMethod = needCompareServiceMethod; - return this; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - PathMatcher that = (PathMatcher) o; - return serviceMethodEqual(that, this) || pathMatch(that); - } - - private boolean pathMatch(PathMatcher that) { - return (!that.needCompareServiceMethod && !needCompareServiceMethod) // no need service method compare - && pathEqual(that) // path compare - && Objects.equals(version, that.version) // service version compare - && httpMethodMatch(that) // http method compare - && Objects.equals(group, that.group) - && Objects.equals(port, that.port); - } - - /** - * it is needed to compare http method when one of needCompareHttpMethod is true,and don`t compare when both needCompareHttpMethod are false - * - * @param that - * @return - */ - private boolean httpMethodMatch(PathMatcher that) { - return !that.needCompareHttpMethod || !this.needCompareHttpMethod - ? true - : Objects.equals(this.httpMethod, that.httpMethod); - } - - private boolean serviceMethodEqual(PathMatcher thatPathMatcher, PathMatcher thisPathMatcher) { - Method thatMethod = thatPathMatcher.method; - Method thisMethod = thisPathMatcher.method; - return thatMethod != null - && thisMethod != null - && (thatPathMatcher.needCompareServiceMethod || thisPathMatcher.needCompareServiceMethod) - && thisMethod.getName().equals(thatMethod.getName()) - && Arrays.equals(thisMethod.getParameterTypes(), thatMethod.getParameterTypes()); - } - - @Override - public int hashCode() { - return Objects.hash(version, group, port); - } - - private boolean pathEqual(PathMatcher pathMatcher) { - // path is null return false directly - if (this.path == null || pathMatcher.path == null) { - return false; - } - - // no place hold - if (!pathMatcher.hasPathVariable) { - return this.path.equals(pathMatcher.path); - } - - String[] pathSplits = pathMatcher.pathSplits; - String[] thisPathSplits = this.pathSplits; - - if (thisPathSplits.length != pathSplits.length) { - return false; - } - - for (int i = 0; i < pathSplits.length; i++) { - boolean equals = thisPathSplits[i].equals(pathSplits[i]); - if (equals) { - continue; - } else { - if (placeHoldCompare(pathSplits[i], thisPathSplits[i])) { - continue; - } else { - return false; - } - } - } - - return true; - } - - private boolean placeHoldCompare(String pathSplit, String pathToCompare) { - boolean startAndEndEqual = isPlaceHold(pathSplit) || isPlaceHold(pathToCompare); - - // start { end } - if (!startAndEndEqual) { - return false; - } - - // exclude {} - boolean lengthCondition = pathSplit.length() >= 3 || pathToCompare.length() >= 3; - - if (!lengthCondition) { - return false; - } - - return true; - } - - private boolean isPlaceHold(String pathSplit) { - return pathSplit.startsWith("{") && pathSplit.endsWith("}"); - } - - private String contextPathFormat(String contextPath) { - - if (contextPath == null || contextPath.equals(SEPARATOR) || contextPath.length() == 0) { - return ""; - } - - return pathFormat(contextPath); - } - - private String pathFormat(String path) { - if (path.startsWith(SEPARATOR)) { - return path; - } else { - return SEPARATOR + path; - } - } - - @Override - public String toString() { - return "PathMatcher{" + "path='" - + path + '\'' + ", version='" - + version + '\'' + ", group='" - + group + '\'' + ", port=" - + port + ", hasPathVariable=" - + hasPathVariable + ", contextPath='" - + contextPath + '\'' + ", httpMethod='" - + httpMethod + '\'' + '}'; - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/PathUtil.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/PathUtil.java deleted file mode 100644 index 90cc7cd8fad..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/PathUtil.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest; - -import org.apache.dubbo.metadata.MetadataConstants; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * is used to parse url pathVariable - *

- * String[] splits= url.split("/") - * List strings = Arrays.asList(split); - * strings.set(UrlSplitIndex, (String) args.get(argIndex)); - */ -public class PathUtil { - private static final String SEPARATOR = MetadataConstants.PATH_SEPARATOR; - - /** - * generate real path from rawPath according to argInfo and method args - * - * @param rawPath - * @param argInfos - * @param args - * @return - */ - public static String resolvePathVariable(String rawPath, List argInfos, List args) { - - String[] split = rawPath.split(SEPARATOR); - - List strings = Arrays.asList(split); - - List pathArgInfos = new ArrayList<>(); - - for (ArgInfo argInfo : argInfos) { - if (ParamType.PATH.supportAnno(argInfo.getParamAnnotationType())) { - pathArgInfos.add(argInfo); - } - } - - for (ArgInfo pathArgInfo : pathArgInfos) { - strings.set(pathArgInfo.getUrlSplitIndex(), String.valueOf(args.get(pathArgInfo.getIndex()))); - } - - String pat = SEPARATOR; - - for (String string : strings) { - - if (string.length() == 0) { - continue; - } - - pat = pat + string + SEPARATOR; - } - - if (pat.endsWith(SEPARATOR)) { - pat = pat.substring(0, pat.lastIndexOf(SEPARATOR)); - } - - return pat; - } - - /** - * parse pathVariable index from url by annotation info - * - * @param rawPath - * @param argInfos - */ - public static void setArgInfoSplitIndex(String rawPath, List argInfos) { - String[] split = rawPath.split(SEPARATOR); - - List pathPairs = new ArrayList<>(); - - for (ArgInfo argInfo : argInfos) { - if (ParamType.PATH.supportAnno(argInfo.getParamAnnotationType())) { - pathPairs.add(new PathPair(argInfo)); - } - } - - for (int i = 0; i < split.length; i++) { - String s = split[i]; - for (PathPair pathPair : pathPairs) { - boolean match = pathPair.match(s); - if (match) { - pathPair.setArgInfoSplitIndex(i); - } - } - } - } - - public static class PathPair { - - String value; - - ArgInfo argInfo; - - public PathPair(ArgInfo argInfo) { - this.argInfo = argInfo; - this.value = argInfo.getAnnotationNameAttribute(); - } - - public String getPatten() { - return "{" + value + "}"; - } - - public String getLeftPatten() { - return "{" + value; - } - - public String getRightPatten() { - return "}"; - } - - public boolean match(String value) { - return getPatten().equals(value) // for : {id} - || (value.startsWith(getLeftPatten()) && value.endsWith(getRightPatten())); // for : {id: \d+} - } - - public String getValue() { - return value; - } - - public void setArgInfo(ArgInfo argInfo) { - this.argInfo = argInfo; - } - - public void setArgInfoSplitIndex(int urlSplitIndex) { - this.argInfo.setUrlSplitIndex(urlSplitIndex); - } - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/RequestMetadata.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/RequestMetadata.java deleted file mode 100644 index bdac2575e4f..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/RequestMetadata.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest; - -import org.apache.dubbo.common.utils.CollectionUtils; - -import java.io.Serializable; -import java.util.Collection; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -import static java.util.Collections.unmodifiableMap; -import static org.apache.dubbo.common.utils.PathUtils.normalize; -import static org.apache.dubbo.common.utils.StringUtils.SLASH; -import static org.apache.dubbo.common.utils.StringUtils.isBlank; - -/** - * The metadata class for REST request - * - * @since 2.7.6 - */ -public class RequestMetadata implements Serializable { - - private static final long serialVersionUID = -240099840085329958L; - - private String method; - - private String path; - - private Map> params = new LinkedHashMap<>(); - - private Map> headers = new LinkedHashMap<>(); - - private Set consumes = new LinkedHashSet<>(); - - private Set produces = new LinkedHashSet<>(); - - /** - * Default Constructor - */ - public RequestMetadata() {} - - public String getMethod() { - return method; - } - - public void setMethod(String method) { - this.method = method == null ? null : method.toUpperCase(); - } - - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = normalize(path); - - if (!path.startsWith(SLASH)) { - this.path = SLASH + path; - } - } - - public Map> getParams() { - return unmodifiableMap(params); - } - - public void setParams(Map> params) { - params(params); - } - - private static void add(Map> multiValueMap, String key, String value) { - if (isBlank(key)) { - return; - } - List values = get(multiValueMap, key, true); - values.add(value); - } - - private static > void addAll( - Map> multiValueMap, Map source) { - for (Map.Entry entry : source.entrySet()) { - String key = entry.getKey(); - for (String value : entry.getValue()) { - add(multiValueMap, key, value); - } - } - } - - private static String getFirst(Map> multiValueMap, String key) { - List values = get(multiValueMap, key); - return CollectionUtils.isNotEmpty(values) ? values.get(0) : null; - } - - private static List get(Map> multiValueMap, String key) { - return get(multiValueMap, key, false); - } - - private static List get(Map> multiValueMap, String key, boolean createIfAbsent) { - return createIfAbsent ? multiValueMap.computeIfAbsent(key, k -> new LinkedList<>()) : multiValueMap.get(key); - } - - public Map> getHeaders() { - return unmodifiableMap(headers); - } - - public void setHeaders(Map> headers) { - headers(headers); - } - - public Set getConsumes() { - return consumes; - } - - public void setConsumes(Set consumes) { - this.consumes = consumes; - } - - public Set getProduces() { - return produces; - } - - public void setProduces(Set produces) { - this.produces = produces; - } - - public Set getParamNames() { - return new HashSet<>(params.keySet()); - } - - public Set getHeaderNames() { - return new HashSet<>(headers.keySet()); - } - - // public List getConsumeMediaTypes() { - // return toMediaTypes(consumes); - // } - // - // public List getProduceMediaTypes() { - // return toMediaTypes(produces); - // } - - public String getParameter(String name) { - return getFirst(params, name); - } - - public String getHeader(String name) { - return getFirst(headers, name); - } - - public RequestMetadata addParam(String name, String value) { - add(params, name, value); - return this; - } - - public RequestMetadata addHeader(String name, String value) { - add(headers, name, value); - return this; - } - - private > RequestMetadata params(Map params) { - addAll(this.params, params); - return this; - } - - private > RequestMetadata headers(Map> headers) { - if (headers != null && !headers.isEmpty()) { - Map> httpHeaders = new LinkedHashMap<>(); - // Add all headers - addAll(httpHeaders, headers); - // Handles "Content-Type" and "Accept" headers if present - // mediaTypes(httpHeaders, HttpHeaders.CONTENT_TYPE, this.consumes); - // mediaTypes(httpHeaders, HttpHeaders.ACCEPT, this.produces); - this.headers.putAll(httpHeaders); - } - return this; - } - - public void appendContextPathFromUrl(String contextPathFromUrl) { - if (contextPathFromUrl == null) { - return; - } - setPath(contextPathFromUrl + path); - } - - public boolean methodAllowed(String method) { - return method != null && method.equals(this.method); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof RequestMetadata)) { - return false; - } - RequestMetadata that = (RequestMetadata) o; - return Objects.equals(method, that.method) - && Objects.equals(path, that.path) - && Objects.equals(consumes, that.consumes) - && Objects.equals(produces, that.produces) - && - // Metadata should not compare the values - Objects.equals(getParamNames(), that.getParamNames()) - && Objects.equals(getHeaderNames(), that.getHeaderNames()); - } - - @Override - public int hashCode() { - // The values of metadata should not use for the hashCode() method - return Objects.hash(method, path, consumes, produces, getParamNames(), getHeaderNames()); - } - - @Override - public String toString() { - return "RequestMetadata{" + "method='" + method + '\'' + ", path='" + path + '\'' - + ", params=" + params + ", headers=" + headers + ", consumes=" + consumes - + ", produces=" + produces + '}'; - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/RestMetadataConstants.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/RestMetadataConstants.java deleted file mode 100644 index 97bca97595f..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/RestMetadataConstants.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest; - -import java.lang.annotation.Annotation; - -import static org.apache.dubbo.common.utils.ClassUtils.getClassLoader; -import static org.apache.dubbo.common.utils.ClassUtils.resolveClass; - -/** - * The REST Metadata Constants definition interface - * - * @since 2.7.6 - */ -public interface RestMetadataConstants { - - /** - * The encoding of metadata - */ - String METADATA_ENCODING = "UTF-8"; - - /** - * {@link ServiceRestMetadata} Resource PATH - */ - String SERVICE_REST_METADATA_RESOURCE_PATH = "META-INF/dubbo/service-rest-metadata.json"; - - /** - * JAX-RS - */ - interface JAX_RS { - - /** - * The annotation class name of @Path - */ - String PATH_ANNOTATION_CLASS_NAME = "javax.ws.rs.Path"; - - /** - * The annotation class name of @HttpMethod - */ - String HTTP_METHOD_ANNOTATION_CLASS_NAME = "javax.ws.rs.HttpMethod"; - - /** - * The annotation class name of @Produces - */ - String PRODUCES_ANNOTATION_CLASS_NAME = "javax.ws.rs.Produces"; - - /** - * The annotation class name of @Consumes - */ - String CONSUMES_ANNOTATION_CLASS_NAME = "javax.ws.rs.Consumes"; - - /** - * The annotation class name of @DefaultValue - */ - String DEFAULT_VALUE_ANNOTATION_CLASS_NAME = "javax.ws.rs.DefaultValue"; - - /** - * The annotation class name of @FormParam - */ - String FORM_PARAM_ANNOTATION_CLASS_NAME = "javax.ws.rs.FormParam"; - - /** - * The annotation class name of @HeaderParam - */ - String HEADER_PARAM_ANNOTATION_CLASS_NAME = "javax.ws.rs.HeaderParam"; - - /** - * The annotation class name of @MatrixParam - */ - String MATRIX_PARAM_ANNOTATION_CLASS_NAME = "javax.ws.rs.MatrixParam"; - - /** - * The annotation class name of @QueryParam - */ - String QUERY_PARAM_ANNOTATION_CLASS_NAME = "javax.ws.rs.QueryParam"; - - /** - * The annotation class name of @Body - */ - String REST_EASY_BODY_ANNOTATION_CLASS_NAME = "org.jboss.resteasy.annotations.Body"; - - /** - * The annotation class name of @Form - */ - String REST_EASY_FORM_BODY_ANNOTATION_CLASS_NAME = "org.jboss.resteasy.annotations.Form"; - - /** - * The annotation class name of @PathParam - */ - String PATH_PARAM_ANNOTATION_CLASS_NAME = "javax.ws.rs.PathParam"; - } - - /** - * Spring MVC - */ - interface SPRING_MVC { - - /** - * The annotation class name of @Controller - */ - String CONTROLLER_ANNOTATION_CLASS_NAME = "org.springframework.stereotype.Controller"; - - /** - * The annotation class name of @FeignClient - */ - String FEIGN_CLIENT_CLASS_NAME = "org.springframework.cloud.openfeign.FeignClient"; - - /** - * The annotation class name of @RequestMapping - */ - String REQUEST_MAPPING_ANNOTATION_CLASS_NAME = "org.springframework.web.bind.annotation.RequestMapping"; - - /** - * The annotation class name of @RequestHeader - */ - String REQUEST_HEADER_ANNOTATION_CLASS_NAME = "org.springframework.web.bind.annotation.RequestHeader"; - - /** - * The annotation class name of @RequestParam - */ - String REQUEST_PARAM_ANNOTATION_CLASS_NAME = "org.springframework.web.bind.annotation.RequestParam"; - - /** - * The annotation class name of @RequestBody - */ - String REQUEST_BODY_ANNOTATION_CLASS_NAME = "org.springframework.web.bind.annotation.RequestBody"; - - /** - * The annotation class name of @PathVariable - */ - String PATH_VARIABLE_ANNOTATION_CLASS_NAME = "org.springframework.web.bind.annotation.PathVariable"; - - /** - * The class of @Controller - * - * @since 2.7.9 - */ - Class CONTROLLER_ANNOTATION_CLASS = - (Class) resolveClass(CONTROLLER_ANNOTATION_CLASS_NAME, getClassLoader()); - - /** - * The class of @RequestMapping - * - * @since 2.7.9 - */ - Class REQUEST_MAPPING_ANNOTATION_CLASS = - (Class) resolveClass(REQUEST_MAPPING_ANNOTATION_CLASS_NAME, getClassLoader()); - - /** - * The annotation class name of AnnotatedElementUtils - * - * @since 2.7.9 - */ - String ANNOTATED_ELEMENT_UTILS_CLASS_NAME = "org.springframework.core.annotation.AnnotatedElementUtils"; - - /** - * The class of AnnotatedElementUtils - * - * @since 2.7.9 - */ - Class ANNOTATED_ELEMENT_UTILS_CLASS = resolveClass(ANNOTATED_ELEMENT_UTILS_CLASS_NAME, getClassLoader()); - - Class FEIGN_CLIENT_CLASS = - (Class) resolveClass(FEIGN_CLIENT_CLASS_NAME, getClassLoader()); - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/RestMethodMetadata.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/RestMethodMetadata.java deleted file mode 100644 index e820b5fa75a..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/RestMethodMetadata.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest; - -import org.apache.dubbo.metadata.definition.model.MethodDefinition; -import org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver; -import org.apache.dubbo.metadata.rest.tag.NoAnnotationTag; - -import java.io.Serializable; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -import static java.util.Collections.emptyList; - -/** - * The metadata class for {@link RequestMetadata HTTP(REST) request} and - * its binding {@link MethodDefinition method definition} - * - * @since 2.7.6 - */ -public class RestMethodMetadata implements Serializable { - - private static final long serialVersionUID = 2935252016200830694L; - - private MethodDefinition method; - - private RequestMetadata request; - - private Integer urlIndex; - - private Integer bodyIndex; - - private Integer headerMapIndex; - - private String bodyType; - - private Map> indexToName; - - private List formParams; - - private Map indexToEncoded; - - private List argInfos; - - private Method reflectMethod; - - /** - * make a distinction between mvc & resteasy - */ - private Class codeStyle; - - public MethodDefinition getMethod() { - if (method == null) { - method = new MethodDefinition(); - } - return method; - } - - public void setMethod(MethodDefinition method) { - this.method = method; - } - - public RequestMetadata getRequest() { - if (request == null) { - request = new RequestMetadata(); - } - return request; - } - - public void setRequest(RequestMetadata request) { - this.request = request; - } - - public Integer getUrlIndex() { - return urlIndex; - } - - public void setUrlIndex(Integer urlIndex) { - this.urlIndex = urlIndex; - } - - public Integer getBodyIndex() { - return bodyIndex; - } - - public void setBodyIndex(Integer bodyIndex) { - this.bodyIndex = bodyIndex; - } - - public Integer getHeaderMapIndex() { - return headerMapIndex; - } - - public void setHeaderMapIndex(Integer headerMapIndex) { - this.headerMapIndex = headerMapIndex; - } - - public String getBodyType() { - return bodyType; - } - - public void setBodyType(String bodyType) { - this.bodyType = bodyType; - } - - public Map> getIndexToName() { - if (indexToName == null) { - indexToName = new LinkedHashMap<>(); - } - return indexToName; - } - - public void setIndexToName(Map> indexToName) { - this.indexToName = indexToName; - } - - public void addIndexToName(Integer index, String name) { - if (index == null) { - return; - } - - if (name.startsWith("arg") && name.endsWith(index.toString())) { - // Ignore this value because of the Java byte-code without the metadata of method parameters - return; - } - - Map> indexToName = getIndexToName(); - Collection parameterNames = indexToName.computeIfAbsent(index, i -> new ArrayList<>(1)); - parameterNames.add(name); - } - - public boolean hasIndexedName(Integer index, String name) { - Map> indexToName = getIndexToName(); - return indexToName.getOrDefault(index, emptyList()).contains(name); - } - - public List getFormParams() { - return formParams; - } - - public void setFormParams(List formParams) { - this.formParams = formParams; - } - - public Map getIndexToEncoded() { - return indexToEncoded; - } - - public void setIndexToEncoded(Map indexToEncoded) { - this.indexToEncoded = indexToEncoded; - } - - public List getArgInfos() { - if (argInfos == null) { - argInfos = new ArrayList<>(); - } - return argInfos; - } - - public void addArgInfo(ArgInfo argInfo) { - if (currentCodeStyleIsNoAnnotationMode()) { - argInfo.setParamAnnotationType(NoAnnotationTag.class); - } - getArgInfos().add(argInfo); - } - - public Method getReflectMethod() { - return reflectMethod; - } - - public void setReflectMethod(Method reflectMethod) { - this.reflectMethod = reflectMethod; - } - - public Class getCodeStyle() { - return codeStyle; - } - - public void setCodeStyle(Class codeStyle) { - this.codeStyle = codeStyle; - } - - public boolean currentCodeStyleIsNoAnnotationMode() { - return NoAnnotationServiceRestMetadataResolver.class.equals(getCodeStyle()); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof RestMethodMetadata)) { - return false; - } - RestMethodMetadata that = (RestMethodMetadata) o; - return Objects.equals(getMethod(), that.getMethod()) - && Objects.equals(getRequest(), that.getRequest()) - && Objects.equals(getUrlIndex(), that.getUrlIndex()) - && Objects.equals(getBodyIndex(), that.getBodyIndex()) - && Objects.equals(getHeaderMapIndex(), that.getHeaderMapIndex()) - && Objects.equals(getBodyType(), that.getBodyType()) - && Objects.equals(getFormParams(), that.getFormParams()) - && Objects.equals(getIndexToEncoded(), that.getIndexToEncoded()); - } - - @Override - public int hashCode() { - return Objects.hash( - getMethod(), - getRequest(), - getUrlIndex(), - getBodyIndex(), - getHeaderMapIndex(), - getBodyType(), - getFormParams(), - getIndexToEncoded()); - } - - @Override - public String toString() { - return "RestMethodMetadata{" + "method=" - + method + ", request=" - + request + ", urlIndex=" - + urlIndex + ", bodyIndex=" - + bodyIndex + ", headerMapIndex=" - + headerMapIndex + ", bodyType='" - + bodyType + '\'' + ", indexToName=" - + indexToName + ", formParams=" - + formParams + ", indexToEncoded=" - + indexToEncoded + ", argInfos=" - + argInfos + ", reflectMethod=" - + reflectMethod + ", codeStyle=" - + codeStyle + '}'; - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadata.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadata.java deleted file mode 100644 index f18da310978..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadata.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest; - -import org.apache.dubbo.common.utils.PathUtils; -import org.apache.dubbo.metadata.ParameterTypesComparator; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -/** - * The metadata class for {@link RequestMetadata HTTP(REST) request} and - * its binding Dubbo service metadata - * - * @since 2.7.6 - */ -public class ServiceRestMetadata implements Serializable { - - private static final long serialVersionUID = -4549723140727443569L; - - private String serviceInterface; - - private String version; - - private String group; - - private Set meta; - - private Integer port; - - private boolean consumer; - - private String contextPathFromUrl; - - /** - * make a distinction between mvc & resteasy - */ - private Class codeStyle; - - private Map pathToServiceMapContainPathVariable = new HashMap<>(); - private Map pathToServiceMapUnContainPathVariable = new HashMap<>(); - private Map> methodToServiceMap = new HashMap<>(); - - public ServiceRestMetadata(String serviceInterface, String version, String group, boolean consumer) { - this.serviceInterface = serviceInterface; - this.version = version; - this.group = group; - this.consumer = consumer; - } - - public ServiceRestMetadata() {} - - public ServiceRestMetadata(String serviceInterface, String version, String group) { - this(serviceInterface, version, group, false); - } - - public String getServiceInterface() { - return serviceInterface; - } - - public void setServiceInterface(String serviceInterface) { - this.serviceInterface = serviceInterface; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getGroup() { - return group; - } - - public void setGroup(String group) { - this.group = group; - } - - public Set getMeta() { - if (meta == null) { - meta = new LinkedHashSet<>(); - } - return meta; - } - - public void setMeta(Set meta) { - this.meta = meta; - } - - public void addRestMethodMetadata(RestMethodMetadata restMethodMetadata) { - PathMatcher pathMather = new PathMatcher( - restMethodMetadata.getRequest().getPath(), - this.getVersion(), - this.getGroup(), - this.getPort(), - restMethodMetadata.getRequest().getMethod()); - pathMather.setMethod(restMethodMetadata.getReflectMethod()); - addPathToServiceMap(pathMather, restMethodMetadata); - addMethodToServiceMap(restMethodMetadata); - getMeta().add(restMethodMetadata); - } - - public Map getPathContainPathVariableToServiceMap() { - return pathToServiceMapContainPathVariable; - } - - public Map getPathUnContainPathVariableToServiceMap() { - return pathToServiceMapUnContainPathVariable; - } - - public void addPathToServiceMap(PathMatcher pathMather, RestMethodMetadata restMethodMetadata) { - - if (pathMather.hasPathVariable()) { - doublePathCheck(pathToServiceMapContainPathVariable, pathMather, restMethodMetadata, true); - } else { - doublePathCheck(pathToServiceMapUnContainPathVariable, pathMather, restMethodMetadata, false); - } - } - - private void doublePathCheck( - Map pathMatcherRestMethodMetadataMap, - PathMatcher pathMather, - RestMethodMetadata restMethodMetadata, - boolean containPathVariable) { - if (pathMatcherRestMethodMetadataMap.containsKey(pathMather)) { - if (containPathVariable) { - throw new IllegalArgumentException( - "dubbo rest metadata resolve double path error,and contain path variable is: " + pathMather - + ", rest method metadata is: " + restMethodMetadata); - - } else { - throw new IllegalArgumentException( - "dubbo rest metadata resolve double path error,and do not contain path variable is: " - + pathMather + ", rest method metadata is: " + restMethodMetadata); - } - } - - pathMatcherRestMethodMetadataMap.put(pathMather, restMethodMetadata); - } - - public Integer getPort() { - return port; - } - - public void setPort(Integer port) { - this.port = port; - setPort(port, getPathContainPathVariableToServiceMap()); - setPort(port, getPathUnContainPathVariableToServiceMap()); - } - - private void setPort(Integer port, Map pathToServiceMapContainPathVariable) { - for (PathMatcher pathMather : pathToServiceMapContainPathVariable.keySet()) { - pathMather.setPort(port); - } - } - - public boolean isConsumer() { - return consumer; - } - - public void setConsumer(boolean consumer) { - this.consumer = consumer; - } - - public Map> getMethodToServiceMap() { - return methodToServiceMap; - } - - public void addMethodToServiceMap(RestMethodMetadata restMethodMetadata) { - if (this.methodToServiceMap == null) { - this.methodToServiceMap = new HashMap<>(); - } - - this.methodToServiceMap - .computeIfAbsent(restMethodMetadata.getReflectMethod().getName(), k -> new HashMap<>()) - .put( - ParameterTypesComparator.getInstance( - restMethodMetadata.getReflectMethod().getParameterTypes()), - restMethodMetadata); - } - - public Class getCodeStyle() { - return codeStyle; - } - - public void setCodeStyle(Class codeStyle) { - this.codeStyle = codeStyle; - } - - public String getContextPathFromUrl() { - return contextPathFromUrl == null ? "" : contextPathFromUrl; - } - - public void setContextPathFromUrl(String contextPathFromUrl) { - this.contextPathFromUrl = PathUtils.normalize(contextPathFromUrl); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof ServiceRestMetadata)) { - return false; - } - ServiceRestMetadata that = (ServiceRestMetadata) o; - return Objects.equals(getServiceInterface(), that.getServiceInterface()) - && Objects.equals(getVersion(), that.getVersion()) - && Objects.equals(getGroup(), that.getGroup()) - && Objects.equals(getMeta(), that.getMeta()) - && Objects.equals(getPort(), that.getPort()); - } - - @Override - public int hashCode() { - return Objects.hash(getServiceInterface(), getVersion(), getGroup(), getMeta(), getPort()); - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("ServiceRestMetadata{"); - sb.append("serviceInterface='").append(serviceInterface).append('\''); - sb.append(", version='").append(version).append('\''); - sb.append(", group='").append(group).append('\''); - sb.append(", meta=").append(meta); - sb.append(", port=").append(port); - sb.append('}'); - return sb.toString(); - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadataReader.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadataReader.java deleted file mode 100644 index 6a590260c32..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadataReader.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest; - -import org.apache.dubbo.common.extension.SPI; - -import java.util.List; - -/** - * An interface to read {@link ServiceRestMetadata} - * - * @see ServiceRestMetadata - * @since 2.7.6 - */ -@SPI -public interface ServiceRestMetadataReader { - - /** - * Read the instances of {@link ServiceRestMetadata} - * - * @return non-null - */ - List read(); -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadataResolver.java deleted file mode 100644 index b36ba51decd..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadataResolver.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest; - -import org.apache.dubbo.common.extension.ExtensionScope; -import org.apache.dubbo.common.extension.SPI; - -/** - * The interface to resolve the {@link ServiceRestMetadata REST metadata} from the specified - * Dubbo Service interface or type. - * - * @since 2.7.6 - */ -@SPI(scope = ExtensionScope.APPLICATION) -public interface ServiceRestMetadataResolver { - - /** - * Support to resolve {@link ServiceRestMetadata REST metadata} or not - * - * @param serviceType Dubbo Service interface or type - * @return If supports, return true, or false - */ - boolean supports(Class serviceType); - - boolean supports(Class serviceType, boolean consumer); - - /** - * Resolve the {@link ServiceRestMetadata REST metadata} from the specified - * Dubbo Service interface or type - * - * @param serviceType Dubbo Service interface or type - * @return - */ - ServiceRestMetadata resolve(Class serviceType); - - ServiceRestMetadata resolve(Class serviceType, ServiceRestMetadata serviceRestMetadata); -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/SpringMvcClassConstants.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/SpringMvcClassConstants.java deleted file mode 100644 index d16ba215234..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/SpringMvcClassConstants.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest; - -import static org.apache.dubbo.common.utils.ClassUtils.getClassLoader; -import static org.apache.dubbo.common.utils.ClassUtils.resolveClass; - -public interface SpringMvcClassConstants extends RestMetadataConstants.SPRING_MVC { - /** - * The annotation class of @RequestMapping - */ - Class REQUEST_MAPPING_ANNOTATION_CLASS = resolveClass(REQUEST_MAPPING_ANNOTATION_CLASS_NAME, getClassLoader()); - - /** - * The annotation class of @RequestHeader - */ - Class REQUEST_HEADER_ANNOTATION_CLASS = resolveClass(REQUEST_HEADER_ANNOTATION_CLASS_NAME, getClassLoader()); - - /** - * The annotation class of @RequestParam - */ - Class REQUEST_PARAM_ANNOTATION_CLASS = resolveClass(REQUEST_PARAM_ANNOTATION_CLASS_NAME, getClassLoader()); - - /** - * The annotation class of @RequestBody - */ - Class REQUEST_BODY_ANNOTATION_CLASS = resolveClass(REQUEST_BODY_ANNOTATION_CLASS_NAME, getClassLoader()); - - /** - * The annotation class of @RequestBody - */ - Class PATH_VARIABLE_ANNOTATION_CLASS = resolveClass(PATH_VARIABLE_ANNOTATION_CLASS_NAME, getClassLoader()); -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/BodyParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/BodyParameterProcessor.java deleted file mode 100644 index 2ee067091b6..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/BodyParameterProcessor.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.jaxrs; - -import org.apache.dubbo.metadata.rest.AbstractAnnotatedMethodParameterProcessor; -import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor; -import org.apache.dubbo.metadata.rest.ArgInfo; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.lang.reflect.Parameter; - -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.REST_EASY_BODY_ANNOTATION_CLASS_NAME; - -/** - * The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @FormParam - * - * @since 2.7.6 - */ -public class BodyParameterProcessor extends AbstractAnnotatedMethodParameterProcessor { - - @Override - public String getAnnotationName() { - return REST_EASY_BODY_ANNOTATION_CLASS_NAME; - } - - @Override - public void process( - Annotation annotation, - Parameter parameter, - int parameterIndex, - Method method, - Class serviceType, - Class serviceInterfaceClass, - RestMethodMetadata restMethodMetadata) { - ArgInfo argInfo = ArgInfo.build(parameterIndex, parameter).setParamAnnotationType(getAnnotationClass()); - restMethodMetadata.addArgInfo(argInfo); - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/DefaultValueParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/DefaultValueParameterProcessor.java deleted file mode 100644 index 5b3a4ee2a26..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/DefaultValueParameterProcessor.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.jaxrs; - -import org.apache.dubbo.metadata.rest.AbstractAnnotatedMethodParameterProcessor; -import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor; -import org.apache.dubbo.metadata.rest.RequestMetadata; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.lang.reflect.Parameter; -import java.util.List; -import java.util.Map; - -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.DEFAULT_VALUE_ANNOTATION_CLASS_NAME; - -/** - * The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @DefaultValue - * * - * - * @since 2.7.6 - */ -public class DefaultValueParameterProcessor extends AbstractAnnotatedMethodParameterProcessor { - - @Override - public String getAnnotationName() { - return DEFAULT_VALUE_ANNOTATION_CLASS_NAME; - } - - @Override - protected void process( - String annotationValue, - String defaultValue, - Annotation annotation, - Parameter parameter, - int parameterIndex, - Method method, - RestMethodMetadata restMethodMetadata) { - RequestMetadata requestMetadata = restMethodMetadata.getRequest(); - - // process the request parameters - setDefaultValue(requestMetadata.getParams(), defaultValue, annotationValue); - // process the request headers - setDefaultValue(requestMetadata.getHeaders(), defaultValue, annotationValue); - } - - private void setDefaultValue(Map> source, String placeholderValue, String defaultValue) { - OUTTER: - for (Map.Entry> entry : source.entrySet()) { - List values = entry.getValue(); - int size = values.size(); - for (int i = 0; i < size; i++) { - String value = values.get(i); - if (placeholderValue.equals(value)) { - values.set(i, defaultValue); - break OUTTER; - } - } - } - } - - @Override - public int getPriority() { - return MIN_PRIORITY; - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/FormBodyParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/FormBodyParameterProcessor.java deleted file mode 100644 index 26483885bf1..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/FormBodyParameterProcessor.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.jaxrs; - -import org.apache.dubbo.metadata.rest.AbstractAnnotatedMethodParameterProcessor; -import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.lang.reflect.Parameter; - -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.REST_EASY_FORM_BODY_ANNOTATION_CLASS_NAME; -import static org.apache.dubbo.metadata.rest.media.MediaType.APPLICATION_FORM_URLENCODED_VALUE; - -/** - * The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @FormParam - * - * @since 2.7.6 - */ -public class FormBodyParameterProcessor extends AbstractAnnotatedMethodParameterProcessor { - - @Override - public String getAnnotationName() { - return REST_EASY_FORM_BODY_ANNOTATION_CLASS_NAME; - } - - @Override - public void process( - Annotation annotation, - Parameter parameter, - int parameterIndex, - Method method, - Class serviceType, - Class serviceInterfaceClass, - RestMethodMetadata restMethodMetadata) { - super.process( - annotation, parameter, parameterIndex, method, serviceType, serviceInterfaceClass, restMethodMetadata); - restMethodMetadata.getRequest().getConsumes().add(APPLICATION_FORM_URLENCODED_VALUE.value); - } - - @Override - protected String getAnnotationValue(Annotation annotation, Parameter parameter, int parameterIndex) { - return null; - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/FormParamParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/FormParamParameterProcessor.java deleted file mode 100644 index 6dae712118f..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/FormParamParameterProcessor.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.jaxrs; - -import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor; - -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.FORM_PARAM_ANNOTATION_CLASS_NAME; - -/** - * The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @FormParam - * - * @since 2.7.6 - */ -public class FormParamParameterProcessor extends ParamAnnotationParameterProcessor { - - @Override - public String getAnnotationName() { - return FORM_PARAM_ANNOTATION_CLASS_NAME; - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/HeaderParamParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/HeaderParamParameterProcessor.java deleted file mode 100644 index 9fc5299e831..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/HeaderParamParameterProcessor.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.jaxrs; - -import org.apache.dubbo.metadata.rest.AbstractAnnotatedMethodParameterProcessor; -import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor; -import org.apache.dubbo.metadata.rest.RequestMetadata; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.lang.reflect.Parameter; - -import static org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor.buildDefaultValue; -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.HEADER_PARAM_ANNOTATION_CLASS_NAME; - -/** - * The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @HeaderParam - * - * @since 2.7.6 - */ -public class HeaderParamParameterProcessor extends AbstractAnnotatedMethodParameterProcessor { - - @Override - public String getAnnotationName() { - return HEADER_PARAM_ANNOTATION_CLASS_NAME; - } - - @Override - protected void process( - String headerName, - String defaultValue, - Annotation annotation, - Parameter parameter, - int parameterIndex, - Method method, - RestMethodMetadata restMethodMetadata) { - RequestMetadata requestMetadata = restMethodMetadata.getRequest(); - // Add the placeholder as header value - requestMetadata.addHeader(headerName, buildDefaultValue(parameterIndex)); - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/JAXRSServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/JAXRSServiceRestMetadataResolver.java deleted file mode 100644 index d344c279fce..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/JAXRSServiceRestMetadataResolver.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.jaxrs; - -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.metadata.rest.AbstractServiceRestMetadataResolver; -import org.apache.dubbo.metadata.rest.ServiceRestMetadataResolver; -import org.apache.dubbo.rpc.model.ApplicationModel; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.util.Set; -import java.util.stream.Stream; - -import static org.apache.dubbo.common.utils.AnnotationUtils.findAnnotation; -import static org.apache.dubbo.common.utils.AnnotationUtils.findMetaAnnotation; -import static org.apache.dubbo.common.utils.AnnotationUtils.getValue; -import static org.apache.dubbo.common.utils.AnnotationUtils.isAnnotationPresent; -import static org.apache.dubbo.common.utils.PathUtils.buildPath; -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.CONSUMES_ANNOTATION_CLASS_NAME; -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.HTTP_METHOD_ANNOTATION_CLASS_NAME; -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.PATH_ANNOTATION_CLASS_NAME; -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.PRODUCES_ANNOTATION_CLASS_NAME; - -/** - * JAX-RS {@link ServiceRestMetadataResolver} implementation - * - * @since 2.7.6 - */ -@Activate(order = 100) -public class JAXRSServiceRestMetadataResolver extends AbstractServiceRestMetadataResolver { - public JAXRSServiceRestMetadataResolver(ApplicationModel applicationModel) { - super(applicationModel); - } - - @Override - protected boolean supports0(Class serviceType) { - return isAnnotationPresent(serviceType, PATH_ANNOTATION_CLASS_NAME) - // method @Path - || isServiceMethodAnnotationPresent(serviceType, PATH_ANNOTATION_CLASS_NAME); - } - - @Override - protected boolean isRestCapableMethod(Method serviceMethod, Class serviceType, Class serviceInterfaceClass) { - return isAnnotationPresent(serviceMethod, HTTP_METHOD_ANNOTATION_CLASS_NAME); - } - - @Override - protected String resolveRequestMethod(Method serviceMethod, Class serviceType, Class serviceInterfaceClass) { - Annotation httpMethod = findMetaAnnotation(serviceMethod, HTTP_METHOD_ANNOTATION_CLASS_NAME); - return getValue(httpMethod); - } - - @Override - protected String resolveRequestPath(Method serviceMethod, Class serviceType, Class serviceInterfaceClass) { - String requestBasePath = resolveRequestPathFromType(serviceType, serviceInterfaceClass); - String requestRelativePath = resolveRequestPathFromMethod(serviceMethod); - return buildPath(requestBasePath, requestRelativePath); - } - - private String resolveRequestPathFromType(Class serviceType, Class serviceInterfaceClass) { - Annotation path = findAnnotation(serviceType, PATH_ANNOTATION_CLASS_NAME); - if (path == null) { - path = findAnnotation(serviceInterfaceClass, PATH_ANNOTATION_CLASS_NAME); - } - return getValue(path); - } - - private String resolveRequestPathFromMethod(Method serviceMethod) { - Annotation path = findAnnotation(serviceMethod, PATH_ANNOTATION_CLASS_NAME); - return getValue(path); - } - - @Override - protected void processProduces( - Method serviceMethod, Class serviceType, Class serviceInterfaceClass, Set produces) { - addAnnotationValues(serviceMethod, PRODUCES_ANNOTATION_CLASS_NAME, produces); - addAnnotationValues(serviceType, PRODUCES_ANNOTATION_CLASS_NAME, produces); - addAnnotationValues(serviceInterfaceClass, PRODUCES_ANNOTATION_CLASS_NAME, produces); - } - - @Override - protected void processConsumes( - Method serviceMethod, Class serviceType, Class serviceInterfaceClass, Set consumes) { - addAnnotationValues(serviceMethod, CONSUMES_ANNOTATION_CLASS_NAME, consumes); - addAnnotationValues(serviceType, CONSUMES_ANNOTATION_CLASS_NAME, consumes); - addAnnotationValues(serviceInterfaceClass, CONSUMES_ANNOTATION_CLASS_NAME, consumes); - } - - private void addAnnotationValues(Method serviceMethod, String annotationAttributeName, Set result) { - Annotation annotation = findAnnotation(serviceMethod, annotationAttributeName); - String[] value = getValue(annotation); - if (value != null) { - Stream.of(value).forEach(result::add); - } - } - - private void addAnnotationValues(Class serviceType, String annotationAttributeName, Set result) { - Annotation annotation = findAnnotation(serviceType, annotationAttributeName); - String[] value = getValue(annotation); - if (value != null) { - Stream.of(value).forEach(result::add); - } - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/MatrixParamParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/MatrixParamParameterProcessor.java deleted file mode 100644 index a75284a6898..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/MatrixParamParameterProcessor.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.jaxrs; - -import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor; - -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.MATRIX_PARAM_ANNOTATION_CLASS_NAME; - -/** - * The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @MatrixParam - * - * @since 2.7.6 - */ -public class MatrixParamParameterProcessor extends ParamAnnotationParameterProcessor { - - @Override - public String getAnnotationName() { - return MATRIX_PARAM_ANNOTATION_CLASS_NAME; - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/ParamAnnotationParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/ParamAnnotationParameterProcessor.java deleted file mode 100644 index e2feefb9cb1..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/ParamAnnotationParameterProcessor.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.jaxrs; - -import org.apache.dubbo.metadata.rest.AbstractAnnotatedMethodParameterProcessor; -import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor; -import org.apache.dubbo.metadata.rest.RequestMetadata; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.lang.reflect.Parameter; - -/** - * The abstract {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @*Param - */ -public abstract class ParamAnnotationParameterProcessor extends AbstractAnnotatedMethodParameterProcessor { - - @Override - protected void process( - String name, - String defaultValue, - Annotation annotation, - Parameter parameter, - int parameterIndex, - Method method, - RestMethodMetadata restMethodMetadata) { - RequestMetadata requestMetadata = restMethodMetadata.getRequest(); - requestMetadata.addParam(name, defaultValue); - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/PathParamParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/PathParamParameterProcessor.java deleted file mode 100644 index 478182312ee..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/PathParamParameterProcessor.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.jaxrs; - -import org.apache.dubbo.metadata.rest.AbstractAnnotatedMethodParameterProcessor; -import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor; - -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.PATH_PARAM_ANNOTATION_CLASS_NAME; - -/** - * The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @PathParam - * - * @since 2.7.6 - */ -public class PathParamParameterProcessor extends AbstractAnnotatedMethodParameterProcessor { - - @Override - public String getAnnotationName() { - return PATH_PARAM_ANNOTATION_CLASS_NAME; - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/QueryParamParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/QueryParamParameterProcessor.java deleted file mode 100644 index ed6972f17ac..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/QueryParamParameterProcessor.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.jaxrs; - -import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor; - -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.QUERY_PARAM_ANNOTATION_CLASS_NAME; - -/** - * The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @QueryParam - * - * @since 2.7.6 - */ -public class QueryParamParameterProcessor extends ParamAnnotationParameterProcessor { - - @Override - public String getAnnotationName() { - return QUERY_PARAM_ANNOTATION_CLASS_NAME; - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/media/MediaType.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/media/MediaType.java deleted file mode 100644 index df59aa4961b..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/media/MediaType.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.media; - -import java.util.Arrays; -import java.util.List; - -public enum MediaType { - ALL_VALUE("*/*"), - APPLICATION_JSON_VALUE("application/json"), - APPLICATION_FORM_URLENCODED_VALUE("application/x-www-form-urlencoded"), - TEXT_PLAIN("text/plain"), - TEXT_XML("text/xml"), - OCTET_STREAM("application/octet-stream"), - ; - - MediaType(String value) { - this.value = value; - } - - public String value; - - public static String getAllContentType() { - - MediaType[] values = MediaType.values(); - - StringBuilder stringBuilder = new StringBuilder(); - - for (MediaType mediaType : values) { - stringBuilder.append(mediaType.value + " "); - } - return stringBuilder.toString(); - } - - public static List getSupportMediaTypes() { - return Arrays.asList( - APPLICATION_JSON_VALUE, APPLICATION_FORM_URLENCODED_VALUE, TEXT_PLAIN, TEXT_XML, OCTET_STREAM); - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/noannotaion/NoAnnotationServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/noannotaion/NoAnnotationServiceRestMetadataResolver.java deleted file mode 100644 index 61cb1abb625..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/noannotaion/NoAnnotationServiceRestMetadataResolver.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.metadata.rest.noannotaion; - -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.metadata.rest.AbstractServiceRestMetadataResolver; -import org.apache.dubbo.metadata.rest.ArgInfo; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; -import org.apache.dubbo.metadata.rest.media.MediaType; -import org.apache.dubbo.rpc.model.ApplicationModel; - -import java.lang.reflect.Method; -import java.lang.reflect.Parameter; -import java.util.Set; - -import static org.apache.dubbo.common.utils.PathUtils.buildPath; - -/** - * NoAnnotationServiceRestMetadataResolver - * - * @since 3.3 - */ -@Activate(order = Integer.MAX_VALUE) -public class NoAnnotationServiceRestMetadataResolver extends AbstractServiceRestMetadataResolver { - - private static final String CONTENT_TYPE = MediaType.APPLICATION_JSON_VALUE.value; - private static final String REQUEST_METHOD = "POST"; - - public NoAnnotationServiceRestMetadataResolver(ApplicationModel applicationModel) { - super(applicationModel); - } - - @Override - protected boolean supports0(Class serviceType) { - // class @Controller or @RequestMapping - return true; - } - - @Override - protected boolean isRestCapableMethod(Method serviceMethod, Class serviceType, Class serviceInterfaceClass) { - // method only match @RequestMapping - return true; - } - - @Override - protected String resolveRequestMethod(Method serviceMethod, Class serviceType, Class serviceInterfaceClass) { - - return REQUEST_METHOD; - } - - @Override - protected String resolveRequestPath(Method serviceMethod, Class serviceType, Class serviceInterfaceClass) { - - // use serviceInterfaceClass class name - return buildPath(serviceInterfaceClass.getName(), serviceMethod.getName()); - } - - @Override - protected void processProduces( - Method serviceMethod, Class serviceType, Class serviceInterfaceClass, Set produces) { - produces.add(CONTENT_TYPE); - } - - @Override - protected void processConsumes( - Method serviceMethod, Class serviceType, Class serviceInterfaceClass, Set consumes) { - consumes.add(CONTENT_TYPE); - } - - @Override - protected void processAnnotatedMethodParameter( - Parameter parameter, - int parameterIndex, - Method serviceMethod, - Class serviceType, - Class serviceInterfaceClass, - RestMethodMetadata metadata) { - ArgInfo argInfo = ArgInfo.build(parameterIndex, parameter); - metadata.addArgInfo(argInfo); - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/AbstractRequestAnnotationParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/AbstractRequestAnnotationParameterProcessor.java deleted file mode 100644 index 2eac157d671..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/AbstractRequestAnnotationParameterProcessor.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.springmvc; - -import org.apache.dubbo.common.utils.AnnotationUtils; -import org.apache.dubbo.metadata.rest.AbstractAnnotatedMethodParameterProcessor; -import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Parameter; -import java.util.Objects; - -import static org.apache.dubbo.common.utils.AnnotationUtils.getAttribute; - -/** - * The abstract {@link AnnotatedMethodParameterProcessor} implementation for Spring Web MVC's @Request* - */ -public abstract class AbstractRequestAnnotationParameterProcessor extends AbstractAnnotatedMethodParameterProcessor { - - @Override - protected String getAnnotationValue(Annotation annotation, Parameter parameter, int parameterIndex) { - // try to get "value" attribute first - String name = super.getAnnotationValue(annotation, parameter, parameterIndex); - - // try to get "name" attribute if required - if (isEmpty(name)) { - name = getAttribute(annotation, "name"); - } - - // finally , try to the name of parameter - if (isEmpty(name)) { - name = parameter.getName(); - } - - return name; - } - - @Override - protected String getDefaultValue(Annotation annotation, Parameter parameter, int parameterIndex) { - String attributeName = "defaultValue"; - String attributeValue = getAttribute(annotation, attributeName); - - if (isEmpty(attributeValue) || isDefaultValue(annotation, attributeName, attributeValue)) { - attributeValue = super.getDefaultValue(annotation, parameter, parameterIndex); - } - return attributeValue; - } - - private boolean isDefaultValue(Annotation annotation, String attributeName, Object attributeValue) { - String defaultValue = AnnotationUtils.getDefaultValue(annotation, attributeName); - return Objects.deepEquals(attributeValue, defaultValue); - } - - protected boolean isEmpty(String str) { - return str == null || str.isEmpty(); - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/FormBodyNoAnnotatedProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/FormBodyNoAnnotatedProcessor.java deleted file mode 100644 index 38dc88663ff..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/FormBodyNoAnnotatedProcessor.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.springmvc; - -import org.apache.dubbo.metadata.rest.AbstractNoAnnotatedParameterProcessor; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; -import org.apache.dubbo.metadata.rest.media.MediaType; -import org.apache.dubbo.metadata.rest.tag.BodyTag; - -import static org.apache.dubbo.metadata.rest.media.MediaType.APPLICATION_FORM_URLENCODED_VALUE; - -public class FormBodyNoAnnotatedProcessor extends AbstractNoAnnotatedParameterProcessor { - @Override - public MediaType consumerContentType() { - return APPLICATION_FORM_URLENCODED_VALUE; - } - - @Override - public String defaultAnnotationClassName(RestMethodMetadata restMethodMetadata) { - return BodyTag.class.getName(); - } - - @Override - protected boolean isFormContentType(RestMethodMetadata restMethodMetadata) { - return true; - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/JsonBodyNoAnnotatedProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/JsonBodyNoAnnotatedProcessor.java deleted file mode 100644 index 64df7adf51e..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/JsonBodyNoAnnotatedProcessor.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.springmvc; - -import org.apache.dubbo.metadata.rest.AbstractNoAnnotatedParameterProcessor; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; -import org.apache.dubbo.metadata.rest.media.MediaType; -import org.apache.dubbo.metadata.rest.tag.BodyTag; - -import static org.apache.dubbo.metadata.rest.media.MediaType.APPLICATION_JSON_VALUE; - -public class JsonBodyNoAnnotatedProcessor extends AbstractNoAnnotatedParameterProcessor { - @Override - public MediaType consumerContentType() { - return APPLICATION_JSON_VALUE; - } - - @Override - public String defaultAnnotationClassName(RestMethodMetadata restMethodMetadata) { - return BodyTag.class.getName(); - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/ParamNoAnnotatedProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/ParamNoAnnotatedProcessor.java deleted file mode 100644 index a591c289614..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/ParamNoAnnotatedProcessor.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.springmvc; - -import org.apache.dubbo.metadata.rest.AbstractNoAnnotatedParameterProcessor; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; -import org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver; -import org.apache.dubbo.metadata.rest.media.MediaType; -import org.apache.dubbo.metadata.rest.tag.BodyTag; -import org.apache.dubbo.metadata.rest.tag.ParamTag; - -import static org.apache.dubbo.metadata.rest.media.MediaType.ALL_VALUE; - -public class ParamNoAnnotatedProcessor extends AbstractNoAnnotatedParameterProcessor { - @Override - public MediaType consumerContentType() { - return ALL_VALUE; - } - - @Override - public String defaultAnnotationClassName(RestMethodMetadata restMethodMetadata) { - - if (JAXRSServiceRestMetadataResolver.class.equals(restMethodMetadata.getCodeStyle())) { - return BodyTag.class.getName(); - } - - return ParamTag.class.getName(); - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/PathVariableParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/PathVariableParameterProcessor.java deleted file mode 100644 index fe239f62215..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/PathVariableParameterProcessor.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.springmvc; - -import org.apache.dubbo.metadata.rest.AbstractAnnotatedMethodParameterProcessor; -import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Parameter; - -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SPRING_MVC.PATH_VARIABLE_ANNOTATION_CLASS_NAME; - -/** - * The {@link AnnotatedMethodParameterProcessor} implementation for Spring Web MVC's @PathVariable - */ -public class PathVariableParameterProcessor extends AbstractAnnotatedMethodParameterProcessor { - - @Override - public String getAnnotationName() { - return PATH_VARIABLE_ANNOTATION_CLASS_NAME; - } - - @Override - protected String getDefaultValue(Annotation annotation, Parameter parameter, int parameterIndex) { - return null; - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestBodyParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestBodyParameterProcessor.java deleted file mode 100644 index 0c93615e68b..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestBodyParameterProcessor.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.springmvc; - -import org.apache.dubbo.metadata.rest.AbstractAnnotatedMethodParameterProcessor; -import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Parameter; - -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SPRING_MVC.REQUEST_BODY_ANNOTATION_CLASS_NAME; - -/** - * The {@link AnnotatedMethodParameterProcessor} implementation for Spring Web MVC's @RequestBody - */ -public class RequestBodyParameterProcessor extends AbstractAnnotatedMethodParameterProcessor { - - @Override - public String getAnnotationName() { - return REQUEST_BODY_ANNOTATION_CLASS_NAME; - } - - @Override - protected String getAnnotationValue(Annotation annotation, Parameter parameter, int parameterIndex) { - return null; - } - - @Override - protected String getDefaultValue(Annotation annotation, Parameter parameter, int parameterIndex) { - return null; - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestHeaderParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestHeaderParameterProcessor.java deleted file mode 100644 index 1edb86fc050..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestHeaderParameterProcessor.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.metadata.rest.springmvc; - -import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.lang.reflect.Parameter; - -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SPRING_MVC.REQUEST_HEADER_ANNOTATION_CLASS_NAME; - -/** - * The {@link AnnotatedMethodParameterProcessor} implementation for Spring Web MVC's @RequestHeader - */ -public class RequestHeaderParameterProcessor extends AbstractRequestAnnotationParameterProcessor { - - @Override - public String getAnnotationName() { - return REQUEST_HEADER_ANNOTATION_CLASS_NAME; - } - - @Override - protected void process( - String name, - String defaultValue, - Annotation annotation, - Parameter parameter, - int parameterIndex, - Method method, - RestMethodMetadata restMethodMetadata) { - restMethodMetadata.getRequest().addHeader(name, defaultValue); - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestParamParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestParamParameterProcessor.java deleted file mode 100644 index ad457d3c94c..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestParamParameterProcessor.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.metadata.rest.springmvc; - -import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.lang.reflect.Parameter; - -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SPRING_MVC.REQUEST_PARAM_ANNOTATION_CLASS_NAME; - -/** - * The {@link AnnotatedMethodParameterProcessor} implementation for Spring Web MVC's @RequestParam - */ -public class RequestParamParameterProcessor extends AbstractRequestAnnotationParameterProcessor { - - @Override - public String getAnnotationName() { - return REQUEST_PARAM_ANNOTATION_CLASS_NAME; - } - - @Override - protected void process( - String name, - String defaultValue, - Annotation annotation, - Parameter parameter, - int parameterIndex, - Method method, - RestMethodMetadata restMethodMetadata) { - restMethodMetadata.getRequest().addParam(name, defaultValue); - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/SpringMvcServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/SpringMvcServiceRestMetadataResolver.java deleted file mode 100644 index fe8c9c2f70c..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/SpringMvcServiceRestMetadataResolver.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.springmvc; - -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.metadata.rest.AbstractServiceRestMetadataResolver; -import org.apache.dubbo.metadata.rest.ServiceRestMetadataResolver; -import org.apache.dubbo.rpc.model.ApplicationModel; - -import java.lang.annotation.Annotation; -import java.lang.reflect.AnnotatedElement; -import java.lang.reflect.Array; -import java.lang.reflect.Method; -import java.util.Set; - -import static java.lang.String.valueOf; -import static java.lang.reflect.Array.getLength; -import static java.util.stream.Stream.of; -import static org.apache.dubbo.common.utils.AnnotationUtils.findAnnotation; -import static org.apache.dubbo.common.utils.AnnotationUtils.getAttribute; -import static org.apache.dubbo.common.utils.AnnotationUtils.isAnnotationPresent; -import static org.apache.dubbo.common.utils.ArrayUtils.isEmpty; -import static org.apache.dubbo.common.utils.ArrayUtils.isNotEmpty; -import static org.apache.dubbo.common.utils.MethodUtils.findMethod; -import static org.apache.dubbo.common.utils.PathUtils.buildPath; -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SPRING_MVC.ANNOTATED_ELEMENT_UTILS_CLASS; -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SPRING_MVC.CONTROLLER_ANNOTATION_CLASS; -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SPRING_MVC.FEIGN_CLIENT_CLASS; -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SPRING_MVC.REQUEST_MAPPING_ANNOTATION_CLASS; -import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SPRING_MVC.REQUEST_MAPPING_ANNOTATION_CLASS_NAME; - -/** - * {@link ServiceRestMetadataResolver} - * - * @since 2.7.6 - */ -@Activate(order = 100) -public class SpringMvcServiceRestMetadataResolver extends AbstractServiceRestMetadataResolver { - - private static final int FIRST_ELEMENT_INDEX = 0; - - public SpringMvcServiceRestMetadataResolver(ApplicationModel applicationModel) { - super(applicationModel); - } - - @Override - protected boolean supports0(Class serviceType) { - // class @Controller or @RequestMapping - return isAnnotationPresent(serviceType, CONTROLLER_ANNOTATION_CLASS) - || isAnnotationPresent(serviceType, FEIGN_CLIENT_CLASS) - || isAnnotationPresent(serviceType, REQUEST_MAPPING_ANNOTATION_CLASS) // method @RequestMapping - || isServiceMethodAnnotationPresent(serviceType, REQUEST_MAPPING_ANNOTATION_CLASS_NAME); - } - - @Override - protected boolean isRestCapableMethod(Method serviceMethod, Class serviceType, Class serviceInterfaceClass) { - // method only match @RequestMapping - return isAnnotationPresent(serviceMethod, REQUEST_MAPPING_ANNOTATION_CLASS); - } - - @Override - protected String resolveRequestMethod(Method serviceMethod, Class serviceType, Class serviceInterfaceClass) { - Annotation requestMapping = getRequestMapping(serviceMethod); - - // httpMethod is an array of RequestMethod - Object httpMethod = getAttribute(requestMapping, "method"); - - if (httpMethod == null || getLength(httpMethod) < 1) { - return null; - } - - // TODO Is is required to support more request methods? - return valueOf(Array.get(httpMethod, FIRST_ELEMENT_INDEX)); - } - - @Override - protected String resolveRequestPath(Method serviceMethod, Class serviceType, Class serviceInterfaceClass) { - String feignClientBasePath = resolveFeignClientBaseRequestPath(serviceType); - String requestMappingBasePath = resolveRequestPath(serviceType); - String requestRelativePath = resolveRequestPath(serviceMethod); - return buildPath(feignClientBasePath, buildPath(requestMappingBasePath, requestRelativePath)); - } - - @Override - protected void processProduces( - Method serviceMethod, Class serviceType, Class serviceInterfaceClass, Set produces) { - addMediaTypes(serviceMethod, "produces", produces); - addMediaTypes(serviceType, "produces", produces); - addMediaTypes(serviceInterfaceClass, "produces", produces); - } - - @Override - protected void processConsumes( - Method serviceMethod, Class serviceType, Class serviceInterfaceClass, Set consumes) { - addMediaTypes(serviceMethod, "consumes", consumes); - addMediaTypes(serviceType, "consumes", consumes); - addMediaTypes(serviceInterfaceClass, "consumes", consumes); - } - - private String resolveFeignClientBaseRequestPath(AnnotatedElement annotatedElement) { - Annotation feignClient = findAnnotation(annotatedElement, FEIGN_CLIENT_CLASS); - - String path = getAttribute(feignClient, "path"); - - if (path == null) { - return ""; - } - - return path; - } - - private String resolveRequestPath(AnnotatedElement annotatedElement) { - Annotation mappingAnnotation = getRequestMapping(annotatedElement); - - // try "value" first - String[] value = getAttribute(mappingAnnotation, "value"); - - if (isEmpty(value)) { // try "path" later - value = getAttribute(mappingAnnotation, "path"); - } - - if (isEmpty(value)) { - return ""; - } - // TODO Is is required to support more request paths? - return value[FIRST_ELEMENT_INDEX]; - } - - private void addMediaTypes(Method serviceMethod, String annotationAttributeName, Set mediaTypesSet) { - - Annotation mappingAnnotation = getRequestMapping(serviceMethod); - - String[] mediaTypes = getAttribute(mappingAnnotation, annotationAttributeName); - - if (isNotEmpty(mediaTypes)) { - of(mediaTypes).forEach(mediaTypesSet::add); - } - } - - private void addMediaTypes(Class serviceType, String annotationAttributeName, Set mediaTypesSet) { - - Annotation mappingAnnotation = getRequestMapping(serviceType); - - String[] mediaTypes = getAttribute(mappingAnnotation, annotationAttributeName); - - if (isNotEmpty(mediaTypes)) { - of(mediaTypes).forEach(mediaTypesSet::add); - } - } - - private Annotation getRequestMapping(AnnotatedElement annotatedElement) { - // try "@RequestMapping" first - Annotation requestMapping = findAnnotation(annotatedElement, REQUEST_MAPPING_ANNOTATION_CLASS); - if (requestMapping == null) { - // To try the meta-annotated annotation if can't be found. - // For example, if the annotation "@GetMapping" is used in the Spring Framework is 4.2 or above, - // because of "@GetMapping" alias for ("@AliasFor") "@RequestMapping" , both of them belongs to - // the artifact "spring-web" which depends on "spring-core", thus Spring core's - // AnnotatedElementUtils.findMergedAnnotation(AnnotatedElement, Class) must be involved. - Method method = findMethod( - ANNOTATED_ELEMENT_UTILS_CLASS, "findMergedAnnotation", AnnotatedElement.class, Class.class); - if (method != null) { - try { - requestMapping = - (Annotation) method.invoke(null, annotatedElement, REQUEST_MAPPING_ANNOTATION_CLASS); - } catch (Exception ignored) { - } - } - } - return requestMapping; - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/tag/BodyTag.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/tag/BodyTag.java deleted file mode 100644 index c308bcee0ba..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/tag/BodyTag.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.metadata.rest.tag; - -/** - * for @RequestBody class no found - */ -public interface BodyTag {} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/tag/NoAnnotationTag.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/tag/NoAnnotationTag.java deleted file mode 100644 index 949157b0beb..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/tag/NoAnnotationTag.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.metadata.rest.tag; - -/** - * for no annotation mode param - */ -public interface NoAnnotationTag {} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/tag/ParamTag.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/tag/ParamTag.java deleted file mode 100644 index cfc16e36642..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/tag/ParamTag.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.metadata.rest.tag; - -/** - * for @RequestParam or @QueryParam class no found - */ -public interface ParamTag {} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor b/dubbo-metadata/dubbo-metadata-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor deleted file mode 100644 index 141ce6f8e0f..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor +++ /dev/null @@ -1,15 +0,0 @@ -# JAX-RS's implementations -jax-rs.query-param = org.apache.dubbo.metadata.rest.jaxrs.QueryParamParameterProcessor -jax-rs.form-param = org.apache.dubbo.metadata.rest.jaxrs.FormParamParameterProcessor -jax-rs.matrix-param = org.apache.dubbo.metadata.rest.jaxrs.MatrixParamParameterProcessor -jax-rs.header-param = org.apache.dubbo.metadata.rest.jaxrs.HeaderParamParameterProcessor -jax-rs.default-value-param = org.apache.dubbo.metadata.rest.jaxrs.DefaultValueParameterProcessor -jax-rs.body = org.apache.dubbo.metadata.rest.jaxrs.BodyParameterProcessor -jax-rs.form-body = org.apache.dubbo.metadata.rest.jaxrs.FormBodyParameterProcessor -jax-rs.path-param = org.apache.dubbo.metadata.rest.jaxrs.PathParamParameterProcessor - -# Spring Web MVC's implementations -spring-webmvc.request-param = org.apache.dubbo.metadata.rest.springmvc.RequestParamParameterProcessor -spring-webmvc.request-header = org.apache.dubbo.metadata.rest.springmvc.RequestHeaderParameterProcessor -spring-webmvc.request-body = org.apache.dubbo.metadata.rest.springmvc.RequestBodyParameterProcessor -spring-webmvc.request-path = org.apache.dubbo.metadata.rest.springmvc.PathVariableParameterProcessor diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.NoAnnotatedParameterRequestTagProcessor b/dubbo-metadata/dubbo-metadata-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.NoAnnotatedParameterRequestTagProcessor deleted file mode 100644 index 5324f222215..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.NoAnnotatedParameterRequestTagProcessor +++ /dev/null @@ -1,3 +0,0 @@ -body-form=org.apache.dubbo.metadata.rest.springmvc.FormBodyNoAnnotatedProcessor -body-json=org.apache.dubbo.metadata.rest.springmvc.JsonBodyNoAnnotatedProcessor -param=org.apache.dubbo.metadata.rest.springmvc.ParamNoAnnotatedProcessor diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.ServiceRestMetadataResolver b/dubbo-metadata/dubbo-metadata-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.ServiceRestMetadataResolver deleted file mode 100644 index ac37a96c5ea..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.ServiceRestMetadataResolver +++ /dev/null @@ -1,4 +0,0 @@ -default = -jax-rs = org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver -spring-webmvc = org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver -no-annotation = org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/PathMatcherTest.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/PathMatcherTest.java deleted file mode 100644 index 875b589b2bf..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/PathMatcherTest.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.metadata; - -import org.apache.dubbo.metadata.rest.PathMatcher; - -import java.lang.reflect.Method; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public class PathMatcherTest { - - @Test - void testPathMatcher() { - PathMatcher pathMatherMeta = new PathMatcher("/a/b/c/{path1}/d/{path2}/e"); - - PathMatcher requestPathMather = new PathMatcher("/a/b/c/1/d/2/e"); - Assertions.assertEquals(requestPathMather, pathMatherMeta); - - PathMatcher requestPathMather1 = new PathMatcher("/{c}/b/c/1/d/2/e"); - Assertions.assertEquals(requestPathMather, requestPathMather1); - - PathMatcher pathMatcher = new PathMatcher("/{d}/b/c/1/d/2/e"); - - pathMatcher.setGroup(null); - pathMatcher.setPort(null); - pathMatcher.setVersion(null); - pathMatcher.setContextPath(""); - - Assertions.assertEquals(pathMatherMeta, pathMatcher); - } - - @Test - void testEqual() { - PathMatcher pathMatherMeta = new PathMatcher("/a/b/c"); - pathMatherMeta.setContextPath("/context"); - PathMatcher pathMatherMeta1 = new PathMatcher("/a/b/d"); - - pathMatherMeta1.setContextPath("/context"); - Assertions.assertNotEquals(pathMatherMeta, pathMatherMeta1); - - pathMatherMeta1 = new PathMatcher("/a/b/c"); - pathMatherMeta1.setContextPath("/context"); - - Assertions.assertEquals(pathMatherMeta, pathMatherMeta1); - - pathMatherMeta.setContextPath("context"); - - pathMatherMeta1.setContextPath("context"); - - Assertions.assertEquals(pathMatherMeta, pathMatherMeta1); - Assertions.assertEquals(pathMatherMeta.toString(), pathMatherMeta1.toString()); - } - - @Test - void testMethodCompare() { - Method hashCode = null; - Method equals = null; - try { - hashCode = Object.class.getDeclaredMethod("hashCode"); - equals = Object.class.getDeclaredMethod("equals", Object.class); - } catch (NoSuchMethodException e) { - - } - - // no need to compare service method - PathMatcher pathMatcher = new PathMatcher(hashCode); - PathMatcher pathMatchers = new PathMatcher(hashCode); - Assertions.assertNotEquals(pathMatcher, pathMatchers); - - // equal - PathMatcher pathMatherMetaHashCode = PathMatcher.getInvokeCreatePathMatcher(hashCode); - PathMatcher pathMatherMetaHashCodes = new PathMatcher(hashCode); - Assertions.assertEquals(pathMatherMetaHashCode, pathMatherMetaHashCodes); - - PathMatcher pathMatherMetaEquals = PathMatcher.getInvokeCreatePathMatcher(equals); - PathMatcher pathMatherMetaEqual = PathMatcher.getInvokeCreatePathMatcher(equals); - Assertions.assertEquals(pathMatherMetaEqual, pathMatherMetaEquals); - - Assertions.assertNotEquals(pathMatherMetaHashCode, pathMatherMetaEquals); - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/TestMediaType.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/TestMediaType.java deleted file mode 100644 index 1a6fbad425e..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/TestMediaType.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata; - -import org.apache.dubbo.metadata.rest.media.MediaType; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public class TestMediaType { - - @Test - void testGetAll() { - Assertions.assertDoesNotThrow(() -> { - MediaType.getAllContentType(); - MediaType.getSupportMediaTypes(); - }); - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/DefaultRestService.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/DefaultRestService.java deleted file mode 100644 index 56075447d5d..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/DefaultRestService.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.metadata.rest; - -import org.apache.dubbo.config.annotation.Service; - -import java.util.Map; - -/** - * The default implementation of {@link RestService} - * - * @since 2.7.6 - */ -@Service(version = "1.0.0") -public class DefaultRestService implements RestService { - - @Override - public String param(String param) { - return null; - } - - @Override - public String params(int a, String b) { - return null; - } - - @Override - public String headers(String header, String header2, Integer param) { - return null; - } - - @Override - public String pathVariables(String path1, String path2, String param) { - return null; - } - - @Override - public String form(String form) { - return null; - } - - @Override - public User requestBodyMap(Map data, String param) { - return null; - } - - @Override - public Map requestBodyUser(User user) { - return null; - } - - @Override - public void noAnnotationJsonBody(User user) {} - - @Override - public void noAnnotationFormBody(User user) {} - - @Override - public void noAnnotationParam(String text) {} - - public User user(User user) { - return user; - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/RestService.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/RestService.java deleted file mode 100644 index 049335e0f54..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/RestService.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest; - -import java.util.Map; - -/** - * An interface for REST service - * - * @since 2.7.6 - */ -public interface RestService { - - String param(String param); - - String params(int a, String b); - - String headers(String header, String header2, Integer param); - - String pathVariables(String path1, String path2, String param); - - String form(String form); - - User requestBodyMap(Map data, String param); - - Map requestBodyUser(User user); - - void noAnnotationJsonBody(User user); - - void noAnnotationFormBody(User user); - - void noAnnotationParam(String text); -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java deleted file mode 100644 index 05c3fea7ef6..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest; - -import org.apache.dubbo.config.annotation.DubboService; - -import java.util.HashMap; -import java.util.Map; - -import org.springframework.http.MediaType; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -/** - * Spring MVC {@link RestService} - * - * @since 2.7.6 - */ -@DubboService(version = "2.0.0", group = "spring") -@RestController -public class SpringRestService implements RestService { - - @Override - @GetMapping(value = "/param") - public String param(@RequestParam(defaultValue = "value-param") String param) { - return null; - } - - @Override - @PostMapping("/params") - public String params( - @RequestParam(defaultValue = "value-a") int a, @RequestParam(defaultValue = "value-b") String b) { - return null; - } - - @Override - @GetMapping("/headers") - public String headers( - @RequestHeader(name = "h", defaultValue = "value-h") String header, - @RequestHeader(name = "h2", defaultValue = "value-h2") String header2, - @RequestParam(value = "v", defaultValue = "1") Integer param) { - return null; - } - - @Override - @GetMapping("/path-variables/{p1}/{p2}") - public String pathVariables( - @PathVariable("p1") String path1, @PathVariable("p2") String path2, @RequestParam("v") String param) { - return null; - } - - @Override - @PostMapping("/form") - public String form(@RequestParam("f") String form) { - return String.valueOf(form); - } - - @Override - @PostMapping(value = "/request/body/map", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - public User requestBodyMap(@RequestBody Map data, @RequestParam("param") String param) { - User user = new User(); - user.setId(((Integer) data.get("id")).longValue()); - user.setName((String) data.get("name")); - user.setAge((Integer) data.get("age")); - return user; - } - - @PostMapping(value = "/request/body/user", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) - @Override - public Map requestBodyUser(@RequestBody User user) { - Map map = new HashMap<>(); - map.put("id", user.getId()); - map.put("name", user.getName()); - map.put("age", user.getAge()); - return map; - } - - @PostMapping(value = "/request/body/user/json", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) - @Override - public void noAnnotationJsonBody(User user) {} - - @PostMapping(value = "/request/body/user/form", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) - @Override - public void noAnnotationFormBody(User user) {} - - @PostMapping(value = "/request/body/user/param") - @Override - public void noAnnotationParam(String text) {} -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java deleted file mode 100644 index 45b84b9ce34..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest; - -import org.apache.dubbo.config.annotation.DubboService; - -import javax.ws.rs.Consumes; -import javax.ws.rs.FormParam; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; - -import java.util.HashMap; -import java.util.Map; - -/** - * JAX-RS {@link RestService} - */ -@DubboService( - version = "3.0.0", - protocol = {"dubbo", "rest"}, - group = "standard") -@Path("/") -public class StandardRestService implements RestService { - - @Override - @Path("param") - @GET - public String param(@QueryParam("param") String param) { - return param; - } - - @Override - @Path("params") - @POST - public String params(@QueryParam("a") int a, @QueryParam("b") String b) { - return a + b; - } - - @Override - @Path("headers") - @GET - public String headers( - @HeaderParam("h") String header, @HeaderParam("h2") String header2, @QueryParam("v") Integer param) { - String result = header + " , " + header2 + " , " + param; - return result; - } - - @Override - @Path("path-variables/{p1}/{p2}") - @GET - public String pathVariables( - @PathParam("p1") String path1, @PathParam("p2") String path2, @QueryParam("v") String param) { - String result = path1 + " , " + path2 + " , " + param; - return result; - } - - // @CookieParam does not support : https://github.com/OpenFeign/feign/issues/913 - // @CookieValue also does not support - - @Override - @Path("form") - @POST - public String form(@FormParam("f") String form) { - return String.valueOf(form); - } - - @Override - @Path("request/body/map") - @POST - @Produces("application/json;charset=UTF-8") - public User requestBodyMap(Map data, @QueryParam("param") String param) { - User user = new User(); - user.setId(((Integer) data.get("id")).longValue()); - user.setName((String) data.get("name")); - user.setAge((Integer) data.get("age")); - return user; - } - - @Path("request/body/user") - @POST - @Override - @Consumes("application/json;charset=UTF-8") - public Map requestBodyUser(User user) { - Map map = new HashMap<>(); - map.put("id", user.getId()); - map.put("name", user.getName()); - map.put("age", user.getAge()); - return map; - } - - @Path("noAnnotationJsonBody/json") - @POST - @Consumes(MediaType.APPLICATION_JSON) - @Override - public void noAnnotationJsonBody(User user) {} - - @Path("noAnnotationFormBody/form") - @Consumes(MediaType.APPLICATION_FORM_URLENCODED) - @POST - @Override - public void noAnnotationFormBody(User user) {} - - @Path("noAnnotationParam/text") - @POST - @Override - public void noAnnotationParam(String text) {} -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/User.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/User.java deleted file mode 100644 index 2b6c4a21baa..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/User.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest; - -import java.io.Serializable; - -/** - * User Entity - * - * @since 2.7.6 - */ -public class User implements Serializable { - - private Long id; - - private String name; - - private Integer age; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Integer getAge() { - return age; - } - - public void setAge(Integer age) { - this.age = age; - } - - @Override - public String toString() { - return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/AnotherUserRestService.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/AnotherUserRestService.java deleted file mode 100644 index 7afb0fc37a8..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/AnotherUserRestService.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.api; - -import org.apache.dubbo.metadata.rest.User; - -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; - -@Path("u") -@Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) -@Produces({MediaType.APPLICATION_JSON}) -public interface AnotherUserRestService { - - @GET - @Path("{id : \\d+}") - User getUser(@PathParam("id") Long id); - - @POST - @Path("register") - String registerUser(User user); - - @GET - @Path("context") - String getContext(); -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestDoubleCheckContainsPathVariableService.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestDoubleCheckContainsPathVariableService.java deleted file mode 100644 index 324ba19adeb..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestDoubleCheckContainsPathVariableService.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.api; - -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; - -@Path("/test") -public interface JaxrsRestDoubleCheckContainsPathVariableService { - @Path("/a/{b}") - @Consumes(MediaType.TEXT_PLAIN) - @Produces(MediaType.TEXT_PLAIN) - @GET - String param(@QueryParam("param") String param); - - @Path("/{b}/b") - @Consumes(MediaType.TEXT_PLAIN) - @Produces(MediaType.TEXT_PLAIN) - @GET - String header(@HeaderParam("header") String header); -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestDoubleCheckService.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestDoubleCheckService.java deleted file mode 100644 index 389af5e78c9..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestDoubleCheckService.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.api; - -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; - -@Path("/test") -public interface JaxrsRestDoubleCheckService { - @Path("/param") - @Consumes(MediaType.TEXT_PLAIN) - @Produces(MediaType.TEXT_PLAIN) - @GET - String param(@QueryParam("param") String param); - - @Path("/param") - @Consumes(MediaType.TEXT_PLAIN) - @Produces(MediaType.TEXT_PLAIN) - @GET - String header(@HeaderParam("header") String header); -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestService.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestService.java deleted file mode 100644 index 3cc8416fbdc..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestService.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.api; - -import org.apache.dubbo.metadata.rest.User; - -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; - -public interface JaxrsRestService { - - @Path("/param") - @Consumes(MediaType.TEXT_PLAIN) - @Produces(MediaType.TEXT_PLAIN) - @GET - String param(@QueryParam("param") String param); - - @Path("/header") - @Consumes(MediaType.TEXT_PLAIN) - @Produces(MediaType.TEXT_PLAIN) - @GET - String header(@HeaderParam("header") String header); - - @Path("/body") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @POST - User body(User user); - - @Path("/multiValue") - @Consumes(MediaType.APPLICATION_FORM_URLENCODED) - @Produces(MediaType.APPLICATION_FORM_URLENCODED) - @POST - MultivaluedMap multiValue(MultivaluedMap map); - - @Path("/pathVariable/{a}") - @Consumes(MediaType.APPLICATION_FORM_URLENCODED) - @Produces(MediaType.APPLICATION_FORM_URLENCODED) - @POST - String pathVariable(@PathParam("a") String a); - - @Path("/noAnno") - @Consumes(MediaType.TEXT_PLAIN) - @Produces(MediaType.TEXT_PLAIN) - @POST - String noAnno(String a); -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestServiceImpl.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestServiceImpl.java deleted file mode 100644 index 2f309e28c05..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestServiceImpl.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.api; - -import org.apache.dubbo.metadata.rest.User; - -import javax.ws.rs.core.MultivaluedMap; - -public class JaxrsRestServiceImpl implements JaxrsRestService { - - @Override - public String param(String param) { - return param; - } - - @Override - public String header(String header) { - return header; - } - - @Override - public User body(User user) { - return user; - } - - @Override - public MultivaluedMap multiValue(MultivaluedMap map) { - return map; - } - - @Override - public String pathVariable(String a) { - return a; - } - - @Override - public String noAnno(String a) { - return a; - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsUsingService.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsUsingService.java deleted file mode 100644 index 4bcc761f1d9..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsUsingService.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.api; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -@Path("usingService") -@Consumes({MediaType.APPLICATION_JSON}) -@Produces({MediaType.APPLICATION_JSON}) -public interface JaxrsUsingService { - - @GET - Response getUsers(); - - @POST - Response createUser(Object user); - - @GET - @Path("{uid}") - Response getUserByUid(@PathParam("uid") String uid); - - @DELETE - @Path("{uid}") - Response deleteUserByUid(@PathParam("uid") String uid); -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/SpringControllerService.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/SpringControllerService.java deleted file mode 100644 index 479714a4d46..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/SpringControllerService.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.metadata.rest.api; - -import org.apache.dubbo.metadata.rest.User; - -import org.springframework.http.MediaType; -import org.springframework.util.MultiValueMap; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class SpringControllerService { - @RequestMapping( - value = "/param", - method = RequestMethod.GET, - consumes = MediaType.TEXT_PLAIN_VALUE, - produces = MediaType.TEXT_PLAIN_VALUE) - public String param(@RequestParam String param) { - return param; - } - - @RequestMapping( - value = "/header", - method = RequestMethod.GET, - consumes = MediaType.TEXT_PLAIN_VALUE, - produces = MediaType.TEXT_PLAIN_VALUE) - public String header(@RequestHeader String header) { - return header; - } - - @RequestMapping( - value = "/body", - method = RequestMethod.POST, - consumes = MediaType.APPLICATION_JSON_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE) - public User body(@RequestBody User user) { - return user; - } - - @RequestMapping( - value = "/multiValue", - method = RequestMethod.POST, - consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, - produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE) - public MultiValueMap multiValue(@RequestBody MultiValueMap map) { - return map; - } - - @RequestMapping( - value = "/pathVariable/{a}", - method = RequestMethod.POST, - consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, - produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE) - public String pathVariable(@PathVariable String a) { - return a; - } - - @RequestMapping( - value = "/noAnnoParam", - method = RequestMethod.POST, - consumes = MediaType.TEXT_PLAIN_VALUE, - produces = MediaType.TEXT_PLAIN_VALUE) - public String noAnnoParam(String a) { - return a; - } - - @RequestMapping( - value = "/noAnnoNumber", - method = RequestMethod.POST, - consumes = MediaType.ALL_VALUE, - produces = MediaType.ALL_VALUE) - public int noAnnoNumber(Integer b) { - return b; - } - - @RequestMapping( - value = "/noAnnoPrimitive", - method = RequestMethod.POST, - consumes = MediaType.ALL_VALUE, - produces = MediaType.ALL_VALUE) - public int noAnnoPrimitive(int c) { - return c; - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/SpringRestService.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/SpringRestService.java deleted file mode 100644 index 8a8c727553f..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/SpringRestService.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.api; - -import org.apache.dubbo.metadata.rest.User; - -import org.springframework.http.MediaType; -import org.springframework.util.MultiValueMap; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public interface SpringRestService { - - @RequestMapping( - value = "/param", - method = RequestMethod.GET, - consumes = MediaType.TEXT_PLAIN_VALUE, - produces = MediaType.TEXT_PLAIN_VALUE) - String param(@RequestParam("param") String param); - - @RequestMapping( - value = "/header", - method = RequestMethod.GET, - consumes = MediaType.TEXT_PLAIN_VALUE, - produces = MediaType.TEXT_PLAIN_VALUE) - String header(@RequestHeader("header") String header); - - @RequestMapping( - value = "/body", - method = RequestMethod.POST, - consumes = MediaType.APPLICATION_JSON_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE) - User body(@RequestBody User user); - - @RequestMapping( - value = "/multiValue", - method = RequestMethod.POST, - consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, - produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE) - MultiValueMap multiValue(@RequestBody MultiValueMap map); - - @RequestMapping( - value = "/pathVariable/{a}", - method = RequestMethod.POST, - consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, - produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE) - String pathVariable(@PathVariable String a); - - @RequestMapping( - value = "/noAnnoParam", - method = RequestMethod.POST, - consumes = MediaType.TEXT_PLAIN_VALUE, - produces = MediaType.TEXT_PLAIN_VALUE) - String noAnnoParam(String a); - - @RequestMapping( - value = "/noAnnoNumber", - method = RequestMethod.POST, - consumes = MediaType.ALL_VALUE, - produces = MediaType.ALL_VALUE) - int noAnnoNumber(Integer b); - - @RequestMapping( - value = "/noAnnoPrimitive", - method = RequestMethod.POST, - consumes = MediaType.ALL_VALUE, - produces = MediaType.ALL_VALUE) - int noAnnoPrimitive(int c); -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/SpringRestServiceImpl.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/SpringRestServiceImpl.java deleted file mode 100644 index a9cfb9c3080..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/SpringRestServiceImpl.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.api; - -import org.apache.dubbo.metadata.rest.User; - -import org.springframework.util.MultiValueMap; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class SpringRestServiceImpl implements SpringRestService { - - @Override - public String param(String param) { - return param; - } - - @Override - public String header(String header) { - return header; - } - - @Override - public User body(User user) { - return user; - } - - @Override - public MultiValueMap multiValue(MultiValueMap map) { - return map; - } - - @Override - public String pathVariable(String a) { - return a; - } - - @Override - public String noAnnoParam(String a) { - return a; - } - - @Override - public int noAnnoNumber(Integer b) { - return b; - } - - @Override - public int noAnnoPrimitive(int c) { - return c; - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/feign/FeignClientController.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/feign/FeignClientController.java deleted file mode 100644 index e3b0ecbf7b7..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/feign/FeignClientController.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.feign; - -import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -@FeignClient(path = "/feign") -@RequestMapping("/context") -public interface FeignClientController { - - @RequestMapping(value = "/hello", method = RequestMethod.GET) - String hello(); -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/feign/FeignClientControllerImpl.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/feign/FeignClientControllerImpl.java deleted file mode 100644 index 8f0cc225be4..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/feign/FeignClientControllerImpl.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.feign; - -public class FeignClientControllerImpl implements FeignClientController { - - @Override - public String hello() { - return "hello, feign"; - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/jaxrs/JAXRSServiceRestMetadataResolverTest.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/jaxrs/JAXRSServiceRestMetadataResolverTest.java deleted file mode 100644 index e68b995e84e..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/jaxrs/JAXRSServiceRestMetadataResolverTest.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.jaxrs; - -import org.apache.dubbo.common.utils.CollectionUtils; -import org.apache.dubbo.common.utils.JsonUtils; -import org.apache.dubbo.metadata.rest.ClassPathServiceRestMetadataReader; -import org.apache.dubbo.metadata.rest.DefaultRestService; -import org.apache.dubbo.metadata.rest.PathUtil; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; -import org.apache.dubbo.metadata.rest.RestService; -import org.apache.dubbo.metadata.rest.ServiceRestMetadata; -import org.apache.dubbo.metadata.rest.StandardRestService; -import org.apache.dubbo.metadata.rest.api.AnotherUserRestService; -import org.apache.dubbo.metadata.rest.api.JaxrsRestService; -import org.apache.dubbo.metadata.rest.api.JaxrsRestServiceImpl; -import org.apache.dubbo.metadata.rest.api.SpringRestService; -import org.apache.dubbo.rpc.model.ApplicationModel; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.List; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * {@link JAXRSServiceRestMetadataResolver} Test - * - * @since 2.7.6 - */ -class JAXRSServiceRestMetadataResolverTest { - - private JAXRSServiceRestMetadataResolver instance = - new JAXRSServiceRestMetadataResolver(ApplicationModel.defaultModel()); - - @Test - void testSupports() { - // JAX-RS RestService class - assertTrue(instance.supports(StandardRestService.class)); - // Spring MVC RestService class - assertFalse(instance.supports(SpringRestService.class)); - // Default RestService class - assertFalse(instance.supports(DefaultRestService.class)); - // No annotated RestService class - assertFalse(instance.supports(RestService.class)); - // null - assertFalse(instance.supports(null)); - } - - @Test - @Disabled - void testResolve() { - // Generated by "dubbo-metadata-processor" - ClassPathServiceRestMetadataReader reader = - new ClassPathServiceRestMetadataReader("META-INF/dubbo/jax-rs-service-rest-metadata.json"); - List serviceRestMetadataList = reader.read(); - - ServiceRestMetadata expectedServiceRestMetadata = serviceRestMetadataList.get(0); - ServiceRestMetadata serviceRestMetadata = instance.resolve(StandardRestService.class); - - assertTrue(CollectionUtils.equals(expectedServiceRestMetadata.getMeta(), serviceRestMetadata.getMeta())); - - assertEquals(expectedServiceRestMetadata, serviceRestMetadata); - } - - @Test - void testResolves() { - testResolve(JaxrsRestService.class); - testResolve(JaxrsRestServiceImpl.class); - } - - void testResolve(Class service) { - // Generated by "dubbo-metadata-processor" - - List jsons = Arrays.asList( - "{\"argInfos\":[{\"annotationNameAttribute\":\"a\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.BodyTag\",\"paramName\":\"a\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver\",\"indexToName\":{0:[\"a\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"text/plain\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/noAnno\",\"produces\":[\"text/plain\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"a\",\"defaultValue\":\"{0}\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"javax.ws.rs.PathParam\",\"paramName\":\"a\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":2}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver\",\"indexToName\":{0:[\"a\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/x-www-form-urlencoded\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/pathVariable/{a}\",\"produces\":[\"application/x-www-form-urlencoded\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"map\",\"formContentType\":true,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.BodyTag\",\"paramName\":\"map\",\"paramType\":\"javax.ws.rs.core.MultivaluedMap\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver\",\"indexToName\":{0:[\"map\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/x-www-form-urlencoded\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/multiValue\",\"produces\":[\"application/x-www-form-urlencoded\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"user\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.BodyTag\",\"paramName\":\"user\",\"paramType\":\"org.apache.dubbo.metadata.rest.User\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver\",\"indexToName\":{0:[\"user\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/body\",\"produces\":[\"application/json\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"param\",\"defaultValue\":\"{0}\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"javax.ws.rs.QueryParam\",\"paramName\":\"param\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver\",\"indexToName\":{0:[\"param\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"text/plain\"],\"headerNames\":[],\"headers\":{},\"method\":\"GET\",\"paramNames\":[\"param\"],\"params\":{\"param\":[\"{0}\"]},\"path\":\"/param\",\"produces\":[\"text/plain\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"header\",\"defaultValue\":\"{0}\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"javax.ws.rs.HeaderParam\",\"paramName\":\"header\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver\",\"indexToName\":{0:[\"header\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"text/plain\"],\"headerNames\":[\"header\"],\"headers\":{\"header\":[\"{0}\"]},\"method\":\"GET\",\"paramNames\":[],\"params\":{},\"path\":\"/header\",\"produces\":[\"text/plain\"]}}"); - - ServiceRestMetadata jaxrsRestMetadata = new ServiceRestMetadata(); - jaxrsRestMetadata.setServiceInterface(service.getName()); - ServiceRestMetadata jaxrsMetadata = instance.resolve(service, jaxrsRestMetadata); - - List jsonsTmp = new ArrayList<>(); - for (RestMethodMetadata restMethodMetadata : jaxrsMetadata.getMeta()) { - restMethodMetadata.setReflectMethod(null); - restMethodMetadata.setMethod(null); - jsonsTmp.add(JsonUtils.toJson(restMethodMetadata)); - } - - Comparator comparator = new Comparator() { - @Override - public int compare(String o1, String o2) { - return o1.length() - o2.length(); - } - }; - jsons.sort(comparator); - jsonsTmp.sort(comparator); - - for (int i = 0; i < jsons.size(); i++) { - assertEquals(jsons.get(i), jsonsTmp.get(i)); - } - } - - @Test - void testJaxrsPathPattern() { - Class service = AnotherUserRestService.class; - ServiceRestMetadata jaxrsRestMetadata = new ServiceRestMetadata(); - jaxrsRestMetadata.setServiceInterface(service.getName()); - ServiceRestMetadata jaxrsMetadata = instance.resolve(service, jaxrsRestMetadata); - - RestMethodMetadata[] objects = jaxrsMetadata.getMeta().toArray(new RestMethodMetadata[0]); - RestMethodMetadata object = null; - for (RestMethodMetadata obj : objects) { - if ("getUser".equals(obj.getReflectMethod().getName())) { - object = obj; - } - } - - Assertions.assertEquals( - "/u/1", PathUtil.resolvePathVariable("/u/{id : \\d+}", object.getArgInfos(), Arrays.asList(1))); - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/jaxrs/JaxrsRestDoubleCheckTest.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/jaxrs/JaxrsRestDoubleCheckTest.java deleted file mode 100644 index 362e7f3acbd..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/jaxrs/JaxrsRestDoubleCheckTest.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.jaxrs; - -import org.apache.dubbo.metadata.rest.PathMatcher; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; -import org.apache.dubbo.metadata.rest.ServiceRestMetadata; -import org.apache.dubbo.metadata.rest.api.JaxrsRestDoubleCheckContainsPathVariableService; -import org.apache.dubbo.metadata.rest.api.JaxrsRestDoubleCheckService; -import org.apache.dubbo.metadata.rest.api.JaxrsUsingService; -import org.apache.dubbo.rpc.model.ApplicationModel; - -import java.util.Map; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public class JaxrsRestDoubleCheckTest { - private JAXRSServiceRestMetadataResolver instance = - new JAXRSServiceRestMetadataResolver(ApplicationModel.defaultModel()); - - @Test - void testDoubleCheckException() { - - Assertions.assertThrows(IllegalArgumentException.class, () -> { - ServiceRestMetadata resolve = new ServiceRestMetadata(); - resolve.setServiceInterface(JaxrsRestDoubleCheckService.class.getName()); - instance.resolve(JaxrsRestDoubleCheckService.class, resolve); - }); - - Assertions.assertThrows(IllegalArgumentException.class, () -> { - ServiceRestMetadata resolve = new ServiceRestMetadata(); - resolve.setServiceInterface(JaxrsRestDoubleCheckContainsPathVariableService.class.getName()); - instance.resolve(JaxrsRestDoubleCheckContainsPathVariableService.class, resolve); - }); - } - - @Test - void testSameHttpMethodException() { - - Assertions.assertDoesNotThrow(() -> { - ServiceRestMetadata resolve = new ServiceRestMetadata(); - resolve.setServiceInterface(JaxrsUsingService.class.getName()); - instance.resolve(JaxrsUsingService.class, resolve); - }); - - ServiceRestMetadata resolve = new ServiceRestMetadata(); - resolve.setServiceInterface(JaxrsUsingService.class.getName()); - instance.resolve(JaxrsUsingService.class, resolve); - - Map pathContainPathVariableToServiceMap = - resolve.getPathContainPathVariableToServiceMap(); - - RestMethodMetadata restMethodMetadata = pathContainPathVariableToServiceMap.get( - PathMatcher.getInvokeCreatePathMatcher("/usingService/aaa", null, null, null, "TEST")); - - Assertions.assertNotNull(restMethodMetadata); - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/noannotation/NoAnnotationServiceRestMetadataResolverTest.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/noannotation/NoAnnotationServiceRestMetadataResolverTest.java deleted file mode 100644 index 1db4aae9821..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/noannotation/NoAnnotationServiceRestMetadataResolverTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.noannotation; - -import org.apache.dubbo.common.utils.JsonUtils; -import org.apache.dubbo.metadata.rest.DefaultRestService; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; -import org.apache.dubbo.metadata.rest.ServiceRestMetadata; -import org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver; -import org.apache.dubbo.rpc.model.ApplicationModel; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.List; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class NoAnnotationServiceRestMetadataResolverTest { - private NoAnnotationServiceRestMetadataResolver instance = - new NoAnnotationServiceRestMetadataResolver(ApplicationModel.defaultModel()); - - @Test - void testResolve() { - - List jsons = Arrays.asList( - "{\"argInfos\":[{\"annotationNameAttribute\":\"form\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"form\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"form\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/form\",\"produces\":[\"application/json\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"header\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"header\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0},{\"annotationNameAttribute\":\"header2\",\"formContentType\":false,\"index\":1,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"header2\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0},{\"annotationNameAttribute\":\"param\",\"formContentType\":false,\"index\":2,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"param\",\"paramType\":\"java.lang.Integer\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"header\"],1:[\"header2\"],2:[\"param\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/headers\",\"produces\":[\"application/json\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"user\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"user\",\"paramType\":\"org.apache.dubbo.metadata.rest.User\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"user\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/noAnnotationFormBody\",\"produces\":[\"application/json\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"user\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"user\",\"paramType\":\"org.apache.dubbo.metadata.rest.User\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"user\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/noAnnotationJsonBody\",\"produces\":[\"application/json\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"text\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"text\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"text\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/noAnnotationParam\",\"produces\":[\"application/json\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"param\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"param\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"param\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/param\",\"produces\":[\"application/json\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"a\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"a\",\"paramType\":\"int\",\"urlSplitIndex\":0},{\"annotationNameAttribute\":\"b\",\"formContentType\":false,\"index\":1,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"b\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"a\"],1:[\"b\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/params\",\"produces\":[\"application/json\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"path1\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"path1\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0},{\"annotationNameAttribute\":\"path2\",\"formContentType\":false,\"index\":1,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"path2\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0},{\"annotationNameAttribute\":\"param\",\"formContentType\":false,\"index\":2,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"param\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"path1\"],1:[\"path2\"],2:[\"param\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/pathVariables\",\"produces\":[\"application/json\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"data\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"data\",\"paramType\":\"java.util.Map\",\"urlSplitIndex\":0},{\"annotationNameAttribute\":\"param\",\"formContentType\":false,\"index\":1,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"param\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"data\"],1:[\"param\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/requestBodyMap\",\"produces\":[\"application/json\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"user\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"user\",\"paramType\":\"org.apache.dubbo.metadata.rest.User\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"user\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/requestBodyUser\",\"produces\":[\"application/json\"]}}"); - - boolean supports = instance.supports(DefaultRestService.class); - - Assertions.assertEquals(true, supports); - - ServiceRestMetadata serviceRestMetadata = instance.resolve(DefaultRestService.class); - - List jsonsTmp = new ArrayList<>(); - for (RestMethodMetadata restMethodMetadata : serviceRestMetadata.getMeta()) { - restMethodMetadata.setReflectMethod(null); - restMethodMetadata.setMethod(null); - jsonsTmp.add(JsonUtils.toJson(restMethodMetadata)); - } - - Comparator comparator = new Comparator() { - @Override - public int compare(String o1, String o2) { - return o1.length() - o2.length(); - } - }; - jsons.sort(comparator); - jsonsTmp.sort(comparator); - - for (int i = 0; i < jsons.size(); i++) { - assertEquals(jsons.get(i), jsonsTmp.get(i)); - } - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/springmvc/FeignClientAnnotationTest.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/springmvc/FeignClientAnnotationTest.java deleted file mode 100644 index f2aa5b88ff0..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/springmvc/FeignClientAnnotationTest.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.springmvc; - -import org.apache.dubbo.metadata.rest.PathMatcher; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; -import org.apache.dubbo.metadata.rest.ServiceRestMetadata; -import org.apache.dubbo.metadata.rest.feign.FeignClientController; -import org.apache.dubbo.rpc.model.ApplicationModel; - -import java.util.Map; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public class FeignClientAnnotationTest { - - private SpringMvcServiceRestMetadataResolver instance = - new SpringMvcServiceRestMetadataResolver(ApplicationModel.defaultModel()); - - @Test - void testFeignClientAnnotationResolve() { - - Assertions.assertEquals(true, instance.supports(FeignClientController.class)); - Class service = FeignClientController.class; - ServiceRestMetadata serviceRestMetadata = new ServiceRestMetadata(); - serviceRestMetadata.setServiceInterface(service.getName()); - - ServiceRestMetadata resolve = instance.resolve(service, serviceRestMetadata); - - Map unContainPathVariableToServiceMap = - resolve.getPathUnContainPathVariableToServiceMap(); - RestMethodMetadata restMethodMetadata = unContainPathVariableToServiceMap.get( - PathMatcher.getInvokeCreatePathMatcher("/feign/context/hello", null, null, null, "GET")); - Assertions.assertNotNull(restMethodMetadata); - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/springmvc/SpringMvcServiceRestMetadataResolverTest.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/springmvc/SpringMvcServiceRestMetadataResolverTest.java deleted file mode 100644 index 4c96e383345..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/springmvc/SpringMvcServiceRestMetadataResolverTest.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.rest.springmvc; - -import org.apache.dubbo.common.utils.CollectionUtils; -import org.apache.dubbo.common.utils.JsonUtils; -import org.apache.dubbo.metadata.rest.ClassPathServiceRestMetadataReader; -import org.apache.dubbo.metadata.rest.DefaultRestService; -import org.apache.dubbo.metadata.rest.PathMatcher; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; -import org.apache.dubbo.metadata.rest.RestService; -import org.apache.dubbo.metadata.rest.ServiceRestMetadata; -import org.apache.dubbo.metadata.rest.StandardRestService; -import org.apache.dubbo.metadata.rest.api.SpringControllerService; -import org.apache.dubbo.metadata.rest.api.SpringRestService; -import org.apache.dubbo.metadata.rest.api.SpringRestServiceImpl; -import org.apache.dubbo.rpc.model.ApplicationModel; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.List; -import java.util.Map; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * {@link SpringMvcServiceRestMetadataResolver} Test - * - * @since 2.7.9 - */ -class SpringMvcServiceRestMetadataResolverTest { - - private SpringMvcServiceRestMetadataResolver instance = - new SpringMvcServiceRestMetadataResolver(ApplicationModel.defaultModel()); - - @Test - void testSupports() { - // Spring MVC RestService class - assertTrue(instance.supports(SpringRestService.class, true)); - // JAX-RS RestService class - assertFalse(instance.supports(StandardRestService.class, true)); - // Default RestService class - assertFalse(instance.supports(DefaultRestService.class, true)); - // No annotated RestService class - assertFalse(instance.supports(RestService.class, true)); - // null - assertFalse(instance.supports(null, true)); - } - - @Test - @Disabled - void testResolve() { - // Generated by "dubbo-metadata-processor" - ClassPathServiceRestMetadataReader reader = - new ClassPathServiceRestMetadataReader("META-INF/dubbo/spring-mvc-service-rest-metadata.json"); - List serviceRestMetadataList = reader.read(); - - ServiceRestMetadata expectedServiceRestMetadata = serviceRestMetadataList.get(0); - ServiceRestMetadata serviceRestMetadata = instance.resolve(SpringRestService.class); - - assertTrue(CollectionUtils.equals(expectedServiceRestMetadata.getMeta(), serviceRestMetadata.getMeta())); - - assertEquals(expectedServiceRestMetadata, serviceRestMetadata); - } - - @Test - void testResolves() { - testResolve(SpringRestService.class); - testResolve(SpringRestServiceImpl.class); - testResolve(SpringControllerService.class); - } - - void testResolve(Class service) { - List jsons = Arrays.asList( - "{\"argInfos\":[{\"annotationNameAttribute\":\"b\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.ParamTag\",\"paramName\":\"b\",\"paramType\":\"java.lang.Integer\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"b\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"*/*\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/noAnnoNumber\",\"produces\":[\"*/*\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"c\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.ParamTag\",\"paramName\":\"c\",\"paramType\":\"int\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"c\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"*/*\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/noAnnoPrimitive\",\"produces\":[\"*/*\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"a\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.ParamTag\",\"paramName\":\"a\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"a\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"text/plain\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/noAnnoParam\",\"produces\":[\"text/plain\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.springframework.web.bind.annotation.PathVariable\",\"paramName\":\"a\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":2}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"a\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/x-www-form-urlencoded\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/pathVariable/{a}\",\"produces\":[\"application/x-www-form-urlencoded\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"user\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.springframework.web.bind.annotation.RequestBody\",\"paramName\":\"user\",\"paramType\":\"org.apache.dubbo.metadata.rest.User\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"user\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/body\",\"produces\":[\"application/json\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"param\",\"defaultValue\":\"{0}\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.springframework.web.bind.annotation.RequestParam\",\"paramName\":\"param\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"param\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"text/plain\"],\"headerNames\":[],\"headers\":{},\"method\":\"GET\",\"paramNames\":[\"param\"],\"params\":{\"param\":[\"{0}\"]},\"path\":\"/param\",\"produces\":[\"text/plain\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"map\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.springframework.web.bind.annotation.RequestBody\",\"paramName\":\"map\",\"paramType\":\"org.springframework.util.MultiValueMap\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"map\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/x-www-form-urlencoded\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/multiValue\",\"produces\":[\"application/x-www-form-urlencoded\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"header\",\"defaultValue\":\"{0}\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.springframework.web.bind.annotation.RequestHeader\",\"paramName\":\"header\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"header\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"text/plain\"],\"headerNames\":[\"header\"],\"headers\":{\"header\":[\"{0}\"]},\"method\":\"GET\",\"paramNames\":[],\"params\":{},\"path\":\"/header\",\"produces\":[\"text/plain\"]}}"); - - ServiceRestMetadata springRestMetadata = new ServiceRestMetadata(); - springRestMetadata.setServiceInterface(service.getName()); - ServiceRestMetadata springMetadata = instance.resolve(service, springRestMetadata); - - List jsonsTmp = new ArrayList<>(); - for (RestMethodMetadata restMethodMetadata : springMetadata.getMeta()) { - restMethodMetadata.setReflectMethod(null); - restMethodMetadata.setMethod(null); - jsonsTmp.add(JsonUtils.toJson(restMethodMetadata)); - } - - Comparator comparator = new Comparator() { - @Override - public int compare(String o1, String o2) { - return o1.length() - o2.length(); - } - }; - jsons.sort(comparator); - jsonsTmp.sort(comparator); - - for (int i = 0; i < jsons.size(); i++) { - assertEquals(jsons.get(i), jsonsTmp.get(i)); - } - } - - @Test - void testDoubleCheck() { - - ServiceRestMetadata springRestMetadata = new ServiceRestMetadata(); - springRestMetadata.setServiceInterface(SpringRestServiceImpl.class.getName()); - ServiceRestMetadata springMetadata = instance.resolve(SpringRestServiceImpl.class, springRestMetadata); - - springMetadata.setContextPathFromUrl("context"); - - Assertions.assertEquals("context", springMetadata.getContextPathFromUrl()); - - springMetadata.setContextPathFromUrl("//context"); - Assertions.assertEquals("/context", springMetadata.getContextPathFromUrl()); - springMetadata.setPort(404); - Map pathContainPathVariableToServiceMap = - springMetadata.getPathContainPathVariableToServiceMap(); - - for (PathMatcher pathMatcher : pathContainPathVariableToServiceMap.keySet()) { - Assertions.assertTrue(pathMatcher.hasPathVariable()); - Assertions.assertEquals(404, pathMatcher.getPort()); - } - - Map pathUnContainPathVariableToServiceMap = - springMetadata.getPathUnContainPathVariableToServiceMap(); - - for (PathMatcher pathMatcher : pathUnContainPathVariableToServiceMap.keySet()) { - Assertions.assertFalse(pathMatcher.hasPathVariable()); - Assertions.assertEquals(404, pathMatcher.getPort()); - } - } -} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/resources/META-INF/dubbo/jax-rs-service-rest-metadata.json b/dubbo-metadata/dubbo-metadata-rest/src/test/resources/META-INF/dubbo/jax-rs-service-rest-metadata.json deleted file mode 100644 index d5779f6ffdb..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/resources/META-INF/dubbo/jax-rs-service-rest-metadata.json +++ /dev/null @@ -1,324 +0,0 @@ -[ - { - "serviceInterface": "org.apache.dubbo.metadata.rest.RestService", - "version": "3.0.0", - "group": "standard", - "meta": [ - { - "method": { - "name": "form", - "parameterTypes": [ - "java.lang.String" - ], - "returnType": "java.lang.String", - "parameters": [ - { - "type": "java.lang.String", - "items": [], - "enum": [], - "properties": {} - } - ] - }, - "request": { - "method": "POST", - "path": "/form", - "params": { - "f": [ - "{0}" - ] - }, - "headers": {}, - "consumes": [], - "produces": [] - }, - "indexToName": { - "0": [ - "form" - ] - } - }, - { - "method": { - "name": "headers", - "parameterTypes": [ - "java.lang.String", - "java.lang.String", - "java.lang.Integer" - ], - "returnType": "java.lang.String", - "parameters": [ - { - "type": "java.lang.String", - "items": [], - "enum": [], - "properties": {} - }, - { - "type": "java.lang.String", - "items": [], - "enum": [], - "properties": {} - }, - { - "type": "java.lang.Integer", - "items": [], - "enum": [], - "properties": {} - } - ] - }, - "request": { - "method": "GET", - "path": "/headers", - "params": { - "v": [ - "{2}" - ] - }, - "headers": { - "h": [ - "{0}" - ], - "h2": [ - "{1}" - ] - }, - "consumes": [], - "produces": [] - }, - "indexToName": { - "0": [ - "header" - ], - "1": [ - "header2" - ], - "2": [ - "param" - ] - } - }, - { - "method": { - "name": "param", - "parameterTypes": [ - "java.lang.String" - ], - "returnType": "java.lang.String", - "parameters": [ - { - "type": "java.lang.String", - "items": [], - "enum": [], - "properties": {} - } - ] - }, - "request": { - "method": "GET", - "path": "/param", - "params": { - "param": [ - "{0}" - ] - }, - "headers": {}, - "consumes": [], - "produces": [] - }, - "indexToName": { - "0": [ - "param" - ] - } - }, - { - "method": { - "name": "params", - "parameterTypes": [ - "int", - "java.lang.String" - ], - "returnType": "java.lang.String", - "parameters": [ - { - "type": "int", - "items": [], - "enum": [], - "properties": {} - }, - { - "type": "java.lang.String", - "items": [], - "enum": [], - "properties": {} - } - ] - }, - "request": { - "method": "POST", - "path": "/params", - "params": { - "a": [ - "{0}" - ], - "b": [ - "{1}" - ] - }, - "headers": {}, - "consumes": [], - "produces": [] - }, - "indexToName": { - "0": [ - "a" - ], - "1": [ - "b" - ] - } - }, - { - "method": { - "name": "pathVariables", - "parameterTypes": [ - "java.lang.String", - "java.lang.String", - "java.lang.String" - ], - "returnType": "java.lang.String", - "parameters": [ - { - "type": "java.lang.String", - "items": [], - "enum": [], - "properties": {} - }, - { - "type": "java.lang.String", - "items": [], - "enum": [], - "properties": {} - }, - { - "type": "java.lang.String", - "items": [], - "enum": [], - "properties": {} - } - ] - }, - "request": { - "method": "GET", - "path": "/path-variables/{p1}/{p2}", - "params": { - "v": [ - "{2}" - ] - }, - "headers": {}, - "consumes": [], - "produces": [] - }, - "indexToName": { - "0": [ - "path1" - ], - "1": [ - "path2" - ], - "2": [ - "param" - ] - } - }, - { - "method": { - "name": "requestBodyMap", - "parameterTypes": [ - "java.util.Map\u003cjava.lang.String,java.lang.Object\u003e", - "java.lang.String" - ], - "returnType": "org.apache.dubbo.metadata.rest.User", - "parameters": [ - { - "type": "java.util.Map\u003cjava.lang.String,java.lang.Object\u003e", - "items": [ - "java.lang.String", - "java.lang.Object" - ], - "enum": [], - "properties": {} - }, - { - "type": "java.lang.String", - "items": [], - "enum": [], - "properties": {} - } - ] - }, - "request": { - "method": "POST", - "path": "/request/body/map", - "params": { - "param": [ - "{1}" - ] - }, - "headers": {}, - "consumes": [], - "produces": [ - "application/json;charset\u003dUTF-8" - ] - }, - "indexToName": { - "0": [ - "data" - ], - "1": [ - "param" - ] - } - }, - { - "method": { - "name": "requestBodyUser", - "parameterTypes": [ - "org.apache.dubbo.metadata.rest.User" - ], - "returnType": "java.util.Map\u003cjava.lang.String,java.lang.Object\u003e", - "parameters": [ - { - "type": "org.apache.dubbo.metadata.rest.User", - "items": [], - "enum": [], - "properties": { - "name": "java.lang.String", - "id": "java.lang.Long", - "age": "java.lang.Integer" - } - } - ] - }, - "request": { - "method": "POST", - "path": "/request/body/user", - "params": {}, - "headers": {}, - "consumes": [ - "application/json;charset\u003dUTF-8" - ], - "produces": [] - }, - "indexToName": { - "0": [ - "user" - ] - } - } - ] - } -] \ No newline at end of file diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/resources/META-INF/dubbo/spring-mvc-service-rest-metadata.json b/dubbo-metadata/dubbo-metadata-rest/src/test/resources/META-INF/dubbo/spring-mvc-service-rest-metadata.json deleted file mode 100644 index c0f25f59a55..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/resources/META-INF/dubbo/spring-mvc-service-rest-metadata.json +++ /dev/null @@ -1,321 +0,0 @@ -[ - { - "serviceInterface": "org.apache.dubbo.metadata.rest.RestService", - "version": "2.0.0", - "group": "spring", - "meta": [ - { - "method": { - "name": "form", - "parameterTypes": [ - "java.lang.String" - ], - "returnType": "java.lang.String", - "parameters": [ - { - "type": "java.lang.String", - "items": [], - "enum": [], - "properties": {} - } - ] - }, - "request": { - "method": "POST", - "path": "/form", - "params": { - "f": [ - "{0}" - ] - }, - "headers": {}, - "consumes": [], - "produces": [] - }, - "indexToName": { - "0": [ - "form" - ] - } - }, - { - "method": { - "name": "headers", - "parameterTypes": [ - "java.lang.String", - "java.lang.String", - "java.lang.Integer" - ], - "returnType": "java.lang.String", - "parameters": [ - { - "type": "java.lang.String", - "items": [], - "enum": [], - "properties": {} - }, - { - "type": "java.lang.String", - "items": [], - "enum": [], - "properties": {} - }, - { - "type": "java.lang.Integer", - "items": [], - "enum": [], - "properties": {} - } - ] - }, - "request": { - "method": "GET", - "path": "/headers", - "params": { - "v": [ - "1" - ] - }, - "headers": { - "h": [ - "value-h" - ], - "h2": [ - "value-h2" - ] - }, - "consumes": [], - "produces": [] - }, - "indexToName": { - "0": [ - "header" - ], - "1": [ - "header2" - ], - "2": [ - "param" - ] - } - }, - { - "method": { - "name": "param", - "parameterTypes": [ - "java.lang.String" - ], - "returnType": "java.lang.String", - "parameters": [ - { - "type": "java.lang.String", - "items": [], - "enum": [], - "properties": {} - } - ] - }, - "request": { - "method": "GET", - "path": "/param", - "params": { - "param": [ - "value-param" - ] - }, - "headers": {}, - "consumes": [], - "produces": [] - }, - "indexToName": { - "0": [ - "param" - ] - } - }, - { - "method": { - "name": "params", - "parameterTypes": [ - "int", - "java.lang.String" - ], - "returnType": "java.lang.String", - "parameters": [ - { - "type": "int", - "items": [], - "enum": [], - "properties": {} - }, - { - "type": "java.lang.String", - "items": [], - "enum": [], - "properties": {} - } - ] - }, - "request": { - "method": "POST", - "path": "/params", - "params": { - "a": [ - "value-a" - ], - "b": [ - "value-b" - ] - }, - "headers": {}, - "consumes": [], - "produces": [] - }, - "indexToName": { - "0": [ - "a" - ], - "1": [ - "b" - ] - } - }, - { - "method": { - "name": "pathVariables", - "parameterTypes": [ - "java.lang.String", - "java.lang.String", - "java.lang.String" - ], - "returnType": "java.lang.String", - "parameters": [ - { - "type": "java.lang.String", - "items": [], - "enum": [], - "properties": {} - }, - { - "type": "java.lang.String", - "items": [], - "enum": [], - "properties": {} - }, - { - "type": "java.lang.String", - "items": [], - "enum": [], - "properties": {} - } - ] - }, - "request": { - "method": "GET", - "path": "/path-variables/{p1}/{p2}", - "params": { - "v": [ - "{2}" - ] - }, - "headers": {}, - "consumes": [], - "produces": [] - }, - "indexToName": { - "0": [ - "path1" - ], - "1": [ - "path2" - ], - "2": [ - "param" - ] - } - }, - { - "method": { - "name": "requestBodyMap", - "parameterTypes": [ - "java.util.Map\u003cjava.lang.String,java.lang.Object\u003e", - "java.lang.String" - ], - "returnType": "org.apache.dubbo.metadata.rest.User", - "parameters": [ - { - "type": "java.util.Map\u003cjava.lang.String,java.lang.Object\u003e", - "items": ["java.lang.String", "java.lang.Object"], - "enum": [], - "properties": {} - }, - { - "type": "java.lang.String", - "items": [], - "enum": [], - "properties": {} - } - ] - }, - "request": { - "method": "POST", - "path": "/request/body/map", - "params": { - "param": [ - "{1}" - ] - }, - "headers": {}, - "consumes": [], - "produces": [ - "application/json;charset\u003dUTF-8" - ] - }, - "indexToName": { - "0": [ - "data" - ], - "1": [ - "param" - ] - } - }, - { - "method": { - "name": "requestBodyUser", - "parameterTypes": [ - "org.apache.dubbo.metadata.rest.User" - ], - "returnType": "java.util.Map\u003cjava.lang.String,java.lang.Object\u003e", - "parameters": [ - { - "type": "org.apache.dubbo.metadata.rest.User", - "items": [], - "enum": [], - "properties": { - "name": "java.lang.String", - "id": "java.lang.Long", - "age": "java.lang.Integer" - } - } - ] - }, - "request": { - "method": "POST", - "path": "/request/body/user", - "params": {}, - "headers": {}, - "consumes": [ - "application/json;charset\u003dUTF-8" - ], - "produces": [] - }, - "indexToName": { - "0": [ - "user" - ] - } - } - ] - } -] \ No newline at end of file diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/resources/log4j2-test.xml b/dubbo-metadata/dubbo-metadata-rest/src/test/resources/log4j2-test.xml deleted file mode 100644 index ba99f52cc2d..00000000000 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/resources/log4j2-test.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - diff --git a/dubbo-metadata/pom.xml b/dubbo-metadata/pom.xml index 4ef046aa6aa..81af6197aa6 100644 --- a/dubbo-metadata/pom.xml +++ b/dubbo-metadata/pom.xml @@ -28,7 +28,6 @@ pom dubbo-metadata-api - dubbo-metadata-rest dubbo-metadata-definition-protobuf dubbo-metadata-processor dubbo-metadata-report-zookeeper diff --git a/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterTest.java b/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterTest.java index 5304963a042..e8198a3d05f 100644 --- a/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterTest.java +++ b/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterTest.java @@ -51,6 +51,7 @@ class PrometheusMetricsReporterTest { private MetricsConfig metricsConfig; private ApplicationModel applicationModel; private FrameworkModel frameworkModel; + HttpServer prometheusExporterHttpServer; @BeforeEach public void setup() { @@ -64,6 +65,9 @@ public void setup() { @AfterEach public void teardown() { applicationModel.destroy(); + if (prometheusExporterHttpServer != null) { + prometheusExporterHttpServer.stop(0); + } } @Test @@ -146,7 +150,7 @@ void testPushgateway() { private void exportHttpServer(PrometheusMetricsReporter reporter, int port) { try { - HttpServer prometheusExporterHttpServer = HttpServer.create(new InetSocketAddress(port), 0); + prometheusExporterHttpServer = HttpServer.create(new InetSocketAddress(port), 0); prometheusExporterHttpServer.createContext("/metrics", httpExchange -> { reporter.resetIfSamplesChanged(); String response = reporter.getPrometheusRegistry().scrape(); diff --git a/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsThreadPoolTest.java b/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsThreadPoolTest.java index 5591cd8c54c..83b062e1c11 100644 --- a/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsThreadPoolTest.java +++ b/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsThreadPoolTest.java @@ -62,6 +62,8 @@ public class PrometheusMetricsThreadPoolTest { DefaultMetricsCollector metricsCollector; + HttpServer prometheusExporterHttpServer; + @BeforeEach public void setup() { applicationModel = ApplicationModel.defaultModel(); @@ -77,6 +79,9 @@ public void setup() { @AfterEach public void teardown() { applicationModel.destroy(); + if (prometheusExporterHttpServer != null) { + prometheusExporterHttpServer.stop(0); + } } @Test @@ -121,7 +126,7 @@ void testExporterThreadpoolName() { private void exportHttpServer(PrometheusMetricsReporter reporter, int port) { try { - HttpServer prometheusExporterHttpServer = HttpServer.create(new InetSocketAddress(port), 0); + prometheusExporterHttpServer = HttpServer.create(new InetSocketAddress(port), 0); prometheusExporterHttpServer.createContext("/metrics", httpExchange -> { reporter.resetIfSamplesChanged(); String response = reporter.getPrometheusRegistry().scrape(); diff --git a/dubbo-plugin/dubbo-compiler/src/main/resources/ReactorDubbo3TripleStub.mustache b/dubbo-plugin/dubbo-compiler/src/main/resources/ReactorDubbo3TripleStub.mustache index ad9e2e232e5..c36513f9165 100644 --- a/dubbo-plugin/dubbo-compiler/src/main/resources/ReactorDubbo3TripleStub.mustache +++ b/dubbo-plugin/dubbo-compiler/src/main/resources/ReactorDubbo3TripleStub.mustache @@ -54,6 +54,7 @@ public final class {{className}} { private static final StubServiceDescriptor serviceDescriptor = new StubServiceDescriptor(SERVICE_NAME,{{interfaceClassName}}.class); static { + org.apache.dubbo.rpc.protocol.tri.service.SchemaDescriptorRegistry.addSchemaDescriptor(SERVICE_NAME,{{outerClassName}}.getDescriptor()); StubSuppliers.addSupplier(SERVICE_NAME, {{className}}::newStub); StubSuppliers.addSupplier({{interfaceClassName}}.JAVA_SERVICE_NAME, {{className}}::newStub); StubSuppliers.addDescriptor(SERVICE_NAME, serviceDescriptor); diff --git a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java index 00276dda8c1..ac3c1554636 100644 --- a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java +++ b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java @@ -42,7 +42,7 @@ public abstract class AbstractCacheFactory implements CacheFactory { /** * This is used to store factory level-1 cached data. */ - private final ConcurrentMap caches = new ConcurrentHashMap(); + private final ConcurrentMap caches = new ConcurrentHashMap<>(); private final Object MONITOR = new Object(); diff --git a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringMap.java b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringMap.java index cec8854d7d7..9061e7a6f44 100644 --- a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringMap.java +++ b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringMap.java @@ -158,7 +158,7 @@ public void putAll(Map inMap) { @Override public Collection values() { - List list = new ArrayList(); + List list = new ArrayList<>(); Set> delegatedSet = delegateMap.entrySet(); for (Entry entry : delegatedSet) { ExpiryObject value = entry.getValue(); diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/pom.xml b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/pom.xml deleted file mode 100644 index ac2b0b9d64d..00000000000 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/pom.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - 4.0.0 - - org.apache.dubbo - dubbo-plugin - ${revision} - ../pom.xml - - - dubbo-plugin-proxy-bytebuddy - jar - - - - org.apache.dubbo - dubbo-rpc-api - ${project.version} - - - net.bytebuddy - byte-buddy - - - diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyInterceptor.java b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyInterceptor.java deleted file mode 100644 index 25d5311d2e6..00000000000 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyInterceptor.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.proxy.bytebuddy; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; - -import net.bytebuddy.implementation.bind.annotation.AllArguments; -import net.bytebuddy.implementation.bind.annotation.Origin; -import net.bytebuddy.implementation.bind.annotation.RuntimeType; -import net.bytebuddy.implementation.bind.annotation.This; - -public class ByteBuddyInterceptor { - - private final InvocationHandler handler; - - ByteBuddyInterceptor(InvocationHandler handler) { - this.handler = handler; - } - - @RuntimeType - public Object intercept(@This Object obj, @AllArguments Object[] allArguments, @Origin Method method) - throws Throwable { - return handler.invoke(obj, method, allArguments); - } -} diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxy.java b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxy.java deleted file mode 100644 index d414e542a19..00000000000 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxy.java +++ /dev/null @@ -1,130 +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.proxy.bytebuddy; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Proxy; -import java.util.Arrays; -import java.util.Comparator; -import java.util.Map; -import java.util.WeakHashMap; -import java.util.concurrent.ConcurrentHashMap; - -import net.bytebuddy.ByteBuddy; -import net.bytebuddy.description.ByteCodeElement; -import net.bytebuddy.implementation.MethodDelegation; -import net.bytebuddy.matcher.ElementMatcher; -import net.bytebuddy.matcher.ElementMatchers; - -import static org.apache.dubbo.common.constants.CommonConstants.MAX_PROXY_COUNT; - -public class ByteBuddyProxy { - - private static final Map> PROXY_CACHE_MAP = new WeakHashMap<>(); - - private final Class proxyClass; - - private final InvocationHandler handler; - - private ByteBuddyProxy(Class proxyClass, InvocationHandler handler) { - this.proxyClass = proxyClass; - this.handler = handler; - } - - public static Object newInstance(ClassLoader cl, Class[] interfaces, InvocationHandler handler) { - return getProxy(cl, interfaces, handler).newInstance(); - } - - private static ByteBuddyProxy getProxy(ClassLoader cl, Class[] interfaces, InvocationHandler handler) { - if (interfaces.length > MAX_PROXY_COUNT) { - throw new IllegalArgumentException("interface limit exceeded"); - } - interfaces = interfaces.clone(); - Arrays.sort(interfaces, Comparator.comparing(Class::getName)); - CacheKey key = new CacheKey(interfaces); - // get cache by class loader. - final Map cache; - synchronized (PROXY_CACHE_MAP) { - cache = PROXY_CACHE_MAP.computeIfAbsent(cl, k -> new ConcurrentHashMap<>()); - } - - ByteBuddyProxy proxy = cache.get(key); - if (proxy == null) { - synchronized (interfaces[0]) { - proxy = cache.get(key); - if (proxy == null) { - // create ByteBuddyProxy class. - proxy = new ByteBuddyProxy(buildProxyClass(cl, interfaces, handler), handler); - cache.put(key, proxy); - } - } - } - return proxy; - } - - private Object newInstance() { - try { - Constructor constructor = proxyClass.getDeclaredConstructor(InvocationHandler.class); - return constructor.newInstance(handler); - } catch (ReflectiveOperationException e) { - throw new RuntimeException(e); - } - } - - private static Class buildProxyClass(ClassLoader cl, Class[] ics, InvocationHandler handler) { - ElementMatcher.Junction methodMatcher = Arrays.stream(ics) - .map(ElementMatchers::isDeclaredBy) - .reduce(ElementMatcher.Junction::or) - .orElse(ElementMatchers.none()) - .and(ElementMatchers.not(ElementMatchers.isDeclaredBy(Object.class))); - return new ByteBuddy() - .subclass(Proxy.class) - .implement(ics) - .method(methodMatcher) - .intercept(MethodDelegation.to(new ByteBuddyInterceptor(handler))) - .make() - .load(cl) - .getLoaded(); - } - - private static class CacheKey { - - private final Class[] classes; - - private CacheKey(Class[] classes) { - this.classes = classes; - } - - public Class[] getClasses() { - return classes; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - CacheKey that = (CacheKey) o; - return Arrays.equals(classes, that.classes); - } - - @Override - public int hashCode() { - return Arrays.hashCode(classes); - } - } -} diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyFactory.java b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyFactory.java deleted file mode 100644 index 7f346866479..00000000000 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyFactory.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.proxy.bytebuddy; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.proxy.AbstractFallbackJdkProxyFactory; -import org.apache.dubbo.rpc.proxy.InvokerInvocationHandler; - -/** - * ByteBuddyRpcProxyFactory - */ -public class ByteBuddyProxyFactory extends AbstractFallbackJdkProxyFactory { - - @Override - protected Invoker doGetInvoker(T proxy, Class type, URL url) { - return ByteBuddyProxyInvoker.newInstance(proxy, type, url); - } - - @Override - @SuppressWarnings("unchecked") - protected T doGetProxy(Invoker invoker, Class[] interfaces) { - ClassLoader classLoader = invoker.getInterface().getClassLoader(); - return (T) ByteBuddyProxy.newInstance(classLoader, interfaces, new InvokerInvocationHandler(invoker)); - } -} diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyInvoker.java b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyInvoker.java deleted file mode 100644 index 9fd17783849..00000000000 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyInvoker.java +++ /dev/null @@ -1,56 +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.proxy.bytebuddy; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.rpc.proxy.AbstractProxyInvoker; -import org.apache.dubbo.rpc.proxy.MethodInvoker; - -class ByteBuddyProxyInvoker extends AbstractProxyInvoker { - - private final MethodInvoker methodInvoker; - - private ByteBuddyProxyInvoker(T proxy, Class type, URL url, MethodInvoker methodInvoker) { - super(proxy, type, url); - this.methodInvoker = methodInvoker; - } - - @Override - protected Object doInvoke(T instance, String methodName, Class[] parameterTypes, Object[] arguments) - throws Throwable { - if ("getClass".equals(methodName)) { - return instance.getClass(); - } - if ("hashCode".equals(methodName)) { - return instance.hashCode(); - } - if ("toString".equals(methodName)) { - return instance.toString(); - } - if ("equals".equals(methodName)) { - if (arguments.length == 1) { - return instance.equals(arguments[0]); - } - throw new IllegalArgumentException("Invoke method [" + methodName + "] argument number error."); - } - return methodInvoker.invoke(instance, methodName, parameterTypes, arguments); - } - - static ByteBuddyProxyInvoker newInstance(T proxy, Class type, URL url) { - return new ByteBuddyProxyInvoker<>(proxy, type, url, MethodInvoker.newInstance(proxy.getClass())); - } -} diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.ProxyFactory b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.ProxyFactory deleted file mode 100644 index 54bdcb8d11e..00000000000 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.ProxyFactory +++ /dev/null @@ -1 +0,0 @@ -bytebuddy=org.apache.dubbo.rpc.proxy.bytebuddy.ByteBuddyProxyFactory diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/AbstractProxyTest.java b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/AbstractProxyTest.java deleted file mode 100644 index 09158b38dfc..00000000000 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/AbstractProxyTest.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.rpc.proxy; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.ProxyFactory; -import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.service.Destroyable; -import org.apache.dubbo.rpc.service.EchoService; -import org.apache.dubbo.rpc.support.DemoService; -import org.apache.dubbo.rpc.support.DemoServiceImpl; -import org.apache.dubbo.rpc.support.MyInvoker; - -import java.util.Arrays; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public abstract class AbstractProxyTest { - - public static ProxyFactory factory; - - @Test - void testGetProxy() { - URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); - - MyInvoker invoker = new MyInvoker<>(url); - - DemoService proxy = factory.getProxy(invoker); - - Assertions.assertNotNull(proxy); - - Assertions.assertTrue(Arrays.asList(proxy.getClass().getInterfaces()).contains(DemoService.class)); - Assertions.assertTrue(Arrays.asList(proxy.getClass().getInterfaces()).contains(Destroyable.class)); - Assertions.assertTrue(Arrays.asList(proxy.getClass().getInterfaces()).contains(EchoService.class)); - - Assertions.assertEquals( - invoker.invoke(new RpcInvocation( - "echo", - DemoService.class.getName(), - DemoService.class.getName() + ":dubbo", - new Class[] {String.class}, - new Object[] {"aa"})) - .getValue(), - proxy.echo("aa")); - - Destroyable destroyable = (Destroyable) proxy; - destroyable.$destroy(); - Assertions.assertTrue(invoker.isDestroyed()); - } - - @Test - void testGetInvoker() { - URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); - - DemoService origin = new DemoServiceImpl(); - - Invoker invoker = factory.getInvoker(new DemoServiceImpl(), DemoService.class, url); - - Assertions.assertEquals(invoker.getInterface(), DemoService.class); - - Assertions.assertEquals( - invoker.invoke(new RpcInvocation( - "echo", - DemoService.class.getName(), - DemoService.class.getName() + ":dubbo", - new Class[] {String.class}, - new Object[] {"aa"})) - .getValue(), - origin.echo("aa")); - } -} diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/RemoteService.java b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/RemoteService.java deleted file mode 100644 index 1cf9878afe8..00000000000 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/RemoteService.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.rpc.proxy; - -import java.rmi.Remote; -import java.rmi.RemoteException; - -public interface RemoteService extends Remote { - String sayHello(String name) throws RemoteException; - - String getThreadName() throws RemoteException; -} diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyInterceptorTest.java b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyInterceptorTest.java deleted file mode 100644 index 3ea668a5324..00000000000 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyInterceptorTest.java +++ /dev/null @@ -1,45 +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.proxy.bytebuddy; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - -class ByteBuddyInterceptorTest { - - @AfterEach - public void after() { - Mockito.clearAllCaches(); - } - - @Test - void testIntercept() throws Throwable { - InvocationHandler handler = Mockito.mock(InvocationHandler.class); - ByteBuddyInterceptor interceptor = new ByteBuddyInterceptor(handler); - Method method = Mockito.mock(Method.class); - Proxy proxy = Mockito.mock(Proxy.class); - Object[] args = new Object[0]; - interceptor.intercept(proxy, args, method); - // 'intercept' method will call 'invoke' method directly - Mockito.verify(handler, Mockito.times(1)).invoke(proxy, method, args); - } -} diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyFactoryTest.java b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyFactoryTest.java deleted file mode 100644 index 776dfa3d6c7..00000000000 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyFactoryTest.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.rpc.proxy.bytebuddy; - -import org.apache.dubbo.rpc.proxy.AbstractProxyTest; - -class ByteBuddyProxyFactoryTest extends AbstractProxyTest { - - static { - AbstractProxyTest.factory = new ByteBuddyProxyFactory(); - } -} diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyInvokerTest.java b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyInvokerTest.java deleted file mode 100644 index 6dd9c004a38..00000000000 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyInvokerTest.java +++ /dev/null @@ -1,41 +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.proxy.bytebuddy; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.rpc.proxy.RemoteService; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - -class ByteBuddyProxyInvokerTest { - - @Test - void testNewInstance() throws Throwable { - URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); - RemoteService proxy = Mockito.mock(RemoteService.class); - ByteBuddyProxyInvoker invoker = - ByteBuddyProxyInvoker.newInstance(proxy, RemoteService.class, url); - invoker.doInvoke(proxy, "sayHello", new Class[] {String.class}, new Object[] {"test"}); - Mockito.verify(proxy, Mockito.times(1)).sayHello("test"); - - Assertions.assertThrows( - IllegalArgumentException.class, - () -> invoker.doInvoke(proxy, "equals", new Class[] {String.class}, new Object[] {"test", "test2"})); - } -} diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyTest.java b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyTest.java deleted file mode 100644 index 9cf18e41d6b..00000000000 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyTest.java +++ /dev/null @@ -1,44 +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.proxy.bytebuddy; - -import org.apache.dubbo.rpc.proxy.InvokerInvocationHandler; -import org.apache.dubbo.rpc.proxy.RemoteService; - -import java.lang.reflect.Proxy; - -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - -import static org.junit.jupiter.api.Assertions.assertInstanceOf; -import static org.mockito.ArgumentMatchers.any; - -class ByteBuddyProxyTest { - - @Test - void testNewInstance() throws Throwable { - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - InvokerInvocationHandler handler = Mockito.mock(InvokerInvocationHandler.class); - Object proxy = ByteBuddyProxy.newInstance(cl, new Class[] {RemoteService.class}, handler); - assertInstanceOf(RemoteService.class, proxy); - assertInstanceOf(Proxy.class, proxy); - RemoteService remoteService = (RemoteService) proxy; - remoteService.getThreadName(); - remoteService.sayHello("test"); - Mockito.verify(handler, Mockito.times(2)).invoke(any(), any(), any()); - } -} diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/support/DemoService.java b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/support/DemoService.java deleted file mode 100644 index 8bc9395c8b7..00000000000 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/support/DemoService.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.rpc.support; - -public interface DemoService { - String echo(String text); -} diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/support/DemoServiceImpl.java b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/support/DemoServiceImpl.java deleted file mode 100644 index 90fd7b1f84b..00000000000 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/support/DemoServiceImpl.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.rpc.support; - -/** - * DemoServiceImpl - */ -public class DemoServiceImpl implements DemoService { - public String echo(String text) { - return text; - } -} diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java deleted file mode 100644 index 670a3f78855..00000000000 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java +++ /dev/null @@ -1,89 +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.support; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.rpc.AppResponse; -import org.apache.dubbo.rpc.AsyncRpcResult; -import org.apache.dubbo.rpc.Invocation; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.Result; -import org.apache.dubbo.rpc.RpcException; - -import java.util.concurrent.CompletableFuture; - -/** - * MockInvoker.java - */ -public class MyInvoker implements Invoker { - - URL url; - Class type; - boolean hasException = false; - boolean destroyed = false; - - public MyInvoker(URL url) { - this.url = url; - type = (Class) DemoService.class; - } - - public MyInvoker(URL url, boolean hasException) { - this.url = url; - type = (Class) DemoService.class; - this.hasException = hasException; - } - - @Override - public Class getInterface() { - return type; - } - - public URL getUrl() { - return url; - } - - @Override - public boolean isAvailable() { - return false; - } - - @Override - public Result invoke(Invocation invocation) throws RpcException { - AppResponse result = new AppResponse(); - if (!hasException) { - result.setValue("alibaba"); - } else { - result.setException(new RuntimeException("mocked exception")); - } - - return new AsyncRpcResult(CompletableFuture.completedFuture(result), invocation); - } - - @Override - public void destroy() { - destroyed = true; - } - - public boolean isDestroyed() { - return destroyed; - } - - @Override - public String toString() { - return "MyInvoker.toString()"; - } -} diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/resources/log4j2-test.xml b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/resources/log4j2-test.xml deleted file mode 100644 index ba99f52cc2d..00000000000 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/resources/log4j2-test.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/decoder/HttpCommandDecoder.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/decoder/HttpCommandDecoder.java index 77e7fa8928e..2d0367ae6a0 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/decoder/HttpCommandDecoder.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/decoder/HttpCommandDecoder.java @@ -46,7 +46,7 @@ public static CommandContext decode(HttpRequest request) { commandContext = CommandContextFactory.newInstance(name); commandContext.setHttp(true); } else { - List valueList = new ArrayList(); + List valueList = new ArrayList<>(); for (List values : queryStringDecoder.parameters().values()) { valueList.addAll(values); @@ -56,7 +56,7 @@ public static CommandContext decode(HttpRequest request) { } } else if (request.method() == HttpMethod.POST) { HttpPostRequestDecoder httpPostRequestDecoder = new HttpPostRequestDecoder(request); - List valueList = new ArrayList(); + List valueList = new ArrayList<>(); for (InterfaceHttpData interfaceHttpData : httpPostRequestDecoder.getBodyHttpDatas()) { if (interfaceHttpData.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) { Attribute attribute = (Attribute) interfaceHttpData; diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/ChangeTelnet.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/ChangeTelnet.java index e16d7e41b62..4eac865f2c5 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/ChangeTelnet.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/ChangeTelnet.java @@ -58,7 +58,8 @@ public String execute(CommandContext commandContext, String[] args) { for (Exporter exporter : dubboProtocol.getExporters()) { if (message.equals(exporter.getInvoker().getInterface().getSimpleName()) || message.equals(exporter.getInvoker().getInterface().getName()) - || message.equals(exporter.getInvoker().getUrl().getPath())) { + || message.equals(exporter.getInvoker().getUrl().getPath()) + || message.equals(exporter.getInvoker().getUrl().getServiceKey())) { found = true; break; } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/CountTelnet.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/CountTelnet.java index 9d89c983063..e81c8a0c959 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/CountTelnet.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/CountTelnet.java @@ -85,7 +85,8 @@ public String execute(CommandContext commandContext, String[] args) { for (Exporter exporter : dubboProtocol.getExporters()) { if (service.equals(exporter.getInvoker().getInterface().getSimpleName()) || service.equals(exporter.getInvoker().getInterface().getName()) - || service.equals(exporter.getInvoker().getUrl().getPath())) { + || service.equals(exporter.getInvoker().getUrl().getPath()) + || service.equals(exporter.getInvoker().getUrl().getServiceKey())) { invoker = exporter.getInvoker(); break; } @@ -154,8 +155,8 @@ public void send(Channel channel, Object message) throws RemotingException { private String count(Invoker invoker, String method) { URL url = invoker.getUrl(); - List> table = new ArrayList>(); - List header = new ArrayList(); + List> table = new ArrayList<>(); + List header = new ArrayList<>(); header.add("method"); header.add("total"); header.add("failed"); @@ -187,7 +188,7 @@ private String count(Invoker invoker, String method) { } private List createRow(String methodName, RpcStatus count) { - List row = new ArrayList(); + List row = new ArrayList<>(); row.add(methodName); row.add(String.valueOf(count.getTotal())); row.add(String.valueOf(count.getFailed())); diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/util/CommandHelper.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/util/CommandHelper.java index faad6041de8..0889eecf153 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/util/CommandHelper.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/util/CommandHelper.java @@ -46,7 +46,7 @@ public boolean hasCommand(String commandName) { public List> getAllCommandClass() { final Set commandList = frameworkModel.getExtensionLoader(BaseCommand.class).getSupportedExtensions(); - final List> classes = new ArrayList>(); + final List> classes = new ArrayList<>(); for (String commandName : commandList) { BaseCommand command = diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/CtrlCHandler.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/CtrlCHandler.java new file mode 100644 index 00000000000..9a4a203a04b --- /dev/null +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/CtrlCHandler.java @@ -0,0 +1,71 @@ +/* + * 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.qos.server.handler; + +import org.apache.dubbo.qos.common.QosConstants; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; +import io.netty.util.CharsetUtil; + +public class CtrlCHandler extends SimpleChannelInboundHandler { + /** + * When type 'Ctrl+C', telnet client will send the following sequence: + * 'FF F4 FF FD 06', it can be divided into two parts: + *

+ * 1. 'FF F4' is telnet interrupt process command. + *

+ * 2. 'FF FD 06' is to suppress the output of the process that is to be + * interrupted by the interrupt process command. + *

+ * We need to response with 'FF FC 06' to ignore it and tell the client continue + * display output. + */ + private byte[] CTRLC_BYTES_SEQUENCE = new byte[] {(byte) 0xff, (byte) 0xf4, (byte) 0xff, (byte) 0xfd, (byte) 0x06}; + + private byte[] RESPONSE_SEQUENCE = new byte[] {(byte) 0xff, (byte) 0xfc, 0x06}; + + @Override + protected void channelRead0(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception { + // find ctrl+c + final int readerIndex = buffer.readerIndex(); + for (int i = readerIndex; i < buffer.writerIndex(); i++) { + if (buffer.readableBytes() - i < CTRLC_BYTES_SEQUENCE.length) { + break; + } + boolean match = true; + for (int j = 0; j < CTRLC_BYTES_SEQUENCE.length; j++) { + if (CTRLC_BYTES_SEQUENCE[j] != buffer.getByte(i + j)) { + match = false; + break; + } + } + + if (match) { + buffer.readerIndex(readerIndex + buffer.readableBytes()); + ctx.writeAndFlush(Unpooled.wrappedBuffer(RESPONSE_SEQUENCE)); + ctx.writeAndFlush(Unpooled.wrappedBuffer( + (QosConstants.BR_STR + QosProcessHandler.PROMPT).getBytes(CharsetUtil.UTF_8))); + + return; + } + } + ctx.fireChannelRead(buffer); + } +} diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/QosProcessHandler.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/QosProcessHandler.java index 93b9f1d663e..353a2eed7c5 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/QosProcessHandler.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/QosProcessHandler.java @@ -89,6 +89,7 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) t p.addLast(new HttpProcessHandler(frameworkModel, qosConfiguration)); p.remove(this); } else { + p.addLast(new CtrlCHandler()); p.addLast(new LineBasedFrameDecoder(2048)); p.addLast(new StringDecoder(CharsetUtil.UTF_8)); p.addLast(new StringEncoder(CharsetUtil.UTF_8)); diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TLadder.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TLadder.java index f89996d0efb..66e8421c6f8 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TLadder.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TLadder.java @@ -35,7 +35,7 @@ public class TLadder implements TComponent { // indent length private static final int INDENT_STEP = 2; - private final List items = new LinkedList(); + private final List items = new LinkedList<>(); @Override public String rendering() { 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 f96e8571844..326f1be16eb 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 @@ -299,7 +299,7 @@ public static class ColumnDefine { private final Align align; // data rows - private final List rows = new ArrayList(); + private final List rows = new ArrayList<>(); public ColumnDefine(int width, boolean isAutoResize, Align align) { this.width = width; 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 6b599da45a7..8c4d6506825 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 @@ -181,7 +181,7 @@ private static class Node { /** * child nodes */ - final List children = new ArrayList(); + final List children = new ArrayList<>(); /** * begin timestamp diff --git a/dubbo-plugin/dubbo-qos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.qos.api.BaseCommand b/dubbo-plugin/dubbo-qos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.qos.api.BaseCommand index fb1e1171fac..a837d2b7024 100644 --- a/dubbo-plugin/dubbo-qos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.qos.api.BaseCommand +++ b/dubbo-plugin/dubbo-qos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.qos.api.BaseCommand @@ -11,7 +11,7 @@ ready=org.apache.dubbo.qos.command.impl.Ready startup=org.apache.dubbo.qos.command.impl.Startup live=org.apache.dubbo.qos.command.impl.Live version=org.apache.dubbo.qos.command.impl.Version -publish-metadata=org.apache.dubbo.qos.command.impl.PublishMetadata +publishMetadata=org.apache.dubbo.qos.command.impl.PublishMetadata cd=org.apache.dubbo.qos.command.impl.ChangeTelnet count=org.apache.dubbo.qos.command.impl.CountTelnet pwd=org.apache.dubbo.qos.command.impl.PwdTelnet diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/ChangeTelnetTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/ChangeTelnetTest.java index 6a8b67531d0..a182a5e168e 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/ChangeTelnetTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/ChangeTelnetTest.java @@ -71,7 +71,7 @@ public void beforeEach() { mockChannel.attr(ChangeTelnet.SERVICE_KEY).set("org.apache.dubbo.rpc.protocol.dubbo.support.DemoService"); given(mockCommandContext.getRemote()).willReturn(mockChannel); given(mockInvoker.getInterface()).willReturn(DemoService.class); - given(mockInvoker.getUrl()).willReturn(URL.valueOf("dubbo://127.0.0.1:20884/demo")); + given(mockInvoker.getUrl()).willReturn(URL.valueOf("dubbo://127.0.0.1:20884/demo?group=g&version=1.0.0")); } @AfterEach @@ -110,6 +110,15 @@ void testChangePath() { assertEquals("Used the demo as default.\r\nYou can cancel default service by command: cd /", result); } + @Test + void testChangeServiceKey() { + ExtensionLoader.getExtensionLoader(Protocol.class) + .getExtension(DubboProtocol.NAME) + .export(mockInvoker); + String result = change.execute(mockCommandContext, new String[] {"g/demo:1.0.0"}); + assertEquals("Used the g/demo:1.0.0 as default.\r\nYou can cancel default service by command: cd /", result); + } + @Test void testChangeMessageNull() { String result = change.execute(mockCommandContext, null); diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/CountTelnetTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/CountTelnetTest.java index 0777e395464..a1eafa4daa9 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/CountTelnetTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/CountTelnetTest.java @@ -52,7 +52,7 @@ class CountTelnetTest { private CommandContext mockCommandContext; private CountDownLatch latch; - private final URL url = URL.valueOf("dubbo://127.0.0.1:20884/demo"); + private final URL url = URL.valueOf("dubbo://127.0.0.1:20884/demo?group=g&version=1.0.0"); @BeforeEach public void setUp() { @@ -70,12 +70,14 @@ public void setUp() { public void tearDown() { FrameworkModel.destroyAll(); mockChannel.close(); + RpcStatus.removeStatus(url); reset(mockInvoker, mockCommandContext); } @Test void test() throws Exception { String methodName = "sayHello"; + RpcStatus.removeStatus(url, methodName); String[] args = new String[] {"org.apache.dubbo.qos.legacy.service.DemoService", "sayHello", "1"}; ExtensionLoader.getExtensionLoader(Protocol.class) @@ -94,6 +96,28 @@ void test() throws Exception { assertThat(sb.toString(), containsString(buildTable(methodName, 10, 10, "1", "0", "0"))); } + @Test + void testCountByServiceKey() throws Exception { + String methodName = "sayHello"; + RpcStatus.removeStatus(url, methodName); + String[] args = new String[] {"g/demo:1.0.0", "sayHello", "1"}; + + ExtensionLoader.getExtensionLoader(Protocol.class) + .getExtension(DubboProtocol.NAME) + .export(mockInvoker); + RpcStatus.beginCount(url, methodName); + RpcStatus.endCount(url, methodName, 10L, true); + count.execute(mockCommandContext, args); + latch.await(); + + StringBuilder sb = new StringBuilder(); + for (Object o : mockChannel.getReceivedObjects()) { + sb.append(o.toString()); + } + + assertThat(sb.toString(), containsString(buildTable(methodName, 10, 10, "1", "0", "0"))); + } + public static String buildTable( String methodName, long averageElapsed, long maxElapsed, String total, String failed, String active) { List header = new LinkedList<>(); diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/LiveTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/LiveTest.java index 60da31680a8..70a90986b86 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/LiveTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/LiveTest.java @@ -35,6 +35,7 @@ public void setUp() { @AfterEach public void reset() { frameworkModel.destroy(); + MockLivenessProbe.setCheckReturnValue(false); } @Test diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/CtrlCHandlerTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/CtrlCHandlerTest.java new file mode 100644 index 00000000000..0ed51753478 --- /dev/null +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/CtrlCHandlerTest.java @@ -0,0 +1,74 @@ +/* + * 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.qos.server.handler; + +import org.apache.dubbo.qos.common.QosConstants; + +import java.nio.charset.StandardCharsets; + +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerContext; +import io.netty.util.CharsetUtil; +import org.junit.jupiter.api.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +public class CtrlCHandlerTest { + private byte[] CTRLC_BYTES_SEQUENCE = new byte[] {(byte) 0xff, (byte) 0xf4, (byte) 0xff, (byte) 0xfd, (byte) 0x06}; + + private byte[] RESPONSE_SEQUENCE = new byte[] {(byte) 0xff, (byte) 0xfc, 0x06}; + + @Test + void testMatchedExactly() throws Exception { + ChannelHandlerContext context = mock(ChannelHandlerContext.class); + CtrlCHandler ctrlCHandler = new CtrlCHandler(); + ctrlCHandler.channelRead(context, Unpooled.wrappedBuffer(CTRLC_BYTES_SEQUENCE)); + verify(context).writeAndFlush(Unpooled.wrappedBuffer(RESPONSE_SEQUENCE)); + verify(context) + .writeAndFlush(Unpooled.wrappedBuffer( + (QosConstants.BR_STR + QosProcessHandler.PROMPT).getBytes(CharsetUtil.UTF_8))); + } + + @Test + void testMatchedNotExactly() throws Exception { + ChannelHandlerContext context = mock(ChannelHandlerContext.class); + CtrlCHandler ctrlCHandler = new CtrlCHandler(); + // before 'ctrl c', user typed other command like 'help' + String arbitraryCommand = "help"; + byte[] commandBytes = arbitraryCommand.getBytes(StandardCharsets.UTF_8); + ctrlCHandler.channelRead(context, Unpooled.wrappedBuffer(commandBytes, CTRLC_BYTES_SEQUENCE)); + verify(context).writeAndFlush(Unpooled.wrappedBuffer(RESPONSE_SEQUENCE)); + verify(context) + .writeAndFlush(Unpooled.wrappedBuffer( + (QosConstants.BR_STR + QosProcessHandler.PROMPT).getBytes(CharsetUtil.UTF_8))); + } + + @Test + void testNotMatched() throws Exception { + ChannelHandlerContext context = mock(ChannelHandlerContext.class); + CtrlCHandler ctrlCHandler = new CtrlCHandler(); + String arbitraryCommand = "help" + QosConstants.BR_STR; + byte[] commandBytes = arbitraryCommand.getBytes(StandardCharsets.UTF_8); + ctrlCHandler.channelRead(context, Unpooled.wrappedBuffer(commandBytes)); + verify(context, never()).writeAndFlush(Unpooled.wrappedBuffer(RESPONSE_SEQUENCE)); + verify(context, never()) + .writeAndFlush(Unpooled.wrappedBuffer( + (QosConstants.BR_STR + QosProcessHandler.PROMPT).getBytes(CharsetUtil.UTF_8))); + } +} diff --git a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/AbstractTripleReactorSubscriber.java b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/AbstractTripleReactorSubscriber.java index 86db8575829..b3d6fa058e7 100644 --- a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/AbstractTripleReactorSubscriber.java +++ b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/AbstractTripleReactorSubscriber.java @@ -53,7 +53,7 @@ public void subscribe(final CallStreamObserver downstream) { if (downstream == null) { throw new NullPointerException(); } - if (this.downstream == null && SUBSCRIBED.compareAndSet(false, true)) { + if (SUBSCRIBED.compareAndSet(false, true)) { this.downstream = downstream; subscription.request(1); } diff --git a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ServerTripleReactorSubscriber.java b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ServerTripleReactorSubscriber.java index ce4206b2b68..3a4a9729a00 100644 --- a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ServerTripleReactorSubscriber.java +++ b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ServerTripleReactorSubscriber.java @@ -20,11 +20,31 @@ import org.apache.dubbo.rpc.protocol.tri.CancelableStreamObserver; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; + /** * The Subscriber in server to passing the data produced by user publisher to responseStream. */ public class ServerTripleReactorSubscriber extends AbstractTripleReactorSubscriber { + /** + * The execution future of the current task, in order to be returned to stubInvoker + */ + private final CompletableFuture> executionFuture = new CompletableFuture<>(); + /** + * The result elements collected by the current task. + * This class is a flux subscriber, which usually means there will be multiple elements, so it is declared as a list type. + */ + private final List collectedData = new ArrayList<>(); + + public ServerTripleReactorSubscriber() {} + + public ServerTripleReactorSubscriber(CallStreamObserver streamObserver) { + this.downstream = streamObserver; + } + @Override public void subscribe(CallStreamObserver downstream) { super.subscribe(downstream); @@ -40,4 +60,26 @@ public void subscribe(CallStreamObserver downstream) { context.addListener(ctx -> super.cancel()); } } + + @Override + public void onNext(T t) { + super.onNext(t); + collectedData.add(t); + } + + @Override + public void onError(Throwable throwable) { + super.onError(throwable); + executionFuture.completeExceptionally(throwable); + } + + @Override + public void onComplete() { + super.onComplete(); + executionFuture.complete(this.collectedData); + } + + public CompletableFuture> getExecutionFuture() { + return executionFuture; + } } diff --git a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/calls/ReactorServerCalls.java b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/calls/ReactorServerCalls.java index b514bfaf44f..3e1de817c69 100644 --- a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/calls/ReactorServerCalls.java +++ b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/calls/ReactorServerCalls.java @@ -19,8 +19,11 @@ import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.reactive.ServerTripleReactorPublisher; import org.apache.dubbo.reactive.ServerTripleReactorSubscriber; +import org.apache.dubbo.rpc.StatusRpcException; +import org.apache.dubbo.rpc.TriRpcStatus; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; +import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.Function; @@ -42,16 +45,18 @@ private ReactorServerCalls() {} * @param func service implementation */ public static void oneToOne(T request, StreamObserver responseObserver, Function, Mono> func) { - func.apply(Mono.just(request)).subscribe(res -> { - CompletableFuture.completedFuture(res).whenComplete((r, t) -> { - if (t != null) { - responseObserver.onError(t); - } else { - responseObserver.onNext(r); - responseObserver.onCompleted(); - } - }); - }); + try { + func.apply(Mono.just(request)) + .subscribe( + res -> { + responseObserver.onNext(res); + responseObserver.onCompleted(); + }, + throwable -> doOnResponseHasException(throwable, responseObserver), + () -> doOnResponseHasException(TriRpcStatus.NOT_FOUND.asException(), responseObserver)); + } catch (Throwable throwable) { + doOnResponseHasException(throwable, responseObserver); + } } /** @@ -61,14 +66,20 @@ public static void oneToOne(T request, StreamObserver responseObserver * @param responseObserver response StreamObserver * @param func service implementation */ - public static void oneToMany( + public static CompletableFuture> oneToMany( T request, StreamObserver responseObserver, Function, Flux> func) { try { + CallStreamObserver callStreamObserver = (CallStreamObserver) responseObserver; Flux response = func.apply(Mono.just(request)); - ServerTripleReactorSubscriber subscriber = response.subscribeWith(new ServerTripleReactorSubscriber<>()); - subscriber.subscribe((CallStreamObserver) responseObserver); + ServerTripleReactorSubscriber reactorSubscriber = + new ServerTripleReactorSubscriber<>(callStreamObserver); + response.subscribeWith(reactorSubscriber).subscribe(callStreamObserver); + return reactorSubscriber.getExecutionFuture(); } catch (Throwable throwable) { - responseObserver.onError(throwable); + doOnResponseHasException(throwable, responseObserver); + CompletableFuture> future = new CompletableFuture<>(); + future.completeExceptionally(throwable); + return future; } } @@ -82,7 +93,7 @@ public static void oneToMany( public static StreamObserver manyToOne( StreamObserver responseObserver, Function, Mono> func) { ServerTripleReactorPublisher serverPublisher = - new ServerTripleReactorPublisher((CallStreamObserver) responseObserver); + new ServerTripleReactorPublisher<>((CallStreamObserver) responseObserver); try { Mono responseMono = func.apply(Flux.from(serverPublisher)); responseMono.subscribe( @@ -117,7 +128,7 @@ public static StreamObserver manyToMany( StreamObserver responseObserver, Function, Flux> func) { // responseObserver is also a subscription of publisher, we can use it to request more data ServerTripleReactorPublisher serverPublisher = - new ServerTripleReactorPublisher((CallStreamObserver) responseObserver); + new ServerTripleReactorPublisher<>((CallStreamObserver) responseObserver); try { Flux responseFlux = func.apply(Flux.from(serverPublisher)); ServerTripleReactorSubscriber serverSubscriber = @@ -130,4 +141,10 @@ public static StreamObserver manyToMany( return serverPublisher; } + + private static void doOnResponseHasException(Throwable throwable, StreamObserver responseObserver) { + StatusRpcException statusRpcException = + TriRpcStatus.getStatus(throwable).asException(); + responseObserver.onError(statusRpcException); + } } diff --git a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/OneToManyMethodHandler.java b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/OneToManyMethodHandler.java index b5b0534fff6..fc2e4df9f00 100644 --- a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/OneToManyMethodHandler.java +++ b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/OneToManyMethodHandler.java @@ -42,7 +42,6 @@ public OneToManyMethodHandler(Function, Flux> func) { public CompletableFuture invoke(Object[] arguments) { T request = (T) arguments[0]; StreamObserver responseObserver = (StreamObserver) arguments[1]; - ReactorServerCalls.oneToMany(request, responseObserver, func); - return CompletableFuture.completedFuture(null); + return ReactorServerCalls.oneToMany(request, responseObserver, func); } } diff --git a/dubbo-plugin/dubbo-rest-jaxrs/pom.xml b/dubbo-plugin/dubbo-rest-jaxrs/pom.xml index 26ab19d02f0..6370496dfae 100644 --- a/dubbo-plugin/dubbo-rest-jaxrs/pom.xml +++ b/dubbo-plugin/dubbo-rest-jaxrs/pom.xml @@ -62,41 +62,5 @@ jaxb-runtime test - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - test - - - javax.validation - validation-api - - - io.swagger - swagger-jaxrs - - - io.swagger - swagger-annotations - - - org.eclipse.jetty - jetty-servlet - - - org.apache.tomcat.embed - tomcat-embed-core - - - org.eclipse.jetty - jetty-server - - - org.jboss.resteasy - resteasy-client - - - diff --git a/dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/JaxrsRestProtocolTest.java b/dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/JaxrsRestProtocolTest.java index 9caa0b6a93f..fa4b681843c 100644 --- a/dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/JaxrsRestProtocolTest.java +++ b/dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/JaxrsRestProtocolTest.java @@ -53,6 +53,7 @@ import org.jboss.resteasy.specimpl.MultivaluedMapImpl; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import static org.apache.dubbo.remoting.Constants.SERVER_KEY; @@ -60,6 +61,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; +@Disabled class JaxrsRestProtocolTest { private final Protocol tProtocol = ApplicationModel.defaultModel().getExtensionLoader(Protocol.class).getExtension("tri"); diff --git a/dubbo-plugin/dubbo-rest-spring/pom.xml b/dubbo-plugin/dubbo-rest-spring/pom.xml index 5366743d486..21b3d9c084c 100644 --- a/dubbo-plugin/dubbo-rest-spring/pom.xml +++ b/dubbo-plugin/dubbo-rest-spring/pom.xml @@ -71,45 +71,5 @@ jaxb-runtime test - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - test - - - javax.validation - validation-api - - - io.swagger - swagger-jaxrs - - - io.swagger - swagger-annotations - - - org.eclipse.jetty - jetty-servlet - - - org.apache.tomcat.embed - tomcat-embed-core - - - org.apache.httpcomponents - httpclient - - - org.eclipse.jetty - jetty-server - - - org.jboss.resteasy - resteasy-client - - - diff --git a/dubbo-plugin/dubbo-rest-spring/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/compatible/SpringMvcRestProtocolTest.java b/dubbo-plugin/dubbo-rest-spring/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/compatible/SpringMvcRestProtocolTest.java index 6e124fe2ae8..b3b8107dc4b 100644 --- a/dubbo-plugin/dubbo-rest-spring/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/compatible/SpringMvcRestProtocolTest.java +++ b/dubbo-plugin/dubbo-rest-spring/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/compatible/SpringMvcRestProtocolTest.java @@ -36,6 +36,7 @@ import org.hamcrest.CoreMatchers; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.springframework.aop.framework.AdvisedSupport; import org.springframework.aop.framework.AopProxy; @@ -46,6 +47,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; +@Disabled public class SpringMvcRestProtocolTest { private final Protocol tProtocol = ApplicationModel.defaultModel().getExtensionLoader(Protocol.class).getExtension("tri"); diff --git a/dubbo-plugin/pom.xml b/dubbo-plugin/pom.xml index a345ab5db26..fa1466ef0a2 100644 --- a/dubbo-plugin/pom.xml +++ b/dubbo-plugin/pom.xml @@ -40,7 +40,6 @@ dubbo-compiler dubbo-filter-cache dubbo-filter-validation - dubbo-plugin-proxy-bytebuddy dubbo-rest-jaxrs dubbo-rest-servlet dubbo-rest-spring diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java index 341d8926f84..48775813211 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java @@ -84,7 +84,7 @@ public AbstractServiceDiscovery(ApplicationModel applicationModel, URL registryU this(applicationModel, applicationModel.getApplicationName(), registryURL); MetadataReportInstance metadataReportInstance = applicationModel.getBeanFactory().getBean(MetadataReportInstance.class); - metadataType = metadataReportInstance.getMetadataType(); + this.metadataType = metadataReportInstance.getMetadataType(); this.metadataReport = metadataReportInstance.getMetadataReport(registryURL.getParameter(REGISTRY_CLUSTER_KEY)); } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryDirectory.java index 4304cf2a272..74c35a746d4 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryDirectory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryDirectory.java @@ -791,6 +791,12 @@ public Result invoke(Invocation invocation) throws RpcException { invocation instanceof RpcInvocation ? ((RpcInvocation) invocation).getInvokeMode() : null); copiedInvocation.setObjectAttachment(CommonConstants.GROUP_KEY, protocolServiceKey.getGroup()); copiedInvocation.setObjectAttachment(CommonConstants.VERSION_KEY, protocolServiceKey.getVersion()); + // When there are multiple MethodDescriptors with the same method name, the return type will be wrong + // same with org.apache.dubbo.rpc.stub.StubInvocationUtil.call + // fix https://github.com/apache/dubbo/issues/13931 + if (invocation instanceof RpcInvocation) { + copiedInvocation.setReturnType(((RpcInvocation) invocation).getReturnType()); + } return originInvoker.invoke(copiedInvocation); } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceNameMapping.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceNameMapping.java index 62322d820b6..57c7dd51d36 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceNameMapping.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceNameMapping.java @@ -109,7 +109,7 @@ public boolean map(URL url) { String[] oldAppNames = oldConfigContent.split(","); if (oldAppNames.length > 0) { for (String oldAppName : oldAppNames) { - if (oldAppName.equals(appName)) { + if (StringUtils.trim(oldAppName).equals(appName)) { succeeded = true; break; } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationRuleHandler.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationRuleHandler.java index ccf2dd8cd6a..e83ace2c3c6 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationRuleHandler.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationRuleHandler.java @@ -23,6 +23,8 @@ import org.apache.dubbo.registry.client.migration.model.MigrationRule; import org.apache.dubbo.registry.client.migration.model.MigrationStep; +import java.util.concurrent.locks.ReentrantLock; + import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_NO_PARAMETERS_URL; @@ -35,33 +37,43 @@ public class MigrationRuleHandler { private volatile MigrationStep currentStep; private volatile Float currentThreshold = 0f; private final URL consumerURL; + private final ReentrantLock lock = new ReentrantLock(); public MigrationRuleHandler(MigrationClusterInvoker invoker, URL url) { this.migrationInvoker = invoker; this.consumerURL = url; } - public synchronized void doMigrate(MigrationRule rule) { - if (migrationInvoker instanceof ServiceDiscoveryMigrationInvoker) { - refreshInvoker(MigrationStep.FORCE_APPLICATION, 1.0f, rule); - return; - } + public void doMigrate(MigrationRule rule) { + lock.lock(); + try { + if (migrationInvoker instanceof ServiceDiscoveryMigrationInvoker) { + refreshInvoker(MigrationStep.FORCE_APPLICATION, 1.0f, rule); + return; + } - // initial step : APPLICATION_FIRST - MigrationStep step = MigrationStep.APPLICATION_FIRST; - float threshold = -1f; + // initial step : APPLICATION_FIRST + MigrationStep step = MigrationStep.APPLICATION_FIRST; + float threshold = -1f; - try { - step = rule.getStep(consumerURL); - threshold = rule.getThreshold(consumerURL); - } catch (Exception e) { - logger.error( - REGISTRY_NO_PARAMETERS_URL, "", "", "Failed to get step and threshold info from rule: " + rule, e); - } + try { + step = rule.getStep(consumerURL); + threshold = rule.getThreshold(consumerURL); + } catch (Exception e) { + logger.error( + REGISTRY_NO_PARAMETERS_URL, + "", + "", + "Failed to get step and threshold info from rule: " + rule, + e); + } - if (refreshInvoker(step, threshold, rule)) { - // refresh success, update rule - setMigrationRule(rule); + if (refreshInvoker(step, threshold, rule)) { + // refresh success, update rule + setMigrationRule(rule); + } + } finally { + lock.unlock(); } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/InterfaceCompatibleRegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/InterfaceCompatibleRegistryProtocol.java index ba3e936d161..8ee41924a25 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/InterfaceCompatibleRegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/InterfaceCompatibleRegistryProtocol.java @@ -75,6 +75,6 @@ protected ClusterInvoker getMigrationInvoker( URL url, URL consumerUrl) { // ClusterInvoker invoker = getInvoker(cluster, registry, type, url); - return new MigrationInvoker(registryProtocol, cluster, registry, type, url, consumerUrl); + return new MigrationInvoker<>(registryProtocol, cluster, registry, type, url, consumerUrl); } } diff --git a/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java b/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java index c5e386bb993..6763543c7c0 100644 --- a/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java +++ b/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java @@ -82,7 +82,7 @@ public class MulticastRegistry extends FailbackRegistry { private final int multicastPort; - private final ConcurrentMap> received = new ConcurrentHashMap>(); + private final ConcurrentMap> received = new ConcurrentHashMap<>(); private final ScheduledExecutorService cleanExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("DubboMulticastRegistryCleanTimer", true)); @@ -361,7 +361,7 @@ protected void unregistered(URL url) { } if (urls == null || urls.isEmpty()) { if (urls == null) { - urls = new ConcurrentHashSet(); + urls = new ConcurrentHashSet<>(); } URL empty = url.setProtocol(EMPTY_PROTOCOL); urls.add(empty); @@ -380,7 +380,7 @@ protected void subscribed(URL url, NotifyListener listener) { } private List toList(Set urls) { - List list = new ArrayList(); + List list = new ArrayList<>(); if (CollectionUtils.isNotEmpty(urls)) { list.addAll(urls); } diff --git a/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleRegistry.java b/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleRegistry.java index 44a2e571261..4a7edf788be 100644 --- a/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleRegistry.java +++ b/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleRegistry.java @@ -268,7 +268,7 @@ public List getEffectReferenceRegistryURLs() { protected static class MultipleNotifyListenerWrapper implements NotifyListener { - Map registryMap = new ConcurrentHashMap(4); + Map registryMap = new ConcurrentHashMap<>(4); NotifyListener sourceNotifyListener; public MultipleNotifyListenerWrapper(NotifyListener sourceNotifyListener) { diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java index ea53a2035b9..b2e934c1948 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java @@ -37,6 +37,7 @@ import java.util.Arrays; import java.util.Collection; import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; @@ -73,6 +74,7 @@ import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_ENABLE_EMPTY_PROTECTION; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.ENABLE_EMPTY_PROTECTION_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.NACOE_REGISTER_COMPATIBLE; import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_CONSUMER_URL_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; @@ -109,9 +111,8 @@ public class NacosRegistry extends FailbackRegistry { private static final String UP = "UP"; /** - * The separator for service name - * Change a constant to be configurable, it's designed for Windows file name that is compatible with old - * Nacos binary release(< 0.6.1) + * The separator for service name Change a constant to be configurable, it's designed for Windows file name that is + * compatible with old Nacos binary release(< 0.6.1) */ private static final String SERVICE_NAME_SEPARATOR = SystemPropertyConfigUtils.getSystemProperty( CommonConstants.ThirdPartyProperty.NACOS_SERVICE_NAME_SEPARATOR, ":"); @@ -177,18 +178,33 @@ public List lookup(final URL url) { public void doRegister(URL url) { try { if (PROVIDER_SIDE.equals(url.getSide()) || getUrl().getParameter(REGISTER_CONSUMER_URL_KEY, false)) { - String serviceName = getServiceName(url); Instance instance = createInstance(url); + + Set serviceNames = new HashSet<>(); + // by default servicename is "org.apache.dubbo.xxService:1.0.0:" + String serviceName = getServiceName(url, false); + serviceNames.add(serviceName); + + // in https://github.com/apache/dubbo/issues/14075 + if (getUrl().getParameter(NACOE_REGISTER_COMPATIBLE, false)) { + // servicename is "org.apache.dubbo.xxService:1.0.0" + String compatibleServiceName = getServiceName(url, true); + serviceNames.add(compatibleServiceName); + } + /** - * namingService.registerInstance with {@link org.apache.dubbo.registry.support.AbstractRegistry#registryUrl} + * namingService.registerInstance with + * {@link org.apache.dubbo.registry.support.AbstractRegistry#registryUrl} * default {@link DEFAULT_GROUP} * * in https://github.com/apache/dubbo/issues/5978 */ - namingService.registerInstance(serviceName, getUrl().getGroup(Constants.DEFAULT_GROUP), instance); + for (String service : serviceNames) { + namingService.registerInstance(service, getUrl().getGroup(Constants.DEFAULT_GROUP), instance); + } } else { - logger.info( - "Please set 'dubbo.registry.parameters.register-consumer-url=true' to turn on consumer url registration."); + logger.info("Please set 'dubbo.registry.parameters.register-consumer-url=true' to turn on consumer " + + "url registration."); } } catch (SkipFailbackWrapperException exception) { throw exception; @@ -201,10 +217,24 @@ public void doRegister(URL url) { @Override public void doUnregister(final URL url) { try { - String serviceName = getServiceName(url); Instance instance = createInstance(url); - namingService.deregisterInstance( - serviceName, getUrl().getGroup(Constants.DEFAULT_GROUP), instance.getIp(), instance.getPort()); + + Set serviceNames = new HashSet<>(); + // by default servicename is "org.apache.dubbo.xxService:1.0.0:" + String serviceName = getServiceName(url, false); + serviceNames.add(serviceName); + + // in https://github.com/apache/dubbo/issues/14075 + if (getUrl().getParameter(NACOE_REGISTER_COMPATIBLE, false)) { + // servicename is "org.apache.dubbo.xxService:1.0.0" + String serviceName1 = getServiceName(url, true); + serviceNames.add(serviceName1); + } + + for (String service : serviceNames) { + namingService.deregisterInstance( + service, getUrl().getGroup(Constants.DEFAULT_GROUP), instance.getIp(), instance.getPort()); + } } catch (SkipFailbackWrapperException exception) { throw exception; } catch (Exception cause) { @@ -233,7 +263,8 @@ private void doSubscribe(final URL url, final NacosAggregateListener listener, f * Get all instances with serviceNames to avoid instance overwrite and but with empty instance mentioned * in https://github.com/apache/dubbo/issues/5885 and https://github.com/apache/dubbo/issues/5899 * - * namingService.getAllInstances with {@link org.apache.dubbo.registry.support.AbstractRegistry#registryUrl} + * namingService.getAllInstances with + * {@link org.apache.dubbo.registry.support.AbstractRegistry#registryUrl} * default {@link DEFAULT_GROUP} * * in https://github.com/apache/dubbo/issues/5978 @@ -271,8 +302,8 @@ private void doSubscribe(final URL url, final NacosAggregateListener listener, f } /** - * Since 2.7.6 the legacy service name will be added to serviceNames - * to fix bug with https://github.com/apache/dubbo/issues/5442 + * Since 2.7.6 the legacy service name will be added to serviceNames to fix bug with + * https://github.com/apache/dubbo/issues/5442 * * @param url * @return @@ -293,7 +324,8 @@ public void doUnsubscribe(URL url, NotifyListener listener) { "", "", String.format( - "No aggregate listener found for url %s, this service might have already been unsubscribed.", + "No aggregate listener found for url %s, " + + "this service might have already been unsubscribed.", url)); return; } @@ -584,7 +616,8 @@ private List toUrlWithEmpty(URL consumerURL, Collection instances REGISTRY_NACOS_EXCEPTION, "", "", - "Received empty url address list and empty protection is disabled, will clear current available addresses"); + "Received empty url address list and empty protection is " + + "disabled, will clear current available addresses"); URL empty = URLBuilder.from(consumerURL) .setProtocol(EMPTY_PROTOCOL) .addParameter(CATEGORY_KEY, DEFAULT_CATEGORY) @@ -700,7 +733,10 @@ private NacosServiceName createServiceName(URL url) { return valueOf(url); } - private String getServiceName(URL url) { + private String getServiceName(URL url, boolean needCompatible) { + if (needCompatible) { + return getCompatibleServiceName(url, url.getCategory(DEFAULT_CATEGORY)); + } return getServiceName(url, url.getCategory(DEFAULT_CATEGORY)); } @@ -708,6 +744,10 @@ private String getServiceName(URL url, String category) { return category + SERVICE_NAME_SEPARATOR + url.getColonSeparatedKey(); } + private String getCompatibleServiceName(URL url, String category) { + return category + SERVICE_NAME_SEPARATOR + url.getCompatibleColonSeparatedKey(); + } + private void filterEnabledInstances(Collection instances) { filterData(instances, Instance::isEnabled); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ReplierDispatcher.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ReplierDispatcher.java index 549593a888a..979c49c2a5e 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ReplierDispatcher.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ReplierDispatcher.java @@ -30,7 +30,7 @@ public class ReplierDispatcher implements Replier { private final Replier defaultReplier; - private final Map, Replier> repliers = new ConcurrentHashMap, Replier>(); + private final Map, Replier> repliers = new ConcurrentHashMap<>(); public ReplierDispatcher() { this(null, null); 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 340c50c724d..2204076aba8 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 @@ -161,7 +161,7 @@ private void cancelCloseTask() { @Override public Collection getExchangeChannels() { - Collection exchangeChannels = new ArrayList(); + Collection exchangeChannels = new ArrayList<>(); Collection channels = server.getChannels(); if (CollectionUtils.isNotEmpty(channels)) { for (Channel channel : channels) { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/codec/TelnetCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/codec/TelnetCodec.java index c106572e3f3..3f1140b22c5 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/codec/TelnetCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/codec/TelnetCodec.java @@ -283,7 +283,7 @@ protected Object decode(Channel channel, ChannelBuffer buffer, int readable, byt String result = toString(message, getCharset(channel)); if (result.trim().length() > 0) { if (history == null) { - history = new LinkedList(); + history = new LinkedList<>(); channel.setAttribute(HISTORY_LIST_KEY, history); } if (history.isEmpty()) { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/HelpTelnetHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/HelpTelnetHandler.java index da5b7273985..f33c61360b6 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/HelpTelnetHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/HelpTelnetHandler.java @@ -73,12 +73,12 @@ private String generateForOneCommand(String message) { } private String generateForAllCommand(Channel channel) { - List> table = new ArrayList>(); + List> table = new ArrayList<>(); List handlers = extensionLoader.getActivateExtension(channel.getUrl(), "telnet"); if (CollectionUtils.isNotEmpty(handlers)) { for (TelnetHandler handler : handlers) { Help help = handler.getClass().getAnnotation(Help.class); - List row = new ArrayList(); + List row = new ArrayList<>(); String parameter = " " + extensionLoader.getExtensionName(handler) + " " + (help != null ? help.parameter().replace("\r\n", " ").replace("\n", " ") : ""); row.add(parameter.length() > 55 ? parameter.substring(0, 55) + "..." : parameter); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/StatusTelnetHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/StatusTelnetHandler.java index f65966321cd..d111a87fc91 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/StatusTelnetHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/StatusTelnetHandler.java @@ -53,8 +53,8 @@ public String telnet(Channel channel, String message) { if ("-l".equals(message)) { List checkers = extensionLoader.getActivateExtension(channel.getUrl(), STATUS_KEY); String[] header = new String[] {"resource", "status", "message"}; - List> table = new ArrayList>(); - Map statuses = new HashMap(); + List> table = new ArrayList<>(); + Map statuses = new HashMap<>(); if (CollectionUtils.isNotEmpty(checkers)) { for (StatusChecker checker : checkers) { String name = extensionLoader.getExtensionName(checker); @@ -66,7 +66,7 @@ public String telnet(Channel channel, String message) { } statuses.put(name, stat); if (stat.getLevel() != null && stat.getLevel() != Status.Level.UNKNOWN) { - List row = new ArrayList(); + List row = new ArrayList<>(); row.add(name); row.add(String.valueOf(stat.getLevel())); row.add(stat.getMessage() == null ? "" : stat.getMessage()); @@ -75,7 +75,7 @@ public String telnet(Channel channel, String message) { } } Status stat = StatusUtils.getSummaryStatus(statuses); - List row = new ArrayList(); + List row = new ArrayList<>(); row.add("summary"); row.add(String.valueOf(stat.getLevel())); row.add(stat.getMessage()); @@ -85,7 +85,7 @@ public String telnet(Channel channel, String message) { return "Unsupported parameter " + message + " for status."; } String status = channel.getUrl().getParameter("status"); - Map statuses = new HashMap(); + Map statuses = new HashMap<>(); if (StringUtils.isNotEmpty(status)) { String[] ss = COMMA_SPLIT_PATTERN.split(status); for (String s : ss) { 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 7b465c66498..7be50fff2e9 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 @@ -21,6 +21,7 @@ import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.threadpool.manager.ExecutorRepository; +import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; @@ -28,9 +29,11 @@ import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.transport.dispatcher.ChannelHandlers; +import org.apache.dubbo.rpc.model.FrameworkModel; import java.net.InetSocketAddress; import java.util.concurrent.ExecutorService; +import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; @@ -41,6 +44,11 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CONNECT_PROVIDER; import static org.apache.dubbo.config.Constants.CLIENT_THREAD_POOL_NAME; +import static org.apache.dubbo.remoting.Constants.HEARTBEAT_CHECK_TICK; +import static org.apache.dubbo.remoting.Constants.LEAST_HEARTBEAT_DURATION; +import static org.apache.dubbo.remoting.Constants.LEAST_RECONNECT_DURATION; +import static org.apache.dubbo.remoting.Constants.LEAST_RECONNECT_DURATION_KEY; +import static org.apache.dubbo.remoting.utils.UrlUtils.getIdleTimeout; /** * AbstractClient @@ -55,13 +63,23 @@ public abstract class AbstractClient extends AbstractEndpoint implements Client protected volatile ExecutorService executor; + protected volatile ScheduledExecutorService connectivityExecutor; + + private FrameworkModel frameworkModel; + + protected long reconnectDuaration; + public AbstractClient(URL url, ChannelHandler handler) throws RemotingException { super(url, handler); // set default needReconnect true when channel is not connected needReconnect = url.getParameter(Constants.SEND_RECONNECT_KEY, true); + frameworkModel = url.getOrDefaultFrameworkModel(); + initExecutor(url); + reconnectDuaration = getReconnectDuration(url); + try { doOpen(); } catch (Throwable t) { @@ -134,6 +152,11 @@ private void initExecutor(URL url) { url = url.addParameter(THREAD_NAME_KEY, CLIENT_THREAD_POOL_NAME) .addParameterIfAbsent(THREADPOOL_KEY, DEFAULT_CLIENT_THREADPOOL); executor = executorRepository.createExecutorIfAbsent(url); + + connectivityExecutor = frameworkModel + .getBeanFactory() + .getBean(FrameworkExecutorRepository.class) + .getConnectivityScheduledExecutor(); } protected static ChannelHandler wrapChannelHandler(URL url, ChannelHandler handler) { @@ -296,6 +319,25 @@ public void disconnect() { } } + private long getReconnectDuration(URL url) { + int idleTimeout = getIdleTimeout(url); + long heartbeatTimeoutTick = calculateLeastDuration(idleTimeout); + return calculateReconnectDuration(url, heartbeatTimeoutTick); + } + + private long calculateLeastDuration(int time) { + if (time / HEARTBEAT_CHECK_TICK <= 0) { + return LEAST_HEARTBEAT_DURATION; + } else { + return time / HEARTBEAT_CHECK_TICK; + } + } + + private long calculateReconnectDuration(URL url, long tick) { + long leastReconnectDuration = url.getParameter(LEAST_RECONNECT_DURATION_KEY, LEAST_RECONNECT_DURATION); + return Math.max(leastReconnectDuration, tick); + } + @Override public void reconnect() throws RemotingException { connectLock.lock(); 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 8023274ac4d..d3e24111a39 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 @@ -42,9 +42,9 @@ public class CodecSupport { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(CodecSupport.class); - private static Map ID_SERIALIZATION_MAP = new HashMap(); - private static Map ID_SERIALIZATIONNAME_MAP = new HashMap(); - private static Map SERIALIZATIONNAME_ID_MAP = new HashMap(); + private static Map ID_SERIALIZATION_MAP = new HashMap<>(); + private static Map ID_SERIALIZATIONNAME_MAP = new HashMap<>(); + private static Map SERIALIZATIONNAME_ID_MAP = new HashMap<>(); // Cache null object serialize results, for heartbeat request/response serialize use. private static ConcurrentMap ID_NULLBYTES_MAP = new ConcurrentHashMap<>(); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/ChannelHandlerDispatcherTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/ChannelHandlerDispatcherTest.java index 2e7fdf28389..df6b3559e0b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/ChannelHandlerDispatcherTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/ChannelHandlerDispatcherTest.java @@ -24,12 +24,18 @@ import java.util.Collections; import java.util.HashSet; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class ChannelHandlerDispatcherTest { + @AfterEach + public void tearDown() { + MockChannelHandler.reset(); + } + @Test void test() { ChannelHandlerDispatcher channelHandlerDispatcher = new ChannelHandlerDispatcher(); @@ -138,4 +144,12 @@ public static int getReceivedCount() { public static int getCaughtCount() { return caughtCount; } + + public static void reset() { + sentCount = 0; + connectedCount = 0; + disconnectedCount = 0; + receivedCount = 0; + caughtCount = 0; + } } diff --git a/dubbo-remoting/dubbo-remoting-http/pom.xml b/dubbo-remoting/dubbo-remoting-http/pom.xml deleted file mode 100644 index 91834389bb3..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/pom.xml +++ /dev/null @@ -1,85 +0,0 @@ - - - - 4.0.0 - - org.apache.dubbo - dubbo-remoting - ${revision} - ../pom.xml - - dubbo-remoting-http - jar - ${project.artifactId} - The http remoting module of dubbo project - - false - - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-api - ${project.parent.version} - - - org.eclipse.jetty - jetty-server - - - org.eclipse.jetty - jetty-servlet - - - org.apache.tomcat.embed - tomcat-embed-core - - - org.apache.httpcomponents - fluent-hc - 4.5.14 - test - - - org.apache.logging.log4j - log4j-slf4j-impl - test - - - - com.squareup.okhttp3 - okhttp - - - - org.apache.dubbo - dubbo-rpc-api - ${project.parent.version} - - - - org.apache.httpcomponents - httpclient - - - - diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/BaseRestClient.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/BaseRestClient.java deleted file mode 100644 index 23c78419ad6..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/BaseRestClient.java +++ /dev/null @@ -1,41 +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.http; - -import org.apache.dubbo.remoting.http.config.HttpClientConfig; - -public abstract class BaseRestClient implements RestClient { - - protected CLIENT client; - - protected HttpClientConfig clientConfig; - - public BaseRestClient(HttpClientConfig clientConfig) { - this.clientConfig = clientConfig; - client = createHttpClient(clientConfig); - } - - protected abstract CLIENT createHttpClient(HttpClientConfig clientConfig); - - public HttpClientConfig getClientConfig() { - return clientConfig; - } - - public CLIENT getClient() { - return client; - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpBinder.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpBinder.java deleted file mode 100644 index 26db36d92cf..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpBinder.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.remoting.http; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.Adaptive; -import org.apache.dubbo.common.extension.ExtensionScope; -import org.apache.dubbo.common.extension.SPI; -import org.apache.dubbo.remoting.Constants; - -/** - * HttpBinder - */ -@SPI(value = "jetty", scope = ExtensionScope.FRAMEWORK) -public interface HttpBinder { - - /** - * bind the server. - * - * @param url server url. - * @return server. - */ - @Adaptive({Constants.SERVER_KEY}) - HttpServer bind(URL url, HttpHandler handler); -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpHandler.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpHandler.java deleted file mode 100644 index 27085f67bc7..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpHandler.java +++ /dev/null @@ -1,34 +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.http; - -import java.io.IOException; - -/** - * http invocation handler. - */ -public interface HttpHandler { - - /** - * invoke. - * - * @param request request. - * @param response response. - * @throws IOException - */ - void handle(REQUEST request, RESPONSE response) throws IOException; -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpServer.java deleted file mode 100644 index d85582eb76a..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpServer.java +++ /dev/null @@ -1,71 +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.http; - -import org.apache.dubbo.common.Resetable; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.RemotingServer; - -import java.net.InetSocketAddress; - -public interface HttpServer extends Resetable, RemotingServer { - - /** - * get http handler. - * - * @return http handler. - */ - HttpHandler getHttpHandler(); - - /** - * get url. - * - * @return url - */ - URL getUrl(); - - /** - * get local address. - * - * @return local address. - */ - InetSocketAddress getLocalAddress(); - - /** - * close the channel. - */ - void close(); - - /** - * Graceful close the channel. - */ - void close(int timeout); - - /** - * is bound. - * - * @return bound - */ - boolean isBound(); - - /** - * is closed. - * - * @return closed - */ - boolean isClosed(); -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/RequestTemplate.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/RequestTemplate.java deleted file mode 100644 index d02d63be29d..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/RequestTemplate.java +++ /dev/null @@ -1,299 +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.http; - -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.rpc.Invocation; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -public class RequestTemplate implements Serializable { - private static final long serialVersionUID = 1L; - public static final String CONTENT_ENCODING = "Content-Encoding"; - private static final String CONTENT_LENGTH = "Content-Length"; - public static final String ENCODING_GZIP = "gzip"; - public static final String ENCODING_DEFLATE = "deflate"; - private static final List EMPTY_ARRAYLIST = new ArrayList<>(); - - private final Map> queries = new LinkedHashMap>(); - private final Map> headers = new LinkedHashMap>(); - private String httpMethod; - private String path; - private String address; - private Object body; - private byte[] byteBody = new byte[0]; - private String protocol = "http://"; - private final Invocation invocation; - private String contextPath = ""; - private Class bodyType; - - public RequestTemplate(Invocation invocation, String httpMethod, String address) { - this(invocation, httpMethod, address, ""); - } - - public RequestTemplate(Invocation invocation, String httpMethod, String address, String contextPath) { - this.httpMethod = httpMethod; - this.address = address; - this.invocation = invocation; - this.contextPath = contextPath; - } - - public String getURL() { - StringBuilder stringBuilder = new StringBuilder(getProtocol() + address); - - stringBuilder.append(getUri()); - return stringBuilder.toString(); - } - - public String getUri() { - StringBuilder stringBuilder = new StringBuilder(getContextPath() + path); - return stringBuilder.append(getQueryString()).toString(); - } - - public String getQueryString() { - - if (queries.isEmpty()) { - return ""; - } - - StringBuilder queryBuilder = new StringBuilder("?"); - for (String field : queries.keySet()) { - - Collection queryValues = queries.get(field); - - if (queryValues == null || queryValues.isEmpty()) { - continue; - } - - for (String value : queryValues) { - queryBuilder.append('&'); - queryBuilder.append(field); - if (value == null) { - continue; - } - - queryBuilder.append('='); - queryBuilder.append(value); - } - } - - return queryBuilder.toString().replace("?&", "?"); - } - - public RequestTemplate path(String path) { - this.path = path; - return this; - } - - public String getHttpMethod() { - return httpMethod; - } - - public RequestTemplate httpMethod(String httpMethod) { - this.httpMethod = httpMethod; - return this; - } - - public byte[] getSerializedBody() { - return byteBody; - } - - public void serializeBody(byte[] body) { - addHeader(CONTENT_LENGTH, body.length); // must header - this.byteBody = body; - } - - public boolean isBodyEmpty() { - return getUnSerializedBody() == null; - } - - public RequestTemplate body(Object body, Class bodyType) { - this.body = body; - setBodyType(bodyType); - return this; - } - - public Object getUnSerializedBody() { - return body; - } - - public Map> getAllHeaders() { - return headers; - } - - public Collection getHeaders(String name) { - return headers.get(name); - } - - public String getHeader(String name) { - if (headers.containsKey(name)) { - - Collection headers = getHeaders(name); - - if (headers.isEmpty()) { - return null; - } - String[] strings = headers.toArray(new String[0]); - return strings[0]; - - } else { - return null; - } - } - - public Collection getEncodingValues() { - if (headers.containsKey(CONTENT_ENCODING)) { - return headers.get(CONTENT_ENCODING); - } - return EMPTY_ARRAYLIST; - } - - public boolean isGzipEncodedRequest() { - return getEncodingValues().contains(ENCODING_GZIP); - } - - public boolean isDeflateEncodedRequest() { - return getEncodingValues().contains(ENCODING_DEFLATE); - } - - public void addHeader(String key, String value) { - addValueByKey(key, value, this.headers); - } - - public void addHeader(String key, Object value) { - addValueByKey(key, String.valueOf(value), this.headers); - } - - public void addKeepAliveHeader(int time) { - addHeader(Constants.KEEP_ALIVE_HEADER, time); - addHeader(Constants.CONNECTION, Constants.KEEP_ALIVE); - } - - public void addHeaders(String key, Collection values) { - Collection header = getHeaders(key); - - if (header == null) { - header = new HashSet<>(); - this.headers.put(key, header); - } - header.addAll(values); - } - - public void addParam(String key, String value) { - addValueByKey(key, value, this.queries); - } - - public void addParam(String key, Object value) { - addParam(key, String.valueOf(value)); - } - - public Map> getQueries() { - return queries; - } - - public Collection getParam(String key) { - return getQueries().get(key); - } - - public void addParams(String key, Collection values) { - Collection params = getParam(key); - - if (params == null) { - params = new HashSet<>(); - this.queries.put(key, params); - } - params.addAll(values); - } - - public void addValueByKey(String key, String value, Map> maps) { - - if (value == null) { - return; - } - - Collection values = null; - if (!maps.containsKey(key)) { - values = new HashSet<>(); - maps.put(key, values); - } - values = maps.get(key); - - values.add(value); - } - - public Integer getContentLength() { - - if (!getAllHeaders().containsKey(CONTENT_LENGTH)) { - return null; - } - - HashSet strings = (HashSet) getAllHeaders().get(CONTENT_LENGTH); - - return Integer.parseInt(new ArrayList<>(strings).get(0)); - } - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - addHeader("Host", address); // must header - this.address = address; - } - - public String getProtocol() { - return protocol; - } - - public void setProtocol(String protocol) { - this.protocol = protocol; - } - - public Invocation getInvocation() { - return invocation; - } - - public String getContextPath() { - if (contextPath == null || contextPath.length() == 0) { - return ""; - } - - if (contextPath.startsWith("/")) { - return contextPath; - } else { - return "/" + contextPath; - } - } - - public void setContextPath(String contextPath) { - this.contextPath = contextPath; - } - - public Class getBodyType() { - return bodyType; - } - - public void setBodyType(Class bodyType) { - this.bodyType = bodyType; - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/RestClient.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/RestClient.java deleted file mode 100644 index e5b8cecf7df..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/RestClient.java +++ /dev/null @@ -1,48 +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.http; - -import org.apache.dubbo.remoting.RemotingException; - -import java.util.concurrent.CompletableFuture; - -public interface RestClient { - /** - * send message. - * - * @param message - * @throws RemotingException - */ - CompletableFuture send(RequestTemplate message); - - /** - * close the channel. - */ - void close(); - - /** - * Graceful close the channel. - */ - void close(int timeout); - - /** - * is closed. - * - * @return closed - */ - boolean isClosed(); -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/RestResult.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/RestResult.java deleted file mode 100644 index bb057675dfe..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/RestResult.java +++ /dev/null @@ -1,42 +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.http; - -import java.io.IOException; -import java.util.List; -import java.util.Map; - -/** - * rest response facade - */ -public interface RestResult { - String getContentType(); - - byte[] getBody() throws IOException; - - Map> headers(); - - byte[] getErrorResponse() throws IOException; - - int getResponseCode() throws IOException; - - String getMessage() throws IOException; - - default String appendErrorMessage(String message, String errorInfo) { - return message + "\n error info is: " + errorInfo; - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/config/HttpClientConfig.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/config/HttpClientConfig.java deleted file mode 100644 index 09e0ab92a13..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/config/HttpClientConfig.java +++ /dev/null @@ -1,60 +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.http.config; - -public class HttpClientConfig { - private int readTimeout = 6 * 1000; - private int writeTimeout = 6 * 1000; - private int connectTimeout = 6 * 1000; - private int chunkLength = 8196; - - private int HTTP_CLIENT_CONNECTION_MANAGER_MAX_PER_ROUTE = 20; - private int HTTP_CLIENT_CONNECTION_MANAGER_MAX_TOTAL = 20; - private int HTTPCLIENT_KEEP_ALIVE_DURATION = 30 * 1000; - private int HTTP_CLIENT_CONNECTION_MANAGER_CLOSE_WAIT_TIME_MS = 1000; - private int HTTP_CLIENT_CONNECTION_MANAGER_CLOSE_IDLE_TIME_S = 30; - - public HttpClientConfig() {} - - public int getReadTimeout() { - return readTimeout; - } - - public void setReadTimeout(int readTimeout) { - this.readTimeout = readTimeout; - } - - public int getWriteTimeout() { - return writeTimeout; - } - - public void setWriteTimeout(int writeTimeout) { - this.writeTimeout = writeTimeout; - } - - public int getConnectTimeout() { - return connectTimeout; - } - - public void setConnectTimeout(int connectTimeout) { - this.connectTimeout = connectTimeout; - } - - public int getChunkLength() { - return chunkLength; - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/AbstractHttpClientFactory.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/AbstractHttpClientFactory.java deleted file mode 100644 index ad9e7f7821f..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/AbstractHttpClientFactory.java +++ /dev/null @@ -1,63 +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.http.factory; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.remoting.http.RestClient; -import org.apache.dubbo.remoting.http.config.HttpClientConfig; -import org.apache.dubbo.rpc.RpcException; - -/** - * AbstractHttpClientFactory - */ -public abstract class AbstractHttpClientFactory implements RestClientFactory { - - protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); - - // TODO load config - protected HttpClientConfig httpClientConfig = new HttpClientConfig(); - - //////////////////////////////////////// implements start /////////////////////////////////////////////// - @Override - public RestClient createRestClient(URL url) throws RpcException { - - beforeCreated(url); - - // create a raw client - RestClient restClient = doCreateRestClient(url); - - // postprocessor - afterCreated(restClient); - - return restClient; - } - - //////////////////////////////////////// implements end /////////////////////////////////////////////// - - //////////////////////////////////////// inner methods /////////////////////////////////////////////// - - protected void beforeCreated(URL url) {} - - protected abstract RestClient doCreateRestClient(URL url) throws RpcException; - - protected void afterCreated(RestClient client) {} - - //////////////////////////////////////// inner methods /////////////////////////////////////////////// - -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/RestClientFactory.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/RestClientFactory.java deleted file mode 100644 index c64453dbda9..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/RestClientFactory.java +++ /dev/null @@ -1,35 +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.http.factory; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.Adaptive; -import org.apache.dubbo.common.extension.ExtensionScope; -import org.apache.dubbo.common.extension.SPI; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.remoting.http.RestClient; -import org.apache.dubbo.rpc.RpcException; - -/** - * RestClientFactory. (API/SPI, Singleton, ThreadSafe) - */ -@SPI(value = Constants.OK_HTTP, scope = ExtensionScope.FRAMEWORK) -public interface RestClientFactory { - - @Adaptive({Constants.CLIENT_KEY}) - RestClient createRestClient(URL url) throws RpcException; -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/impl/ApacheHttpClientFactory.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/impl/ApacheHttpClientFactory.java deleted file mode 100644 index 89d9c36f6fb..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/impl/ApacheHttpClientFactory.java +++ /dev/null @@ -1,35 +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.http.factory.impl; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.remoting.http.RestClient; -import org.apache.dubbo.remoting.http.factory.AbstractHttpClientFactory; -import org.apache.dubbo.remoting.http.restclient.HttpClientRestClient; -import org.apache.dubbo.rpc.RpcException; - -@Activate(Constants.APACHE_HTTP_CLIENT) -public class ApacheHttpClientFactory extends AbstractHttpClientFactory { - - @Override - protected RestClient doCreateRestClient(URL url) throws RpcException { - - return new HttpClientRestClient(httpClientConfig); - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/impl/OkHttpClientFactory.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/impl/OkHttpClientFactory.java deleted file mode 100644 index 523df3caf89..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/impl/OkHttpClientFactory.java +++ /dev/null @@ -1,35 +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.http.factory.impl; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.remoting.http.RestClient; -import org.apache.dubbo.remoting.http.factory.AbstractHttpClientFactory; -import org.apache.dubbo.remoting.http.restclient.OKHttpRestClient; -import org.apache.dubbo.rpc.RpcException; - -@Activate(Constants.OK_HTTP) -public class OkHttpClientFactory extends AbstractHttpClientFactory { - - @Override - protected RestClient doCreateRestClient(URL url) throws RpcException { - - return new OKHttpRestClient(httpClientConfig); - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/impl/URLConnectionClientFactory.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/impl/URLConnectionClientFactory.java deleted file mode 100644 index 40c2a82a66a..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/impl/URLConnectionClientFactory.java +++ /dev/null @@ -1,35 +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.http.factory.impl; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.remoting.http.RestClient; -import org.apache.dubbo.remoting.http.factory.AbstractHttpClientFactory; -import org.apache.dubbo.remoting.http.restclient.URLConnectionRestClient; -import org.apache.dubbo.rpc.RpcException; - -@Activate(Constants.URL_CONNECTION) -public class URLConnectionClientFactory extends AbstractHttpClientFactory { - - @Override - protected RestClient doCreateRestClient(URL url) throws RpcException { - - return new URLConnectionRestClient(httpClientConfig); - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinder.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinder.java deleted file mode 100644 index 05e5dc5a354..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinder.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.remoting.http.jetty; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.http.HttpBinder; -import org.apache.dubbo.remoting.http.HttpHandler; -import org.apache.dubbo.remoting.http.HttpServer; - -/** - * JettyHttpTransporter - */ -public class JettyHttpBinder implements HttpBinder { - - @Override - public HttpServer bind(URL url, HttpHandler handler) { - return new JettyHttpServer(url, handler); - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpServer.java deleted file mode 100644 index 0139a5d79ff..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpServer.java +++ /dev/null @@ -1,113 +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.http.jetty; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.remoting.http.HttpHandler; -import org.apache.dubbo.remoting.http.servlet.DispatcherServlet; -import org.apache.dubbo.remoting.http.servlet.ServletManager; -import org.apache.dubbo.remoting.http.support.AbstractHttpServer; - -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.ServerConnector; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.eclipse.jetty.util.thread.QueuedThreadPool; - -import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS; -import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; -import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_STOP_HTTP_SERVER; - -public class JettyHttpServer extends AbstractHttpServer { - - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(JettyHttpServer.class); - - private Server server; - - private URL url; - - public JettyHttpServer(URL url, final HttpHandler handler) { - super(url, handler); - this.url = url; - - // set dubbo's logger - System.setProperty("org.eclipse.jetty.util.log.class", JettyLoggerAdapter.class.getName()); - - DispatcherServlet.addHttpHandler(url.getParameter(Constants.BIND_PORT_KEY, url.getPort()), handler); - - int threads = url.getParameter(THREADS_KEY, DEFAULT_THREADS); - QueuedThreadPool threadPool = new QueuedThreadPool(); - threadPool.setDaemon(true); - threadPool.setMaxThreads(threads); - threadPool.setMinThreads(threads); - - server = new Server(threadPool); - - ServerConnector connector = new ServerConnector(server); - - String bindIp = url.getParameter(Constants.BIND_IP_KEY, url.getHost()); - if (!url.isAnyHost() && NetUtils.isValidLocalHost(bindIp)) { - connector.setHost(bindIp); - } - connector.setPort(url.getParameter(Constants.BIND_PORT_KEY, url.getPort())); - - server.addConnector(connector); - - ServletHandler servletHandler = new ServletHandler(); - ServletHolder servletHolder = servletHandler.addServletWithMapping(DispatcherServlet.class, "/*"); - servletHolder.setInitOrder(2); - - // dubbo's original impl can't support the use of ServletContext - // server.addHandler(servletHandler); - // TODO Context.SESSIONS is the best option here? (In jetty 9.x, it becomes ServletContextHandler.SESSIONS) - ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS); - context.setServletHandler(servletHandler); - ServletManager.getInstance() - .addServletContext( - url.getParameter(Constants.BIND_PORT_KEY, url.getPort()), context.getServletContext()); - - try { - server.start(); - } catch (Exception e) { - throw new IllegalStateException( - "Failed to start jetty server on " + url.getParameter(Constants.BIND_IP_KEY) + ":" - + url.getParameter(Constants.BIND_PORT_KEY) + ", cause: " + e.getMessage(), - e); - } - } - - @Override - public void close() { - super.close(); - - // - ServletManager.getInstance().removeServletContext(url.getParameter(Constants.BIND_PORT_KEY, url.getPort())); - - if (server != null) { - try { - server.stop(); - } catch (Exception e) { - logger.warn(COMMON_FAILED_STOP_HTTP_SERVER, "", "", e.getMessage(), e); - } - } - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyLoggerAdapter.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyLoggerAdapter.java deleted file mode 100644 index b93cb3f2ce1..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyLoggerAdapter.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.remoting.http.jetty; - -import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; -import org.apache.dubbo.common.logger.LoggerFactory; - -import org.eclipse.jetty.util.log.AbstractLogger; -import org.eclipse.jetty.util.log.Logger; - -import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; - -/** - * logger adapter for jetty - */ -public class JettyLoggerAdapter extends AbstractLogger { - protected String name; - - private final ErrorTypeAwareLogger logger; - - private static boolean debugEnabled = false; - - public JettyLoggerAdapter() { - this("org.apache.dubbo.remoting.http.jetty"); - } - - public JettyLoggerAdapter(Class clazz) { - this(clazz.getName()); - } - - public JettyLoggerAdapter(String name) { - this.name = name; - this.logger = LoggerFactory.getErrorTypeAwareLogger(name); - } - - @Override - protected Logger newLogger(String name) { - return new JettyLoggerAdapter(name); - } - - @Override - public String getName() { - return this.name; - } - - @Override - public void warn(String msg, Object... objects) { - if (logger.isWarnEnabled()) { - logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", this.format(msg, objects)); - } - } - - @Override - public void warn(Throwable throwable) { - if (logger.isWarnEnabled()) { - logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", throwable.getMessage(), throwable); - } - } - - @Override - public void warn(String msg, Throwable throwable) { - if (logger.isWarnEnabled()) { - logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", msg, throwable); - } - } - - @Override - public void info(String msg, Object... objects) { - if (logger.isInfoEnabled()) { - logger.info(this.format(msg, objects)); - } - } - - @Override - public void info(Throwable throwable) { - if (logger.isInfoEnabled()) { - logger.info(throwable); - } - } - - @Override - public void info(String msg, Throwable throwable) { - if (logger.isInfoEnabled()) { - logger.info(msg, throwable); - } - } - - @Override - public boolean isDebugEnabled() { - return debugEnabled; - } - - @Override - public void setDebugEnabled(boolean enabled) { - debugEnabled = enabled; - } - - @Override - public void debug(String msg, Object... objects) { - if (debugEnabled && logger.isDebugEnabled()) { - logger.debug(this.format(msg, objects)); - } - } - - @Override - public void debug(Throwable throwable) { - if (debugEnabled && logger.isDebugEnabled()) { - logger.debug(throwable); - } - } - - @Override - public void debug(String msg, Throwable throwable) { - if (debugEnabled && logger.isDebugEnabled()) { - logger.debug(msg, throwable); - } - } - - @Override - public void ignore(Throwable throwable) { - if (logger.isWarnEnabled()) { - logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "IGNORED EXCEPTION ", throwable); - } - } - - private String format(String msg, Object... args) { - msg = String.valueOf(msg); // Avoids NPE - String braces = "{}"; - StringBuilder builder = new StringBuilder(); - int start = 0; - for (Object arg : args) { - int bracesIndex = msg.indexOf(braces, start); - if (bracesIndex < 0) { - builder.append(msg.substring(start)); - builder.append(' '); - builder.append(arg); - start = msg.length(); - } else { - builder.append(msg, start, bracesIndex); - builder.append(arg); - start = bracesIndex + braces.length(); - } - } - builder.append(msg.substring(start)); - return builder.toString(); - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/restclient/HttpClientRestClient.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/restclient/HttpClientRestClient.java deleted file mode 100644 index f09b288c5f8..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/restclient/HttpClientRestClient.java +++ /dev/null @@ -1,188 +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.http.restclient; - -import org.apache.dubbo.remoting.http.RequestTemplate; -import org.apache.dubbo.remoting.http.RestClient; -import org.apache.dubbo.remoting.http.RestResult; -import org.apache.dubbo.remoting.http.config.HttpClientConfig; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.stream.Collectors; - -import org.apache.commons.io.IOUtils; -import org.apache.http.Header; -import org.apache.http.HttpEntityEnclosingRequest; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpHead; -import org.apache.http.client.methods.HttpOptions; -import org.apache.http.client.methods.HttpPatch; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.client.methods.HttpTrace; -import org.apache.http.entity.ByteArrayEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; - -public class HttpClientRestClient implements RestClient { - private final CloseableHttpClient closeableHttpClient; - private final HttpClientConfig httpClientConfig; - - public HttpClientRestClient(HttpClientConfig clientConfig) { - closeableHttpClient = createHttpClient(); - httpClientConfig = clientConfig; - } - - @Override - public CompletableFuture send(RequestTemplate requestTemplate) { - - HttpRequestBase httpRequest = null; - String httpMethod = requestTemplate.getHttpMethod(); - - httpRequest = createHttpUriRequest(httpMethod, requestTemplate); - - if (httpRequest instanceof HttpEntityEnclosingRequest) { - ((HttpEntityEnclosingRequestBase) httpRequest) - .setEntity(new ByteArrayEntity(requestTemplate.getSerializedBody())); - } - - Map> allHeaders = requestTemplate.getAllHeaders(); - - allHeaders.remove("Content-Length"); - // header - for (String headerName : allHeaders.keySet()) { - Collection headerValues = allHeaders.get(headerName); - - for (String headerValue : headerValues) { - httpRequest.addHeader(headerName, headerValue); - } - } - - httpRequest.setConfig(getRequestConfig(httpClientConfig)); - - CompletableFuture future = new CompletableFuture<>(); - try { - CloseableHttpResponse response = closeableHttpClient.execute(httpRequest); - future.complete(new RestResult() { - @Override - public String getContentType() { - Header header = response.getFirstHeader("Content-Type"); - return header == null ? null : header.getValue(); - } - - @Override - public byte[] getBody() throws IOException { - if (response.getEntity() == null) { - return new byte[0]; - } - return IOUtils.toByteArray(response.getEntity().getContent()); - } - - @Override - public Map> headers() { - return Arrays.stream(response.getAllHeaders()) - .collect(Collectors.toMap(Header::getName, h -> Collections.singletonList(h.getValue()))); - } - - @Override - public byte[] getErrorResponse() throws IOException { - return getBody(); - } - - @Override - public int getResponseCode() { - return response.getStatusLine().getStatusCode(); - } - - @Override - public String getMessage() throws IOException { - return appendErrorMessage( - response.getStatusLine().getReasonPhrase(), new String(getErrorResponse())); - } - }); - } catch (IOException e) { - future.completeExceptionally(e); - } - return future; - } - - private RequestConfig getRequestConfig(HttpClientConfig clientConfig) { - - // TODO config - return RequestConfig.custom().build(); - } - - @Override - public void close() { - try { - closeableHttpClient.close(); - } catch (IOException e) { - - } - } - - @Override - public void close(int timeout) {} - - @Override - public boolean isClosed() { - // TODO close judge - return true; - } - - public CloseableHttpClient createHttpClient() { - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); - return HttpClients.custom().setConnectionManager(connectionManager).build(); - } - - protected HttpRequestBase createHttpUriRequest(String httpMethod, RequestTemplate requestTemplate) { - String uri = requestTemplate.getURL(); - HttpRequestBase httpUriRequest = null; - if (HttpGet.METHOD_NAME.equals(httpMethod)) { - httpUriRequest = new HttpGet(uri); - } else if (HttpHead.METHOD_NAME.equals(httpMethod)) { - httpUriRequest = new HttpHead(uri); - } else if (HttpPost.METHOD_NAME.equals(httpMethod)) { - httpUriRequest = new HttpPost(uri); - } else if (HttpPut.METHOD_NAME.equals(httpMethod)) { - httpUriRequest = new HttpPut(uri); - } else if (HttpPatch.METHOD_NAME.equals(httpMethod)) { - httpUriRequest = new HttpPatch(uri); - } else if (HttpDelete.METHOD_NAME.equals(httpMethod)) { - httpUriRequest = new HttpDelete(uri); - } else if (HttpOptions.METHOD_NAME.equals(httpMethod)) { - httpUriRequest = new HttpOptions(uri); - } else if (HttpTrace.METHOD_NAME.equals(httpMethod)) { - httpUriRequest = new HttpTrace(uri); - } else { - throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod); - } - return httpUriRequest; - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/restclient/OKHttpRestClient.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/restclient/OKHttpRestClient.java deleted file mode 100644 index 36ba2e6d187..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/restclient/OKHttpRestClient.java +++ /dev/null @@ -1,150 +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.http.restclient; - -import org.apache.dubbo.remoting.http.RequestTemplate; -import org.apache.dubbo.remoting.http.RestClient; -import org.apache.dubbo.remoting.http.RestResult; -import org.apache.dubbo.remoting.http.config.HttpClientConfig; - -import java.io.IOException; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.TimeUnit; - -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import okhttp3.internal.http.HttpMethod; - -// TODO add version 4.0 implements ,and default version is < 4.0,for dependency conflict -public class OKHttpRestClient implements RestClient { - private final OkHttpClient okHttpClient; - private final HttpClientConfig httpClientConfig; - - public OKHttpRestClient(HttpClientConfig clientConfig) { - this.okHttpClient = createHttpClient(clientConfig); - this.httpClientConfig = clientConfig; - } - - @Override - public CompletableFuture send(RequestTemplate requestTemplate) { - - Request.Builder builder = new Request.Builder(); - // url - builder.url(requestTemplate.getURL()); - - Map> allHeaders = requestTemplate.getAllHeaders(); - - boolean hasBody = false; - RequestBody requestBody = null; - // GET & HEAD body is forbidden - if (HttpMethod.permitsRequestBody(requestTemplate.getHttpMethod())) { - requestBody = RequestBody.create(null, requestTemplate.getSerializedBody()); - hasBody = true; - } - - // header - for (String headerName : allHeaders.keySet()) { - Collection headerValues = allHeaders.get(headerName); - if (!hasBody && "Content-Length".equals(headerName)) { - continue; - } - for (String headerValue : headerValues) { - - builder.addHeader(headerName, headerValue); - } - } - - builder.method(requestTemplate.getHttpMethod(), requestBody); - - CompletableFuture future = new CompletableFuture<>(); - - okHttpClient.newCall(builder.build()).enqueue(new Callback() { - @Override - public void onFailure(Call call, IOException e) { - future.completeExceptionally(e); - } - - @Override - public void onResponse(Call call, Response response) throws IOException { - future.complete(new RestResult() { - @Override - public String getContentType() { - return response.header("Content-Type"); - } - - @Override - public byte[] getBody() throws IOException { - ResponseBody body = response.body(); - return body == null ? null : body.bytes(); - } - - @Override - public Map> headers() { - return response.headers().toMultimap(); - } - - @Override - public byte[] getErrorResponse() throws IOException { - return getBody(); - } - - @Override - public int getResponseCode() throws IOException { - return response.code(); - } - - @Override - public String getMessage() throws IOException { - return appendErrorMessage(response.message(), new String(getBody())); - } - }); - } - }); - - return future; - } - - @Override - public void close() { - okHttpClient.connectionPool().evictAll(); - } - - @Override - public void close(int timeout) {} - - @Override - public boolean isClosed() { - return okHttpClient.retryOnConnectionFailure(); - } - - public OkHttpClient createHttpClient(HttpClientConfig httpClientConfig) { - OkHttpClient client = new OkHttpClient.Builder() - .readTimeout(httpClientConfig.getReadTimeout(), TimeUnit.SECONDS) - .writeTimeout(httpClientConfig.getWriteTimeout(), TimeUnit.SECONDS) - .connectTimeout(httpClientConfig.getConnectTimeout(), TimeUnit.SECONDS) - .build(); - return client; - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/restclient/URLConnectionRestClient.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/restclient/URLConnectionRestClient.java deleted file mode 100644 index 65f20a19f28..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/restclient/URLConnectionRestClient.java +++ /dev/null @@ -1,170 +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.http.restclient; - -import org.apache.dubbo.remoting.http.RequestTemplate; -import org.apache.dubbo.remoting.http.RestClient; -import org.apache.dubbo.remoting.http.RestResult; -import org.apache.dubbo.remoting.http.config.HttpClientConfig; - -import java.io.IOException; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.zip.DeflaterOutputStream; -import java.util.zip.GZIPOutputStream; - -import org.apache.commons.io.IOUtils; - -public class URLConnectionRestClient implements RestClient { - private final HttpClientConfig clientConfig; - - public URLConnectionRestClient(HttpClientConfig clientConfig) { - this.clientConfig = clientConfig; - } - - @Override - public CompletableFuture send(RequestTemplate requestTemplate) { - - CompletableFuture future = new CompletableFuture<>(); - - try { - HttpURLConnection connection = (HttpURLConnection) new URL(requestTemplate.getURL()).openConnection(); - connection.setConnectTimeout(clientConfig.getConnectTimeout()); - connection.setReadTimeout(clientConfig.getReadTimeout()); - connection.setRequestMethod(requestTemplate.getHttpMethod()); - - prepareConnection(connection, requestTemplate.getHttpMethod()); - - // writeHeaders - - for (String field : requestTemplate.getAllHeaders().keySet()) { - for (String value : requestTemplate.getHeaders(field)) { - connection.addRequestProperty(field, value); - } - } - - // writeBody - - boolean gzipEncodedRequest = requestTemplate.isGzipEncodedRequest(); - boolean deflateEncodedRequest = requestTemplate.isDeflateEncodedRequest(); - if (requestTemplate.isBodyEmpty()) { - future.complete(getRestResultFromConnection(connection)); - return future; - } - Integer contentLength = requestTemplate.getContentLength(); - - if (contentLength != null) { - connection.setFixedLengthStreamingMode(contentLength); - } else { - connection.setChunkedStreamingMode(clientConfig.getChunkLength()); - } - - OutputStream out = connection.getOutputStream(); - if (gzipEncodedRequest) { - out = new GZIPOutputStream(out); - } else if (deflateEncodedRequest) { - out = new DeflaterOutputStream(out); - } - try { - out.write(requestTemplate.getSerializedBody()); - } finally { - try { - out.close(); - } catch (IOException suppressed) { - } - } - - future.complete(getRestResultFromConnection(connection)); - } catch (Exception e) { - future.completeExceptionally(e); - } - - return future; - } - - @Override - public void close() {} - - @Override - public void close(int timeout) {} - - @Override - public boolean isClosed() { - return true; - } - - private RestResult getRestResultFromConnection(HttpURLConnection connection) { - - return new RestResult() { - @Override - public String getContentType() { - return connection.getContentType(); - } - - @Override - public byte[] getBody() throws IOException { - return IOUtils.toByteArray(connection.getInputStream()); - } - - @Override - public Map> headers() { - return connection.getHeaderFields(); - } - - @Override - public byte[] getErrorResponse() throws IOException { - return IOUtils.toByteArray(connection.getErrorStream()); - } - - @Override - public int getResponseCode() throws IOException { - return connection.getResponseCode(); - } - - @Override - public String getMessage() throws IOException { - return appendErrorMessage(connection.getResponseMessage(), new String(getErrorResponse())); - } - }; - } - - private void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException { - - connection.setDoInput(true); - - if ("GET".equals(httpMethod)) { - connection.setInstanceFollowRedirects(true); - } else { - connection.setInstanceFollowRedirects(false); - } - - if ("POST".equals(httpMethod) - || "PUT".equals(httpMethod) - || "PATCH".equals(httpMethod) - || "DELETE".equals(httpMethod)) { - connection.setDoOutput(true); - } else { - connection.setDoOutput(false); - } - - connection.setRequestMethod(httpMethod); - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/BootstrapListener.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/BootstrapListener.java deleted file mode 100644 index 0a902f292f9..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/BootstrapListener.java +++ /dev/null @@ -1,37 +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.http.servlet; - -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; - -/** - * This class must be defined before something like spring's ContextLoaderListener in web.xml - */ -public class BootstrapListener implements ServletContextListener { - - @Override - public void contextInitialized(ServletContextEvent servletContextEvent) { - ServletManager.getInstance() - .addServletContext(ServletManager.EXTERNAL_SERVER_PORT, servletContextEvent.getServletContext()); - } - - @Override - public void contextDestroyed(ServletContextEvent servletContextEvent) { - ServletManager.getInstance().removeServletContext(ServletManager.EXTERNAL_SERVER_PORT); - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/DispatcherServlet.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/DispatcherServlet.java deleted file mode 100644 index ced2170b3b0..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/DispatcherServlet.java +++ /dev/null @@ -1,65 +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.http.servlet; - -import org.apache.dubbo.remoting.http.HttpHandler; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Service dispatcher Servlet. - */ -public class DispatcherServlet extends HttpServlet { - - private static final long serialVersionUID = 5766349180380479888L; - private static final Map HANDLERS = new ConcurrentHashMap(); - private static DispatcherServlet INSTANCE; - - public DispatcherServlet() { - DispatcherServlet.INSTANCE = this; - } - - public static void addHttpHandler(int port, HttpHandler processor) { - HANDLERS.put(port, processor); - } - - public static void removeHttpHandler(int port) { - HANDLERS.remove(port); - } - - public static DispatcherServlet getInstance() { - return INSTANCE; - } - - @Override - protected void service(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - HttpHandler handler = HANDLERS.get(request.getLocalPort()); - if (handler == null) { // service not found. - response.sendError(HttpServletResponse.SC_NOT_FOUND, "Service not found."); - } else { - handler.handle(request, response); - } - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpBinder.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpBinder.java deleted file mode 100644 index 33aecc5aff5..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpBinder.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.remoting.http.servlet; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.http.HttpBinder; -import org.apache.dubbo.remoting.http.HttpHandler; -import org.apache.dubbo.remoting.http.HttpServer; - -/** - * ServletHttpTransporter - */ -public class ServletHttpBinder implements HttpBinder { - - @Override - public HttpServer bind(URL url, HttpHandler handler) { - return new ServletHttpServer(url, handler); - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpServer.java deleted file mode 100644 index bf0b01457e1..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpServer.java +++ /dev/null @@ -1,30 +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.http.servlet; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.remoting.http.HttpHandler; -import org.apache.dubbo.remoting.http.support.AbstractHttpServer; - -public class ServletHttpServer extends AbstractHttpServer { - - public ServletHttpServer(URL url, HttpHandler handler) { - super(url, handler); - DispatcherServlet.addHttpHandler(url.getParameter(Constants.BIND_PORT_KEY, 8080), handler); - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletManager.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletManager.java deleted file mode 100644 index a261b6e54c4..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletManager.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.remoting.http.servlet; - -import javax.servlet.ServletContext; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * TODO this may not be a pretty elegant solution, - */ -public class ServletManager { - - public static final int EXTERNAL_SERVER_PORT = -1234; - - private static final ServletManager INSTANCE = new ServletManager(); - - private final Map contextMap = new ConcurrentHashMap(); - - public static ServletManager getInstance() { - return INSTANCE; - } - - public void addServletContext(int port, ServletContext servletContext) { - contextMap.put(port, servletContext); - } - - public void removeServletContext(int port) { - contextMap.remove(port); - } - - public ServletContext getServletContext(int port) { - return contextMap.get(port); - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/support/AbstractHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/support/AbstractHttpServer.java deleted file mode 100644 index cc01b1e0645..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/support/AbstractHttpServer.java +++ /dev/null @@ -1,124 +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.http.support; - -import org.apache.dubbo.common.Parameters; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.Channel; -import org.apache.dubbo.remoting.ChannelHandler; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.http.HttpHandler; -import org.apache.dubbo.remoting.http.HttpServer; - -import java.net.InetSocketAddress; -import java.util.Collection; - -/** - * AbstractHttpServer - */ -public abstract class AbstractHttpServer implements HttpServer { - - private final URL url; - - private final HttpHandler handler; - - private volatile boolean closed; - - public AbstractHttpServer(URL url, HttpHandler handler) { - if (url == null) { - throw new IllegalArgumentException("url == null"); - } - if (handler == null) { - throw new IllegalArgumentException("handler == null"); - } - this.url = url; - this.handler = handler; - } - - @Override - public HttpHandler getHttpHandler() { - return handler; - } - - @Override - public URL getUrl() { - return url; - } - - @Override - public void reset(URL url) {} - - @Override - public boolean isBound() { - return true; - } - - @Override - public InetSocketAddress getLocalAddress() { - return url.toInetSocketAddress(); - } - - @Override - public void close() { - closed = true; - } - - @Override - public void close(int timeout) { - close(); - } - - @Override - public boolean isClosed() { - return closed; - } - - /** - * Following methods are extended from RemotingServer, useless for http servers - */ - @Override - public boolean canHandleIdle() { - return false; - } - - @Override - public Collection getChannels() { - return null; - } - - @Override - public Channel getChannel(InetSocketAddress remoteAddress) { - return null; - } - - @Override - public void reset(Parameters parameters) {} - - @Override - public ChannelHandler getChannelHandler() { - return null; - } - - @Override - public void send(Object message) throws RemotingException {} - - @Override - public void send(Object message, boolean sent) throws RemotingException {} - - @Override - public void startClose() {} -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinder.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinder.java deleted file mode 100755 index 92b4bf1c70b..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinder.java +++ /dev/null @@ -1,30 +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.http.tomcat; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.http.HttpBinder; -import org.apache.dubbo.remoting.http.HttpHandler; -import org.apache.dubbo.remoting.http.HttpServer; - -public class TomcatHttpBinder implements HttpBinder { - - @Override - public HttpServer bind(URL url, HttpHandler handler) { - return new TomcatHttpServer(url, handler); - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java deleted file mode 100755 index 002f963c350..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java +++ /dev/null @@ -1,100 +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.http.tomcat; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; -import org.apache.dubbo.remoting.http.HttpHandler; -import org.apache.dubbo.remoting.http.servlet.DispatcherServlet; -import org.apache.dubbo.remoting.http.servlet.ServletManager; -import org.apache.dubbo.remoting.http.support.AbstractHttpServer; - -import java.io.File; - -import org.apache.catalina.Context; -import org.apache.catalina.LifecycleException; -import org.apache.catalina.connector.Connector; -import org.apache.catalina.startup.Tomcat; - -import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS; -import static org.apache.dubbo.common.constants.CommonConstants.SystemProperty.SYSTEM_JAVA_IO_TMPDIR; -import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; -import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_STOP_HTTP_SERVER; -import static org.apache.dubbo.remoting.Constants.ACCEPTS_KEY; - -public class TomcatHttpServer extends AbstractHttpServer { - - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(TomcatHttpServer.class); - - private final Tomcat tomcat; - - private final URL url; - - public TomcatHttpServer(URL url, final HttpHandler handler) { - super(url, handler); - - this.url = url; - DispatcherServlet.addHttpHandler(url.getPort(), handler); - String baseDir = new File(SystemPropertyConfigUtils.getSystemProperty(SYSTEM_JAVA_IO_TMPDIR)).getAbsolutePath(); - tomcat = new Tomcat(); - - Connector connector = tomcat.getConnector(); - connector.setPort(url.getPort()); - connector.setProperty("maxThreads", String.valueOf(url.getParameter(THREADS_KEY, DEFAULT_THREADS))); - connector.setProperty("maxConnections", String.valueOf(url.getParameter(ACCEPTS_KEY, -1))); - connector.setProperty("URIEncoding", "UTF-8"); - connector.setProperty("connectionTimeout", "60000"); - connector.setProperty("maxKeepAliveRequests", "-1"); - - tomcat.setBaseDir(baseDir); - tomcat.setPort(url.getPort()); - - Context context = tomcat.addContext("/", baseDir); - Tomcat.addServlet(context, "dispatcher", new DispatcherServlet()); - // Issue : https://github.com/apache/dubbo/issues/6418 - // addServletMapping method will be removed since Tomcat 9 - // context.addServletMapping("/*", "dispatcher"); - context.addServletMappingDecoded("/*", "dispatcher"); - ServletManager.getInstance().addServletContext(url.getPort(), context.getServletContext()); - - // tell tomcat to fail on startup failures. - System.setProperty("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE", "true"); - - try { - tomcat.start(); - } catch (LifecycleException e) { - throw new IllegalStateException("Failed to start tomcat server at " + url.getAddress(), e); - } - } - - @Override - public void close() { - super.close(); - - ServletManager.getInstance().removeServletContext(url.getPort()); - - try { - tomcat.stop(); - // close port by destroy() - tomcat.destroy(); - } catch (Exception e) { - logger.warn(COMMON_FAILED_STOP_HTTP_SERVER, "", "", e.getMessage(), e); - } - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.http.HttpBinder b/dubbo-remoting/dubbo-remoting-http/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.http.HttpBinder deleted file mode 100644 index 845124bb435..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.http.HttpBinder +++ /dev/null @@ -1,3 +0,0 @@ -servlet=org.apache.dubbo.remoting.http.servlet.ServletHttpBinder -jetty=org.apache.dubbo.remoting.http.jetty.JettyHttpBinder -tomcat=org.apache.dubbo.remoting.http.tomcat.TomcatHttpBinder \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.http.factory.RestClientFactory b/dubbo-remoting/dubbo-remoting-http/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.http.factory.RestClientFactory deleted file mode 100644 index 95dd12e072d..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.http.factory.RestClientFactory +++ /dev/null @@ -1,4 +0,0 @@ -ok-http=org.apache.dubbo.remoting.http.factory.impl.OkHttpClientFactory -url-connection=org.apache.dubbo.remoting.http.factory.impl.URLConnectionClientFactory -apache-http-client=org.apache.dubbo.remoting.http.factory.impl.ApacheHttpClientFactory - diff --git a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinderTest.java b/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinderTest.java deleted file mode 100644 index 04fc431863c..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinderTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.remoting.http.jetty; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.url.component.ServiceConfigURL; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.remoting.http.HttpHandler; -import org.apache.dubbo.remoting.http.HttpServer; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import java.io.IOException; - -import org.apache.http.client.fluent.Request; -import org.junit.jupiter.api.Test; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.Is.is; - -class JettyHttpBinderTest { - @Test - void shouldAbleHandleRequestForJettyBinder() throws Exception { - int port = NetUtils.getAvailablePort(); - URL url = new ServiceConfigURL( - "http", "localhost", port, new String[] {Constants.BIND_PORT_KEY, String.valueOf(port)}); - HttpServer httpServer = new JettyHttpServer(url, new HttpHandler() { - @Override - public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { - response.getWriter().write("Jetty"); - } - }); - - String response = - Request.Get(url.toJavaURL().toURI()).execute().returnContent().asString(); - - assertThat(response, is("Jetty")); - - httpServer.close(); - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyLoggerAdapterTest.java b/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyLoggerAdapterTest.java deleted file mode 100644 index e4cbbfd5397..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyLoggerAdapterTest.java +++ /dev/null @@ -1,127 +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.http.jetty; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.support.FailsafeErrorTypeAwareLogger; -import org.apache.dubbo.common.url.component.ServiceConfigURL; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.remoting.http.HttpHandler; -import org.apache.dubbo.remoting.http.HttpServer; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import java.io.IOException; -import java.lang.reflect.Field; -import java.lang.reflect.Method; - -import org.apache.http.client.fluent.Request; -import org.eclipse.jetty.util.log.Log; -import org.junit.jupiter.api.Test; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -class JettyLoggerAdapterTest { - - @Test - void testJettyUseDubboLogger() throws Exception { - int port = NetUtils.getAvailablePort(); - URL url = new ServiceConfigURL( - "http", "localhost", port, new String[] {Constants.BIND_PORT_KEY, String.valueOf(port)}); - HttpServer httpServer = new JettyHttpServer(url, new HttpHandler() { - @Override - public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { - response.getWriter().write("Jetty is using Dubbo's logger"); - } - }); - Request.Get(url.toJavaURL().toURI()).execute().returnContent().asString(); - - assertThat(Log.getLog().getClass().isAssignableFrom(JettyLoggerAdapter.class), is(true)); - - httpServer.close(); - } - - @Test - void testSuccessLogger() throws Exception { - Logger successLogger = mock(Logger.class); - Class clazz = Class.forName("org.apache.dubbo.remoting.http.jetty.JettyLoggerAdapter"); - JettyLoggerAdapter jettyLoggerAdapter = - (JettyLoggerAdapter) clazz.getDeclaredConstructor().newInstance(); - - Field loggerField = clazz.getDeclaredField("logger"); - loggerField.setAccessible(true); - loggerField.set(jettyLoggerAdapter, new FailsafeErrorTypeAwareLogger(successLogger)); - jettyLoggerAdapter.setDebugEnabled(true); - - when(successLogger.isDebugEnabled()).thenReturn(true); - when(successLogger.isWarnEnabled()).thenReturn(true); - when(successLogger.isInfoEnabled()).thenReturn(true); - - jettyLoggerAdapter.warn("warn"); - jettyLoggerAdapter.info("info"); - jettyLoggerAdapter.debug("debug"); - - verify(successLogger).warn(anyString()); - verify(successLogger).info(anyString()); - verify(successLogger).debug(anyString()); - - jettyLoggerAdapter.warn(new Exception("warn")); - jettyLoggerAdapter.info(new Exception("info")); - jettyLoggerAdapter.debug(new Exception("debug")); - jettyLoggerAdapter.ignore(new Exception("ignore")); - - jettyLoggerAdapter.warn("warn", new Exception("warn")); - jettyLoggerAdapter.info("info", new Exception("info")); - jettyLoggerAdapter.debug("debug", new Exception("debug")); - } - - @Test - void testNewLogger() { - JettyLoggerAdapter loggerAdapter = new JettyLoggerAdapter(); - org.eclipse.jetty.util.log.Logger logger = - loggerAdapter.newLogger(this.getClass().getName()); - assertThat(logger.getClass().isAssignableFrom(JettyLoggerAdapter.class), is(true)); - } - - @Test - void testDebugEnabled() { - JettyLoggerAdapter loggerAdapter = new JettyLoggerAdapter(); - loggerAdapter.setDebugEnabled(true); - assertThat(loggerAdapter.isDebugEnabled(), is(true)); - } - - @Test - void testLoggerFormat() throws Exception { - Class clazz = Class.forName("org.apache.dubbo.remoting.http.jetty.JettyLoggerAdapter"); - Object newInstance = clazz.getDeclaredConstructor().newInstance(); - - Method method = clazz.getDeclaredMethod("format", String.class, Object[].class); - method.setAccessible(true); - - String print = (String) method.invoke(newInstance, "Hello,{}! I'am {}", new String[] {"World", "Jetty"}); - - assertThat(print, is("Hello,World! I'am Jetty")); - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/rest/RestClientTest.java b/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/rest/RestClientTest.java deleted file mode 100644 index 571861ae3d9..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/rest/RestClientTest.java +++ /dev/null @@ -1,240 +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.http.rest; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.url.component.ServiceConfigURL; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.remoting.http.*; -import org.apache.dubbo.remoting.http.config.HttpClientConfig; -import org.apache.dubbo.remoting.http.jetty.JettyHttpServer; -import org.apache.dubbo.remoting.http.restclient.HttpClientRestClient; -import org.apache.dubbo.remoting.http.restclient.OKHttpRestClient; -import org.apache.dubbo.remoting.http.restclient.URLConnectionRestClient; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CompletableFuture; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.Is.is; - -public class RestClientTest { - - @Test - public void testRestClient() throws Exception { - int port = NetUtils.getAvailablePort(); - URL url = new ServiceConfigURL( - "http", "localhost", port, new String[] {Constants.BIND_PORT_KEY, String.valueOf(port)}); - HttpServer httpServer = new JettyHttpServer(url, new HttpHandler() { - @Override - public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { - response.getWriter().write("Jetty"); - } - }); - - RequestTemplate requestTemplate = new RequestTemplate(null, "POST", "localhost:" + port); - - requestTemplate.addParam("p1", "value1"); - requestTemplate.addParam("p2", "value2"); - - requestTemplate.addParams("p3", Arrays.asList("value3", "value3.1")); - requestTemplate.addHeader("test", "dubbo"); - requestTemplate.addKeepAliveHeader(60); - - requestTemplate.addHeaders("header", Arrays.asList("h1", "h2")); - - requestTemplate.path("/test"); - requestTemplate.serializeBody("test".getBytes(StandardCharsets.UTF_8)); - - RestClient restClient = new OKHttpRestClient(new HttpClientConfig()); - - CompletableFuture send = restClient.send(requestTemplate); - - RestResult restResult = send.get(); - - assertThat(new String(restResult.getBody()), is("Jetty")); - - restClient = new HttpClientRestClient(new HttpClientConfig()); - - send = restClient.send(requestTemplate); - - restResult = send.get(); - - assertThat(new String(restResult.getBody()), is("Jetty")); - - restClient = new URLConnectionRestClient(new HttpClientConfig()); - - send = restClient.send(requestTemplate); - - restResult = send.get(); - - assertThat(new String(restResult.getBody()), is("Jetty")); - - httpServer.close(); - } - - @Test - public void testError() throws Exception { - int port = NetUtils.getAvailablePort(); - URL url = new ServiceConfigURL( - "http", "localhost", port, new String[] {Constants.BIND_PORT_KEY, String.valueOf(port)}); - HttpServer httpServer = new JettyHttpServer(url, new HttpHandler() { - @Override - public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { - response.setStatus(500); - response.getWriter().write("server error"); - response.addHeader("Content-Type", "text/html"); - } - }); - - RequestTemplate requestTemplate = new RequestTemplate(null, null, null); - - requestTemplate.httpMethod("POST"); - requestTemplate.setAddress("localhost:" + port); - requestTemplate.setProtocol("http://"); - requestTemplate.addHeader("test", "dubbo"); - requestTemplate.path("/test"); - requestTemplate.serializeBody("test".getBytes(StandardCharsets.UTF_8)); - - RestClient restClient = new OKHttpRestClient(new HttpClientConfig()); - - CompletableFuture send = restClient.send(requestTemplate); - - String error = "Server Error\n" + " error info is: server error"; - RestResult restResult = send.get(); - - String contentType = "text/html;charset=iso-8859-1"; - - Assertions.assertEquals(500, restResult.getResponseCode()); - Assertions.assertEquals(error, restResult.getMessage()); - Assertions.assertEquals(contentType, restResult.getContentType()); - - Map> headers = restResult.headers(); - restClient.close(); - - restClient = new HttpClientRestClient(new HttpClientConfig()); - send = restClient.send(requestTemplate); - restResult = send.get(); - - Assertions.assertEquals(500, restResult.getResponseCode()); - Assertions.assertEquals(error, restResult.getMessage()); - Assertions.assertEquals(contentType, restResult.getContentType()); - - restClient.close(); - - restClient = new URLConnectionRestClient(new HttpClientConfig()); - send = restClient.send(requestTemplate); - restResult = send.get(); - - Assertions.assertEquals(500, restResult.getResponseCode()); - Assertions.assertEquals(error, restResult.getMessage()); - Assertions.assertEquals(contentType, restResult.getContentType()); - restClient.close(); - - httpServer.close(); - } - - @Test - public void testMethod() { - - RequestTemplate requestTemplate = new RequestTemplate(null, null, null); - - requestTemplate.body(new Object(), Object.class); - - Assertions.assertEquals(requestTemplate.getBodyType(), Object.class); - - requestTemplate.addHeader("Content-Length", 1); - - Integer contentLength = requestTemplate.getContentLength(); - - Assertions.assertEquals(1, contentLength); - - List strings = Arrays.asList("h1", "h2"); - - requestTemplate.addHeaders("header", strings); - - Assertions.assertArrayEquals( - strings.toArray(new String[0]), - requestTemplate.getHeaders("header").toArray(new String[0])); - - strings = Arrays.asList("p1", "p2"); - - requestTemplate.addParams("param", strings); - - Assertions.assertArrayEquals( - strings.toArray(new String[0]), - requestTemplate.getParam("param").toArray(new String[0])); - } - - @Test - void testBuildURL() throws Exception { - int port = NetUtils.getAvailablePort(); - URL url = new ServiceConfigURL( - "http", "localhost", port, new String[] {Constants.BIND_PORT_KEY, String.valueOf(port)}); - HttpServer httpServer = new JettyHttpServer(url, new HttpHandler() { - @Override - public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { - response.setCharacterEncoding("UTF-8"); - response.getWriter().write(request.getQueryString()); - } - }); - - RequestTemplate requestTemplate = new RequestTemplate(null, "POST", "localhost:" + port); - - requestTemplate.addParam("name", "李强"); - requestTemplate.addParam("age", "18"); - requestTemplate.path("/hello/world"); - - // When using the OKHttpRestClient, parameters will be encoded with UTF-8 and appended to the URL - RestClient restClient = new OKHttpRestClient(new HttpClientConfig()); - - CompletableFuture send = restClient.send(requestTemplate); - - RestResult restResult = send.get(); - - assertThat(new String(restResult.getBody()), is("name=%E6%9D%8E%E5%BC%BA&age=18")); - - // When using the HttpClientRestClient, parameters will be encoded with UTF-8 and appended to the URL - restClient = new HttpClientRestClient(new HttpClientConfig()); - - send = restClient.send(requestTemplate); - - restResult = send.get(); - - assertThat(new String(restResult.getBody()), is("name=%E6%9D%8E%E5%BC%BA&age=18")); - - // When using the URLConnectionRestClient, parameters won't be encoded and still appended to the URL - restClient = new URLConnectionRestClient(new HttpClientConfig()); - - send = restClient.send(requestTemplate); - - restResult = send.get(); - - assertThat(new String(restResult.getBody(), StandardCharsets.UTF_8), is("name=李强&age=18")); - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinderTest.java b/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinderTest.java deleted file mode 100644 index 75efc28b412..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinderTest.java +++ /dev/null @@ -1,60 +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.http.tomcat; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.url.component.ServiceConfigURL; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.remoting.http.HttpHandler; -import org.apache.dubbo.remoting.http.HttpServer; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import java.io.IOException; - -import org.apache.http.client.fluent.Request; -import org.junit.jupiter.api.Test; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.Is.is; - -class TomcatHttpBinderTest { - @Test - void shouldAbleHandleRequestForTomcatBinder() throws Exception { - int port = NetUtils.getAvailablePort(); - URL url = new ServiceConfigURL( - "http", "localhost", port, new String[] {Constants.BIND_PORT_KEY, String.valueOf(port)}); - - HttpServer httpServer = new TomcatHttpBinder() - .bind(url, new HttpHandler() { - @Override - public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { - response.getWriter().write("Tomcat"); - } - }); - - String response = - Request.Get(url.toJavaURL().toURI()).execute().returnContent().asString(); - - assertThat(response, is("Tomcat")); - - httpServer.close(); - assertThat(NetUtils.isPortInUsed(port), is(false)); - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/test/resources/log4j2-test.xml b/dubbo-remoting/dubbo-remoting-http/src/test/resources/log4j2-test.xml deleted file mode 100644 index ba99f52cc2d..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/test/resources/log4j2-test.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/AbstractServerHttpChannelObserver.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/AbstractServerHttpChannelObserver.java index a4086cc08f2..9883a8072ec 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/AbstractServerHttpChannelObserver.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/AbstractServerHttpChannelObserver.java @@ -21,33 +21,27 @@ import org.apache.dubbo.remoting.http12.exception.HttpStatusException; import org.apache.dubbo.remoting.http12.message.HttpMessageEncoder; -import java.util.List; -import java.util.Map; - public abstract class AbstractServerHttpChannelObserver implements CustomizableHttpChannelObserver { + private final HttpChannel httpChannel; + private HeadersCustomizer headersCustomizer = HeadersCustomizer.NO_OP; private TrailersCustomizer trailersCustomizer = TrailersCustomizer.NO_OP; private ErrorResponseCustomizer errorResponseCustomizer = ErrorResponseCustomizer.NO_OP; - private final HttpChannel httpChannel; + private HttpMessageEncoder responseEncoder; private boolean headerSent; - private HttpMessageEncoder responseEncoder; - - public AbstractServerHttpChannelObserver(HttpChannel httpChannel) { + protected AbstractServerHttpChannelObserver(HttpChannel httpChannel) { this.httpChannel = httpChannel; } - public void setResponseEncoder(HttpMessageEncoder responseEncoder) { - this.responseEncoder = responseEncoder; - } - - public HttpMessageEncoder getResponseEncoder() { - return responseEncoder; + @Override + public HttpChannel getHttpChannel() { + return httpChannel; } @Override @@ -65,71 +59,38 @@ public void setErrorResponseCustomizer(ErrorResponseCustomizer errorResponseCust this.errorResponseCustomizer = errorResponseCustomizer; } - protected HeadersCustomizer getHeadersCustomizer() { - return headersCustomizer; + public HttpMessageEncoder getResponseEncoder() { + return responseEncoder; } - protected TrailersCustomizer getTrailersCustomizer() { - return trailersCustomizer; + public void setResponseEncoder(HttpMessageEncoder responseEncoder) { + this.responseEncoder = responseEncoder; } @Override - public void onNext(Object data) { + public final void onNext(Object data) { try { - if (data instanceof HttpResult) { - HttpResult result = (HttpResult) data; - if (!headerSent) { - doSendHeaders(String.valueOf(result.getStatus()), result.getHeaders()); - } - data = result.getBody(); - } else if (!headerSent) { - doSendHeaders(HttpStatus.OK.getStatusString(), null); - } - HttpOutputMessage outputMessage = encodeHttpOutputMessage(data); - preOutputMessage(outputMessage); - responseEncoder.encode(outputMessage.getBody(), data); - getHttpChannel().writeMessage(outputMessage); - postOutputMessage(outputMessage); + doOnNext(data); } catch (Throwable e) { onError(e); } } - protected void preOutputMessage(HttpOutputMessage outputMessage) throws Throwable {} - - protected void postOutputMessage(HttpOutputMessage outputMessage) throws Throwable {} - - protected abstract HttpMetadata encodeHttpMetadata(); - - protected HttpOutputMessage encodeHttpOutputMessage(Object data) { - return getHttpChannel().newOutputMessage(); - } - - protected HttpMetadata encodeTrailers(Throwable throwable) { - return null; + protected void doOnNext(Object data) throws Throwable { + if (!headerSent) { + sendHeader(buildMetadata(resolveStatusCode(data), data, null)); + } + sendMessage(buildMessage(data)); } @Override - public void onError(Throwable throwable) { + public final void onError(Throwable throwable) { if (throwable instanceof HttpResultPayloadException) { onNext(((HttpResultPayloadException) throwable).getResult()); return; } - int httpStatusCode = HttpStatus.INTERNAL_SERVER_ERROR.getCode(); - if (throwable instanceof HttpStatusException) { - httpStatusCode = ((HttpStatusException) throwable).getStatusCode(); - } - if (!headerSent) { - doSendHeaders(String.valueOf(httpStatusCode), null); - } try { - ErrorResponse errorResponse = new ErrorResponse(); - errorResponse.setStatus(String.valueOf(httpStatusCode)); - errorResponse.setMessage(throwable.getMessage()); - errorResponseCustomizer.accept(errorResponse, throwable); - HttpOutputMessage httpOutputMessage = encodeHttpOutputMessage(errorResponse); - responseEncoder.encode(httpOutputMessage.getBody(), errorResponse); - getHttpChannel().writeMessage(httpOutputMessage); + doOnError(throwable); } catch (Throwable ex) { throwable = new EncodeException(ex); } finally { @@ -137,35 +98,103 @@ public void onError(Throwable throwable) { } } + protected void doOnError(Throwable throwable) throws Throwable { + String statusCode = resolveStatusCode(throwable); + Object data = buildErrorResponse(statusCode, throwable); + if (!headerSent) { + sendHeader(buildMetadata(statusCode, data, null)); + } + sendMessage(buildMessage(data)); + } + @Override - public void onCompleted() { + public final void onCompleted() { doOnCompleted(null); } - @Override - public HttpChannel getHttpChannel() { - return httpChannel; + protected void doOnCompleted(Throwable throwable) { + HttpMetadata httpMetadata = encodeTrailers(throwable); + if (httpMetadata == null) { + return; + } + trailersCustomizer.accept(httpMetadata.headers(), throwable); + getHttpChannel().writeHeader(httpMetadata); + } + + protected HttpMetadata encodeTrailers(Throwable throwable) { + return null; + } + + protected HttpOutputMessage encodeHttpOutputMessage(Object data) { + return getHttpChannel().newOutputMessage(); + } + + protected abstract HttpMetadata encodeHttpMetadata(); + + protected void preOutputMessage(HttpOutputMessage outputMessage) throws Throwable {} + + protected void postOutputMessage(HttpOutputMessage outputMessage) throws Throwable {} + + protected void preMetadata(HttpMetadata httpMetadata, HttpOutputMessage outputMessage) {} + + protected final String resolveStatusCode(Object data) { + return data instanceof HttpResult + ? String.valueOf(((HttpResult) data).getStatus()) + : HttpStatus.OK.getStatusString(); + } + + protected final String resolveStatusCode(Throwable throwable) { + return throwable instanceof HttpStatusException + ? String.valueOf(((HttpStatusException) throwable).getStatusCode()) + : HttpStatus.INTERNAL_SERVER_ERROR.getStatusString(); + } + + protected final ErrorResponse buildErrorResponse(String statusCode, Throwable throwable) { + ErrorResponse errorResponse = new ErrorResponse(); + errorResponse.setStatus(statusCode); + errorResponse.setMessage(throwable.getMessage()); + errorResponseCustomizer.accept(errorResponse, throwable); + return errorResponse; + } + + protected final HttpOutputMessage buildMessage(Object data) throws Throwable { + if (data instanceof HttpResult) { + data = ((HttpResult) data).getBody(); + } + HttpOutputMessage outputMessage = encodeHttpOutputMessage(data); + try { + preOutputMessage(outputMessage); + responseEncoder.encode(outputMessage.getBody(), data); + } catch (Throwable t) { + outputMessage.close(); + throw t; + } + return outputMessage; + } + + protected final void sendMessage(HttpOutputMessage outputMessage) throws Throwable { + getHttpChannel().writeMessage(outputMessage); + postOutputMessage(outputMessage); } - private void doSendHeaders(String statusCode, Map> additionalHeaders) { + protected final HttpMetadata buildMetadata(String statusCode, Object data, HttpOutputMessage httpOutputMessage) { HttpMetadata httpMetadata = encodeHttpMetadata(); HttpHeaders headers = httpMetadata.headers(); headers.set(HttpHeaderNames.STATUS.getName(), statusCode); headers.set(HttpHeaderNames.CONTENT_TYPE.getName(), responseEncoder.contentType()); - headersCustomizer.accept(headers); - if (additionalHeaders != null) { - headers.putAll(additionalHeaders); + if (data instanceof HttpResult) { + HttpResult result = (HttpResult) data; + if (result.getHeaders() != null) { + headers.putAll(result.getHeaders()); + } } - getHttpChannel().writeHeader(httpMetadata); - headerSent = true; + preMetadata(httpMetadata, httpOutputMessage); + headersCustomizer.accept(headers); + return httpMetadata; } - protected void doOnCompleted(Throwable throwable) { - HttpMetadata httpMetadata = encodeTrailers(throwable); - if (httpMetadata == null) { - return; - } - trailersCustomizer.accept(httpMetadata.headers(), throwable); + protected final void sendHeader(HttpMetadata httpMetadata) { getHttpChannel().writeHeader(httpMetadata); + headerSent = true; } } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpInputMessage.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpInputMessage.java index 60d6a4dec77..717b03665a0 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpInputMessage.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpInputMessage.java @@ -16,9 +16,15 @@ */ package org.apache.dubbo.remoting.http12; +import java.io.IOException; import java.io.InputStream; -public interface HttpInputMessage { +public interface HttpInputMessage extends AutoCloseable { InputStream getBody(); + + @Override + default void close() throws IOException { + getBody().close(); + } } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpOutputMessage.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpOutputMessage.java index e56630430c5..ac64685bd0a 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpOutputMessage.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpOutputMessage.java @@ -17,9 +17,10 @@ package org.apache.dubbo.remoting.http12; import java.io.ByteArrayOutputStream; +import java.io.IOException; import java.io.OutputStream; -public interface HttpOutputMessage { +public interface HttpOutputMessage extends AutoCloseable { HttpOutputMessage EMPTY_MESSAGE = new HttpOutputMessage() { @@ -32,4 +33,9 @@ public OutputStream getBody() { }; OutputStream getBody(); + + @Override + default void close() throws IOException { + getBody().close(); + } } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/DefaultHttp1Request.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/DefaultHttp1Request.java index 1bc610d84bf..d950f8a0407 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/DefaultHttp1Request.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/DefaultHttp1Request.java @@ -20,6 +20,7 @@ import org.apache.dubbo.remoting.http12.HttpInputMessage; import org.apache.dubbo.remoting.http12.RequestMetadata; +import java.io.IOException; import java.io.InputStream; public class DefaultHttp1Request implements Http1Request { @@ -52,4 +53,9 @@ public String method() { public String path() { return httpMetadata.path(); } + + @Override + public void close() throws IOException { + httpInputMessage.close(); + } } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/DefaultHttp1Response.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/DefaultHttp1Response.java index 4f345b6cbe6..75bdb4210c3 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/DefaultHttp1Response.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/DefaultHttp1Response.java @@ -20,6 +20,7 @@ import org.apache.dubbo.remoting.http12.HttpInputMessage; import org.apache.dubbo.remoting.http12.HttpMetadata; +import java.io.IOException; import java.io.InputStream; public class DefaultHttp1Response implements HttpMetadata, HttpInputMessage { @@ -42,4 +43,9 @@ public InputStream getBody() { public HttpHeaders headers() { return httpMetadata.headers(); } + + @Override + public void close() throws IOException { + httpInputMessage.close(); + } } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1OutputMessage.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1OutputMessage.java index 2406b8249cf..dd8844162b0 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1OutputMessage.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1OutputMessage.java @@ -18,8 +18,11 @@ import org.apache.dubbo.remoting.http12.HttpOutputMessage; +import java.io.IOException; import java.io.OutputStream; +import io.netty.buffer.ByteBufOutputStream; + public class Http1OutputMessage implements HttpOutputMessage { private final OutputStream outputStream; @@ -32,4 +35,12 @@ public Http1OutputMessage(OutputStream outputStream) { public OutputStream getBody() { return outputStream; } + + @Override + public void close() throws IOException { + if (outputStream instanceof ByteBufOutputStream) { + ((ByteBufOutputStream) outputStream).buffer().release(); + } + outputStream.close(); + } } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerChannelObserver.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerChannelObserver.java index 6d92b865541..e62fbeb8040 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerChannelObserver.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerChannelObserver.java @@ -19,7 +19,6 @@ import org.apache.dubbo.remoting.http12.AbstractServerHttpChannelObserver; import org.apache.dubbo.remoting.http12.HttpChannel; import org.apache.dubbo.remoting.http12.HttpChannelObserver; -import org.apache.dubbo.remoting.http12.HttpHeaderNames; import org.apache.dubbo.remoting.http12.HttpHeaders; import org.apache.dubbo.remoting.http12.HttpMetadata; import org.apache.dubbo.remoting.http12.HttpOutputMessage; @@ -34,7 +33,6 @@ public Http1ServerChannelObserver(HttpChannel httpChannel) { @Override protected HttpMetadata encodeHttpMetadata() { HttpHeaders httpHeaders = new HttpHeaders(); - httpHeaders.set(HttpHeaderNames.TRANSFER_ENCODING.getName(), "chunked"); return new Http1Metadata(httpHeaders); } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerStreamChannelObserver.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerStreamChannelObserver.java index e5ee7aff442..8c3af9d6842 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerStreamChannelObserver.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerStreamChannelObserver.java @@ -17,6 +17,9 @@ package org.apache.dubbo.remoting.http12.h1; import org.apache.dubbo.remoting.http12.HttpChannel; +import org.apache.dubbo.remoting.http12.HttpHeaderNames; +import org.apache.dubbo.remoting.http12.HttpHeaders; +import org.apache.dubbo.remoting.http12.HttpMetadata; import org.apache.dubbo.remoting.http12.HttpOutputMessage; import java.io.IOException; @@ -33,6 +36,13 @@ public Http1ServerStreamChannelObserver(HttpChannel httpChannel) { super(httpChannel); } + @Override + protected HttpMetadata encodeHttpMetadata() { + HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.set(HttpHeaderNames.TRANSFER_ENCODING.getName(), "chunked"); + return new Http1Metadata(httpHeaders); + } + @Override protected void preOutputMessage(HttpOutputMessage httpMessage) throws IOException { HttpOutputMessage httpOutputMessage = this.getHttpChannel().newOutputMessage(); diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerUnaryChannelObserver.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerUnaryChannelObserver.java new file mode 100644 index 00000000000..8cb2a36edd2 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerUnaryChannelObserver.java @@ -0,0 +1,58 @@ +/* + * 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.http12.h1; + +import org.apache.dubbo.remoting.http12.HttpChannel; +import org.apache.dubbo.remoting.http12.HttpHeaderNames; +import org.apache.dubbo.remoting.http12.HttpMetadata; +import org.apache.dubbo.remoting.http12.HttpOutputMessage; + +import java.io.OutputStream; + +import io.netty.buffer.ByteBufOutputStream; + +public class Http1ServerUnaryChannelObserver extends Http1ServerChannelObserver { + + public Http1ServerUnaryChannelObserver(HttpChannel httpChannel) { + super(httpChannel); + } + + @Override + protected void doOnNext(Object data) throws Throwable { + HttpOutputMessage httpOutputMessage = buildMessage(data); + sendHeader(buildMetadata(resolveStatusCode(data), data, httpOutputMessage)); + sendMessage(httpOutputMessage); + } + + @Override + protected void doOnError(Throwable throwable) throws Throwable { + String statusCode = resolveStatusCode(throwable); + Object data = buildErrorResponse(statusCode, throwable); + HttpOutputMessage httpOutputMessage = buildMessage(data); + sendHeader(buildMetadata(statusCode, data, httpOutputMessage)); + sendMessage(httpOutputMessage); + } + + @Override + protected void preMetadata(HttpMetadata httpMetadata, HttpOutputMessage outputMessage) { + OutputStream body = outputMessage.getBody(); + if (body instanceof ByteBufOutputStream) { + int contentLength = ((ByteBufOutputStream) body).writtenBytes(); + httpMetadata.headers().set(HttpHeaderNames.CONTENT_LENGTH.getName(), String.valueOf(contentLength)); + } + } +} diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/Http2OutputMessageFrame.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/Http2OutputMessageFrame.java index 15c87eb4139..d3ba8ce66da 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/Http2OutputMessageFrame.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/Http2OutputMessageFrame.java @@ -16,8 +16,11 @@ */ package org.apache.dubbo.remoting.http12.h2; +import java.io.IOException; import java.io.OutputStream; +import io.netty.buffer.ByteBufOutputStream; + public class Http2OutputMessageFrame implements Http2OutputMessage { private final OutputStream body; @@ -42,6 +45,14 @@ public OutputStream getBody() { return body; } + @Override + public void close() throws IOException { + if (body instanceof ByteBufOutputStream) { + ((ByteBufOutputStream) body).buffer().release(); + } + body.close(); + } + @Override public boolean isEndStream() { return endStream; 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 695983a22f1..95539ac9ac7 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 @@ -43,11 +43,11 @@ final class NettyChannel extends AbstractChannel { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NettyChannel.class); private static final ConcurrentMap CHANNEL_MAP = - new ConcurrentHashMap(); + new ConcurrentHashMap<>(); private final org.jboss.netty.channel.Channel channel; - private final Map attributes = new ConcurrentHashMap(); + private final Map attributes = new ConcurrentHashMap<>(); private NettyChannel(org.jboss.netty.channel.Channel channel, URL url, ChannelHandler handler) { super(url, handler); diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyHandler.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyHandler.java index f1d4bfd23c8..d864639dacc 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyHandler.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyHandler.java @@ -42,7 +42,7 @@ public class NettyHandler extends SimpleChannelHandler { private static final Logger logger = LoggerFactory.getLogger(NettyHandler.class); - private final Map channels = new ConcurrentHashMap(); // + private final Map channels = new ConcurrentHashMap<>(); // private final URL url; diff --git a/dubbo-remoting/dubbo-remoting-netty4/pom.xml b/dubbo-remoting/dubbo-remoting-netty4/pom.xml index ec180ddb3fb..06d548d1bdf 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/pom.xml +++ b/dubbo-remoting/dubbo-remoting-netty4/pom.xml @@ -84,6 +84,10 @@ linux-aarch_64 runtime + + io.netty + netty-codec-http2 + org.apache.dubbo diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java index 41b7bb5f4cd..8041c72bd84 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java @@ -61,14 +61,13 @@ final class NettyChannel extends AbstractChannel { /** * the cache for netty channel and dubbo channel */ - private static final ConcurrentMap CHANNEL_MAP = - new ConcurrentHashMap(); + private static final ConcurrentMap CHANNEL_MAP = new ConcurrentHashMap<>(); /** * netty channel */ private final Channel channel; - private final Map attributes = new ConcurrentHashMap(); + private final Map attributes = new ConcurrentHashMap<>(); private final AtomicBoolean active = new AtomicBoolean(false); diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConnectionClient.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConnectionClient.java index 6f3171363cc..5f1c9bd0624 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConnectionClient.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConnectionClient.java @@ -31,6 +31,7 @@ import org.apache.dubbo.remoting.transport.netty4.ssl.SslContexts; import org.apache.dubbo.remoting.utils.UrlUtils; +import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; @@ -42,7 +43,6 @@ import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; -import io.netty.channel.EventLoop; import io.netty.channel.socket.SocketChannel; import io.netty.handler.ssl.SslContext; import io.netty.handler.timeout.IdleStateHandler; @@ -74,6 +74,8 @@ public class NettyConnectionClient extends AbstractConnectionClient { public static final AttributeKey CONNECTION = AttributeKey.valueOf("connection"); + private AtomicBoolean isReconnecting; + public NettyConnectionClient(URL url, ChannelHandler handler) throws RemotingException { super(url, handler); } @@ -90,6 +92,7 @@ protected void initConnectionClient() { this.closePromise = new DefaultPromise<>(GlobalEventExecutor.INSTANCE); this.init = new AtomicBoolean(false); this.increase(); + this.isReconnecting = new AtomicBoolean(false); } @Override @@ -157,6 +160,10 @@ protected void doClose() { @Override protected void doConnect() throws RemotingException { + if (!isReconnecting.compareAndSet(false, true)) { + return; + } + if (isClosed()) { if (LOGGER.isDebugEnabled()) { LOGGER.debug( @@ -229,6 +236,13 @@ public void onConnected(Object channel) { } return; } + + // Close the existing channel before setting a new channel + final io.netty.channel.Channel current = getNettyChannel(); + if (current != null) { + current.close(); + } + this.channel.set(nettyChannel); // This indicates that the connection is available. if (this.connectingPromise.get() != null) { @@ -247,6 +261,10 @@ public void onGoaway(Object channel) { } io.netty.channel.Channel nettyChannel = (io.netty.channel.Channel) channel; if (this.channel.compareAndSet(nettyChannel, null)) { + // Ensure the channel is closed + if (nettyChannel.isOpen()) { + nettyChannel.close(); + } NettyChannel.removeChannelIfDisconnected(nettyChannel); if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format("%s goaway", this)); @@ -337,13 +355,20 @@ public void destroy() { @Override public String toString() { return super.toString() + " (Ref=" + this.getCounter() + ",local=" - + (getChannel() == null ? null : getChannel().getLocalAddress()) + ",remote=" + getRemoteAddress(); + + Optional.ofNullable(getChannel()) + .map(Channel::getLocalAddress) + .orElse(null) + ",remote=" + getRemoteAddress(); } class ConnectionListener implements ChannelFutureListener { @Override public void operationComplete(ChannelFuture future) { + + if (!isReconnecting.compareAndSet(true, false)) { + return; + } + if (future.isSuccess()) { return; } @@ -361,8 +386,8 @@ public void operationComplete(ChannelFuture future) { "%s is reconnecting, attempt=%d cause=%s", connectionClient, 0, future.cause().getMessage())); } - final EventLoop loop = future.channel().eventLoop(); - loop.schedule( + + connectivityExecutor.schedule( () -> { try { connectionClient.doConnect(); @@ -374,8 +399,8 @@ public void operationComplete(ChannelFuture future) { "Failed to connect to server: " + getConnectAddress()); } }, - 1L, - TimeUnit.SECONDS); + reconnectDuaration, + TimeUnit.MILLISECONDS); } } } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationServerHandler.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationServerHandler.java index fe07a9e69a0..f3c490376ad 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationServerHandler.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationServerHandler.java @@ -39,6 +39,8 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.ByteToMessageDecoder; +import io.netty.handler.ssl.ApplicationProtocolNames; +import io.netty.handler.ssl.ApplicationProtocolNegotiationHandler; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslHandler; import io.netty.handler.ssl.SslHandshakeCompletionEvent; @@ -119,48 +121,7 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) t if (providerConnectionConfig != null && isSsl(in)) { enableSsl(ctx, providerConnectionConfig); } else { - Set supportedProtocolNames = new HashSet<>(protocols.keySet()); - supportedProtocolNames.retainAll(urlMapper.keySet()); - - for (final String name : supportedProtocolNames) { - WireProtocol protocol = protocols.get(name); - in.markReaderIndex(); - ChannelBuffer buf = new NettyBackedChannelBuffer(in); - final ProtocolDetector.Result result = protocol.detector().detect(buf); - in.resetReaderIndex(); - switch (result.flag()) { - case UNRECOGNIZED: - continue; - case RECOGNIZED: - ChannelHandler localHandler = this.handlerMapper.getOrDefault(name, handler); - URL localURL = this.urlMapper.getOrDefault(name, url); - channel.setUrl(localURL); - NettyConfigOperator operator = new NettyConfigOperator(channel, localHandler); - operator.setDetectResult(result); - protocol.configServerProtocolHandler(url, operator); - ctx.pipeline().remove(this); - case NEED_MORE_DATA: - return; - default: - return; - } - } - byte[] preface = new byte[in.readableBytes()]; - in.readBytes(preface); - Set supported = url.getApplicationModel() - .getExtensionLoader(WireProtocol.class) - .getSupportedExtensions(); - LOGGER.error( - INTERNAL_ERROR, - "unknown error in remoting module", - "", - String.format( - "Can not recognize protocol from downstream=%s . " + "preface=%s protocols=%s", - ctx.channel().remoteAddress(), Bytes.bytes2hex(preface), supported)); - - // Unknown protocol; discard everything and close the connection. - in.clear(); - ctx.close(); + detectProtocol(ctx, url, channel, in); } } @@ -171,6 +132,17 @@ private void enableSsl(ChannelHandlerContext ctx, ProviderCert providerConnectio p.addLast( "unificationA", new NettyPortUnificationServerHandler(url, false, protocols, handler, urlMapper, handlerMapper)); + p.addLast("ALPN", new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_1_1) { + @Override + protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception { + if (!ApplicationProtocolNames.HTTP_2.equals(protocol)) { + return; + } + NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); + ByteBuf in = ctx.alloc().buffer(); + detectProtocol(ctx, url, channel, in); + } + }); p.remove(this); } @@ -181,4 +153,48 @@ private boolean isSsl(ByteBuf buf) { } return false; } + + private void detectProtocol(ChannelHandlerContext ctx, URL url, NettyChannel channel, ByteBuf in) { + Set supportedProtocolNames = new HashSet<>(protocols.keySet()); + supportedProtocolNames.retainAll(urlMapper.keySet()); + + for (final String name : supportedProtocolNames) { + WireProtocol protocol = protocols.get(name); + in.markReaderIndex(); + ChannelBuffer buf = new NettyBackedChannelBuffer(in); + final ProtocolDetector.Result result = protocol.detector().detect(buf); + in.resetReaderIndex(); + switch (result.flag()) { + case UNRECOGNIZED: + continue; + case RECOGNIZED: + ChannelHandler localHandler = this.handlerMapper.getOrDefault(name, handler); + URL localURL = this.urlMapper.getOrDefault(name, url); + channel.setUrl(localURL); + NettyConfigOperator operator = new NettyConfigOperator(channel, localHandler); + operator.setDetectResult(result); + protocol.configServerProtocolHandler(url, operator); + ctx.pipeline().remove(this); + case NEED_MORE_DATA: + return; + default: + return; + } + } + byte[] preface = new byte[in.readableBytes()]; + in.readBytes(preface); + Set supported = + url.getApplicationModel().getExtensionLoader(WireProtocol.class).getSupportedExtensions(); + LOGGER.error( + INTERNAL_ERROR, + "unknown error in remoting module", + "", + String.format( + "Can not recognize protocol from downstream=%s . " + "preface=%s protocols=%s", + ctx.channel().remoteAddress(), Bytes.bytes2hex(preface), supported)); + + // Unknown protocol; discard everything and close the connection. + in.clear(); + ctx.close(); + } } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ssl/SslContexts.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ssl/SslContexts.java index beb7e611420..13b1bbda874 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ssl/SslContexts.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ssl/SslContexts.java @@ -31,11 +31,15 @@ import java.security.Provider; import java.security.Security; +import io.netty.handler.codec.http2.Http2SecurityUtil; +import io.netty.handler.ssl.ApplicationProtocolConfig; +import io.netty.handler.ssl.ApplicationProtocolNames; import io.netty.handler.ssl.ClientAuth; import io.netty.handler.ssl.OpenSsl; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslProvider; +import io.netty.handler.ssl.SupportedCipherSuiteFilter; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE_STREAM; @@ -77,7 +81,16 @@ public static SslContext buildServerSslContext(ProviderCert providerConnectionCo safeCloseStream(serverPrivateKeyPathStream); } try { - return sslClientContextBuilder.sslProvider(findSslProvider()).build(); + return sslClientContextBuilder + .sslProvider(findSslProvider()) + .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) + .applicationProtocolConfig(new ApplicationProtocolConfig( + ApplicationProtocolConfig.Protocol.ALPN, + ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, + ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, + ApplicationProtocolNames.HTTP_2, + ApplicationProtocolNames.HTTP_1_1)) + .build(); } catch (SSLException e) { throw new IllegalStateException("Build SslSession failed.", e); } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ConnectionTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ConnectionTest.java index 37b4439bba6..c90418fa4de 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ConnectionTest.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ConnectionTest.java @@ -28,6 +28,7 @@ import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; +import java.time.Duration; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -39,6 +40,7 @@ import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT; +import static org.awaitility.Awaitility.await; public class ConnectionTest { @@ -138,6 +140,7 @@ void connectSyncTest() throws Throwable { nettyPortUnificationServer.bind(); // auto reconnect + await().atMost(Duration.ofSeconds(100)).until(() -> connectionClient.isAvailable()); Assertions.assertTrue(connectionClient.isAvailable()); connectionClient.close(); diff --git a/dubbo-remoting/pom.xml b/dubbo-remoting/pom.xml index 1a1d0cd0c40..e7aca3685e2 100644 --- a/dubbo-remoting/pom.xml +++ b/dubbo-remoting/pom.xml @@ -29,7 +29,6 @@ The remoting module of dubbo project dubbo-remoting-api - dubbo-remoting-http dubbo-remoting-netty dubbo-remoting-zookeeper-api dubbo-remoting-zookeeper diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcServiceContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcServiceContext.java index 5a8a640bd66..6bc36b75ae4 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcServiceContext.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcServiceContext.java @@ -459,7 +459,7 @@ public List> getInvokers() { public RpcServiceContext setInvokers(List> invokers) { this.invokers = invokers; if (CollectionUtils.isNotEmpty(invokers)) { - List urls = new ArrayList(invokers.size()); + List urls = new ArrayList<>(invokers.size()); for (Invoker invoker : invokers) { urls.add(invoker.getUrl()); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcStatus.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcStatus.java index 30de38825d6..9b0769f5454 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcStatus.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcStatus.java @@ -33,13 +33,12 @@ */ public class RpcStatus { - private static final ConcurrentMap SERVICE_STATISTICS = - new ConcurrentHashMap(); + private static final ConcurrentMap SERVICE_STATISTICS = new ConcurrentHashMap<>(); private static final ConcurrentMap> METHOD_STATISTICS = - new ConcurrentHashMap>(); + new ConcurrentHashMap<>(); - private final ConcurrentMap values = new ConcurrentHashMap(); + private final ConcurrentMap values = new ConcurrentHashMap<>(); private final AtomicInteger active = new AtomicInteger(); private final AtomicLong total = new AtomicLong(); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java index 1cbabd45d01..e1b2c4966c3 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java @@ -44,7 +44,7 @@ public class DeprecatedFilter implements Filter { private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(DeprecatedFilter.class); - private static final Set LOGGED = new ConcurrentHashSet(); + private static final Set LOGGED = new ConcurrentHashSet<>(); @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiter.java index 0410d70c505..645345db3fa 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiter.java @@ -35,7 +35,7 @@ */ public class DefaultTPSLimiter implements TPSLimiter { - private final ConcurrentMap stats = new ConcurrentHashMap(); + private final ConcurrentMap stats = new ConcurrentHashMap<>(); @Override public boolean isAllowable(URL url, Invocation invocation) { diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java index 843754a1dd8..8bd9e41a360 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java @@ -50,7 +50,7 @@ */ public abstract class AbstractProxyProtocol extends AbstractProtocol { - private final List> rpcExceptions = new CopyOnWriteArrayList>(); + private final List> rpcExceptions = new CopyOnWriteArrayList<>(); protected ProxyFactory proxyFactory; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapper.java index 421e1148e7b..52ca299bb82 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapper.java @@ -74,8 +74,7 @@ public Exporter export(Invoker invoker) throws RpcException { .getBeanFactory() .getBean(InjvmExporterListener.class)); } - return new ListenerExporterWrapper( - protocol.export(invoker), Collections.unmodifiableList(exporterListeners)); + return new ListenerExporterWrapper<>(protocol.export(invoker), Collections.unmodifiableList(exporterListeners)); } @Override 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 9e798e51df8..4f35a9cb316 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java @@ -47,8 +47,8 @@ public final class MockInvoker implements Invoker { private final ProxyFactory proxyFactory; - private static final Map> MOCK_MAP = new ConcurrentHashMap>(); - private static final Map THROWABLE_MAP = new ConcurrentHashMap(); + private static final Map> MOCK_MAP = new ConcurrentHashMap<>(); + private static final Map THROWABLE_MAP = new ConcurrentHashMap<>(); private final URL url; private final Class type; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java index 53cd36894de..228392fe021 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java @@ -317,7 +317,7 @@ public static Long convertToNumber(Object obj) { timeout = Long.parseLong((String) obj); } else if (obj instanceof Number) { timeout = ((Number) obj).longValue(); - } else { + } else if (obj != null) { timeout = Long.parseLong(obj.toString()); } } catch (Exception e) { diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcStatusTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcStatusTest.java index efa938e803e..de0eaab48a6 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcStatusTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcStatusTest.java @@ -39,6 +39,10 @@ void testBeginCountEndCount() { URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 91031, DemoService.class.getName()); String methodName = "testBeginCountEndCount"; int max = 2; + + RpcStatus.removeStatus(url); + RpcStatus.removeStatus(url, methodName); + boolean flag = RpcStatus.beginCount(url, methodName, max); RpcStatus urlRpcStatus = RpcStatus.getStatus(url); RpcStatus methodRpcStatus = RpcStatus.getStatus(url, methodName); @@ -65,6 +69,10 @@ void testBeginCountEndCount() { void testBeginCountEndCountInMultiThread() throws Exception { URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 91032, DemoService.class.getName()); String methodName = "testBeginCountEndCountInMultiThread"; + + RpcStatus.removeStatus(url); + RpcStatus.removeStatus(url, methodName); + int max = 50; int threadNum = 10; AtomicInteger successCount = new AtomicInteger(); @@ -99,6 +107,10 @@ void testStatistics() { URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 91033, DemoService.class.getName()); String methodName = "testStatistics"; int max = 0; + + RpcStatus.removeStatus(url); + RpcStatus.removeStatus(url, methodName); + RpcStatus.beginCount(url, methodName, max); RpcStatus.beginCount(url, methodName, max); RpcStatus.beginCount(url, methodName, max); 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 a8bd3c0c02e..4a919adf250 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 @@ -339,7 +339,7 @@ public Exporter export(Invoker invoker) throws RpcException { // export service. String key = serviceKey(url); - DubboExporter exporter = new DubboExporter(invoker, key, exporterMap); + DubboExporter exporter = new DubboExporter<>(invoker, key, exporterMap); // export a stub service for dispatching event boolean isStubSupportEvent = url.getParameter(STUB_EVENT_KEY, DEFAULT_STUB_EVENT); @@ -443,7 +443,7 @@ public Invoker protocolBindingRefer(Class serviceType, URL url) throws optimizeSerialization(url); // create rpc invoker. - DubboInvoker invoker = new DubboInvoker(serviceType, url, getClients(url), invokers); + DubboInvoker invoker = new DubboInvoker<>(serviceType, url, getClients(url), invokers); invokers.add(invoker); return invoker; diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java b/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java index c4955e7ce7f..b3357847090 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java @@ -75,12 +75,12 @@ public int getDefaultPort() { @Override public Exporter export(Invoker invoker) throws RpcException { - return new InjvmExporter(invoker, invoker.getUrl().getServiceKey(), exporterMap); + return new InjvmExporter<>(invoker, invoker.getUrl().getServiceKey(), exporterMap); } @Override public Invoker protocolBindingRefer(Class serviceType, URL url) throws RpcException { - return new InjvmInvoker(serviceType, url, url.getServiceKey(), exporterMap); + return new InjvmInvoker<>(serviceType, url, url.getServiceKey(), exporterMap); } public boolean isInjvmRefer(URL url) { diff --git a/dubbo-rpc/dubbo-rpc-rest/pom.xml b/dubbo-rpc/dubbo-rpc-rest/pom.xml deleted file mode 100644 index 2e27452ad6a..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/pom.xml +++ /dev/null @@ -1,183 +0,0 @@ - - - - 4.0.0 - - org.apache.dubbo - dubbo-rpc - ${revision} - ../pom.xml - - dubbo-rpc-rest - jar - ${project.artifactId} - The rest rpc module of dubbo project - - - false - - - - - org.apache.dubbo - dubbo-rpc-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-http - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.parent.version} - - - - org.apache.dubbo - dubbo-cluster - ${project.parent.version} - - - - org.jboss.resteasy - resteasy-jaxrs - provided - - - - org.jboss.resteasy - resteasy-client - - - - javax.validation - validation-api - - - - - - org.jboss.resteasy - resteasy-netty4 - provided - - - - org.jboss.resteasy - resteasy-jdk-http - provided - - - - org.jboss.resteasy - resteasy-jackson-provider - provided - - - - org.jboss.resteasy - resteasy-jaxb-provider - provided - - - - - io.swagger - swagger-annotations - - - javax.ws.rs - jsr311-api - - - - - io.swagger - swagger-jaxrs - - - javax.ws.rs - jsr311-api - - - - - - org.apache.dubbo - dubbo-serialization-jdk - ${project.parent.version} - test - - - - org.apache.dubbo - dubbo-metadata-rest - ${project.parent.version} - - - - io.netty - netty-codec-http - provided - - - - io.netty - netty-transport - compile - - - - - org.springframework - spring-web - test - - - - org.springframework - spring-context - test - - - - com.google.code.gson - gson - test - - - - org.springframework.cloud - spring-cloud-openfeign-core - test - - - org.springframework.boot - spring-boot-starter-logging - - - - - org.apache.logging.log4j - log4j-slf4j-impl - test - - - diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/Constants.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/Constants.java deleted file mode 100644 index 5aa43155c46..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/Constants.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest; - -/** - * Constants definition. - */ -public interface Constants { - String KEEP_ALIVE_KEY = "keepalive"; - - boolean DEFAULT_KEEP_ALIVE = true; - - String EXTENSION_KEY = "extension"; - - // http server - - String NETTY_HTTP = "netty_http"; -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/PathAndInvokerMapper.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/PathAndInvokerMapper.java deleted file mode 100644 index bf4bcb225ba..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/PathAndInvokerMapper.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest; - -import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.metadata.rest.PathMatcher; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.protocol.rest.exception.DoublePathCheckException; -import org.apache.dubbo.rpc.protocol.rest.pair.InvokerAndRestMethodMetadataPair; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -/** - * save the path & metadata info mapping - */ -public class PathAndInvokerMapper { - private static final ErrorTypeAwareLogger logger = - LoggerFactory.getErrorTypeAwareLogger(PathAndInvokerMapper.class); - - private final Map pathToServiceMapContainPathVariable = - new ConcurrentHashMap<>(); - private final Map pathToServiceMapNoPathVariable = - new ConcurrentHashMap<>(); - - // for http method compare 405 - private final Map> pathMatcherToHttpMethodMap = new HashMap<>(); - - /** - * deploy path metadata - * - * @param metadataMap - * @param invoker - */ - public void addPathAndInvoker(Map metadataMap, Invoker invoker) { - - metadataMap.entrySet().stream().forEach(entry -> { - PathMatcher pathMatcher = entry.getKey(); - if (pathMatcher.hasPathVariable()) { - addPathMatcherToPathMap( - pathMatcher, - pathToServiceMapContainPathVariable, - InvokerAndRestMethodMetadataPair.pair(invoker, entry.getValue())); - } else { - addPathMatcherToPathMap( - pathMatcher, - pathToServiceMapNoPathVariable, - InvokerAndRestMethodMetadataPair.pair(invoker, entry.getValue())); - } - }); - } - - /** - * get rest method metadata by path matcher - * - * @param pathMatcher - * @return - */ - public InvokerAndRestMethodMetadataPair getRestMethodMetadata(PathMatcher pathMatcher) { - - // first search from pathToServiceMapNoPathVariable - if (pathToServiceMapNoPathVariable.containsKey(pathMatcher)) { - return pathToServiceMapNoPathVariable.get(pathMatcher); - } - - // second search from pathToServiceMapContainPathVariable - if (pathToServiceMapContainPathVariable.containsKey(pathMatcher)) { - return pathToServiceMapContainPathVariable.get(pathMatcher); - } - - return null; - } - - /** - * undeploy path metadata - * - * @param pathMatcher - */ - public void removePath(PathMatcher pathMatcher) { - - InvokerAndRestMethodMetadataPair containPathVariablePair = - pathToServiceMapContainPathVariable.remove(pathMatcher); - - InvokerAndRestMethodMetadataPair unContainPathVariablePair = pathToServiceMapNoPathVariable.remove(pathMatcher); - logger.info("dubbo rest undeploy pathMatcher:" + pathMatcher - + ", and path variable method is :" - + (containPathVariablePair == null - ? null - : containPathVariablePair.getRestMethodMetadata().getReflectMethod()) - + ", and no path variable method is :" - + (unContainPathVariablePair == null - ? null - : unContainPathVariablePair.getRestMethodMetadata().getReflectMethod())); - } - - public void addPathMatcherToPathMap( - PathMatcher pathMatcher, - Map pathMatcherPairMap, - InvokerAndRestMethodMetadataPair invokerRestMethodMetadataPair) { - - if (pathMatcherPairMap.containsKey(pathMatcher)) { - - // cover the old service metadata when current interface is old interface & current method desc equals - // old`s method desc,else ,throw double check exception - - InvokerAndRestMethodMetadataPair beforeMetadata = pathMatcherPairMap.get(pathMatcher); - // true when reExport - if (!invokerRestMethodMetadataPair.compareServiceMethod(beforeMetadata)) { - throw new DoublePathCheckException("dubbo rest double path check error, current path is: " + pathMatcher - + " ,and service method is: " - + invokerRestMethodMetadataPair.getRestMethodMetadata().getReflectMethod() - + "before service method is: " - + beforeMetadata.getRestMethodMetadata().getReflectMethod()); - } - } - - pathMatcherPairMap.put(pathMatcher, invokerRestMethodMetadataPair); - - addPathMatcherToHttpMethodsMap(pathMatcher); - - logger.info("dubbo rest deploy pathMatcher:" + pathMatcher + ", and service method is :" - + invokerRestMethodMetadataPair.getRestMethodMetadata().getReflectMethod()); - } - - private void addPathMatcherToHttpMethodsMap(PathMatcher pathMatcher) { - - PathMatcher newPathMatcher = PathMatcher.convertPathMatcher(pathMatcher); - - if (!pathMatcherToHttpMethodMap.containsKey(newPathMatcher)) { - HashSet httpMethods = new HashSet<>(); - - httpMethods.add(pathMatcher.getHttpMethod()); - - pathMatcherToHttpMethodMap.put(newPathMatcher, httpMethods); - } - - Set httpMethods = pathMatcherToHttpMethodMap.get(newPathMatcher); - - httpMethods.add(newPathMatcher.getHttpMethod()); - } - - public boolean isHttpMethodAllowed(PathMatcher pathMatcher) { - - PathMatcher newPathMatcher = PathMatcher.convertPathMatcher(pathMatcher); - if (!pathMatcherToHttpMethodMap.containsKey(newPathMatcher)) { - return false; - } - - Set httpMethods = pathMatcherToHttpMethodMap.get(newPathMatcher); - - return httpMethods.contains(newPathMatcher.getHttpMethod()); - } - - public String pathHttpMethods(PathMatcher pathMatcher) { - - PathMatcher newPathMatcher = PathMatcher.convertPathMatcher(pathMatcher); - if (!pathMatcherToHttpMethodMap.containsKey(newPathMatcher)) { - return null; - } - - Set httpMethods = pathMatcherToHttpMethodMap.get(newPathMatcher); - - return httpMethods.toString(); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/ReferenceCountedClient.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/ReferenceCountedClient.java deleted file mode 100644 index b7dbaa0263c..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/ReferenceCountedClient.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.reference.ReferenceCountedResource; -import org.apache.dubbo.remoting.http.RestClient; -import org.apache.dubbo.remoting.http.factory.RestClientFactory; - -import java.util.concurrent.ConcurrentMap; - -import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_CLIENT; - -public class ReferenceCountedClient extends ReferenceCountedResource { - private static final ErrorTypeAwareLogger logger = - LoggerFactory.getErrorTypeAwareLogger(ReferenceCountedClient.class); - - private ConcurrentMap> clients; - private URL url; - private RestClientFactory clientFactory; - - private T client; - - public ReferenceCountedClient( - T client, - ConcurrentMap> clients, - RestClientFactory clientFactory, - URL url) { - this.client = client; - this.clients = clients; - this.clientFactory = clientFactory; - this.url = url; - } - - public T getClient() { - - // for client destroy and create right now, only lock current client - synchronized (this) { - ReferenceCountedClient referenceCountedClient = clients.get(url.getAddress()); - - // for double check - if (referenceCountedClient.isDestroyed()) { - synchronized (this) { - referenceCountedClient = clients.get(url.getAddress()); - if (referenceCountedClient.isDestroyed()) { - RestClient restClient = clientFactory.createRestClient(url); - clients.put( - url.getAddress(), new ReferenceCountedClient(restClient, clients, clientFactory, url)); - return (T) restClient; - } else { - return (T) referenceCountedClient.client; - } - } - - } else { - return client; - } - } - } - - public boolean isDestroyed() { - return client.isClosed(); - } - - @Override - protected void destroy() { - try { - client.close(); - } catch (Exception e) { - logger.error(PROTOCOL_ERROR_CLOSE_CLIENT, "", "", "Close resteasy client error", e); - } - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestConstraintViolation.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestConstraintViolation.java deleted file mode 100644 index 6447bff8956..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestConstraintViolation.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; - -import java.io.Serializable; - -@XmlRootElement(name = "constraintViolation") -@XmlAccessorType(XmlAccessType.FIELD) -public class RestConstraintViolation implements Serializable { - - private static final long serialVersionUID = -23497234978L; - - private String path; - private String message; - private String value; - - public RestConstraintViolation(String path, String message, String value) { - this.path = path; - this.message = message; - this.value = value; - } - - public RestConstraintViolation() {} - - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestHeaderEnum.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestHeaderEnum.java deleted file mode 100644 index 7eab6db4d6b..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestHeaderEnum.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest; - -import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; - -public enum RestHeaderEnum { - CONTENT_TYPE(RestConstant.CONTENT_TYPE), - ACCEPT(RestConstant.ACCEPT), - GROUP(RestConstant.REST_HEADER_PREFIX + RestConstant.GROUP), - VERSION(RestConstant.REST_HEADER_PREFIX + RestConstant.VERSION), - PATH(RestConstant.REST_HEADER_PREFIX + RestConstant.PATH), - KEEP_ALIVE_HEADER(RestConstant.KEEP_ALIVE_HEADER), - CONNECTION(RestConstant.CONNECTION), - REST_HEADER_PREFIX(RestConstant.REST_HEADER_PREFIX), - TOKEN_KEY(RestConstant.REST_HEADER_PREFIX + RestConstant.TOKEN_KEY), - ; - private final String header; - - RestHeaderEnum(String header) { - this.header = header; - } - - public String getHeader() { - return header; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestInvoker.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestInvoker.java deleted file mode 100644 index 5afb5fecd17..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestInvoker.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.metadata.ParameterTypesComparator; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; -import org.apache.dubbo.metadata.rest.ServiceRestMetadata; -import org.apache.dubbo.metadata.rest.media.MediaType; -import org.apache.dubbo.remoting.http.RequestTemplate; -import org.apache.dubbo.remoting.http.RestClient; -import org.apache.dubbo.remoting.http.RestResult; -import org.apache.dubbo.rpc.AppResponse; -import org.apache.dubbo.rpc.AsyncRpcResult; -import org.apache.dubbo.rpc.Invocation; -import org.apache.dubbo.rpc.Result; -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.protocol.AbstractInvoker; -import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionCreateContext; -import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionPreBuildIntercept; -import org.apache.dubbo.rpc.protocol.rest.exception.ParamParseException; -import org.apache.dubbo.rpc.protocol.rest.exception.PathNoFoundException; -import org.apache.dubbo.rpc.protocol.rest.exception.RemoteServerInternalException; -import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodecManager; -import org.apache.dubbo.rpc.protocol.rest.util.HttpHeaderUtil; -import org.apache.dubbo.rpc.protocol.rest.util.MediaTypeUtil; - -import java.lang.reflect.Method; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.CompletableFuture; - -public class RestInvoker extends AbstractInvoker { - private final ServiceRestMetadata serviceRestMetadata; - private final ReferenceCountedClient referenceCountedClient; - private final Set httpConnectionPreBuildIntercepts; - - public RestInvoker( - Class type, - URL url, - ReferenceCountedClient referenceCountedClient, - Set httpConnectionPreBuildIntercepts, - ServiceRestMetadata serviceRestMetadata) { - super(type, url); - this.serviceRestMetadata = serviceRestMetadata; - this.referenceCountedClient = referenceCountedClient; - this.httpConnectionPreBuildIntercepts = httpConnectionPreBuildIntercepts; - } - - @Override - protected Result doInvoke(Invocation invocation) { - try { - - Map> metadataMap = - serviceRestMetadata.getMethodToServiceMap(); - // get metadata - RestMethodMetadata restMethodMetadata = metadataMap - .get(invocation.getMethodName()) - .get(ParameterTypesComparator.getInstance(invocation.getParameterTypes())); - - // create requestTemplate - RequestTemplate requestTemplate = new RequestTemplate( - invocation, restMethodMetadata.getRequest().getMethod(), getUrl().getAddress()); - - HttpConnectionCreateContext httpConnectionCreateContext = createHttpConnectionCreateContext( - invocation, serviceRestMetadata, restMethodMetadata, requestTemplate); - - // fill real data - for (HttpConnectionPreBuildIntercept intercept : httpConnectionPreBuildIntercepts) { - intercept.intercept(httpConnectionCreateContext); - } - - // TODO check rest client cannot be reused - CompletableFuture future = - referenceCountedClient.getClient().send(requestTemplate); - CompletableFuture responseFuture = new CompletableFuture<>(); - AsyncRpcResult asyncRpcResult = new AsyncRpcResult(responseFuture, invocation); - future.whenComplete((r, t) -> { - if (t != null) { - responseFuture.completeExceptionally(t); - } else { - AppResponse appResponse = new AppResponse(); - try { - int responseCode = r.getResponseCode(); - MediaType mediaType = MediaType.TEXT_PLAIN; - - if (responseCode == 404) { - responseFuture.completeExceptionally(new PathNoFoundException(r.getMessage())); - } else if (400 <= responseCode && responseCode < 500) { - responseFuture.completeExceptionally(new ParamParseException(r.getMessage())); - // TODO add Exception Mapper - } else if (responseCode >= 500) { - responseFuture.completeExceptionally(new RemoteServerInternalException(r.getMessage())); - } else if (responseCode < 400) { - Method reflectMethod = restMethodMetadata.getReflectMethod(); - mediaType = - MediaTypeUtil.convertMediaType(reflectMethod.getReturnType(), r.getContentType()); - Object value = HttpMessageCodecManager.httpMessageDecode( - r.getBody(), - reflectMethod.getReturnType(), - reflectMethod.getGenericReturnType(), - mediaType); - appResponse.setValue(value); - // resolve response attribute & attachment - HttpHeaderUtil.parseResponseHeader(appResponse, r); - responseFuture.complete(appResponse); - } - } catch (Exception e) { - responseFuture.completeExceptionally(e); - } - } - }); - return asyncRpcResult; - } catch (RpcException e) { - throw e; - } - } - - /** - * create intercept context - * - * @param invocation - * @param serviceRestMetadata - * @param restMethodMetadata - * @param requestTemplate - * @return - */ - private HttpConnectionCreateContext createHttpConnectionCreateContext( - Invocation invocation, - ServiceRestMetadata serviceRestMetadata, - RestMethodMetadata restMethodMetadata, - RequestTemplate requestTemplate) { - HttpConnectionCreateContext httpConnectionCreateContext = new HttpConnectionCreateContext(); - httpConnectionCreateContext.setRequestTemplate(requestTemplate); - httpConnectionCreateContext.setRestMethodMetadata(restMethodMetadata); - httpConnectionCreateContext.setServiceRestMetadata(serviceRestMetadata); - httpConnectionCreateContext.setInvocation(invocation); - httpConnectionCreateContext.setUrl(getUrl()); - return httpConnectionCreateContext; - } -} 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 deleted file mode 100644 index 1b4a4294b01..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java +++ /dev/null @@ -1,278 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; -import org.apache.dubbo.common.utils.JsonCompatibilityUtil; -import org.apache.dubbo.metadata.rest.ServiceRestMetadata; -import org.apache.dubbo.remoting.api.pu.DefaultPuHandler; -import org.apache.dubbo.remoting.exchange.PortUnificationExchanger; -import org.apache.dubbo.remoting.http.RestClient; -import org.apache.dubbo.remoting.http.factory.RestClientFactory; -import org.apache.dubbo.rpc.Exporter; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.ProtocolServer; -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.model.FrameworkModel; -import org.apache.dubbo.rpc.protocol.AbstractExporter; -import org.apache.dubbo.rpc.protocol.AbstractProtocol; -import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionPreBuildIntercept; -import org.apache.dubbo.rpc.protocol.rest.annotation.metadata.MetadataResolver; -import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; -import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployerManager; - -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.REST_SERVICE_DEPLOYER_URL_ATTRIBUTE_KEY; -import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_CLIENT; -import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_SERVER; -import static org.apache.dubbo.rpc.protocol.rest.constans.RestConstant.JSON_CHECK_LEVEL; -import static org.apache.dubbo.rpc.protocol.rest.constans.RestConstant.JSON_CHECK_LEVEL_STRICT; -import static org.apache.dubbo.rpc.protocol.rest.constans.RestConstant.JSON_CHECK_LEVEL_WARN; -import static org.apache.dubbo.rpc.protocol.rest.constans.RestConstant.PATH_SEPARATOR; - -public class RestProtocol extends AbstractProtocol { - - private static final int DEFAULT_PORT = 80; - - private final ConcurrentMap> clients = - new ConcurrentHashMap<>(); - - private final RestClientFactory clientFactory; - - private final Set httpConnectionPreBuildIntercepts; - - public RestProtocol(FrameworkModel frameworkModel) { - this.clientFactory = - frameworkModel.getExtensionLoader(RestClientFactory.class).getAdaptiveExtension(); - this.httpConnectionPreBuildIntercepts = new LinkedHashSet<>(frameworkModel - .getExtensionLoader(HttpConnectionPreBuildIntercept.class) - .getActivateExtensions()); - } - - @Override - public int getDefaultPort() { - return DEFAULT_PORT; - } - - @Override - @SuppressWarnings("unchecked") - public Exporter export(final Invoker invoker) throws RpcException { - URL url = invoker.getUrl(); - final String uri = serviceKey(url); - Exporter exporter = (Exporter) exporterMap.get(uri); - if (exporter != null) { - // When modifying the configuration through override, you need to re-expose the newly modified service. - if (Objects.equals(exporter.getInvoker().getUrl(), invoker.getUrl())) { - return exporter; - } - } - - // resolve metadata - ServiceRestMetadata serviceRestMetadata = MetadataResolver.resolveProviderServiceMetadata( - url.getServiceModel().getProxyObject().getClass(), url, getContextPath(url)); - - // check json compatibility - String jsonCheckLevel = url.getUrlParam().getParameter(JSON_CHECK_LEVEL); - checkJsonCompatibility(invoker.getInterface(), jsonCheckLevel); - - // deploy service - URL newURL = ServiceDeployerManager.deploy(url, serviceRestMetadata, invoker); - - // create server - PortUnificationExchanger.bind(newURL, new DefaultPuHandler()); - - ServiceDeployer serviceDeployer = - (ServiceDeployer) newURL.getAttribute(REST_SERVICE_DEPLOYER_URL_ATTRIBUTE_KEY); - - URL finalUrl = newURL; - exporter = new AbstractExporter(invoker) { - @Override - public void afterUnExport() { - destroyInternal(finalUrl); - exporterMap.remove(uri); - serviceDeployer.undeploy(serviceRestMetadata); - } - }; - exporterMap.put(uri, exporter); - return exporter; - } - - private void checkJsonCompatibility(Class clazz, String jsonCheckLevel) throws RpcException { - - if (jsonCheckLevel == null || JSON_CHECK_LEVEL_WARN.equals(jsonCheckLevel)) { - boolean compatibility = JsonCompatibilityUtil.checkClassCompatibility(clazz); - if (!compatibility) { - List unsupportedMethods = JsonCompatibilityUtil.getUnsupportedMethods(clazz); - assert unsupportedMethods != null; - logger.warn( - "", - "", - "", - String.format( - "Interface %s does not support json serialization, the specific methods are %s.", - clazz.getName(), unsupportedMethods)); - } else { - logger.debug( - "Check json compatibility complete, all methods of {} can be serialized using json.", - clazz.getName()); - } - } else if (JSON_CHECK_LEVEL_STRICT.equals(jsonCheckLevel)) { - boolean compatibility = JsonCompatibilityUtil.checkClassCompatibility(clazz); - if (!compatibility) { - List unsupportedMethods = JsonCompatibilityUtil.getUnsupportedMethods(clazz); - assert unsupportedMethods != null; - throw new IllegalStateException(String.format( - "Interface %s does not support json serialization, the specific methods are %s.", - clazz.getName(), unsupportedMethods)); - } else { - logger.debug( - "Check json compatibility complete, all methods of {} can be serialized using json.", - clazz.getName()); - } - } - } - - @Override - protected Invoker protocolBindingRefer(final Class type, final URL url) throws RpcException { - - ReferenceCountedClient refClient = clients.get(url.getAddress()); - if (refClient == null || refClient.isDestroyed()) { - synchronized (clients) { - refClient = clients.get(url.getAddress()); - if (refClient == null || refClient.isDestroyed()) { - refClient = ConcurrentHashMapUtils.computeIfAbsent( - clients, url.getAddress(), _key -> createReferenceCountedClient(url)); - } - } - } - refClient.retain(); - - String contextPathFromUrl = getContextPath(url); - - // resolve metadata - ServiceRestMetadata serviceRestMetadata = - MetadataResolver.resolveConsumerServiceMetadata(type, url, contextPathFromUrl); - - Invoker invoker = - new RestInvoker(type, url, refClient, httpConnectionPreBuildIntercepts, serviceRestMetadata); - - invokers.add(invoker); - return invoker; - } - - /** - * create rest ReferenceCountedClient - * - * @param url - * @return - * @throws RpcException - */ - private ReferenceCountedClient createReferenceCountedClient(URL url) throws RpcException { - - // url -> RestClient - RestClient restClient = clientFactory.createRestClient(url); - - return new ReferenceCountedClient<>(restClient, clients, clientFactory, url); - } - - @Override - public void destroy() { - if (logger.isInfoEnabled()) { - logger.info("Destroying protocol [" + this.getClass().getSimpleName() + "] ..."); - } - - PortUnificationExchanger.close(); - ServiceDeployerManager.close(); - - super.destroy(); - - for (Map.Entry entry : serverMap.entrySet()) { - try { - if (logger.isInfoEnabled()) { - logger.info("Closing the rest server at " + entry.getKey()); - } - entry.getValue().close(); - } catch (Throwable t) { - logger.warn(PROTOCOL_ERROR_CLOSE_SERVER, "", "", "Error closing rest server", t); - } - } - serverMap.clear(); - - if (logger.isInfoEnabled()) { - logger.info("Closing rest clients"); - } - for (ReferenceCountedClient client : clients.values()) { - try { - // destroy directly regardless of the current reference count. - client.destroy(); - } catch (Throwable t) { - logger.warn(PROTOCOL_ERROR_CLOSE_CLIENT, "", "", "Error closing rest client", t); - } - } - clients.clear(); - } - - /** - * getPath() will return: [contextpath + "/" +] path - * 1. contextpath is empty if user does not set through ProtocolConfig or ProviderConfig - * 2. path will never be empty, its default value is the interface name. - * - * @return return path only if user has explicitly gave then a value. - */ - private String getContextPath(URL url) { - String contextPath = url.getPath(); - if (contextPath != null) { - if (contextPath.equalsIgnoreCase(url.getParameter(INTERFACE_KEY))) { - return ""; - } - if (contextPath.endsWith(url.getParameter(INTERFACE_KEY))) { - contextPath = contextPath.substring(0, contextPath.lastIndexOf(url.getParameter(INTERFACE_KEY))); - } - return contextPath.endsWith(PATH_SEPARATOR) - ? contextPath.substring(0, contextPath.length() - 1) - : contextPath; - } else { - return ""; - } - } - - private void destroyInternal(URL url) { - try { - ReferenceCountedClient referenceCountedClient = clients.get(url.getAddress()); - if (referenceCountedClient != null && referenceCountedClient.release()) { - clients.remove(url.getAddress()); - } - } catch (Exception e) { - logger.warn( - PROTOCOL_ERROR_CLOSE_CLIENT, - "", - "", - "Failed to close unused resources in rest protocol. interfaceName [" + url.getServiceInterface() - + "]", - e); - } - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestRPCInvocationUtil.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestRPCInvocationUtil.java deleted file mode 100644 index ffc3b6ec11c..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestRPCInvocationUtil.java +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest; - -import org.apache.dubbo.common.BaseServiceMetadata; -import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.metadata.rest.ArgInfo; -import org.apache.dubbo.metadata.rest.PathMatcher; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.protocol.rest.annotation.ParamParserManager; -import org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider.ProviderParseContext; -import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; -import org.apache.dubbo.rpc.protocol.rest.exception.ParamParseException; -import org.apache.dubbo.rpc.protocol.rest.pair.InvokerAndRestMethodMetadataPair; -import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; -import org.apache.dubbo.rpc.protocol.rest.util.HttpHeaderUtil; -import org.apache.dubbo.rpc.protocol.rest.util.NoAnnotationBodyParseUtil; - -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.List; - -public class RestRPCInvocationUtil { - - private static final ErrorTypeAwareLogger logger = - LoggerFactory.getErrorTypeAwareLogger(RestRPCInvocationUtil.class); - - /** - * service method real args parse - * - * @param rpcInvocation - * @param request - * @param servletRequest - * @param servletResponse - * @param restMethodMetadata - */ - public static void parseMethodArgs( - RpcInvocation rpcInvocation, - RequestFacade request, - Object servletRequest, - Object servletResponse, - RestMethodMetadata restMethodMetadata) { - - try { - ProviderParseContext parseContext = - createParseContext(request, servletRequest, servletResponse, restMethodMetadata); - Object[] args = ParamParserManager.providerParamParse(parseContext); - - List argInfos = parseContext.getArgInfos(); - - for (ArgInfo argInfo : argInfos) { - // TODO set default value - if (argInfo.getParamType().isPrimitive() && args[argInfo.getIndex()] == null) { - throw new ParamParseException("\n dubbo provider primitive arg not exist in request, method is: " - + restMethodMetadata.getReflectMethod() + "\n type is: " + argInfo.getParamType() - + " \n and arg index is: " + argInfo.getIndex()); - } - } - - rpcInvocation.setArguments(args); - } catch (Exception e) { - logger.error("", e.getMessage(), "", "dubbo rest provider method args parse error: ", e); - throw new ParamParseException(e.getMessage()); - } - } - - /** - * create parseMethodArgs context - * - * @param request - * @param originRequest - * @param originResponse - * @param restMethodMetadata - * @return - */ - private static ProviderParseContext createParseContext( - RequestFacade request, Object originRequest, Object originResponse, RestMethodMetadata restMethodMetadata) { - ProviderParseContext parseContext = new ProviderParseContext(request); - parseContext.setResponse(originResponse); - parseContext.setRequest(originRequest); - parseContext.setNoAnnotationMode(restMethodMetadata.currentCodeStyleIsNoAnnotationMode()); - Object[] objects = new Object[restMethodMetadata.getArgInfos().size()]; - parseContext.setArgs(Arrays.asList(objects)); - parseContext.setArgInfos(restMethodMetadata.getArgInfos()); - - // parse object arrays body - if (restMethodMetadata.currentCodeStyleIsNoAnnotationMode()) { - parseContext.setArrayArgs(NoAnnotationBodyParseUtil.doParse(parseContext)); - } - - return parseContext; - } - - /** - * build RpcInvocation - * - * @param request - * @param restMethodMetadata - * @return - */ - public static RpcInvocation createBaseRpcInvocation(RequestFacade request, RestMethodMetadata restMethodMetadata) { - RpcInvocation rpcInvocation = new RpcInvocation(); - - rpcInvocation.setParameterTypes(restMethodMetadata.getReflectMethod().getParameterTypes()); - rpcInvocation.setReturnType(restMethodMetadata.getReflectMethod().getReturnType()); - rpcInvocation.setMethodName(restMethodMetadata.getMethod().getName()); - - // TODO set protocolServiceKey ,but no set method - // - - HttpHeaderUtil.parseRequest(rpcInvocation, request); - - String serviceKey = BaseServiceMetadata.buildServiceKey( - request.getHeader(RestHeaderEnum.PATH.getHeader()), - request.getHeader(RestHeaderEnum.GROUP.getHeader()), - request.getHeader(RestHeaderEnum.VERSION.getHeader())); - rpcInvocation.setTargetServiceUniqueName(serviceKey); - - return rpcInvocation; - } - - /** - * get InvokerAndRestMethodMetadataPair by path matcher - * - * @param pathMatcher - * @return - */ - public static InvokerAndRestMethodMetadataPair getRestMethodMetadataAndInvokerPair( - PathMatcher pathMatcher, ServiceDeployer serviceDeployer) { - - return serviceDeployer.getPathAndInvokerMapper().getRestMethodMetadata(pathMatcher); - } - - /** - * get InvokerAndRestMethodMetadataPair from rpc context - * - * @param request - * @return - */ - public static InvokerAndRestMethodMetadataPair getRestMethodMetadataAndInvokerPair(RequestFacade request) { - - PathMatcher pathMather = createPathMatcher(request); - - return getRestMethodMetadataAndInvokerPair(pathMather, request.getServiceDeployer()); - } - - /** - * get invoker by request - * - * @param request - * @return - */ - public static Invoker getInvokerByRequest(RequestFacade request) { - - PathMatcher pathMatcher = createPathMatcher(request); - - return getInvoker(pathMatcher, request.getServiceDeployer()); - } - - /** - * get invoker by service method - *

- * compare method`s name,param types - * - * @param serviceMethod - * @return - */ - public static Invoker getInvokerByServiceInvokeMethod(Method serviceMethod, ServiceDeployer serviceDeployer) { - - if (serviceMethod == null) { - return null; - } - - PathMatcher pathMatcher = PathMatcher.getInvokeCreatePathMatcher(serviceMethod); - - InvokerAndRestMethodMetadataPair pair = getRestMethodMetadataAndInvokerPair(pathMatcher, serviceDeployer); - - if (pair == null) { - return null; - } - - return pair.getInvoker(); - } - - /** - * get invoker by path matcher - * - * @param pathMatcher - * @return - */ - public static Invoker getInvoker(PathMatcher pathMatcher, ServiceDeployer serviceDeployer) { - InvokerAndRestMethodMetadataPair pair = getRestMethodMetadataAndInvokerPair(pathMatcher, serviceDeployer); - - if (pair == null) { - return null; - } - - return pair.getInvoker(); - } - - /** - * create path matcher by request - * - * @param request - * @return - */ - public static PathMatcher createPathMatcher(RequestFacade request) { - String path = request.getPath(); - String version = request.getHeader(RestHeaderEnum.VERSION.getHeader()); - String group = request.getHeader(RestHeaderEnum.GROUP.getHeader()); - String method = request.getMethod(); - - return PathMatcher.getInvokeCreatePathMatcher(path, version, group, null, method); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RpcExceptionMapper.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RpcExceptionMapper.java deleted file mode 100644 index 6336f1cf548..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RpcExceptionMapper.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest; - -import org.apache.dubbo.common.utils.ClassUtils; -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionHandler; -import org.apache.dubbo.rpc.protocol.rest.util.ConstraintViolationExceptionConvert; - -public class RpcExceptionMapper implements ExceptionHandler { - - @Override - public Object result(RpcException e) { - - // javax dependency judge - if (violationDependency()) { - // ConstraintViolationException judge - if (ConstraintViolationExceptionConvert.needConvert(e)) { - return ConstraintViolationExceptionConvert.handleConstraintViolationException(e); - } - } - - return "Internal server error: " + e.getMessage(); - } - - private boolean violationDependency() { - return ClassUtils.isPresent( - "javax.validation.ConstraintViolationException", RpcExceptionMapper.class.getClassLoader()); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/ViolationReport.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/ViolationReport.java deleted file mode 100644 index 0a87d6d8f34..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/ViolationReport.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.rpc.protocol.rest; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; - -import java.io.Serializable; -import java.util.LinkedList; -import java.util.List; - -@XmlRootElement(name = "violationReport") -@XmlAccessorType(XmlAccessType.FIELD) -public class ViolationReport implements Serializable { - - private static final long serialVersionUID = -130498234L; - - private List constraintViolations; - - public List getConstraintViolations() { - return constraintViolations; - } - - public void setConstraintViolations(List constraintViolations) { - this.constraintViolations = constraintViolations; - } - - public void addConstraintViolation(RestConstraintViolation constraintViolation) { - if (constraintViolations == null) { - constraintViolations = new LinkedList(); - } - constraintViolations.add(constraintViolation); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/BaseParseContext.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/BaseParseContext.java deleted file mode 100644 index e5de8f8e513..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/BaseParseContext.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.annotation; - -import org.apache.dubbo.metadata.rest.ArgInfo; - -import java.util.List; - -public class BaseParseContext { - - protected List args; - - protected List argInfos; - - boolean isNoAnnotationMode; - - public List getArgs() { - return args; - } - - public void setArgs(List args) { - this.args = args; - } - - public List getArgInfos() { - return argInfos; - } - - public void setArgInfos(List argInfos) { - this.argInfos = argInfos; - } - - public ArgInfo getArgInfoByIndex(int index) { - return getArgInfos().get(index); - } - - public boolean isNoAnnotationMode() { - return isNoAnnotationMode; - } - - public void setNoAnnotationMode(boolean noAnnotationMode) { - isNoAnnotationMode = noAnnotationMode; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/ParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/ParamParser.java deleted file mode 100644 index a093b0edf95..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/ParamParser.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.annotation; - -import org.apache.dubbo.metadata.rest.ArgInfo; - -public interface ParamParser { - void parse(T parseContext, ArgInfo argInfo); -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/ParamParserManager.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/ParamParserManager.java deleted file mode 100644 index 06bce8f6e70..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/ParamParserManager.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.rpc.protocol.rest.annotation; - -import org.apache.dubbo.metadata.rest.ArgInfo; -import org.apache.dubbo.rpc.model.FrameworkModel; -import org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer.BaseConsumerParamParser; -import org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer.ConsumerParseContext; -import org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider.BaseProviderParamParser; -import org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider.ProviderParseContext; - -import java.util.List; - -public class ParamParserManager { - - private static final List consumerParamParsers = FrameworkModel.defaultModel() - .getExtensionLoader(BaseConsumerParamParser.class) - .getActivateExtensions(); - - private static final List providerParamParsers = FrameworkModel.defaultModel() - .getExtensionLoader(BaseProviderParamParser.class) - .getActivateExtensions(); - - /** - * provider Design Description: - *

- * Object[] args=new Object[0]; - * List argsList=new ArrayList<>; - *

- * setValueByIndex(int index,Object value); - *

- * args=toArray(new Object[0]); - */ - public static Object[] providerParamParse(ProviderParseContext parseContext) { - - List args = parseContext.getArgInfos(); - - for (int i = 0; i < args.size(); i++) { - for (BaseProviderParamParser paramParser : providerParamParsers) { - - if (paramParser.matchParseType(args.get(i).getParamAnnotationType())) { - paramParser.parse(parseContext, args.get(i)); - // one arg only can be parsed by one parser - break; - } - } - } - // TODO add param require or default & body arg size pre judge - return parseContext.getArgs().toArray(new Object[0]); - } - - /** - * consumer Design Description: - *

- * Object[] args=new Object[0]; - * List argsList=new ArrayList<>; - *

- * setValueByIndex(int index,Object value); - *

- * args=toArray(new Object[0]); - */ - public static void consumerParamParse(ConsumerParseContext parseContext) { - - List argInfos = parseContext.getArgInfos(); - - for (int i = 0; i < argInfos.size(); i++) { - for (BaseConsumerParamParser paramParser : consumerParamParsers) { - ArgInfo argInfoByIndex = parseContext.getArgInfoByIndex(i); - - if (!paramParser.paramTypeMatch(argInfoByIndex)) { - continue; - } - - paramParser.parse(parseContext, argInfoByIndex); - } - } - - // TODO add param require or default - - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/HttpConnectionCreateContext.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/HttpConnectionCreateContext.java deleted file mode 100644 index a251bebf08c..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/HttpConnectionCreateContext.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.rpc.protocol.rest.annotation.consumer; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; -import org.apache.dubbo.metadata.rest.ServiceRestMetadata; -import org.apache.dubbo.remoting.http.RequestTemplate; -import org.apache.dubbo.rpc.Invocation; - -public class HttpConnectionCreateContext { - - private RequestTemplate requestTemplate; - private RestMethodMetadata restMethodMetadata; - private ServiceRestMetadata serviceRestMetadata; - private Invocation invocation; - private URL url; - - public HttpConnectionCreateContext() {} - - public void setRequestTemplate(RequestTemplate requestTemplate) { - this.requestTemplate = requestTemplate; - } - - public RequestTemplate getRequestTemplate() { - return requestTemplate; - } - - public ServiceRestMetadata getServiceRestMetadata() { - return serviceRestMetadata; - } - - public RestMethodMetadata getRestMethodMetadata() { - return restMethodMetadata; - } - - public void setRestMethodMetadata(RestMethodMetadata restMethodMetadata) { - this.restMethodMetadata = restMethodMetadata; - } - - public Invocation getInvocation() { - return invocation; - } - - public void setInvocation(Invocation invocation) { - this.invocation = invocation; - } - - public URL getUrl() { - return url; - } - - public void setUrl(URL url) { - this.url = url; - } - - public void setServiceRestMetadata(ServiceRestMetadata serviceRestMetadata) { - this.serviceRestMetadata = serviceRestMetadata; - } - - public boolean isNoAnnotationMode() { - return restMethodMetadata.currentCodeStyleIsNoAnnotationMode(); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/HttpConnectionPreBuildIntercept.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/HttpConnectionPreBuildIntercept.java deleted file mode 100644 index a25466ed20d..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/HttpConnectionPreBuildIntercept.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.annotation.consumer; - -import org.apache.dubbo.common.extension.ExtensionScope; -import org.apache.dubbo.common.extension.SPI; - -/** - * http request build intercept - */ -@SPI(scope = ExtensionScope.FRAMEWORK) -public interface HttpConnectionPreBuildIntercept { - void intercept(HttpConnectionCreateContext connectionCreateContext); -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/AddMustAttachmentIntercept.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/AddMustAttachmentIntercept.java deleted file mode 100644 index 49a50116250..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/AddMustAttachmentIntercept.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.annotation.consumer.inercept; - -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.metadata.rest.ServiceRestMetadata; -import org.apache.dubbo.remoting.http.RequestTemplate; -import org.apache.dubbo.rpc.protocol.rest.RestHeaderEnum; -import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionCreateContext; -import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionPreBuildIntercept; -import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; - -/** - * add some must attachment - */ -@Activate(value = RestConstant.ADD_MUST_ATTTACHMENT, order = 1) -public class AddMustAttachmentIntercept implements HttpConnectionPreBuildIntercept { - - @Override - public void intercept(HttpConnectionCreateContext connectionCreateContext) { - - RequestTemplate requestTemplate = connectionCreateContext.getRequestTemplate(); - ServiceRestMetadata serviceRestMetadata = connectionCreateContext.getServiceRestMetadata(); - - requestTemplate.addHeader(RestHeaderEnum.GROUP.getHeader(), serviceRestMetadata.getGroup()); - requestTemplate.addHeader(RestHeaderEnum.VERSION.getHeader(), serviceRestMetadata.getVersion()); - requestTemplate.addHeader(RestHeaderEnum.PATH.getHeader(), serviceRestMetadata.getServiceInterface()); - requestTemplate.addHeader( - RestHeaderEnum.TOKEN_KEY.getHeader(), - connectionCreateContext.getUrl().getParameter(RestConstant.TOKEN_KEY)); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/AttachmentIntercept.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/AttachmentIntercept.java deleted file mode 100644 index c6a4a26548e..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/AttachmentIntercept.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.annotation.consumer.inercept; - -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.remoting.http.RequestTemplate; -import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionCreateContext; -import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionPreBuildIntercept; -import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; -import org.apache.dubbo.rpc.protocol.rest.util.HttpHeaderUtil; - -/** - * add client rpc context to request geader - */ -@Activate(value = RestConstant.RPCCONTEXT_INTERCEPT, order = 3) -public class AttachmentIntercept implements HttpConnectionPreBuildIntercept { - - @Override - public void intercept(HttpConnectionCreateContext connectionCreateContext) { - - RequestTemplate requestTemplate = connectionCreateContext.getRequestTemplate(); - - HttpHeaderUtil.addRequestAttachments( - requestTemplate, connectionCreateContext.getInvocation().getObjectAttachments()); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/ParamParseIntercept.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/ParamParseIntercept.java deleted file mode 100644 index e1d155d2663..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/ParamParseIntercept.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.annotation.consumer.inercept; - -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.remoting.http.RequestTemplate; -import org.apache.dubbo.rpc.protocol.rest.annotation.ParamParserManager; -import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionCreateContext; -import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionPreBuildIntercept; -import org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer.ConsumerParseContext; - -import java.util.Arrays; - -/** - * resolve method args by args info - */ -@Activate(value = "paramparse", order = 5) -public class ParamParseIntercept implements HttpConnectionPreBuildIntercept { - - @Override - public void intercept(HttpConnectionCreateContext connectionCreateContext) { - - RequestTemplate requestTemplate = connectionCreateContext.getRequestTemplate(); - Object[] arguments = connectionCreateContext.getInvocation().getArguments(); - - // no annotation mode set array body - if (connectionCreateContext.isNoAnnotationMode()) { - requestTemplate.body(arguments, Object[].class); - } else { - ConsumerParseContext consumerParseContext = new ConsumerParseContext(requestTemplate); - consumerParseContext.setArgInfos( - connectionCreateContext.getRestMethodMetadata().getArgInfos()); - consumerParseContext.setArgs(Arrays.asList(arguments)); - ParamParserManager.consumerParamParse(consumerParseContext); - } - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/PathVariableIntercept.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/PathVariableIntercept.java deleted file mode 100644 index a8ef83d8674..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/PathVariableIntercept.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.annotation.consumer.inercept; - -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.metadata.rest.ArgInfo; -import org.apache.dubbo.metadata.rest.PathUtil; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; -import org.apache.dubbo.remoting.http.RequestTemplate; -import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionCreateContext; -import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionPreBuildIntercept; -import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; - -import java.util.Arrays; -import java.util.List; - -/** - * resolve method args from path - */ -@Activate(value = RestConstant.PATH_INTERCEPT, order = 4) -public class PathVariableIntercept implements HttpConnectionPreBuildIntercept { - - @Override - public void intercept(HttpConnectionCreateContext connectionCreateContext) { - - RestMethodMetadata restMethodMetadata = connectionCreateContext.getRestMethodMetadata(); - RequestTemplate requestTemplate = connectionCreateContext.getRequestTemplate(); - - List argInfos = restMethodMetadata.getArgInfos(); - - // path variable parse - String path = PathUtil.resolvePathVariable( - restMethodMetadata.getRequest().getPath(), - argInfos, - Arrays.asList(connectionCreateContext.getInvocation().getArguments())); - requestTemplate.path(path); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/RequestHeaderIntercept.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/RequestHeaderIntercept.java deleted file mode 100644 index d6fb6f8bf8c..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/RequestHeaderIntercept.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.rpc.protocol.rest.annotation.consumer.inercept; - -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; -import org.apache.dubbo.remoting.http.RequestTemplate; -import org.apache.dubbo.rpc.protocol.rest.RestHeaderEnum; -import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionCreateContext; -import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionPreBuildIntercept; -import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; - -import java.util.Collection; -import java.util.Set; - -/** - * resolve method args from header - */ -@Activate(value = RestConstant.REQUEST_HEADER_INTERCEPT, order = Integer.MAX_VALUE - 1) -public class RequestHeaderIntercept implements HttpConnectionPreBuildIntercept { - - @Override - public void intercept(HttpConnectionCreateContext connectionCreateContext) { - - RestMethodMetadata restMethodMetadata = connectionCreateContext.getRestMethodMetadata(); - RequestTemplate requestTemplate = connectionCreateContext.getRequestTemplate(); - - Set consumes = restMethodMetadata.getRequest().getConsumes(); - - requestTemplate.addHeaders(RestHeaderEnum.CONTENT_TYPE.getHeader(), consumes); - - Collection produces = restMethodMetadata.getRequest().getProduces(); - if (produces == null || produces.isEmpty()) { - requestTemplate.addHeader(RestHeaderEnum.ACCEPT.getHeader(), RestConstant.DEFAULT_ACCEPT); - } else { - requestTemplate.addHeaders(RestHeaderEnum.ACCEPT.getHeader(), produces); - } - - // URL url = connectionCreateContext.getUrl(); - - // - // requestTemplate.addKeepAliveHeader(url.getParameter(RestConstant.KEEP_ALIVE_TIMEOUT_PARAM,RestConstant.KEEP_ALIVE_TIMEOUT)); - - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/SerializeBodyIntercept.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/SerializeBodyIntercept.java deleted file mode 100644 index 6e898cea561..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/SerializeBodyIntercept.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.annotation.consumer.inercept; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.LoggerCodeConstants; -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.metadata.rest.media.MediaType; -import org.apache.dubbo.remoting.http.RequestTemplate; -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionCreateContext; -import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionPreBuildIntercept; -import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; -import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodecManager; -import org.apache.dubbo.rpc.protocol.rest.util.MediaTypeUtil; - -import java.io.ByteArrayOutputStream; -import java.util.Collection; - -/** - * for request body Serialize - */ -@Activate(value = RestConstant.SERIALIZE_INTERCEPT, order = Integer.MAX_VALUE) -public class SerializeBodyIntercept implements HttpConnectionPreBuildIntercept { - - private static final ErrorTypeAwareLogger logger = - LoggerFactory.getErrorTypeAwareLogger(SerializeBodyIntercept.class); - - @Override - public void intercept(HttpConnectionCreateContext connectionCreateContext) { - RequestTemplate requestTemplate = connectionCreateContext.getRequestTemplate(); - - if (requestTemplate.isBodyEmpty()) { - return; - } - - try { - Object unSerializedBody = requestTemplate.getUnSerializedBody(); - URL url = connectionCreateContext.getUrl(); - // TODO pool - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - Collection headers = requestTemplate.getHeaders(RestConstant.CONTENT_TYPE); - MediaType mediaType = - MediaTypeUtil.convertMediaType(requestTemplate.getBodyType(), headers.toArray(new String[0])); - - // add mediaType by targetClass serialize - if (mediaType != null && !mediaType.equals(MediaType.ALL_VALUE)) { - headers.clear(); - headers.add(mediaType.value); - } - HttpMessageCodecManager.httpMessageEncode( - outputStream, unSerializedBody, url, mediaType, requestTemplate.getBodyType()); - requestTemplate.serializeBody(outputStream.toByteArray()); - outputStream.close(); - } catch (Exception e) { - logger.error( - LoggerCodeConstants.PROTOCOL_ERROR_DESERIALIZE, - "", - "", - "Rest SerializeBodyIntercept serialize error: {}", - e); - throw new RpcException(e); - } - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/metadata/MetadataResolver.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/metadata/MetadataResolver.java deleted file mode 100644 index 26a1d13955d..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/metadata/MetadataResolver.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.annotation.metadata; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.metadata.rest.ServiceRestMetadata; -import org.apache.dubbo.metadata.rest.ServiceRestMetadataResolver; -import org.apache.dubbo.rpc.protocol.rest.exception.CodeStyleNotSupportException; - -public class MetadataResolver { - private MetadataResolver() {} - - /** - * for consumer - * - * @param targetClass target service class - * @param url consumer url - * @return rest metadata - * @throws CodeStyleNotSupportException not support type - */ - public static ServiceRestMetadata resolveConsumerServiceMetadata( - Class targetClass, URL url, String contextPathFromUrl) { - ExtensionLoader extensionLoader = - url.getOrDefaultApplicationModel().getExtensionLoader(ServiceRestMetadataResolver.class); - - for (ServiceRestMetadataResolver serviceRestMetadataResolver : extensionLoader.getActivateExtensions()) { - if (serviceRestMetadataResolver.supports(targetClass, true)) { - ServiceRestMetadata serviceRestMetadata = - new ServiceRestMetadata(url.getServiceInterface(), url.getVersion(), url.getGroup(), true); - serviceRestMetadata.setContextPathFromUrl(contextPathFromUrl); - ServiceRestMetadata resolve = serviceRestMetadataResolver.resolve(targetClass, serviceRestMetadata); - return resolve; - } - } - - // TODO support Dubbo style service - throw new CodeStyleNotSupportException("service is: " + targetClass + ", only support " - + extensionLoader.getSupportedExtensions() + " annotation"); - } - - public static ServiceRestMetadata resolveProviderServiceMetadata( - Class serviceImpl, URL url, String contextPathFromUrl) { - ExtensionLoader extensionLoader = - url.getOrDefaultApplicationModel().getExtensionLoader(ServiceRestMetadataResolver.class); - - for (ServiceRestMetadataResolver serviceRestMetadataResolver : extensionLoader.getActivateExtensions()) { - boolean supports = serviceRestMetadataResolver.supports(serviceImpl); - if (supports) { - ServiceRestMetadata serviceRestMetadata = - new ServiceRestMetadata(url.getServiceInterface(), url.getVersion(), url.getGroup(), false); - serviceRestMetadata.setContextPathFromUrl(contextPathFromUrl); - ServiceRestMetadata resolve = serviceRestMetadataResolver.resolve(serviceImpl, serviceRestMetadata); - return resolve; - } - } - throw new CodeStyleNotSupportException( - "service is:" + serviceImpl + ",just support rest or spring-web annotation"); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/BaseConsumerParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/BaseConsumerParamParser.java deleted file mode 100644 index 6393daca5fd..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/BaseConsumerParamParser.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer; - -import org.apache.dubbo.common.extension.ExtensionScope; -import org.apache.dubbo.common.extension.SPI; -import org.apache.dubbo.metadata.rest.ArgInfo; -import org.apache.dubbo.rpc.protocol.rest.annotation.ParamParser; - -@SPI(scope = ExtensionScope.FRAMEWORK) -public interface BaseConsumerParamParser extends ParamParser { - - boolean paramTypeMatch(ArgInfo argInfo); -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/BodyConsumerParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/BodyConsumerParamParser.java deleted file mode 100644 index 3c300861e9d..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/BodyConsumerParamParser.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer; - -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.metadata.rest.ArgInfo; -import org.apache.dubbo.metadata.rest.ParamType; -import org.apache.dubbo.remoting.http.RequestTemplate; - -import java.util.List; - -@Activate("consumer-body") -public class BodyConsumerParamParser implements BaseConsumerParamParser { - @Override - public void parse(ConsumerParseContext parseContext, ArgInfo argInfo) { - - List args = parseContext.getArgs(); - - RequestTemplate requestTemplate = parseContext.getRequestTemplate(); - - requestTemplate.body(args.get(argInfo.getIndex()), argInfo.getParamType()); - } - - @Override - public boolean paramTypeMatch(ArgInfo argInfo) { - return ParamType.BODY.supportAnno(argInfo.getParamAnnotationType()); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/ConsumerParseContext.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/ConsumerParseContext.java deleted file mode 100644 index c6833f40568..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/ConsumerParseContext.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer; - -import org.apache.dubbo.remoting.http.RequestTemplate; -import org.apache.dubbo.rpc.protocol.rest.annotation.BaseParseContext; - -public class ConsumerParseContext extends BaseParseContext { - private RequestTemplate requestTemplate; - - public ConsumerParseContext(RequestTemplate requestTemplate) { - this.requestTemplate = requestTemplate; - } - - public RequestTemplate getRequestTemplate() { - return requestTemplate; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/FormConsumerParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/FormConsumerParamParser.java deleted file mode 100644 index e4fdbb0c0bc..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/FormConsumerParamParser.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer; - -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.common.utils.CollectionUtils; -import org.apache.dubbo.common.utils.ReflectUtils; -import org.apache.dubbo.metadata.rest.ArgInfo; -import org.apache.dubbo.metadata.rest.ParamType; -import org.apache.dubbo.metadata.rest.media.MediaType; -import org.apache.dubbo.remoting.http.RequestTemplate; -import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; -import org.apache.dubbo.rpc.protocol.rest.util.DataParseUtils; - -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -@Activate("consumer-form") -public class FormConsumerParamParser implements BaseConsumerParamParser { - @Override - public void parse(ConsumerParseContext parseContext, ArgInfo argInfo) { - - List args = parseContext.getArgs(); - - RequestTemplate requestTemplate = parseContext.getRequestTemplate(); - Object value = args.get(argInfo.getIndex()); - - if (value == null) { - return; - } - - Map> tmp = new HashMap<>(); - if (DataParseUtils.isTextType(value.getClass())) { - tmp.put(argInfo.getAnnotationNameAttribute(), Arrays.asList(String.valueOf(value))); - requestTemplate.body(tmp, Map.class); - } else if (value instanceof Map) { - requestTemplate.body(value, Map.class); - } else { - Set allFieldNames = ReflectUtils.getAllFieldNames(value.getClass()); - - allFieldNames.stream().forEach(entry -> { - Object fieldValue = ReflectUtils.getFieldValue(value, entry); - tmp.put(String.valueOf(entry), Arrays.asList(String.valueOf(fieldValue))); - }); - - requestTemplate.body(tmp, Map.class); - } - - Collection headers = requestTemplate.getHeaders(RestConstant.CONTENT_TYPE); - if (CollectionUtils.isEmpty(headers)) { - requestTemplate.addHeader(RestConstant.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE.value); - } - } - - @Override - public boolean paramTypeMatch(ArgInfo argInfo) { - return ParamType.FORM.supportAnno(argInfo.getParamAnnotationType()); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/HeaderConsumerParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/HeaderConsumerParamParser.java deleted file mode 100644 index c62f1750a06..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/HeaderConsumerParamParser.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer; - -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.metadata.rest.ArgInfo; -import org.apache.dubbo.metadata.rest.ParamType; -import org.apache.dubbo.remoting.http.RequestTemplate; - -import java.util.List; -import java.util.Map; - -@Activate("consumer-header") -public class HeaderConsumerParamParser implements BaseConsumerParamParser { - @Override - public void parse(ConsumerParseContext parseContext, ArgInfo argInfo) { - List args = parseContext.getArgs(); - - RequestTemplate requestTemplate = parseContext.getRequestTemplate(); - - Object headerValue = args.get(argInfo.getIndex()); - - if (headerValue == null) { - return; - } - - // Map - if (Map.class.isAssignableFrom(argInfo.getParamType())) { - Map headerValues = (Map) headerValue; - for (Object name : headerValues.keySet()) { - requestTemplate.addHeader(String.valueOf(name), headerValues.get(name)); - } - } else { - // others - requestTemplate.addHeader(argInfo.getAnnotationNameAttribute(), headerValue); - } - } - - @Override - public boolean paramTypeMatch(ArgInfo argInfo) { - return ParamType.HEADER.supportAnno(argInfo.getParamAnnotationType()); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/ParameterConsumerParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/ParameterConsumerParamParser.java deleted file mode 100644 index 65f8fe30e8e..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/ParameterConsumerParamParser.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer; - -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.metadata.rest.ArgInfo; -import org.apache.dubbo.metadata.rest.ParamType; -import org.apache.dubbo.remoting.http.RequestTemplate; - -import java.util.List; -import java.util.Map; - -@Activate("consumer-parameter") -public class ParameterConsumerParamParser implements BaseConsumerParamParser { - @Override - public void parse(ConsumerParseContext parseContext, ArgInfo argInfo) { - List args = parseContext.getArgs(); - - RequestTemplate requestTemplate = parseContext.getRequestTemplate(); - - Object paramValue = args.get(argInfo.getIndex()); - - if (paramValue == null) { - return; - } - - if (Map.class.isAssignableFrom(argInfo.getParamType())) { - Map paramValues = (Map) paramValue; - for (Object name : paramValues.keySet()) { - requestTemplate.addParam(String.valueOf(name), paramValues.get(name)); - } - } else { - requestTemplate.addParam(argInfo.getAnnotationNameAttribute(), paramValue); - } - } - - @Override - public boolean paramTypeMatch(ArgInfo argInfo) { - return ParamType.PARAM.supportAnno(argInfo.getParamAnnotationType()); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/BaseProviderParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/BaseProviderParamParser.java deleted file mode 100644 index a10a70d18bf..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/BaseProviderParamParser.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider; - -import org.apache.dubbo.common.extension.ExtensionScope; -import org.apache.dubbo.common.extension.SPI; -import org.apache.dubbo.metadata.rest.ParamType; -import org.apache.dubbo.rpc.protocol.rest.annotation.ParamParser; - -@SPI(scope = ExtensionScope.FRAMEWORK) -public interface BaseProviderParamParser extends ParamParser { - - default boolean matchParseType(Class paramAnno) { - - ParamType paramAnnotType = getParamType(); - return paramAnnotType.supportAnno(paramAnno); - } - - ParamType getParamType(); -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/BodyProviderParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/BodyProviderParamParser.java deleted file mode 100644 index ef851c8112d..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/BodyProviderParamParser.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider; - -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.metadata.rest.ArgInfo; -import org.apache.dubbo.metadata.rest.ParamType; -import org.apache.dubbo.metadata.rest.media.MediaType; -import org.apache.dubbo.rpc.protocol.rest.RestHeaderEnum; -import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; -import org.apache.dubbo.rpc.protocol.rest.exception.ParamParseException; -import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodecManager; -import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; -import org.apache.dubbo.rpc.protocol.rest.util.MediaTypeUtil; - -/** - * body param parse - */ -@Activate(value = RestConstant.PROVIDER_BODY_PARSE) -public class BodyProviderParamParser extends ProviderParamParser { - - @Override - protected void doParse(ProviderParseContext parseContext, ArgInfo argInfo) { - - RequestFacade request = parseContext.getRequestFacade(); - - try { - String contentType = parseContext.getRequestFacade().getHeader(RestHeaderEnum.CONTENT_TYPE.getHeader()); - MediaType mediaType = MediaTypeUtil.convertMediaType(argInfo.getParamType(), contentType); - Object param = HttpMessageCodecManager.httpMessageDecode( - request.getInputStream(), argInfo.getParamType(), argInfo.actualReflectType(), mediaType); - parseContext.setValueByIndex(argInfo.getIndex(), param); - } catch (Throwable e) { - throw new ParamParseException("dubbo rest protocol provider body param parser error: " + e.getMessage()); - } - } - - @Override - public ParamType getParamType() { - return ParamType.PROVIDER_BODY; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/HeaderProviderParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/HeaderProviderParamParser.java deleted file mode 100644 index baa630058e2..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/HeaderProviderParamParser.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider; - -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.metadata.rest.ArgInfo; -import org.apache.dubbo.metadata.rest.ParamType; -import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; -import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; - -import java.util.Enumeration; -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * header param parse - */ -@Activate(value = RestConstant.PROVIDER_HEADER_PARSE) -public class HeaderProviderParamParser extends ProviderParamParser { - @Override - protected void doParse(ProviderParseContext parseContext, ArgInfo argInfo) { - - RequestFacade request = parseContext.getRequestFacade(); - if (Map.class.isAssignableFrom(argInfo.getParamType())) { - - Map headerMap = new LinkedHashMap<>(); - Enumeration headerNames = request.getHeaderNames(); - - while (headerNames.hasMoreElements()) { - String name = headerNames.nextElement(); - headerMap.put(name, request.getHeader(name)); - } - parseContext.setValueByIndex(argInfo.getIndex(), headerMap); - return; - } - - String header = request.getHeader(argInfo.getAnnotationNameAttribute()); - Object headerValue = paramTypeConvert(argInfo.getParamType(), header); - - parseContext.setValueByIndex(argInfo.getIndex(), headerValue); - } - - @Override - public ParamType getParamType() { - return ParamType.HEADER; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/NoAnnotationParamProviderParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/NoAnnotationParamProviderParamParser.java deleted file mode 100644 index 353c07b9e9d..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/NoAnnotationParamProviderParamParser.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider; - -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.common.utils.JsonUtils; -import org.apache.dubbo.metadata.rest.ArgInfo; -import org.apache.dubbo.metadata.rest.ParamType; -import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; - -/** - * body param parse - * users can custom NoAnnotationParamProviderParamParser - * and getParamType must return ParamType.PROVIDER_NO_ANNOTATION - * and order is smaller than NoAnnotationParamProviderParamParser`s order - */ -@Activate(value = RestConstant.PROVIDER_NO_ANNOTATION, order = Integer.MAX_VALUE) -public class NoAnnotationParamProviderParamParser extends ProviderParamParser { - - @Override - protected void doParse(ProviderParseContext parseContext, ArgInfo argInfo) { - - Object[] arrayArgs = parseContext.getArrayArgs(); - - int index = argInfo.getIndex(); - - Object arg = arrayArgs[index]; - - Object convertArg = JsonUtils.toJavaObject(JsonUtils.toJson(arg), argInfo.actualReflectType()); - - parseContext.setValueByIndex(index, convertArg); - } - - @Override - public ParamType getParamType() { - return ParamType.PROVIDER_NO_ANNOTATION; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/ParamProviderParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/ParamProviderParamParser.java deleted file mode 100644 index 91a1eb92502..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/ParamProviderParamParser.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider; - -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.metadata.rest.ArgInfo; -import org.apache.dubbo.metadata.rest.ParamType; -import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; -import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; - -import java.util.Enumeration; -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * Http Parameter param parse - */ -@Activate(value = RestConstant.PROVIDER_PARAM_PARSE) -public class ParamProviderParamParser extends ProviderParamParser { - @Override - protected void doParse(ProviderParseContext parseContext, ArgInfo argInfo) { - - // TODO MAP convert - RequestFacade request = parseContext.getRequestFacade(); - - if (Map.class.isAssignableFrom(argInfo.getParamType())) { - - Map paramMap = new LinkedHashMap<>(); - Enumeration parameterNames = request.getParameterNames(); - - while (parameterNames.hasMoreElements()) { - String name = parameterNames.nextElement(); - paramMap.put(name, request.getParameter(name)); - } - parseContext.setValueByIndex(argInfo.getIndex(), paramMap); - return; - } - - String param = request.getParameter(argInfo.getAnnotationNameAttribute()); - - Object paramValue = paramTypeConvert(argInfo.getParamType(), param); - parseContext.setValueByIndex(argInfo.getIndex(), paramValue); - } - - @Override - public ParamType getParamType() { - return ParamType.PARAM; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/PathProviderParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/PathProviderParamParser.java deleted file mode 100644 index 2d5e9e92b1a..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/PathProviderParamParser.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider; - -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.metadata.rest.ArgInfo; -import org.apache.dubbo.metadata.rest.ParamType; -import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; - -/** - * path param parse - */ -@Activate(value = RestConstant.PROVIDER_PATH_PARSE) -public class PathProviderParamParser extends ProviderParamParser { - @Override - protected void doParse(ProviderParseContext parseContext, ArgInfo argInfo) { - - String pathVariable = parseContext.getPathVariable(argInfo.getUrlSplitIndex()); - - Object pathVariableValue = paramTypeConvert(argInfo.getParamType(), pathVariable); - - parseContext.setValueByIndex(argInfo.getIndex(), pathVariableValue); - } - - @Override - public ParamType getParamType() { - return ParamType.PATH; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/ProviderParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/ProviderParamParser.java deleted file mode 100644 index e37aab25166..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/ProviderParamParser.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider; - -import org.apache.dubbo.metadata.rest.ArgInfo; -import org.apache.dubbo.rpc.protocol.rest.util.DataParseUtils; - -public abstract class ProviderParamParser implements BaseProviderParamParser { - - public void parse(ProviderParseContext parseContext, ArgInfo argInfo) { - - doParse(parseContext, argInfo); - } - - protected abstract void doParse(ProviderParseContext parseContext, ArgInfo argInfo); - - protected Object paramTypeConvert(Class targetType, String value) { - - return DataParseUtils.stringTypeConvert(targetType, value); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/ProviderParseContext.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/ProviderParseContext.java deleted file mode 100644 index 78f92fa04ff..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/ProviderParseContext.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider; - -import org.apache.dubbo.rpc.protocol.rest.annotation.BaseParseContext; -import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; - -public class ProviderParseContext extends BaseParseContext { - - private RequestFacade requestFacade; - private Object response; - private Object request; - private Object[] arrayArgs; - - public ProviderParseContext(RequestFacade request) { - this.requestFacade = request; - } - - public RequestFacade getRequestFacade() { - return requestFacade; - } - - public void setValueByIndex(int index, Object value) { - - this.args.set(index, value); - } - - public Object getResponse() { - return response; - } - - public void setResponse(Object response) { - this.response = response; - } - - public Object getRequest() { - return request; - } - - public void setRequest(Object request) { - this.request = request; - } - - public String getPathVariable(int urlSplitIndex) { - - String[] split = getRequestFacade().getRequestURI().split("/"); - - return split[urlSplitIndex]; - } - - public Object[] getArrayArgs() { - return arrayArgs; - } - - public void setArrayArgs(Object[] objects) { - this.arrayArgs = objects; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/config/FeignClientAnnotationConfigPostProcessor.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/config/FeignClientAnnotationConfigPostProcessor.java deleted file mode 100644 index 4f62417a284..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/config/FeignClientAnnotationConfigPostProcessor.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.protocol.rest.config; - -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.common.utils.AnnotationUtils; -import org.apache.dubbo.common.utils.ClassUtils; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.config.CommonConfigPostProcessor; -import org.apache.dubbo.config.ReferenceConfigBase; - -import java.lang.annotation.Annotation; - -/** - * parsing @FeignClient service name attribute to replace reference config provided by - */ -@Activate -public class FeignClientAnnotationConfigPostProcessor implements CommonConfigPostProcessor { - - @Override - public void postProcessReferConfig(ReferenceConfigBase referenceConfig) { - appendParametersFromInterfaceClassMetadata(referenceConfig.getInterfaceClass(), referenceConfig); - } - - public static void appendParametersFromInterfaceClassMetadata( - Class interfaceClass, ReferenceConfigBase referenceConfig) { - - if (interfaceClass == null) { - return; - } - - Class feignClientAnno = (Class) - ClassUtils.forNameAndTryCatch("org.springframework.cloud.openfeign.FeignClient"); - - if (feignClientAnno == null || !AnnotationUtils.isAnnotationPresent(interfaceClass, feignClientAnno)) { - return; - } - - Annotation annotation = interfaceClass.getAnnotation(feignClientAnno); - - // get feign client service name - String serviceName = AnnotationUtils.getAttribute(annotation, "name", "value"); - - if (StringUtils.isEmpty(serviceName)) { - return; - } - - referenceConfig.setProvidedBy(serviceName); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/constans/RestConstant.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/constans/RestConstant.java deleted file mode 100644 index 8d7d5f73cb3..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/constans/RestConstant.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.rpc.protocol.rest.constans; - -import org.apache.dubbo.common.constants.CommonConstants; -import org.apache.dubbo.rpc.Constants; - -public interface RestConstant { - String VERSION = CommonConstants.VERSION_KEY; - String GROUP = CommonConstants.GROUP_KEY; - String PATH = CommonConstants.PATH_KEY; - String TOKEN_KEY = Constants.TOKEN_KEY; - String LOCAL_ADDR = "LOCAL_ADDR"; - String REMOTE_ADDR = "REMOTE_ADDR"; - String LOCAL_PORT = "LOCAL_PORT"; - String REMOTE_PORT = "REMOTE_PORT"; - String PROVIDER_BODY_PARSE = "body"; - String PROVIDER_PARAM_PARSE = "param"; - String PROVIDER_HEADER_PARSE = "header"; - String PROVIDER_PATH_PARSE = "path"; - String PROVIDER_NO_ANNOTATION = "no-annotation"; - - String ADD_MUST_ATTTACHMENT = "must-intercept"; - String RPCCONTEXT_INTERCEPT = "rpc-context"; - String SERIALIZE_INTERCEPT = "serialize"; - String PATH_SEPARATOR = "/"; - String REQUEST_HEADER_INTERCEPT = "header"; - String PATH_INTERCEPT = "path"; - String KEEP_ALIVE_HEADER = "Keep-Alive"; - String CONNECTION = "Connection"; - String CONTENT_TYPE = "Content-Type"; - String TEXT_PLAIN = "text/plain"; - String ACCEPT_CHARSET = "Accept-Charset"; - String WEIGHT_IDENTIFIER = ";q="; - String ACCEPT = "Accept"; - String DEFAULT_ACCEPT = "*/*"; - String REST_HEADER_PREFIX = "rest-service-"; - - // http - String MAX_INITIAL_LINE_LENGTH_PARAM = "max.initial.line.length"; - String MAX_HEADER_SIZE_PARAM = "max.header.size"; - String MAX_CHUNK_SIZE_PARAM = "max.chunk.size"; - String MAX_REQUEST_SIZE_PARAM = "max.request.size"; - String IDLE_TIMEOUT_PARAM = "idle.timeout"; - String KEEP_ALIVE_TIMEOUT_PARAM = "keep.alive.timeout"; - String DEFAULT_CHARSET = "UTF-8"; - - String JSON_CHECK_LEVEL = "jsonCheckLevel"; - String JSON_CHECK_LEVEL_DISABLED = "disabled"; - String JSON_CHECK_LEVEL_WARN = "warn"; - String JSON_CHECK_LEVEL_STRICT = "strict"; - - int MAX_REQUEST_SIZE = 1024 * 1024 * 10; - int MAX_INITIAL_LINE_LENGTH = 4096; - int MAX_HEADER_SIZE = 8192; - int MAX_CHUNK_SIZE = 8192; - int IDLE_TIMEOUT = -1; - int KEEP_ALIVE_TIMEOUT = 60; - - /** - * ServerAttachment pathAndInvokerMapper key - */ - String PATH_AND_INVOKER_MAPPER = "pathAndInvokerMapper"; -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/deploy/ServiceDeployer.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/deploy/ServiceDeployer.java deleted file mode 100644 index df724b03b88..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/deploy/ServiceDeployer.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.rpc.protocol.rest.deploy; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.ClassUtils; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.metadata.rest.PathMatcher; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; -import org.apache.dubbo.metadata.rest.ServiceRestMetadata; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.protocol.rest.Constants; -import org.apache.dubbo.rpc.protocol.rest.PathAndInvokerMapper; -import org.apache.dubbo.rpc.protocol.rest.RpcExceptionMapper; -import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionMapper; -import org.apache.dubbo.rpc.protocol.rest.exception.mapper.RestEasyExceptionMapper; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; - -public class ServiceDeployer { - - private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); - - private final PathAndInvokerMapper pathAndInvokerMapper = new PathAndInvokerMapper(); - private final ExceptionMapper exceptionMapper = createExceptionMapper(); - - private final Set extensions = new HashSet<>(); - - public void deploy(ServiceRestMetadata serviceRestMetadata, Invoker invoker) { - Map pathToServiceMapContainPathVariable = - serviceRestMetadata.getPathContainPathVariableToServiceMap(); - pathAndInvokerMapper.addPathAndInvoker(pathToServiceMapContainPathVariable, invoker); - - Map pathToServiceMapUnContainPathVariable = - serviceRestMetadata.getPathUnContainPathVariableToServiceMap(); - pathAndInvokerMapper.addPathAndInvoker(pathToServiceMapUnContainPathVariable, invoker); - } - - public void undeploy(ServiceRestMetadata serviceRestMetadata) { - Map pathToServiceMapContainPathVariable = - serviceRestMetadata.getPathContainPathVariableToServiceMap(); - pathToServiceMapContainPathVariable.keySet().stream().forEach(pathAndInvokerMapper::removePath); - - Map pathToServiceMapUnContainPathVariable = - serviceRestMetadata.getPathUnContainPathVariableToServiceMap(); - pathToServiceMapUnContainPathVariable.keySet().stream().forEach(pathAndInvokerMapper::removePath); - } - - public void registerExtension(URL url) { - - for (String clazz : COMMA_SPLIT_PATTERN.split( - url.getParameter(Constants.EXTENSION_KEY, RpcExceptionMapper.class.getName()))) { - - if (StringUtils.isEmpty(clazz)) { - continue; - } - try { - Class aClass = ClassUtils.forName(clazz); - - // exception handler - if (ExceptionMapper.isSupport(aClass)) { - exceptionMapper.registerMapper(clazz); - } else { - - extensions.add(aClass.newInstance()); - } - - } catch (Exception e) { - logger.warn("", "", "dubbo rest registerExtension error: ", e.getMessage(), e); - } - } - } - - public PathAndInvokerMapper getPathAndInvokerMapper() { - return pathAndInvokerMapper; - } - - public ExceptionMapper getExceptionMapper() { - return exceptionMapper; - } - - public Set getExtensions() { - return extensions; - } - - /** - * get extensions by type - * - * @param extensionClass - * @param - * @return - */ - // TODO add javax.annotation.Priority sort - public List getExtensions(Class extensionClass) { - - ArrayList exts = new ArrayList<>(); - if (extensions.isEmpty()) { - return exts; - } - - for (Object extension : extensions) { - if (extensionClass.isAssignableFrom(extension.getClass())) { - exts.add((T) extension); - } - } - - return exts; - } - - private ExceptionMapper createExceptionMapper() { - if (ClassUtils.isPresent( - "javax.ws.rs.ext.ExceptionMapper", Thread.currentThread().getContextClassLoader())) { - return new RestEasyExceptionMapper(); - } - return new ExceptionMapper(); - } - - public boolean isMethodAllowed(PathMatcher pathMatcher) { - return pathAndInvokerMapper.isHttpMethodAllowed(pathMatcher); - } - - public boolean hashRestMethod(PathMatcher pathMatcher) { - return pathAndInvokerMapper.getRestMethodMetadata(pathMatcher) != null; - } - - public String pathHttpMethods(PathMatcher pathMatcher) { - return pathAndInvokerMapper.pathHttpMethods(pathMatcher); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/deploy/ServiceDeployerManager.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/deploy/ServiceDeployerManager.java deleted file mode 100644 index 97bc84982fa..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/deploy/ServiceDeployerManager.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.protocol.rest.deploy; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; -import org.apache.dubbo.metadata.rest.ServiceRestMetadata; -import org.apache.dubbo.rpc.Invoker; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicBoolean; - -import static org.apache.dubbo.common.constants.CommonConstants.REST_SERVICE_DEPLOYER_URL_ATTRIBUTE_KEY; -import static org.apache.dubbo.remoting.Constants.PORT_UNIFICATION_NETTY4_SERVER; -import static org.apache.dubbo.remoting.Constants.REST_SERVER; -import static org.apache.dubbo.remoting.Constants.SERVER_KEY; - -public class ServiceDeployerManager { - private static final ConcurrentMap serviceDeployers = new ConcurrentHashMap<>(); - - public static URL deploy(URL currentURL, ServiceRestMetadata serviceRestMetadata, Invoker invoker) { - - AtomicBoolean isNewCreate = new AtomicBoolean(); - - ServiceDeployer newServiceDeployer = - ConcurrentHashMapUtils.computeIfAbsent(serviceDeployers, currentURL.getAddress(), address -> { - ServiceDeployer serviceDeployer = new ServiceDeployer(); - isNewCreate.set(true); - return serviceDeployer; - }); - - // register service - newServiceDeployer.deploy(serviceRestMetadata, invoker); - - // register exception mapper - newServiceDeployer.registerExtension(currentURL); - - // passing ServiceDeployer to PortUnificationServer through URL - // add attribute for server build - - currentURL = currentURL.putAttribute(REST_SERVICE_DEPLOYER_URL_ATTRIBUTE_KEY, newServiceDeployer); - - // not new URL - if (!isNewCreate.get()) { - return currentURL; - } - - URL tmp = currentURL; - // adapt to older rest versions - if (REST_SERVER.contains(tmp.getParameter(SERVER_KEY))) { - tmp = tmp.addParameter(SERVER_KEY, PORT_UNIFICATION_NETTY4_SERVER); - } - - return tmp; - } - - public static void close() { - serviceDeployers.clear(); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/CodeStyleNotSupportException.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/CodeStyleNotSupportException.java deleted file mode 100644 index 979994750eb..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/CodeStyleNotSupportException.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.exception; - -/** - * only support spring mvc & jaxrs annotation - */ -public class CodeStyleNotSupportException extends RestException { - - public CodeStyleNotSupportException(String message) { - super(message); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/DoublePathCheckException.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/DoublePathCheckException.java deleted file mode 100644 index 450f7a2da7b..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/DoublePathCheckException.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.exception; - -/** - * path mapper contains current path will throw - */ -public class DoublePathCheckException extends RuntimeException { - - public DoublePathCheckException(String message) { - super(message); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/MediaTypeUnSupportException.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/MediaTypeUnSupportException.java deleted file mode 100644 index 29af0d7f1f1..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/MediaTypeUnSupportException.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.exception; - -public class MediaTypeUnSupportException extends RestException { - public MediaTypeUnSupportException(String message) { - super(message); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/ParamParseException.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/ParamParseException.java deleted file mode 100644 index b0cd3d75076..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/ParamParseException.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.exception; - -public class ParamParseException extends RestException { - - public ParamParseException(String message) { - super(message); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/PathNoFoundException.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/PathNoFoundException.java deleted file mode 100644 index e3ced44086a..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/PathNoFoundException.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.exception; - -/** - * response code : 404 path no found exception - */ -public class PathNoFoundException extends RestException { - - public PathNoFoundException(String message) { - super(message); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/RemoteServerInternalException.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/RemoteServerInternalException.java deleted file mode 100644 index fce0964b672..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/RemoteServerInternalException.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.exception; - -/** - * response status code : 500 - */ -public class RemoteServerInternalException extends RestException { - - public RemoteServerInternalException(String message) { - super("dubbo http rest protocol remote error :" + message); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/RestException.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/RestException.java deleted file mode 100644 index 9956eb87f74..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/RestException.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.exception; - -/** - * rest exception super - */ -public class RestException extends RuntimeException { - - public RestException(String message) { - super(message); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/UnSupportContentTypeException.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/UnSupportContentTypeException.java deleted file mode 100644 index 6ab784e8541..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/UnSupportContentTypeException.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.exception; - -import org.apache.dubbo.metadata.rest.media.MediaType; - -public class UnSupportContentTypeException extends MediaTypeUnSupportException { - - public UnSupportContentTypeException(String message) { - - super("Current Support content type: " + MediaType.getAllContentType() + "; Do not support content type" - + message); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/ExceptionHandler.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/ExceptionHandler.java deleted file mode 100644 index 0c6f9fd5fc4..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/ExceptionHandler.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.rpc.protocol.rest.exception.mapper; - -public interface ExceptionHandler { - - Object result(E exception); - - default int status() { - return 200; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/ExceptionHandlerResult.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/ExceptionHandlerResult.java deleted file mode 100644 index 7c5109cacef..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/ExceptionHandlerResult.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.exception.mapper; - -public class ExceptionHandlerResult { - private int status; - private Object entity; - - public ExceptionHandlerResult() {} - - public ExceptionHandlerResult setStatus(int status) { - this.status = status; - return this; - } - - public ExceptionHandlerResult setEntity(Object entity) { - this.entity = entity; - return this; - } - - public static ExceptionHandlerResult build() { - return new ExceptionHandlerResult(); - } - - public int getStatus() { - return status; - } - - public Object getEntity() { - return entity; - } - - @Override - public String toString() { - return "ExceptionHandlerResult{" + "status=" + status + ", entity=" + entity + '}'; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/ExceptionMapper.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/ExceptionMapper.java deleted file mode 100644 index c2204992967..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/ExceptionMapper.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.exception.mapper; - -import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.rpc.protocol.rest.util.ReflectUtils; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -public class ExceptionMapper { - private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); - - private final Map, ExceptionHandler> exceptionHandlerMap = new ConcurrentHashMap<>(); - - private final Map allExceptionHandlers = new ConcurrentHashMap<>(); - - public ExceptionHandlerResult exceptionToResult(Object throwable) { - ExceptionHandler exceptionHandler = (ExceptionHandler) getExceptionHandler(throwable.getClass()); - - Object result = exceptionHandler.result((Throwable) throwable); - - return ExceptionHandlerResult.build().setEntity(result).setStatus(exceptionHandler.status()); - } - - public Object getExceptionHandler(Class causeClass) { - - return getExceptionHandler(allExceptionHandlers, causeClass); - } - - public Object getExceptionHandler(Map exceptionHandlerMap, Class causeClass) { - Object exceptionHandler = null; - while (causeClass != null) { - exceptionHandler = exceptionHandlerMap.get(causeClass); - if (exceptionHandler != null) { - break; - } - // When the exception handling class cannot be obtained, it should recursively search the base class - causeClass = causeClass.getSuperclass(); - } - return exceptionHandler; - } - - public boolean hasExceptionMapper(Object throwable) { - if (throwable == null) { - return false; - } - return allExceptionHandlers.containsKey(throwable.getClass()); - } - - public void registerMapper(Class exceptionHandler) { - - try { - List methods = getExceptionHandlerMethods(exceptionHandler); - - if (methods == null || methods.isEmpty()) { - return; - } - - Set> exceptions = new HashSet<>(); - - for (Method method : methods) { - Class parameterType = method.getParameterTypes()[0]; - - // param type isAssignableFrom throwable - if (!Throwable.class.isAssignableFrom(parameterType)) { - continue; - } - - exceptions.add(parameterType); - } - - ArrayList> classes = new ArrayList<>(exceptions); - - // if size==1 so ,exception handler for Throwable - if (classes.size() != 1) { - // else remove throwable - exceptions.remove(Throwable.class); - } - - List> constructors = ReflectUtils.getConstructList(exceptionHandler); - - if (constructors.isEmpty()) { - throw new RuntimeException( - "dubbo rest exception mapper register mapper need exception handler exist no construct declare, current class is: " - + exceptionHandler); - } - - // if exceptionHandler is inner class , no arg construct don`t appear , so newInstance don`t use - // noArgConstruct - Object handler = constructors - .get(0) - .newInstance(new Object[constructors.get(0).getParameterCount()]); - - putExtensionToMap(exceptions, handler); - - } catch (Exception e) { - throw new RuntimeException("dubbo rest protocol exception mapper register error ", e); - } - } - - protected void putExtensionToMap(Set> exceptions, Object handler) { - - Map exceptionHandlerMaps = getExceptionHandlerMap(handler); - - for (Class exception : exceptions) { - // put to instance map - exceptionHandlerMaps.put(exception, handler); - // put to all map - allExceptionHandlers.put(exception, handler); - } - } - - protected Map getExceptionHandlerMap(Object handler) { - return exceptionHandlerMap; - } - - protected List getExceptionHandlerMethods(Class exceptionHandler) { - if (!ExceptionHandler.class.isAssignableFrom(exceptionHandler)) { - return null; - } - // resolve Java_Zulu_jdk/17.0.6-10/x64 param is not throwable - List methods = ReflectUtils.getMethodByNameList(exceptionHandler, "result"); - return methods; - } - - public void registerMapper(String exceptionMapper) { - try { - registerMapper(ReflectUtils.findClass(exceptionMapper)); - } catch (Exception e) { - logger.warn( - "", - e.getMessage(), - "", - "dubbo rest protocol exception mapper register error ,and current exception mapper is :" - + exceptionMapper); - } - } - - public void unRegisterMapper(Class exception) { - exceptionHandlerMap.remove(exception); - } - - public static boolean isSupport(Class exceptionHandler) { - try { - return ExceptionHandler.class.isAssignableFrom(exceptionHandler) - || ReflectUtils.findClassTryException("javax.ws.rs.ext.ExceptionMapper") - .isAssignableFrom(exceptionHandler); - } catch (Exception e) { - return false; - } - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/RestEasyExceptionMapper.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/RestEasyExceptionMapper.java deleted file mode 100644 index 6731dd04ed7..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/RestEasyExceptionMapper.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.exception.mapper; - -import org.apache.dubbo.rpc.protocol.rest.util.ReflectUtils; - -import javax.ws.rs.core.Response; - -import java.lang.reflect.Method; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * for rest easy exception mapper extension - */ -public class RestEasyExceptionMapper extends ExceptionMapper { - - private final Map, javax.ws.rs.ext.ExceptionMapper> exceptionMappers = new ConcurrentHashMap<>(); - - protected List getExceptionHandlerMethods(Class exceptionHandler) { - if (!javax.ws.rs.ext.ExceptionMapper.class.isAssignableFrom(exceptionHandler)) { - return super.getExceptionHandlerMethods(exceptionHandler); - } - // resolve Java_Zulu_jdk/17.0.6-10/x64 param is not throwable - List methods = ReflectUtils.getMethodByNameList(exceptionHandler, "toResponse"); - return methods; - } - - protected Map getExceptionHandlerMap(Object handler) { - if (handler instanceof ExceptionHandler) { - return super.getExceptionHandlerMap(handler); - } - return exceptionMappers; - } - - public ExceptionHandlerResult exceptionToResult(Object throwable) { - Object exceptionMapper = getExceptionHandler(throwable.getClass()); - if (exceptionMapper == null || exceptionMapper instanceof ExceptionHandler) { - return super.exceptionToResult(throwable); - } - - Response response = ((javax.ws.rs.ext.ExceptionMapper) exceptionMapper).toResponse((Throwable) throwable); - - return ExceptionHandlerResult.build().setStatus(response.getStatus()).setEntity(response.getEntity()); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/ResteasyContext.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/ResteasyContext.java deleted file mode 100644 index 91f2edfb438..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/ResteasyContext.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.extension.resteasy; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.metadata.rest.media.MediaType; -import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; -import org.apache.dubbo.rpc.protocol.rest.extension.resteasy.filter.DubboContainerResponseContextImpl; -import org.apache.dubbo.rpc.protocol.rest.extension.resteasy.filter.DubboPreMatchContainerRequestContext; -import org.apache.dubbo.rpc.protocol.rest.filter.ServiceInvokeRestFilter; -import org.apache.dubbo.rpc.protocol.rest.netty.ChunkOutputStream; -import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; -import org.apache.dubbo.rpc.protocol.rest.request.NettyRequestFacade; -import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; -import org.apache.dubbo.rpc.protocol.rest.util.MediaTypeUtil; - -import javax.ws.rs.container.ContainerRequestFilter; -import javax.ws.rs.container.ContainerResponseFilter; -import javax.ws.rs.core.MultivaluedMap; - -import java.io.IOException; -import java.net.URI; -import java.util.List; -import java.util.Map; - -import io.netty.buffer.ByteBuf; -import io.netty.handler.codec.http.HttpContent; -import io.netty.handler.codec.http.HttpHeaders; -import io.netty.handler.codec.http.HttpRequest; -import org.jboss.resteasy.core.interception.ResponseContainerRequestContext; -import org.jboss.resteasy.plugins.server.netty.NettyHttpRequest; -import org.jboss.resteasy.plugins.server.netty.NettyUtil; -import org.jboss.resteasy.specimpl.BuiltResponse; -import org.jboss.resteasy.specimpl.ResteasyHttpHeaders; -import org.jboss.resteasy.spi.HttpResponse; -import org.jboss.resteasy.spi.ResteasyUriInfo; - -public interface ResteasyContext { - String HTTP_PROTOCOL = "http://"; - String HTTP = "http"; - String HTTPS_PROTOCOL = "https://"; - - /** - * return extensions that are filtered by extension type - * - * @param extension - * @param - * @return - */ - default List getExtension(ServiceDeployer serviceDeployer, Class extension) { - - return serviceDeployer.getExtensions(extension); - } - - default DubboPreMatchContainerRequestContext convertHttpRequestToContainerRequestContext( - RequestFacade requestFacade, ContainerRequestFilter[] requestFilters) { - - NettyRequestFacade nettyRequestFacade = (NettyRequestFacade) requestFacade; - HttpRequest request = (HttpRequest) requestFacade.getRequest(); - - NettyHttpRequest nettyRequest = createNettyHttpRequest(nettyRequestFacade, request); - - if (request instanceof HttpContent) { - - try { - byte[] inputStream = requestFacade.getInputStream(); - ByteBuf buffer = - nettyRequestFacade.getNettyChannelContext().alloc().buffer(); - buffer.writeBytes(inputStream); - nettyRequest.setContentBuffer(buffer); - } catch (IOException e) { - } - } - - return new DubboPreMatchContainerRequestContext(nettyRequest, requestFilters, null); - } - - default ResteasyUriInfo extractUriInfo(HttpRequest request) { - String host = HttpHeaders.getHost(request, "unknown"); - if ("".equals(host)) { - host = "unknown"; - } - String uri = request.getUri(); - - String uriString; - - // If we appear to have an absolute URL, don't try to recreate it from the host and request line. - if (uri.startsWith(HTTP_PROTOCOL) || uri.startsWith(HTTPS_PROTOCOL)) { - uriString = uri; - } else { - uriString = HTTP + "://" + host + uri; - } - - URI absoluteURI = URI.create(uriString); - return new ResteasyUriInfo(uriString, absoluteURI.getRawQuery(), ""); - } - - default NettyHttpRequest createNettyHttpRequest(NettyRequestFacade nettyRequestFacade, HttpRequest request) { - ResteasyHttpHeaders headers = NettyUtil.extractHttpHeaders(request); - ResteasyUriInfo uriInfo = extractUriInfo(request); - NettyHttpRequest nettyRequest = new NettyHttpRequest( - nettyRequestFacade.getNettyChannelContext(), - headers, - uriInfo, - request.getMethod().name(), - null, - null, - HttpHeaders.is100ContinueExpected(request)); - - return nettyRequest; - } - - default NettyHttpRequest createNettyHttpRequest(RequestFacade requestFacade) { - NettyRequestFacade nettyRequestFacade = (NettyRequestFacade) requestFacade; - HttpRequest request = (HttpRequest) requestFacade.getRequest(); - - ResteasyHttpHeaders headers = NettyUtil.extractHttpHeaders(request); - ResteasyUriInfo uriInfo = extractUriInfo(request); - NettyHttpRequest nettyRequest = new NettyHttpRequest( - nettyRequestFacade.getNettyChannelContext(), - headers, - uriInfo, - request.getMethod().name(), - null, - null, - HttpHeaders.is100ContinueExpected(request)); - - return nettyRequest; - } - - default void writeResteasyResponse( - URL url, RequestFacade requestFacade, NettyHttpResponse response, BuiltResponse restResponse) - throws Exception { - if (restResponse.getMediaType() != null) { - MediaType mediaType = MediaTypeUtil.convertMediaType( - restResponse.getEntityClass(), restResponse.getMediaType().toString()); - ServiceInvokeRestFilter.writeResult( - response, url, restResponse.getEntity(), restResponse.getEntityClass(), mediaType); - } else { - ServiceInvokeRestFilter.writeResult( - response, requestFacade, url, restResponse.getEntity(), restResponse.getEntityClass()); - } - } - - default MediaType getAcceptMediaType(RequestFacade request, Class returnType) { - - return ServiceInvokeRestFilter.getAcceptMediaType(request, returnType); - } - - default void addResponseHeaders(NettyHttpResponse response, MultivaluedMap headers) { - if (headers == null || headers.isEmpty()) { - - return; - } - for (Map.Entry> entry : headers.entrySet()) { - - String key = entry.getKey(); - List value = entry.getValue(); - if (value == null || value.isEmpty()) { - continue; - } - for (Object tmp : value) { - response.addOutputHeaders(key, tmp.toString()); - } - } - } - - default DubboContainerResponseContextImpl createContainerResponseContext( - Object originRequest, - RequestFacade request, - HttpResponse httpResponse, - BuiltResponse jaxrsResponse, - ContainerResponseFilter[] responseFilters) { - - NettyHttpRequest nettyHttpRequest = - originRequest == null ? createNettyHttpRequest(request) : (NettyHttpRequest) originRequest; - - ResponseContainerRequestContext requestContext = new ResponseContainerRequestContext(nettyHttpRequest); - DubboContainerResponseContextImpl responseContext = new DubboContainerResponseContextImpl( - nettyHttpRequest, httpResponse, jaxrsResponse, requestContext, responseFilters, null, null); - - return responseContext; - } - - default void restOutputStream(NettyHttpResponse response) throws IOException { - ChunkOutputStream outputStream = (ChunkOutputStream) response.getOutputStream(); - outputStream.reset(); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/DubboBuiltResponse.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/DubboBuiltResponse.java deleted file mode 100644 index 30af5357446..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/DubboBuiltResponse.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.extension.resteasy.filter; - -import org.jboss.resteasy.specimpl.BuiltResponse; - -/** - * wrapper resteasy BuiltResponse - */ -public class DubboBuiltResponse extends BuiltResponse { - - // user reset entity - private boolean resetEntity; - - public DubboBuiltResponse(Object entity, int status, Class entityClass) { - - this.entity = entity; - this.entityClass = entityClass; - this.status = status; - } - - @Override - public void setEntity(Object entity) { - if (entity == null) { - return; - } - - if (entity.equals(this.entity)) { - return; - } - // reset entity true - this.resetEntity = true; - super.setEntity(entity); - } - - public boolean isResetEntity() { - return resetEntity; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/DubboContainerResponseContextImpl.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/DubboContainerResponseContextImpl.java deleted file mode 100644 index 4812038a0c1..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/DubboContainerResponseContextImpl.java +++ /dev/null @@ -1,393 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.extension.resteasy.filter; - -import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; -import org.apache.dubbo.common.logger.LoggerFactory; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.container.ContainerResponseFilter; -import javax.ws.rs.core.EntityTag; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.Link; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.NewCookie; -import javax.ws.rs.core.Response; - -import java.io.IOException; -import java.io.OutputStream; -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; -import java.net.URI; -import java.util.Date; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.function.Consumer; - -import org.jboss.resteasy.core.Dispatcher; -import org.jboss.resteasy.core.ServerResponseWriter; -import org.jboss.resteasy.core.SynchronousDispatcher; -import org.jboss.resteasy.core.interception.ResponseContainerRequestContext; -import org.jboss.resteasy.core.interception.jaxrs.SuspendableContainerResponseContext; -import org.jboss.resteasy.specimpl.BuiltResponse; -import org.jboss.resteasy.spi.ApplicationException; -import org.jboss.resteasy.spi.HttpRequest; -import org.jboss.resteasy.spi.HttpResponse; -import org.jboss.resteasy.spi.ResteasyAsynchronousResponse; -import org.jboss.resteasy.spi.ResteasyProviderFactory; - -public class DubboContainerResponseContextImpl implements SuspendableContainerResponseContext { - private static final ErrorTypeAwareLogger logger = - LoggerFactory.getErrorTypeAwareLogger(DubboContainerResponseContextImpl.class); - - protected final HttpRequest request; - protected final HttpResponse httpResponse; - protected final BuiltResponse jaxrsResponse; - private ResponseContainerRequestContext requestContext; - private ContainerResponseFilter[] responseFilters; - private ServerResponseWriter.RunnableWithIOException continuation; - private int currentFilter; - private boolean suspended; - private boolean filterReturnIsMeaningful = true; - private Map, Object> contextDataMap; - private boolean inFilter; - private Throwable throwable; - private Consumer onComplete; - private boolean weSuspended; - - public DubboContainerResponseContextImpl( - final HttpRequest request, - final HttpResponse httpResponse, - final BuiltResponse serverResponse, - final ResponseContainerRequestContext requestContext, - final ContainerResponseFilter[] responseFilters, - final Consumer onComplete, - final ServerResponseWriter.RunnableWithIOException continuation) { - this.request = request; - this.httpResponse = httpResponse; - this.jaxrsResponse = serverResponse; - this.requestContext = requestContext; - this.responseFilters = responseFilters; - this.continuation = continuation; - this.onComplete = onComplete; - contextDataMap = ResteasyProviderFactory.getContextDataMap(); - } - - public BuiltResponse getJaxrsResponse() { - return jaxrsResponse; - } - - public HttpResponse getHttpResponse() { - return httpResponse; - } - - @Override - public int getStatus() { - return jaxrsResponse.getStatus(); - } - - @Override - public void setStatus(int code) { - httpResponse.setStatus(code); - jaxrsResponse.setStatus(code); - } - - @Override - public Response.StatusType getStatusInfo() { - return jaxrsResponse.getStatusInfo(); - } - - @Override - public void setStatusInfo(Response.StatusType statusInfo) { - httpResponse.setStatus(statusInfo.getStatusCode()); - jaxrsResponse.setStatus(statusInfo.getStatusCode()); - } - - @Override - public Class getEntityClass() { - return jaxrsResponse.getEntityClass(); - } - - @Override - public Type getEntityType() { - return jaxrsResponse.getGenericType(); - } - - @Override - public void setEntity(Object entity) { - if (entity != null && jaxrsResponse.getEntity() != null) { - if (logger.isDebugEnabled()) { - logger.debug("Dubbo container response context filter set entity ,before entity is: " - + jaxrsResponse.getEntity() + "and after entity is: " + entity); - } - } - jaxrsResponse.setEntity(entity); - // it resets the entity in a response filter which results - // in a bad content-length being sent back to the client - // so, we'll remove any content-length setting - getHeaders().remove(HttpHeaders.CONTENT_LENGTH); - } - - @Override - public void setEntity(Object entity, Annotation[] annotations, MediaType mediaType) { - if (entity != null && jaxrsResponse.getEntity() != null) { - if (logger.isDebugEnabled()) { - logger.debug("Dubbo container response context filter set entity ,before entity is: " - + jaxrsResponse.getEntity() + "and after entity is: " + entity); - } - } - jaxrsResponse.setEntity(entity); - jaxrsResponse.setAnnotations(annotations); - jaxrsResponse.getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, mediaType); - // it resets the entity in a response filter which results - // in a bad content-length being sent back to the client - // so, we'll remove any content-length setting - getHeaders().remove(HttpHeaders.CONTENT_LENGTH); - } - - @Override - public MultivaluedMap getHeaders() { - return jaxrsResponse.getMetadata(); - } - - @Override - public Set getAllowedMethods() { - return jaxrsResponse.getAllowedMethods(); - } - - @Override - public Date getDate() { - return jaxrsResponse.getDate(); - } - - @Override - public Locale getLanguage() { - return jaxrsResponse.getLanguage(); - } - - @Override - public int getLength() { - return jaxrsResponse.getLength(); - } - - @Override - public MediaType getMediaType() { - return jaxrsResponse.getMediaType(); - } - - @Override - public Map getCookies() { - return jaxrsResponse.getCookies(); - } - - @Override - public EntityTag getEntityTag() { - return jaxrsResponse.getEntityTag(); - } - - @Override - public Date getLastModified() { - return jaxrsResponse.getLastModified(); - } - - @Override - public URI getLocation() { - return jaxrsResponse.getLocation(); - } - - @Override - public Set getLinks() { - return jaxrsResponse.getLinks(); - } - - @Override - public boolean hasLink(String relation) { - return jaxrsResponse.hasLink(relation); - } - - @Override - public Link getLink(String relation) { - return jaxrsResponse.getLink(relation); - } - - @Override - public Link.Builder getLinkBuilder(String relation) { - return jaxrsResponse.getLinkBuilder(relation); - } - - @Override - public boolean hasEntity() { - return !jaxrsResponse.isClosed() && jaxrsResponse.hasEntity(); - } - - @Override - public Object getEntity() { - return !jaxrsResponse.isClosed() ? jaxrsResponse.getEntity() : null; - } - - @Override - public OutputStream getEntityStream() { - try { - return httpResponse.getOutputStream(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public void setEntityStream(OutputStream entityStream) { - httpResponse.setOutputStream(entityStream); - } - - @Override - public Annotation[] getEntityAnnotations() { - return jaxrsResponse.getAnnotations(); - } - - @Override - public MultivaluedMap getStringHeaders() { - return jaxrsResponse.getStringHeaders(); - } - - @Override - public String getHeaderString(String name) { - return jaxrsResponse.getHeaderString(name); - } - - @Override - public synchronized void suspend() { - if (continuation == null) throw new RuntimeException("Suspend not supported yet"); - suspended = true; - } - - @Override - public synchronized void resume() { - if (!suspended) throw new RuntimeException("Cannot resume: not suspended"); - if (inFilter) { - // suspend/resume within filter, same thread: just ignore and move on - suspended = false; - return; - } - - // go on, but with proper exception handling - try (ResteasyProviderFactory.CloseableContext c = - ResteasyProviderFactory.addCloseableContextDataLevel(contextDataMap)) { - filter(); - } catch (Throwable t) { - // don't throw to client - writeException(t); - } - } - - @Override - public synchronized void resume(Throwable t) { - if (!suspended) throw new RuntimeException("Cannot resume: not suspended"); - if (inFilter) { - // not suspended, or suspend/abortWith within filter, same thread: collect and move on - throwable = t; - suspended = false; - } else { - try (ResteasyProviderFactory.CloseableContext c = - ResteasyProviderFactory.addCloseableContextDataLevel(contextDataMap)) { - writeException(t); - } - } - } - - private void writeException(Throwable t) { - /* - * Here we cannot call AsyncResponse.resume(t) because that would invoke the response filters - * and we should not invoke them because we're already in them. - */ - HttpResponse httpResponse = (HttpResponse) contextDataMap.get(HttpResponse.class); - SynchronousDispatcher dispatcher = (SynchronousDispatcher) contextDataMap.get(Dispatcher.class); - ResteasyAsynchronousResponse asyncResponse = request.getAsyncContext().getAsyncResponse(); - - dispatcher.unhandledAsynchronousException(httpResponse, t); - onComplete.accept(t); - asyncResponse.complete(); - asyncResponse.completionCallbacks(t); - } - - public synchronized void filter() throws IOException { - while (currentFilter < responseFilters.length) { - ContainerResponseFilter filter = responseFilters[currentFilter++]; - try { - suspended = false; - throwable = null; - inFilter = true; - filter.filter(requestContext, this); - } catch (IOException e) { - throw new ApplicationException(e); - } finally { - inFilter = false; - } - if (suspended) { - if (!request.getAsyncContext().isSuspended()) { - request.getAsyncContext().suspend(); - weSuspended = true; - } - // ignore any abort request until we are resumed - filterReturnIsMeaningful = false; - return; - } - if (throwable != null) { - // handle the case where we've been suspended by a previous filter - if (filterReturnIsMeaningful) SynchronousDispatcher.rethrow(throwable); - else { - writeException(throwable); - return; - } - } - } - // here it means we reached the last filter - - // some frameworks don't support async request filters, in which case suspend() is forbidden - // so if we get here we're still synchronous and don't have a continuation, which must be in - // the caller - if (continuation == null) return; - - // if we've never been suspended, the caller is valid so let it handle any exception - if (filterReturnIsMeaningful) { - continuation.run(); - onComplete.accept(null); - return; - } - // if we've been suspended then the caller is a filter and have to invoke our continuation - // try to write it out - try { - continuation.run(); - onComplete.accept(null); - if (weSuspended) { - // if we're the ones who turned the request async, nobody will call complete() for us, so we have to - HttpServletRequest httpServletRequest = - (HttpServletRequest) contextDataMap.get(HttpServletRequest.class); - httpServletRequest.getAsyncContext().complete(); - } - } catch (IOException e) { - logger.error( - "", - "Dubbo container response context filter error", - "request method is: " + request.getHttpMethod() + "and request uri is:" - + request.getUri().getPath(), - "", - e); - } - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/DubboPreMatchContainerRequestContext.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/DubboPreMatchContainerRequestContext.java deleted file mode 100644 index 4964f1792d8..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/DubboPreMatchContainerRequestContext.java +++ /dev/null @@ -1,310 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.extension.resteasy.filter; - -import javax.ws.rs.container.ContainerRequestFilter; -import javax.ws.rs.core.Cookie; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Request; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.core.UriInfo; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.Enumeration; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.function.Supplier; - -import org.jboss.resteasy.core.interception.jaxrs.SuspendableContainerRequestContext; -import org.jboss.resteasy.plugins.server.netty.NettyHttpRequest; -import org.jboss.resteasy.specimpl.BuiltResponse; -import org.jboss.resteasy.specimpl.ResteasyHttpHeaders; -import org.jboss.resteasy.spi.ApplicationException; -import org.jboss.resteasy.spi.ResteasyProviderFactory; - -public class DubboPreMatchContainerRequestContext implements SuspendableContainerRequestContext { - protected final NettyHttpRequest httpRequest; - protected Response response; - private ContainerRequestFilter[] requestFilters; - private int currentFilter; - private boolean suspended; - private boolean filterReturnIsMeaningful = true; - private Supplier continuation; - private Map, Object> contextDataMap; - private boolean inFilter; - private Throwable throwable; - private boolean startedContinuation; - - public DubboPreMatchContainerRequestContext( - final NettyHttpRequest request, - final ContainerRequestFilter[] requestFilters, - final Supplier continuation) { - this.httpRequest = request; - this.requestFilters = requestFilters; - this.continuation = continuation; - contextDataMap = ResteasyProviderFactory.getContextDataMap(); - } - - public NettyHttpRequest getHttpRequest() { - return httpRequest; - } - - public Response getResponseAbortedWith() { - return response; - } - - @Override - public Object getProperty(String name) { - return httpRequest.getAttribute(name); - } - - @Override - public Collection getPropertyNames() { - ArrayList names = new ArrayList(); - Enumeration enames = httpRequest.getAttributeNames(); - while (enames.hasMoreElements()) { - names.add(enames.nextElement()); - } - return names; - } - - @Override - public void setProperty(String name, Object object) { - httpRequest.setAttribute(name, object); - } - - @Override - public void removeProperty(String name) { - httpRequest.removeAttribute(name); - } - - @Override - public UriInfo getUriInfo() { - return httpRequest.getUri(); - } - - @Override - public void setRequestUri(URI requestUri) throws IllegalStateException { - httpRequest.setRequestUri(requestUri); - } - - @Override - public void setRequestUri(URI baseUri, URI requestUri) throws IllegalStateException { - httpRequest.setRequestUri(baseUri, requestUri); - } - - @Override - public String getMethod() { - return httpRequest.getHttpMethod(); - } - - @Override - public void setMethod(String method) { - httpRequest.setHttpMethod(method); - } - - @Override - public MultivaluedMap getHeaders() { - return ((ResteasyHttpHeaders) httpRequest.getHttpHeaders()).getMutableHeaders(); - } - - @Override - public Date getDate() { - return httpRequest.getHttpHeaders().getDate(); - } - - @Override - public Locale getLanguage() { - return httpRequest.getHttpHeaders().getLanguage(); - } - - @Override - public int getLength() { - return httpRequest.getHttpHeaders().getLength(); - } - - @Override - public MediaType getMediaType() { - return httpRequest.getHttpHeaders().getMediaType(); - } - - @Override - public List getAcceptableMediaTypes() { - return httpRequest.getHttpHeaders().getAcceptableMediaTypes(); - } - - @Override - public List getAcceptableLanguages() { - return httpRequest.getHttpHeaders().getAcceptableLanguages(); - } - - @Override - public Map getCookies() { - return httpRequest.getHttpHeaders().getCookies(); - } - - @Override - public boolean hasEntity() { - return getMediaType() != null; - } - - @Override - public InputStream getEntityStream() { - return httpRequest.getInputStream(); - } - - @Override - public void setEntityStream(InputStream entityStream) { - httpRequest.setInputStream(entityStream); - } - - @Override - public SecurityContext getSecurityContext() { - return ResteasyProviderFactory.getContextData(SecurityContext.class); - } - - @Override - public void setSecurityContext(SecurityContext context) { - ResteasyProviderFactory.pushContext(SecurityContext.class, context); - } - - @Override - public Request getRequest() { - return ResteasyProviderFactory.getContextData(Request.class); - } - - @Override - public String getHeaderString(String name) { - return httpRequest.getHttpHeaders().getHeaderString(name); - } - - @Override - public synchronized void suspend() { - if (continuation == null) throw new RuntimeException("Suspend not supported yet"); - suspended = true; - } - - @Override - public synchronized void abortWith(Response response) { - if (suspended && !inFilter) { - try (ResteasyProviderFactory.CloseableContext c = - ResteasyProviderFactory.addCloseableContextDataLevel(contextDataMap)) { - httpRequest.getAsyncContext().getAsyncResponse().resume(response); - } - } else { - // not suspended, or suspend/abortWith within filter, same thread: collect and move on - this.response = response; - suspended = false; - } - } - - @Override - public synchronized void resume() { - if (!suspended) throw new RuntimeException("Cannot resume: not suspended"); - if (inFilter) { - // suspend/resume within filter, same thread: just ignore and move on - suspended = false; - return; - } - - // go on, but with proper exception handling - try (ResteasyProviderFactory.CloseableContext c = - ResteasyProviderFactory.addCloseableContextDataLevel(contextDataMap)) { - filter(); - } catch (Throwable t) { - // don't throw to client - writeException(t); - } - } - - @Override - public synchronized void resume(Throwable t) { - if (!suspended) throw new RuntimeException("Cannot resume: not suspended"); - if (inFilter) { - // not suspended, or suspend/abortWith within filter, same thread: collect and move on - throwable = t; - suspended = false; - } else { - try (ResteasyProviderFactory.CloseableContext c = - ResteasyProviderFactory.addCloseableContextDataLevel(contextDataMap)) { - writeException(t); - } - } - } - - private void writeException(Throwable t) { - /* - * Here, contrary to ContainerResponseContextImpl.writeException, we can use the async response - * to write the exception, because it calls the right response filters, complete() and callbacks - */ - httpRequest.getAsyncContext().getAsyncResponse().resume(t); - } - - public synchronized BuiltResponse filter() throws Throwable { - while (currentFilter < requestFilters.length) { - ContainerRequestFilter filter = requestFilters[currentFilter++]; - try { - suspended = false; - response = null; - throwable = null; - inFilter = true; - filter.filter(this); - } catch (IOException e) { - throw new ApplicationException(e); - } finally { - inFilter = false; - } - if (suspended) { - if (!httpRequest.getAsyncContext().isSuspended()) - // ignore any abort request until we are resumed - filterReturnIsMeaningful = false; - response = null; - return null; - } - BuiltResponse serverResponse = (BuiltResponse) getResponseAbortedWith(); - if (serverResponse != null) { - // handle the case where we've been suspended by a previous filter - return serverResponse; - } - - if (throwable != null) { - // handle the case where we've been suspended by a previous filter - throw throwable; - } - } - // here it means we reached the last filter - // some frameworks don't support async request filters, in which case suspend() is forbidden - // so if we get here we're still synchronous and don't have a continuation, which must be in - // the caller - startedContinuation = true; - if (continuation == null) return null; - // in any case, return the continuation: sync will use it, and async will ignore it - return continuation.get(); - } - - public boolean startedContinuation() { - return startedContinuation; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/ResteasyNettyHttpResponse.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/ResteasyNettyHttpResponse.java deleted file mode 100644 index 92de82f8d92..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/ResteasyNettyHttpResponse.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.extension.resteasy.filter; - -import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; - -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.NewCookie; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.List; -import java.util.Map; - -import org.jboss.resteasy.specimpl.MultivaluedMapImpl; -import org.jboss.resteasy.spi.HttpResponse; - -public class ResteasyNettyHttpResponse implements HttpResponse { - - private NettyHttpResponse response; - - private MultivaluedMap multivaluedMap = new MultivaluedMapImpl<>(); - - public ResteasyNettyHttpResponse(NettyHttpResponse response) { - this.response = response; - Map> outputHeaders = response.getOutputHeaders(); - - for (Map.Entry> headers : outputHeaders.entrySet()) { - String key = headers.getKey(); - List value = headers.getValue(); - - if (value == null || value.isEmpty()) { - continue; - } - - for (String val : value) { - multivaluedMap.add(key, val); - } - } - } - - @Override - public int getStatus() { - return response.getStatus(); - } - - @Override - public void setStatus(int status) { - - response.setStatus(status); - } - - @Override - public MultivaluedMap getOutputHeaders() { - return multivaluedMap; - } - - @Override - public OutputStream getOutputStream() throws IOException { - return response.getOutputStream(); - } - - @Override - public void setOutputStream(OutputStream os) { - response.setOutputStream(os); - } - - @Override - public void addNewCookie(NewCookie cookie) {} - - @Override - public void sendError(int status) throws IOException { - - response.sendError(status); - } - - @Override - public void sendError(int status, String message) throws IOException { - response.sendError(status, message); - } - - @Override - public boolean isCommitted() { - return false; - } - - @Override - public void reset() { - - response.reset(); - } - - @Override - public void flushBuffer() throws IOException {} -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/ResteasyRequestContainerFilterAdapter.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/ResteasyRequestContainerFilterAdapter.java deleted file mode 100644 index eba29dde82a..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/ResteasyRequestContainerFilterAdapter.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.extension.resteasy.filter; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; -import org.apache.dubbo.rpc.protocol.rest.extension.resteasy.ResteasyContext; -import org.apache.dubbo.rpc.protocol.rest.filter.RestRequestFilter; -import org.apache.dubbo.rpc.protocol.rest.filter.context.RestFilterContext; -import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; -import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; - -import javax.ws.rs.container.ContainerRequestFilter; - -import java.util.List; - -import org.jboss.resteasy.specimpl.BuiltResponse; - -@Activate( - value = "resteasy", - onClass = { - "javax.ws.rs.container.ContainerRequestFilter", - "org.jboss.resteasy.plugins.server.netty.NettyHttpRequest", - "org.jboss.resteasy.plugins.server.netty.NettyHttpResponse" - }, - order = Integer.MAX_VALUE - 1) -public class ResteasyRequestContainerFilterAdapter implements RestRequestFilter, ResteasyContext { - - @Override - public void filter(RestFilterContext restFilterContext) throws Exception { - - ServiceDeployer serviceDeployer = restFilterContext.getServiceDeployer(); - RequestFacade requestFacade = restFilterContext.getRequestFacade(); - URL url = restFilterContext.getUrl(); - NettyHttpResponse response = restFilterContext.getResponse(); - - List containerRequestFilters = - getExtension(serviceDeployer, ContainerRequestFilter.class); - - if (containerRequestFilters.isEmpty()) { - - return; - } - - DubboPreMatchContainerRequestContext containerRequestContext = convertHttpRequestToContainerRequestContext( - requestFacade, containerRequestFilters.toArray(new ContainerRequestFilter[0])); - - // set resteasy request for save user`s custom request attribute - restFilterContext.setOriginRequest(containerRequestContext.getHttpRequest()); - - try { - BuiltResponse restResponse = containerRequestContext.filter(); - - if (restResponse == null) { - return; - } - - addResponseHeaders(response, restResponse.getHeaders()); - writeResteasyResponse(url, requestFacade, response, restResponse); - // completed - restFilterContext.setComplete(true); - } catch (Throwable e) { - throw new RuntimeException("dubbo rest resteasy ContainerRequestFilter write response encode error", e); - } finally { - containerRequestContext.getHttpRequest().releaseContentBuffer(); - } - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/ResteasyResponseContainerFilterAdapter.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/ResteasyResponseContainerFilterAdapter.java deleted file mode 100644 index 35e008e7f0e..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/ResteasyResponseContainerFilterAdapter.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.extension.resteasy.filter; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; -import org.apache.dubbo.rpc.protocol.rest.extension.resteasy.ResteasyContext; -import org.apache.dubbo.rpc.protocol.rest.filter.RestResponseFilter; -import org.apache.dubbo.rpc.protocol.rest.filter.context.RestFilterContext; -import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; -import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; - -import javax.ws.rs.container.ContainerResponseFilter; - -import java.util.List; - -import org.jboss.resteasy.spi.HttpResponse; - -@Activate( - value = "resteasy", - order = Integer.MAX_VALUE - 1000, - onClass = { - "org.jboss.resteasy.specimpl.BuiltResponse", - "javax.ws.rs.container.ContainerResponseFilter", - "org.jboss.resteasy.spi.HttpResponse", - "org.jboss.resteasy.plugins.server.netty.NettyHttpResponse" - }) -public class ResteasyResponseContainerFilterAdapter implements RestResponseFilter, ResteasyContext { - @Override - public void filter(RestFilterContext restFilterContext) throws Exception { - - ServiceDeployer serviceDeployer = restFilterContext.getServiceDeployer(); - RequestFacade requestFacade = restFilterContext.getRequestFacade(); - NettyHttpResponse response = restFilterContext.getResponse(); - URL url = restFilterContext.getUrl(); - List containerRequestFilters = - getExtension(serviceDeployer, ContainerResponseFilter.class); - - if (containerRequestFilters.isEmpty()) { - return; - } - - // response filter entity first - - // build jaxrsResponse from rest netty response - DubboBuiltResponse dubboBuiltResponse = - new DubboBuiltResponse(response.getResponseBody(), response.getStatus(), response.getEntityClass()); - // NettyHttpResponse wrapper - HttpResponse httpResponse = new ResteasyNettyHttpResponse(response); - DubboContainerResponseContextImpl containerResponseContext = createContainerResponseContext( - restFilterContext.getOriginRequest(), - requestFacade, - httpResponse, - dubboBuiltResponse, - containerRequestFilters.toArray(new ContainerResponseFilter[0])); - containerResponseContext.filter(); - - // user reset entity - if (dubboBuiltResponse.hasEntity() && dubboBuiltResponse.isResetEntity()) { - // clean output stream data - restOutputStream(response); - writeResteasyResponse(url, requestFacade, response, dubboBuiltResponse); - } - addResponseHeaders(response, httpResponse.getOutputHeaders()); - - restFilterContext.setComplete(true); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/intercept/DubboServerWriterInterceptorContext.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/intercept/DubboServerWriterInterceptorContext.java deleted file mode 100644 index f1697edd804..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/intercept/DubboServerWriterInterceptorContext.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.extension.resteasy.intercept; - -import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; -import org.apache.dubbo.common.logger.LoggerFactory; - -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.ext.WriterInterceptor; - -import java.io.IOException; -import java.io.OutputStream; -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; - -import org.jboss.resteasy.core.interception.ServerWriterInterceptorContext; -import org.jboss.resteasy.spi.HttpRequest; -import org.jboss.resteasy.spi.ResteasyProviderFactory; - -public class DubboServerWriterInterceptorContext extends ServerWriterInterceptorContext { - private static final ErrorTypeAwareLogger logger = - LoggerFactory.getErrorTypeAwareLogger(DubboServerWriterInterceptorContext.class); - - public DubboServerWriterInterceptorContext( - WriterInterceptor[] interceptors, - ResteasyProviderFactory providerFactory, - Object entity, - Class type, - Type genericType, - Annotation[] annotations, - MediaType mediaType, - MultivaluedMap headers, - OutputStream outputStream, - HttpRequest request) { - super( - interceptors, - providerFactory, - entity, - type, - genericType, - annotations, - mediaType, - headers, - outputStream, - request); - } - - @Override - public void proceed() throws IOException, WebApplicationException { - logger.debug("Dubbo server writer intercept context: " + getClass().getName() + " Method : proceed"); - - if (interceptors == null || index >= interceptors.length) { - return; - } else { - - logger.debug("Dubbo server writer intercept context WriterInterceptor: " - + interceptors[index].getClass().getName()); - interceptors[index++].aroundWriteTo(this); - } - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/intercept/ResteasyStatusCodeInterceptor.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/intercept/ResteasyStatusCodeInterceptor.java deleted file mode 100644 index ee988194c95..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/intercept/ResteasyStatusCodeInterceptor.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.rpc.protocol.rest.extension.resteasy.intercept; - -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.rpc.protocol.rest.extension.resteasy.ResteasyContext; -import org.apache.dubbo.rpc.protocol.rest.filter.RestResponseInterceptor; -import org.apache.dubbo.rpc.protocol.rest.filter.context.RestInterceptContext; - -import org.jboss.resteasy.specimpl.AbstractBuiltResponse; - -@Activate( - value = "resteasy-resStatus", - onClass = { - "javax.ws.rs.ext.WriterInterceptorContext", - "org.jboss.resteasy.specimpl.BuiltResponse", - "org.jboss.resteasy.plugins.server.netty.NettyHttpRequest", - "org.jboss.resteasy.plugins.server.netty.NettyHttpResponse" - }, - order = Integer.MAX_VALUE) -public class ResteasyStatusCodeInterceptor implements RestResponseInterceptor, ResteasyContext { - - @Override - public void intercept(RestInterceptContext restResponseInterceptor) throws Exception { - Object result = restResponseInterceptor.getResult(); - - if (result == null || (!(result instanceof AbstractBuiltResponse))) { - return; - } - - AbstractBuiltResponse abstractBuiltResponse = (AbstractBuiltResponse) result; - - restResponseInterceptor.getResponse().setStatus(abstractBuiltResponse.getStatus()); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/intercept/ResteasyWriterInterceptorAdapter.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/intercept/ResteasyWriterInterceptorAdapter.java deleted file mode 100644 index 5116fce40e7..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/intercept/ResteasyWriterInterceptorAdapter.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.extension.resteasy.intercept; - -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.protocol.rest.RestHeaderEnum; -import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; -import org.apache.dubbo.rpc.protocol.rest.extension.resteasy.ResteasyContext; -import org.apache.dubbo.rpc.protocol.rest.filter.RestResponseInterceptor; -import org.apache.dubbo.rpc.protocol.rest.filter.context.RestInterceptContext; -import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; -import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.ext.WriterInterceptor; - -import java.io.ByteArrayOutputStream; -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; -import java.util.List; - -import org.apache.commons.io.IOUtils; -import org.jboss.resteasy.core.interception.AbstractWriterInterceptorContext; -import org.jboss.resteasy.plugins.server.netty.NettyHttpRequest; -import org.jboss.resteasy.specimpl.MultivaluedMapImpl; -import org.jboss.resteasy.spi.HttpRequest; -import org.jboss.resteasy.spi.ResteasyProviderFactory; - -@Activate( - value = "resteasy", - onClass = { - "javax.ws.rs.ext.WriterInterceptorContext", - "org.jboss.resteasy.plugins.server.netty.NettyHttpRequest", - "org.jboss.resteasy.plugins.server.netty.NettyHttpResponse" - }) -public class ResteasyWriterInterceptorAdapter implements RestResponseInterceptor, ResteasyContext { - - private ResteasyProviderFactory resteasyProviderFactory = getResteasyProviderFactory(); - - @Override - public void intercept(RestInterceptContext restResponseInterceptor) throws Exception { - - RpcInvocation rpcInvocation = restResponseInterceptor.getRpcInvocation(); - ServiceDeployer serviceDeployer = restResponseInterceptor.getServiceDeployer(); - RequestFacade request = restResponseInterceptor.getRequestFacade(); - NettyHttpResponse response = restResponseInterceptor.getResponse(); - Object result = restResponseInterceptor.getResult(); - - Class type = rpcInvocation.getReturnType(); - - List extension = serviceDeployer.getExtensions(WriterInterceptor.class); - - if (extension.isEmpty()) { - return; - } - - NettyHttpRequest nettyHttpRequest = (NettyHttpRequest) restResponseInterceptor.getOriginRequest(); - - HttpRequest restRequest = nettyHttpRequest == null ? createNettyHttpRequest(request) : nettyHttpRequest; - - MultivaluedMap headers = new MultivaluedMapImpl(); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - - try { - - // get content-type - String value = getAcceptMediaType(request, type).value; - - MediaType mediaType = MediaType.valueOf(value); - - AbstractWriterInterceptorContext writerContext = getAbstractWriterInterceptorContext( - restRequest, extension, result, type, type, mediaType, os, headers); - - writerContext.proceed(); - ByteArrayOutputStream outputStream = (ByteArrayOutputStream) writerContext.getOutputStream(); - - addResponseHeaders(response, writerContext.getHeaders()); - - if (outputStream.size() <= 0) { - return; - } - - // intercept response first - restOutputStream(response); - - byte[] bytes = outputStream.toByteArray(); - response.getOutputStream().write(bytes); - response.addOutputHeaders(RestHeaderEnum.CONTENT_TYPE.getHeader(), value); - - restResponseInterceptor.setComplete(true); - } finally { - IOUtils.close(os); - } - } - - private AbstractWriterInterceptorContext getAbstractWriterInterceptorContext( - HttpRequest request, - List extension, - Object entity, - Class type, - Type genericType, - MediaType mediaType, - ByteArrayOutputStream os, - MultivaluedMap headers) { - AbstractWriterInterceptorContext writerContext = new DubboServerWriterInterceptorContext( - extension.toArray(new WriterInterceptor[0]), - resteasyProviderFactory, - entity, - type, - genericType, - new Annotation[0], - mediaType, - headers, - os, - request); - return writerContext; - } - - protected ResteasyProviderFactory getResteasyProviderFactory() { - return new ResteasyProviderFactory(); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestFilter.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestFilter.java deleted file mode 100644 index dc7608de8a4..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestFilter.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.filter; - -import org.apache.dubbo.rpc.protocol.rest.filter.context.RestFilterContext; - -/** - * Rest filter is extended by rest request & response filter - */ -public interface RestFilter { - - void filter(RestFilterContext restFilterContext) throws Exception; -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestRequestFilter.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestRequestFilter.java deleted file mode 100644 index da5a2c9a758..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestRequestFilter.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.rpc.protocol.rest.filter; - -import org.apache.dubbo.common.extension.ExtensionScope; -import org.apache.dubbo.common.extension.SPI; - -/** - * Rest filter will be invoked before http handler - */ -@SPI(scope = ExtensionScope.FRAMEWORK) -public interface RestRequestFilter extends RestFilter {} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestResponseFilter.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestResponseFilter.java deleted file mode 100644 index 97fdf00c946..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestResponseFilter.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.rpc.protocol.rest.filter; - -import org.apache.dubbo.common.extension.ExtensionScope; -import org.apache.dubbo.common.extension.SPI; - -/** - * Rest response filter will be invoked when response is written to channel - */ -@SPI(scope = ExtensionScope.FRAMEWORK) -public interface RestResponseFilter extends RestFilter {} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestResponseInterceptor.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestResponseInterceptor.java deleted file mode 100644 index 8e824301ad2..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestResponseInterceptor.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.filter; - -import org.apache.dubbo.common.extension.ExtensionScope; -import org.apache.dubbo.common.extension.SPI; -import org.apache.dubbo.rpc.protocol.rest.filter.context.RestInterceptContext; - -/** - * RestResponseInterceptorChain will take effect before result is written to response - */ -@SPI(scope = ExtensionScope.FRAMEWORK) -public interface RestResponseInterceptor { - - void intercept(RestInterceptContext restResponseInterceptor) throws Exception; -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/ServiceInvokeRestFilter.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/ServiceInvokeRestFilter.java deleted file mode 100644 index 8c0d04a467d..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/ServiceInvokeRestFilter.java +++ /dev/null @@ -1,256 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.filter; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.metadata.rest.PathMatcher; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; -import org.apache.dubbo.metadata.rest.media.MediaType; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.Result; -import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.model.FrameworkModel; -import org.apache.dubbo.rpc.protocol.rest.RestHeaderEnum; -import org.apache.dubbo.rpc.protocol.rest.RestRPCInvocationUtil; -import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; -import org.apache.dubbo.rpc.protocol.rest.exception.PathNoFoundException; -import org.apache.dubbo.rpc.protocol.rest.exception.UnSupportContentTypeException; -import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionHandlerResult; -import org.apache.dubbo.rpc.protocol.rest.filter.context.RestFilterContext; -import org.apache.dubbo.rpc.protocol.rest.filter.context.RestInterceptContext; -import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodecManager; -import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; -import org.apache.dubbo.rpc.protocol.rest.pair.InvokerAndRestMethodMetadataPair; -import org.apache.dubbo.rpc.protocol.rest.pair.MessageCodecResultPair; -import org.apache.dubbo.rpc.protocol.rest.request.NettyRequestFacade; -import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; -import org.apache.dubbo.rpc.protocol.rest.util.MediaTypeUtil; - -import java.util.List; -import java.util.Objects; - -import io.netty.handler.codec.http.FullHttpRequest; -import io.netty.handler.codec.http.HttpRequest; - -@Activate(value = "invoke", order = Integer.MAX_VALUE) -public class ServiceInvokeRestFilter implements RestRequestFilter { - private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); - - private final List restResponseInterceptors; - - public ServiceInvokeRestFilter(FrameworkModel frameworkModel) { - restResponseInterceptors = - frameworkModel.getExtensionLoader(RestResponseInterceptor.class).getActivateExtensions(); - } - - @Override - public void filter(RestFilterContext restFilterContext) throws Exception { - NettyRequestFacade nettyRequestFacade = (NettyRequestFacade) restFilterContext.getRequestFacade(); - - FullHttpRequest nettyHttpRequest = nettyRequestFacade.getRequest(); - - doHandler( - nettyHttpRequest, - restFilterContext.getResponse(), - restFilterContext.getRequestFacade(), - restFilterContext.getUrl(), - restFilterContext.getOriginRequest(), - restFilterContext.getServiceDeployer()); - } - - private void doHandler( - HttpRequest nettyHttpRequest, - NettyHttpResponse nettyHttpResponse, - RequestFacade request, - URL url, - Object originRequest, // resteasy request - ServiceDeployer serviceDeployer) - throws Exception { - PathMatcher pathMatcher = RestRPCInvocationUtil.createPathMatcher(request); - - // path NoFound 404 - if (!serviceDeployer.hashRestMethod(pathMatcher)) { - throw new PathNoFoundException("rest service Path no found, current path info:" + pathMatcher); - } - - // method disallowed - if (!serviceDeployer.isMethodAllowed(pathMatcher)) { - nettyHttpResponse.sendError( - 405, - "service require request method is : " - + serviceDeployer.pathHttpMethods(pathMatcher) - + ", but current request method is: " + request.getMethod()); - return; - } - // compare http method and acquire metadata by request - InvokerAndRestMethodMetadataPair restMethodMetadataPair = - RestRPCInvocationUtil.getRestMethodMetadataAndInvokerPair( - pathMatcher.compareHttpMethod(true), serviceDeployer); - - Invoker invoker = restMethodMetadataPair.getInvoker(); - - RestMethodMetadata restMethodMetadata = restMethodMetadataPair.getRestMethodMetadata(); - - // content-type support judge,throw unSupportException - acceptSupportJudge(request, restMethodMetadata.getReflectMethod().getReturnType()); - - // build RpcInvocation - RpcInvocation rpcInvocation = RestRPCInvocationUtil.createBaseRpcInvocation(request, restMethodMetadata); - - // parse method real args - RestRPCInvocationUtil.parseMethodArgs( - rpcInvocation, request, nettyHttpRequest, nettyHttpResponse, restMethodMetadata); - - // execute business method invoke - Result result = invoker.invoke(rpcInvocation); - - // set raw response - nettyHttpResponse.setResponseBody(result.getValue()); - - if (result.hasException()) { - Throwable exception = result.getException(); - logger.error( - "", exception.getMessage(), "", "dubbo rest protocol provider Invoker invoke error", exception); - - if (serviceDeployer.getExceptionMapper().hasExceptionMapper(exception)) { - ExceptionHandlerResult exceptionToResult = - serviceDeployer.getExceptionMapper().exceptionToResult(result.getException()); - writeResult( - nettyHttpResponse, request, url, exceptionToResult.getEntity(), rpcInvocation.getReturnType()); - nettyHttpResponse.setStatus(exceptionToResult.getStatus()); - } else { - nettyHttpResponse.sendError( - 500, - "\n dubbo rest business exception, error cause is: " - + result.getException().getCause() - + "\n message is: " + result.getException().getMessage() - + "\n stacktrace is: " + stackTraceToString(exception)); - } - } - - try { - RestInterceptContext restFilterContext = new RestInterceptContext( - url, request, nettyHttpResponse, serviceDeployer, result.getValue(), rpcInvocation); - // set filter request - restFilterContext.setOriginRequest(originRequest); - - // invoke the intercept chain before Result write to response - executeResponseIntercepts(restFilterContext); - } catch (Exception exception) { - logger.error( - "", exception.getMessage(), "", "dubbo rest protocol execute ResponseIntercepts error", exception); - throw exception; - } - } - - /** - * write return value by accept - * - * @param nettyHttpResponse - * @param request - * @param value - * @param returnType - * @throws Exception - */ - public static void writeResult( - NettyHttpResponse nettyHttpResponse, RequestFacade request, URL url, Object value, Class returnType) - throws Exception { - MediaType mediaType = getAcceptMediaType(request, returnType); - writeResult(nettyHttpResponse, url, value, returnType, mediaType); - } - - public static void writeResult( - NettyHttpResponse nettyHttpResponse, URL url, Object value, Class returnType, MediaType mediaType) - throws Exception { - MessageCodecResultPair booleanMediaTypePair = HttpMessageCodecManager.httpMessageEncode( - nettyHttpResponse.getOutputStream(), value, url, mediaType, returnType); - // reset raw response result - nettyHttpResponse.setResponseBody(value); - nettyHttpResponse.addOutputHeaders( - RestHeaderEnum.CONTENT_TYPE.getHeader(), booleanMediaTypePair.getMediaType().value); - } - - /** - * return first match , if any multiple content-type - * - * @param request - * @return - */ - public static MediaType getAcceptMediaType(RequestFacade request, Class returnType) { - String accept = request.getHeader(RestHeaderEnum.ACCEPT.getHeader()); - accept = Objects.isNull(accept) ? MediaType.ALL_VALUE.value : accept; - MediaType mediaType = MediaTypeUtil.convertMediaType(returnType, accept); - return mediaType; - } - - /** - * accept can not support will throw UnSupportAcceptException - * - * @param requestFacade - */ - private void acceptSupportJudge(RequestFacade requestFacade, Class returnType) { - try { - // media type judge - getAcceptMediaType(requestFacade, returnType); - } catch (UnSupportContentTypeException e) { - // return type judge - MediaType mediaType = HttpMessageCodecManager.typeSupport(returnType); - - String accept = requestFacade.getHeader(RestHeaderEnum.ACCEPT.getHeader()); - if (mediaType == null || accept == null) { - throw e; - } - - if (!accept.contains(mediaType.value)) { - - throw e; - } - } - } - - public static String stackTraceToString(Throwable throwable) { - StackTraceElement[] stackTrace = throwable.getStackTrace(); - - StringBuilder stringBuilder = new StringBuilder("\n"); - for (StackTraceElement traceElement : stackTrace) { - stringBuilder.append("\tat " + traceElement).append("\n"); - } - - return stringBuilder.toString(); - } - - /** - * execute response Intercepts - * - * @param restFilterContext - * @throws Exception - */ - public void executeResponseIntercepts(RestInterceptContext restFilterContext) throws Exception { - - for (RestResponseInterceptor restResponseInterceptor : restResponseInterceptors) { - - restResponseInterceptor.intercept(restFilterContext); - - if (restFilterContext.complete()) { - break; - } - } - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/ServiceInvokeRestResponseInterceptor.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/ServiceInvokeRestResponseInterceptor.java deleted file mode 100644 index db3c3d8f253..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/ServiceInvokeRestResponseInterceptor.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.filter; - -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.rpc.protocol.rest.filter.context.RestInterceptContext; - -import static org.apache.dubbo.rpc.protocol.rest.filter.ServiceInvokeRestFilter.writeResult; - -/** - * default RestResponseInterceptor - */ -@Activate(value = "invoke", order = Integer.MAX_VALUE) -public class ServiceInvokeRestResponseInterceptor implements RestResponseInterceptor { - - @Override - public void intercept(RestInterceptContext restInterceptContext) throws Exception { - - writeResult( - restInterceptContext.getResponse(), - restInterceptContext.getRequestFacade(), - restInterceptContext.getUrl(), - restInterceptContext.getResult(), - restInterceptContext.getRpcInvocation().getReturnType()); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/context/FilterContext.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/context/FilterContext.java deleted file mode 100644 index c9544f47d8a..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/context/FilterContext.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.filter.context; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; -import org.apache.dubbo.rpc.protocol.rest.netty.HttpResponse; -import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; - -public interface FilterContext { - - URL getUrl(); - - RequestFacade getRequestFacade(); - - HttpResponse getResponse(); - - ServiceDeployer getServiceDeployer(); - - boolean complete(); - - void setComplete(boolean complete); - - Object getOriginRequest(); - - Object getOriginResponse(); -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/context/RestFilterContext.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/context/RestFilterContext.java deleted file mode 100644 index dd3e2c51024..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/context/RestFilterContext.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.filter.context; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; -import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; -import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; - -public class RestFilterContext implements FilterContext { - protected URL url; - protected RequestFacade requestFacade; - protected NettyHttpResponse response; - protected ServiceDeployer serviceDeployer; - protected boolean completed; - protected Object originRequest; - protected Object originResponse; - - public RestFilterContext( - URL url, RequestFacade requestFacade, NettyHttpResponse response, ServiceDeployer serviceDeployer) { - this.url = url; - this.requestFacade = requestFacade; - this.response = response; - this.serviceDeployer = serviceDeployer; - } - - @Override - public URL getUrl() { - return url; - } - - @Override - public RequestFacade getRequestFacade() { - return requestFacade; - } - - @Override - public NettyHttpResponse getResponse() { - return response; - } - - @Override - public ServiceDeployer getServiceDeployer() { - return serviceDeployer; - } - - @Override - public boolean complete() { - return completed; - } - - @Override - public void setComplete(boolean complete) { - this.completed = complete; - } - - @Override - public Object getOriginRequest() { - return originRequest; - } - - @Override - public Object getOriginResponse() { - return originResponse; - } - - public void setOriginRequest(Object originRequest) { - if (this.originRequest != null) { - return; - } - this.originRequest = originRequest; - } - - public void setOriginResponse(Object originResponse) { - this.originResponse = originResponse; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/context/RestInterceptContext.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/context/RestInterceptContext.java deleted file mode 100644 index 9ba91ae87d5..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/context/RestInterceptContext.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.rpc.protocol.rest.filter.context; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; -import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; -import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; - -public class RestInterceptContext extends RestFilterContext { - - private Object result; - private RpcInvocation rpcInvocation; - - public RestInterceptContext( - URL url, - RequestFacade requestFacade, - NettyHttpResponse response, - ServiceDeployer serviceDeployer, - Object result, - RpcInvocation rpcInvocation) { - super(url, requestFacade, response, serviceDeployer); - this.result = result; - this.rpcInvocation = rpcInvocation; - } - - public Object getResult() { - return result; - } - - public RpcInvocation getRpcInvocation() { - return rpcInvocation; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/handler/NettyHttpHandler.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/handler/NettyHttpHandler.java deleted file mode 100644 index 55b24de256d..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/handler/NettyHttpHandler.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.handler; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.remoting.http.HttpHandler; -import org.apache.dubbo.rpc.RpcContext; -import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; -import org.apache.dubbo.rpc.protocol.rest.exception.MediaTypeUnSupportException; -import org.apache.dubbo.rpc.protocol.rest.exception.ParamParseException; -import org.apache.dubbo.rpc.protocol.rest.exception.PathNoFoundException; -import org.apache.dubbo.rpc.protocol.rest.filter.RestFilter; -import org.apache.dubbo.rpc.protocol.rest.filter.RestRequestFilter; -import org.apache.dubbo.rpc.protocol.rest.filter.RestResponseFilter; -import org.apache.dubbo.rpc.protocol.rest.filter.ServiceInvokeRestFilter; -import org.apache.dubbo.rpc.protocol.rest.filter.context.RestFilterContext; -import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; -import org.apache.dubbo.rpc.protocol.rest.request.NettyRequestFacade; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - * netty http request handler - */ -public class NettyHttpHandler implements HttpHandler { - private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); - private final ServiceDeployer serviceDeployer; - private final URL url; - private final List restRequestFilters; - private final List restResponseFilters; - - public NettyHttpHandler(ServiceDeployer serviceDeployer, URL url) { - this.serviceDeployer = serviceDeployer; - this.url = url; - restRequestFilters = new ArrayList<>(url.getOrDefaultFrameworkModel() - .getExtensionLoader(RestRequestFilter.class) - .getActivateExtensions()); - restResponseFilters = new ArrayList<>(url.getOrDefaultFrameworkModel() - .getExtensionLoader(RestResponseFilter.class) - .getActivateExtensions()); - } - - @Override - public void handle(NettyRequestFacade requestFacade, NettyHttpResponse nettyHttpResponse) throws IOException { - - // set remote address - RpcContext.getServiceContext().setRemoteAddress(requestFacade.getRemoteAddr(), requestFacade.getRemotePort()); - - // set local address - RpcContext.getServiceContext().setLocalAddress(requestFacade.getLocalAddr(), requestFacade.getLocalPort()); - - // set request - RpcContext.getServiceContext().setRequest(requestFacade); - - // set response - RpcContext.getServiceContext().setResponse(nettyHttpResponse); - - Object nettyHttpRequest = requestFacade.getRequest(); - - RestFilterContext restFilterContext = - new RestFilterContext(url, requestFacade, nettyHttpResponse, serviceDeployer); - - try { - - // first request filter - executeFilters(restFilterContext, restRequestFilters); - - } catch (PathNoFoundException pathNoFoundException) { - logger.error( - "", - pathNoFoundException.getMessage(), - "", - "dubbo rest protocol provider path no found ,raw request is :" + nettyHttpRequest, - pathNoFoundException); - nettyHttpResponse.sendError(404, pathNoFoundException.getMessage()); - } catch (ParamParseException paramParseException) { - logger.error( - "", - paramParseException.getMessage(), - "", - "dubbo rest protocol provider param parse error ,and raw request is :" + nettyHttpRequest, - paramParseException); - nettyHttpResponse.sendError(400, paramParseException.getMessage()); - } catch (MediaTypeUnSupportException contentTypeException) { - logger.error( - "", - contentTypeException.getMessage(), - "", - "dubbo rest protocol provider content-type un support" + nettyHttpRequest, - contentTypeException); - nettyHttpResponse.sendError(415, contentTypeException.getMessage()); - } catch (Throwable throwable) { - logger.error( - "", - throwable.getMessage(), - "", - "dubbo rest protocol provider error ,and raw request is " + nettyHttpRequest, - throwable); - nettyHttpResponse.sendError( - 500, - "dubbo rest invoke Internal error, message is " + throwable.getMessage() - + " ,and exception type is : " + throwable.getClass() + " , stacktrace is: " - + ServiceInvokeRestFilter.stackTraceToString(throwable)); - } - - // second response filter - try { - executeFilters(restFilterContext, restResponseFilters); - } catch (Throwable throwable) { - logger.error( - "", - throwable.getMessage(), - "", - "dubbo rest protocol provider error ,and raw request is " + nettyHttpRequest, - throwable); - nettyHttpResponse.sendError( - 500, - "dubbo rest invoke Internal error, message is " + throwable.getMessage() - + " ,and exception type is : " + throwable.getClass() + " , stacktrace is: " - + ServiceInvokeRestFilter.stackTraceToString(throwable)); - } - } - - /** - * execute rest filters - * - * @param restFilterContext - * @param restFilters - * @throws Exception - */ - public void executeFilters(RestFilterContext restFilterContext, List restFilters) throws Exception { - - for (RestFilter restFilter : restFilters) { - restFilter.filter(restFilterContext); - if (restFilterContext.complete()) { - break; - } - } - } -} 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 deleted file mode 100644 index bf0652d2cbf..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerApiListingResource.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.integration.swagger; - -import org.apache.dubbo.config.annotation.Service; - -import javax.servlet.ServletConfig; -import javax.servlet.ServletContext; -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 com.fasterxml.jackson.core.JsonProcessingException; -import io.swagger.jaxrs.listing.BaseApiListingResource; - -@Service -public class DubboSwaggerApiListingResource extends BaseApiListingResource implements DubboSwaggerService { - - @Context - ServletContext context; - - @Override - public Response getListingJson(Application app, ServletConfig sc, HttpHeaders headers, UriInfo uriInfo) - throws JsonProcessingException { - Response response = getListingJsonResponse(app, context, sc, headers, uriInfo); - response.getHeaders().add("Access-Control-Allow-Origin", "*"); - response.getHeaders().add("Access-Control-Allow-Headers", "x-requested-with, ssi-token"); - response.getHeaders().add("Access-Control-Max-Age", "3600"); - response.getHeaders().add("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS"); - return response; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerService.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerService.java deleted file mode 100644 index eacdfbd283e..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerService.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.integration.swagger; - -import javax.servlet.ServletConfig; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -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.UriInfo; - -import com.fasterxml.jackson.core.JsonProcessingException; - -@Path("dubbo") -@Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) -@Produces({MediaType.APPLICATION_JSON + "; " + "charset=UTF-8", MediaType.TEXT_XML + "; " + "charset=UTF-8"}) -public interface DubboSwaggerService { - - @GET - @Path("swagger") - Response getListingJson( - @Context Application app, @Context ServletConfig sc, @Context HttpHeaders headers, @Context UriInfo uriInfo) - throws JsonProcessingException; -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageCodec.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageCodec.java deleted file mode 100644 index 08530451038..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageCodec.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.message; - -import org.apache.dubbo.common.extension.ExtensionScope; -import org.apache.dubbo.common.extension.SPI; -import org.apache.dubbo.metadata.rest.media.MediaType; - -/** - * for http body codec - * @param - * @param - */ -@SPI(scope = ExtensionScope.FRAMEWORK) -public interface HttpMessageCodec - extends HttpMessageDecode, HttpMessageEncode { - - /** - * content-type support judge - * @param mediaType - * @param targetType - * @return - */ - boolean contentTypeSupport(MediaType mediaType, Class targetType); - - /** - * class type support judge - * @param targetType - * @return - */ - boolean typeSupport(Class targetType); - - MediaType contentType(); -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageCodecManager.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageCodecManager.java deleted file mode 100644 index 212ebb4ffb5..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageCodecManager.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.message; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.metadata.rest.media.MediaType; -import org.apache.dubbo.rpc.model.FrameworkModel; -import org.apache.dubbo.rpc.protocol.rest.exception.UnSupportContentTypeException; -import org.apache.dubbo.rpc.protocol.rest.pair.MessageCodecResultPair; - -import java.io.OutputStream; -import java.lang.reflect.Type; -import java.util.Set; - -public class HttpMessageCodecManager { - private static final Set httpMessageCodecs = FrameworkModel.defaultModel() - .getExtensionLoader(HttpMessageCodec.class) - .getSupportedExtensionInstances(); - - public static Object httpMessageDecode(byte[] body, Class type, Type actualType, MediaType mediaType) - throws Exception { - if (body == null || body.length == 0) { - return null; - } - - for (HttpMessageCodec httpMessageCodec : httpMessageCodecs) { - if (httpMessageCodec.contentTypeSupport(mediaType, type) || typeJudge(mediaType, type, httpMessageCodec)) { - return httpMessageCodec.decode(body, type, actualType); - } - } - throw new UnSupportContentTypeException("UnSupport content-type :" + mediaType.value); - } - - public static MessageCodecResultPair httpMessageEncode( - OutputStream outputStream, Object unSerializedBody, URL url, MediaType mediaType, Class bodyType) - throws Exception { - - if (unSerializedBody == null) { - for (HttpMessageCodec httpMessageCodec : httpMessageCodecs) { - if (httpMessageCodec.contentTypeSupport(mediaType, bodyType) - || typeJudge(mediaType, bodyType, httpMessageCodec)) { - return MessageCodecResultPair.pair(false, httpMessageCodec.contentType()); - } - } - } - - for (HttpMessageCodec httpMessageCodec : httpMessageCodecs) { - if (httpMessageCodec.contentTypeSupport(mediaType, bodyType) - || typeJudge(mediaType, bodyType, httpMessageCodec)) { - httpMessageCodec.encode(outputStream, unSerializedBody, url); - return MessageCodecResultPair.pair(true, httpMessageCodec.contentType()); - } - } - - throw new UnSupportContentTypeException("UnSupport content-type :" + mediaType.value); - } - - /** - * if content-type is null or all ,will judge media type by class type - * - * @param mediaType - * @param bodyType - * @param httpMessageCodec - * @return - */ - private static boolean typeJudge(MediaType mediaType, Class bodyType, HttpMessageCodec httpMessageCodec) { - return (MediaType.ALL_VALUE.equals(mediaType) || mediaType == null) - && bodyType != null - && httpMessageCodec.typeSupport(bodyType); - } - - public static MediaType typeSupport(Class type) { - for (HttpMessageCodec httpMessageCodec : httpMessageCodecs) { - - if (httpMessageCodec.typeSupport(type)) { - return httpMessageCodec.contentType(); - } - } - - return null; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageDecode.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageDecode.java deleted file mode 100644 index 8b322816009..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageDecode.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.message; - -import java.lang.reflect.Type; - -public interface HttpMessageDecode { - - Object decode(InputStream body, Class targetType, Type actualTYpe) throws Exception; -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageEncode.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageEncode.java deleted file mode 100644 index 8ae427ec5e7..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageEncode.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.message; - -import org.apache.dubbo.common.URL; - -public interface HttpMessageEncode { - - void encode(OutputStream outputStream, Object unSerializedBody, URL url) throws Exception; -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/MediaTypeMatcher.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/MediaTypeMatcher.java deleted file mode 100644 index 71152a81faa..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/MediaTypeMatcher.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.message; - -import org.apache.dubbo.metadata.rest.media.MediaType; - -import java.util.ArrayList; -import java.util.List; - -public enum MediaTypeMatcher { - MULTI_VALUE(createMediaList(MediaType.APPLICATION_FORM_URLENCODED_VALUE)), - APPLICATION_JSON(createMediaList(MediaType.APPLICATION_JSON_VALUE)), - TEXT_PLAIN(createMediaList(MediaType.TEXT_PLAIN, MediaType.OCTET_STREAM)), - TEXT_XML(createMediaList(MediaType.TEXT_XML)), - ; - - private List mediaTypes; - - MediaTypeMatcher(List mediaTypes) { - this.mediaTypes = mediaTypes; - } - - private static List createMediaList(MediaType... mediaTypes) { - List mediaTypeList = getDefaultList(); - - for (MediaType mediaType : mediaTypes) { - - mediaTypeList.add(mediaType); - } - return mediaTypeList; - } - - private static List getDefaultList() { - - List defaultList = new ArrayList<>(); - return defaultList; - } - - public boolean mediaSupport(MediaType mediaType) { - return mediaTypes.contains(mediaType); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/ByteArrayCodec.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/ByteArrayCodec.java deleted file mode 100644 index 2dc0a85ad7a..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/ByteArrayCodec.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.message.codec; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.metadata.rest.media.MediaType; -import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodec; - -import java.io.OutputStream; -import java.lang.reflect.Type; - -/** - * body type is byte array - */ -@Activate("byteArray") -public class ByteArrayCodec implements HttpMessageCodec { - - @Override - public Object decode(byte[] body, Class targetType, Type type) throws Exception { - return body; - } - - @Override - public boolean contentTypeSupport(MediaType mediaType, Class targetType) { - return byte[].class.equals(targetType); - } - - @Override - public boolean typeSupport(Class targetType) { - return byte[].class.equals(targetType); - } - - @Override - public MediaType contentType() { - return MediaType.OCTET_STREAM; - } - - @Override - public void encode(OutputStream outputStream, Object unSerializedBody, URL url) throws Exception { - outputStream.write((byte[]) unSerializedBody); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/JsonCodec.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/JsonCodec.java deleted file mode 100644 index d63b72d00bf..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/JsonCodec.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.message.codec; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.common.utils.JsonUtils; -import org.apache.dubbo.metadata.rest.media.MediaType; -import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodec; -import org.apache.dubbo.rpc.protocol.rest.message.MediaTypeMatcher; -import org.apache.dubbo.rpc.protocol.rest.util.DataParseUtils; - -import java.io.OutputStream; -import java.lang.reflect.Type; -import java.nio.charset.StandardCharsets; -import java.util.HashSet; -import java.util.Set; - -/** - * body is json - */ -@Activate(value = "json", order = 100) -public class JsonCodec implements HttpMessageCodec { - private static final Set unSupportClasses = new HashSet<>(); - - static { - unSupportClasses.add(byte[].class); - } - - @Override - public Object decode(byte[] body, Class targetType, Type actualType) throws Exception { - return DataParseUtils.jsonConvert(actualType, body); - } - - @Override - public boolean contentTypeSupport(MediaType mediaType, Class targetType) { - return MediaTypeMatcher.APPLICATION_JSON.mediaSupport(mediaType) && !unSupportClasses.contains(targetType); - } - - @Override - public boolean typeSupport(Class targetType) { - return !unSupportClasses.contains(targetType) && !DataParseUtils.isTextType(targetType); - } - - @Override - public MediaType contentType() { - return MediaType.APPLICATION_JSON_VALUE; - } - - @Override - public void encode(OutputStream outputStream, Object unSerializedBody, URL url) throws Exception { - outputStream.write(JsonUtils.toJson(unSerializedBody).getBytes(StandardCharsets.UTF_8)); - } - - public static final void addUnSupportClass(Class unSupportClass) { - unSupportClasses.add(unSupportClass); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/MultiValueCodec.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/MultiValueCodec.java deleted file mode 100644 index a78f793c7b9..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/MultiValueCodec.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.message.codec; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.common.utils.ReflectUtils; -import org.apache.dubbo.metadata.rest.media.MediaType; -import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodec; -import org.apache.dubbo.rpc.protocol.rest.message.MediaTypeMatcher; -import org.apache.dubbo.rpc.protocol.rest.util.DataParseUtils; - -import java.io.OutputStream; -import java.lang.reflect.Field; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * body is form - */ -@Activate("multiValue") -public class MultiValueCodec implements HttpMessageCodec { - - @Override - public Object decode(byte[] body, Class targetType, Type type) throws Exception { - Object map = DataParseUtils.multipartFormConvert(body, targetType); - Map valuesMap = (Map) map; - if (Map.class.isAssignableFrom(targetType)) { - return map; - } else if (DataParseUtils.isTextType(targetType)) { - - // only fetch first - Set set = valuesMap.keySet(); - ArrayList arrayList = new ArrayList<>(set); - Object key = arrayList.get(0); - Object value = valuesMap.get(key); - if (value == null) { - return null; - } - return DataParseUtils.stringTypeConvert(targetType, String.valueOf(((List) value).get(0))); - - } else { - - Map beanPropertyFields = ReflectUtils.getBeanPropertyFields(targetType); - - Object emptyObject = ReflectUtils.getEmptyObject(targetType); - - beanPropertyFields.entrySet().stream().forEach(entry -> { - try { - List values = (List) valuesMap.get(entry.getKey()); - String value = values == null ? null : String.valueOf(values.get(0)); - entry.getValue() - .set( - emptyObject, - DataParseUtils.stringTypeConvert( - entry.getValue().getType(), value)); - } catch (IllegalAccessException e) { - - } - }); - - return emptyObject; - } - } - - @Override - public boolean contentTypeSupport(MediaType mediaType, Class targetType) { - return MediaTypeMatcher.MULTI_VALUE.mediaSupport(mediaType); - } - - @Override - public boolean typeSupport(Class targetType) { - return false; - } - - @Override - public MediaType contentType() { - return MediaType.APPLICATION_FORM_URLENCODED_VALUE; - } - - @Override - public void encode(OutputStream outputStream, Object unSerializedBody, URL url) throws Exception { - DataParseUtils.writeFormContent((Map) unSerializedBody, outputStream); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/ResteasyResponseCodec.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/ResteasyResponseCodec.java deleted file mode 100644 index 0cb0efc7b11..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/ResteasyResponseCodec.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.message.codec; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.common.utils.ClassUtils; -import org.apache.dubbo.common.utils.JsonUtils; -import org.apache.dubbo.metadata.rest.media.MediaType; -import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodec; - -import java.io.OutputStream; -import java.lang.reflect.Method; -import java.lang.reflect.Type; -import java.nio.charset.StandardCharsets; - -@Activate(onClass = "javax.ws.rs.core.Response") -public class ResteasyResponseCodec implements HttpMessageCodec { - - private Class responseClass; - - public ResteasyResponseCodec() { - try { - responseClass = ClassUtils.forName("javax.ws.rs.core.Response"); - JsonCodec.addUnSupportClass(responseClass); - } catch (Exception exception) { - responseClass = null; - } - } - - @Override - public boolean contentTypeSupport(MediaType mediaType, Class targetType) { - return isMatch(targetType); - } - - @Override - public boolean typeSupport(Class targetType) { - return isMatch(targetType); - } - - @Override - public MediaType contentType() { - return MediaType.APPLICATION_JSON_VALUE; - } - - @Override - public Object decode(byte[] body, Class targetType, Type type) throws Exception { - if (null == body || body.length == 0) { - return null; - } - - Class builtResponse = ClassUtils.forName("org.jboss.resteasy.specimpl.BuiltResponse"); - - Object o = builtResponse.newInstance(); - - Method method = builtResponse.getMethod("setEntity", Object.class); - - method.invoke(o, new String(body, StandardCharsets.UTF_8)); - - return o; - } - - @Override - public void encode(OutputStream os, Object target, URL url) throws Exception { - if (target != null) { - Method method = target.getClass().getMethod("getEntity"); - method.setAccessible(true); - Object result = method.invoke(target); - os.write(JsonUtils.toJson(result).getBytes(StandardCharsets.UTF_8)); - } - } - - private boolean isMatch(Class targetType) { - return responseClass != null && null != targetType && responseClass.isAssignableFrom(targetType); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/StringCodec.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/StringCodec.java deleted file mode 100644 index 1a543a2ad77..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/StringCodec.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.message.codec; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.metadata.rest.media.MediaType; -import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodec; - -import java.io.OutputStream; -import java.lang.reflect.Type; -import java.nio.charset.StandardCharsets; - -/** - * body is string - */ -@Activate(value = "string", order = 200) -public class StringCodec implements HttpMessageCodec { - - @Override - public Object decode(byte[] body, Class targetType, Type type) throws Exception { - if (body == null || body.length == 0) { - return null; - } - return new String(body); - } - - @Override - public boolean contentTypeSupport(MediaType mediaType, Class targetType) { - return String.class.equals(targetType); - } - - @Override - public boolean typeSupport(Class targetType) { - return String.class.equals(targetType); - } - - @Override - public MediaType contentType() { - return MediaType.TEXT_PLAIN; - } - - @Override - public void encode(OutputStream outputStream, Object unSerializedBody, URL url) throws Exception { - outputStream.write(((String) unSerializedBody).getBytes(StandardCharsets.UTF_8)); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/TextCodec.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/TextCodec.java deleted file mode 100644 index 16f13bd4137..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/TextCodec.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.message.codec; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.metadata.rest.media.MediaType; -import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodec; -import org.apache.dubbo.rpc.protocol.rest.message.MediaTypeMatcher; -import org.apache.dubbo.rpc.protocol.rest.util.DataParseUtils; - -import java.io.OutputStream; -import java.lang.reflect.Type; -import java.nio.charset.StandardCharsets; - -/** - * content-type is text/html - */ -@Activate("text") -public class TextCodec implements HttpMessageCodec { - - @Override - public Object decode(byte[] body, Class targetType, Type type) throws Exception { - return DataParseUtils.stringTypeConvert(targetType, new String(body, StandardCharsets.UTF_8)); - } - - @Override - public boolean contentTypeSupport(MediaType mediaType, Class targetType) { - return MediaTypeMatcher.TEXT_PLAIN.mediaSupport(mediaType); - } - - @Override - public boolean typeSupport(Class targetType) { - return DataParseUtils.isTextType(targetType); - } - - @Override - public MediaType contentType() { - return MediaType.TEXT_PLAIN; - } - - @Override - public void encode(OutputStream outputStream, Object unSerializedBody, URL url) throws Exception { - DataParseUtils.writeTextContent(unSerializedBody, outputStream); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/XMLCodec.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/XMLCodec.java deleted file mode 100644 index f696c91e8e8..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/XMLCodec.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.message.codec; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.metadata.rest.media.MediaType; -import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodec; -import org.apache.dubbo.rpc.protocol.rest.message.MediaTypeMatcher; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.Marshaller; -import javax.xml.bind.Unmarshaller; -import javax.xml.parsers.SAXParserFactory; -import javax.xml.transform.Source; -import javax.xml.transform.sax.SAXSource; - -import java.io.OutputStream; -import java.io.StringReader; -import java.lang.reflect.Type; - -import org.xml.sax.InputSource; - -/** - * body content-type is xml - */ -@Activate("xml") -public class XMLCodec implements HttpMessageCodec { - - @Override - public Object decode(byte[] body, Class targetType, Type type) throws Exception { - - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setFeature("http://xml.org/sax/features/external-general-entities", false); - spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); - spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); - - // Do unmarshall operation - Source xmlSource = - new SAXSource(spf.newSAXParser().getXMLReader(), new InputSource(new StringReader(new String(body)))); - - JAXBContext context = JAXBContext.newInstance(targetType); - Unmarshaller unmarshaller = context.createUnmarshaller(); - return unmarshaller.unmarshal(xmlSource); - } - - @Override - public boolean contentTypeSupport(MediaType mediaType, Class targetType) { - return MediaTypeMatcher.TEXT_XML.mediaSupport(mediaType); - } - - @Override - public boolean typeSupport(Class targetType) { - return false; - } - - @Override - public MediaType contentType() { - return MediaType.TEXT_XML; - } - - @Override - public void encode(OutputStream outputStream, Object unSerializedBody, URL url) throws Exception { - Marshaller marshaller = - JAXBContext.newInstance(unSerializedBody.getClass()).createMarshaller(); - marshaller.marshal(unSerializedBody, outputStream); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/ChunkOutputStream.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/ChunkOutputStream.java deleted file mode 100644 index dcc602ba01c..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/ChunkOutputStream.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.rpc.protocol.rest.netty; - -import org.apache.dubbo.remoting.transport.ExceedPayloadLimitException; - -import java.io.IOException; -import java.io.OutputStream; - -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.http.DefaultHttpContent; - -public class ChunkOutputStream extends OutputStream { - final ByteBuf buffer; - final ChannelHandlerContext ctx; - final NettyHttpResponse response; - int chunkSize = 0; - - ChunkOutputStream(final NettyHttpResponse response, final ChannelHandlerContext ctx, final int chunkSize) { - this.response = response; - if (chunkSize < 1) { - throw new IllegalArgumentException(); - } - this.buffer = Unpooled.buffer(0, chunkSize); - this.chunkSize = chunkSize; - this.ctx = ctx; - } - - @Override - public void write(int b) throws IOException { - if (buffer.maxWritableBytes() < 1) { - throwExceedPayloadLimitException(buffer.readableBytes() + 1); - } - buffer.writeByte(b); - } - - private void throwExceedPayloadLimitException(int dataSize) throws ExceedPayloadLimitException { - throw new ExceedPayloadLimitException("Data length too large: " + dataSize + ", max payload: " + chunkSize); - } - - public void reset() { - if (response.isCommitted()) throw new IllegalStateException(); - buffer.clear(); - } - - @Override - public void close() throws IOException { - flush(); - super.close(); - } - - @Override - public void write(byte[] b, int off, int len) throws IOException { - int dataLengthLeftToWrite = len; - int dataToWriteOffset = off; - if (buffer.maxWritableBytes() < dataLengthLeftToWrite) { - throwExceedPayloadLimitException(buffer.readableBytes() + len); - } - buffer.writeBytes(b, dataToWriteOffset, dataLengthLeftToWrite); - } - - @Override - public void flush() throws IOException { - int readable = buffer.readableBytes(); - if (readable == 0) return; - if (!response.isCommitted()) response.prepareChunkStream(); - ctx.writeAndFlush(new DefaultHttpContent(buffer.copy())); - buffer.clear(); - super.flush(); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/HttpResponse.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/HttpResponse.java deleted file mode 100644 index 888547bf5bd..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/HttpResponse.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.rpc.protocol.rest.netty; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.List; -import java.util.Map; - -public interface HttpResponse { - int getStatus(); - - void setStatus(int status); - - Map> getOutputHeaders(); - - OutputStream getOutputStream() throws IOException; - - void setOutputStream(OutputStream os); - - void sendError(int status) throws IOException; - - void sendError(int status, String message) throws IOException; - - boolean isCommitted(); - - /** - * reset status and headers. Will fail if response is committed - */ - void reset(); - - void flushBuffer() throws IOException; - - void addOutputHeaders(String name, String value); -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/NettyHttpResponse.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/NettyHttpResponse.java deleted file mode 100644 index d29e1941040..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/NettyHttpResponse.java +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.netty; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.metadata.rest.media.MediaType; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.rpc.protocol.rest.RestHeaderEnum; - -import java.io.IOException; -import java.io.OutputStream; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import io.netty.channel.ChannelFuture; -import io.netty.channel.ChannelFutureListener; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.http.DefaultFullHttpResponse; -import io.netty.handler.codec.http.DefaultHttpResponse; -import io.netty.handler.codec.http.HttpHeaders; -import io.netty.handler.codec.http.HttpHeaders.Names; -import io.netty.handler.codec.http.HttpMethod; -import io.netty.handler.codec.http.HttpResponseStatus; -import io.netty.handler.codec.http.LastHttpContent; - -import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; - -/** - * netty http response - */ -public class NettyHttpResponse implements HttpResponse { - private static final int EMPTY_CONTENT_LENGTH = 0; - private int status = 200; - private OutputStream os; - private Map> outputHeaders; - private final ChannelHandlerContext ctx; - private boolean committed; - private boolean keepAlive; - private HttpMethod method; - // raw response body - private Object responseBody; - // raw response class - private Class entityClass; - - public NettyHttpResponse(final ChannelHandlerContext ctx, final boolean keepAlive, URL url) { - this(ctx, keepAlive, null, url); - } - - public NettyHttpResponse(final ChannelHandlerContext ctx, final boolean keepAlive, HttpMethod method, URL url) { - outputHeaders = new HashMap<>(); - this.method = method; - os = new ChunkOutputStream(this, ctx, url.getParameter(Constants.PAYLOAD_KEY, Constants.DEFAULT_PAYLOAD)); - this.ctx = ctx; - this.keepAlive = keepAlive; - } - - public void setOutputStream(OutputStream os) { - this.os = os; - } - - @Override - public int getStatus() { - return status; - } - - @Override - public void setStatus(int status) { - if (status > 200) { - addOutputHeaders(RestHeaderEnum.CONTENT_TYPE.getHeader(), MediaType.TEXT_PLAIN.value); - } - this.status = status; - } - - @Override - public Map> getOutputHeaders() { - return outputHeaders; - } - - @Override - public OutputStream getOutputStream() throws IOException { - return os; - } - - @Override - public void sendError(int status) throws IOException { - sendError(status, null); - } - - @Override - public void sendError(int status, String message) throws IOException { - setStatus(status); - setResponseBody(message); - if (message != null) { - getOutputStream().write(message.getBytes(StandardCharsets.UTF_8)); - } - } - - @Override - public boolean isCommitted() { - return committed; - } - - @Override - public void reset() { - if (committed) { - throw new IllegalStateException("Messages.MESSAGES.alreadyCommitted()"); - } - outputHeaders.clear(); - outputHeaders.clear(); - } - - public boolean isKeepAlive() { - return keepAlive; - } - - public DefaultHttpResponse getDefaultHttpResponse() { - DefaultHttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.valueOf(getStatus())); - transformResponseHeaders(res); - return res; - } - - public DefaultHttpResponse getEmptyHttpResponse() { - DefaultFullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.valueOf(getStatus())); - if (method == null || !method.equals(HttpMethod.HEAD)) { - res.headers().add(Names.CONTENT_LENGTH, EMPTY_CONTENT_LENGTH); - } - transformResponseHeaders(res); - - return res; - } - - private void transformResponseHeaders(io.netty.handler.codec.http.HttpResponse res) { - transformHeaders(this, res); - } - - public void prepareChunkStream() { - committed = true; - DefaultHttpResponse response = getDefaultHttpResponse(); - HttpHeaders.setTransferEncodingChunked(response); - ctx.write(response); - } - - public void finish() throws IOException { - if (os != null) os.flush(); - ChannelFuture future; - if (isCommitted()) { - // if committed this means the output stream was used. - future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); - } else { - future = ctx.writeAndFlush(getEmptyHttpResponse()); - } - - if (!isKeepAlive()) { - future.addListener(ChannelFutureListener.CLOSE); - } - - getOutputStream().close(); - } - - @Override - public void flushBuffer() throws IOException { - if (os != null) os.flush(); - ctx.flush(); - } - - @Override - public void addOutputHeaders(String name, String value) { - - List values = outputHeaders.get(name); - - if (values == null) { - values = new ArrayList<>(); - outputHeaders.put(name, values); - } - - if (values.contains(value)) { - return; - } - - values.add(value); - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - public static void transformHeaders( - NettyHttpResponse nettyResponse, io.netty.handler.codec.http.HttpResponse response) { - // if (nettyResponse.isKeepAlive()) { - // response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); - // } else { - // response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); - // } - - for (Map.Entry> entry : - nettyResponse.getOutputHeaders().entrySet()) { - String key = entry.getKey(); - for (String value : entry.getValue()) { - response.headers().set(key, value); - } - } - } - - public Object getResponseBody() { - return responseBody; - } - - public void setResponseBody(Object responseBody) { - - this.responseBody = responseBody; - - if (responseBody != null) { - this.entityClass = responseBody.getClass(); - } - } - - public Class getEntityClass() { - return entityClass; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/RestHttpRequestDecoder.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/RestHttpRequestDecoder.java deleted file mode 100644 index f89d229d9a6..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/RestHttpRequestDecoder.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.netty; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.threadpool.manager.ExecutorRepository; -import org.apache.dubbo.common.utils.ExecutorUtil; -import org.apache.dubbo.rpc.protocol.rest.RestHeaderEnum; -import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; -import org.apache.dubbo.rpc.protocol.rest.handler.NettyHttpHandler; -import org.apache.dubbo.rpc.protocol.rest.request.NettyRequestFacade; - -import java.io.IOException; -import java.util.List; -import java.util.concurrent.Executor; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.MessageToMessageDecoder; -import io.netty.handler.codec.http.HttpHeaders; - -import static org.apache.dubbo.config.Constants.SERVER_THREAD_POOL_NAME; - -public class RestHttpRequestDecoder extends MessageToMessageDecoder { - private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); - - private final Executor executor; - private final ServiceDeployer serviceDeployer; - private final URL url; - private final NettyHttpHandler nettyHttpHandler; - - public RestHttpRequestDecoder(URL url, ServiceDeployer serviceDeployer) { - - this.url = url; - this.serviceDeployer = serviceDeployer; - executor = ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()) - .createExecutorIfAbsent(ExecutorUtil.setThreadName(url, SERVER_THREAD_POOL_NAME)); - nettyHttpHandler = new NettyHttpHandler(serviceDeployer, url); - } - - @Override - protected void decode( - ChannelHandlerContext ctx, io.netty.handler.codec.http.FullHttpRequest request, List out) - throws Exception { - boolean keepAlive = HttpHeaders.isKeepAlive(request); - - NettyHttpResponse nettyHttpResponse = new NettyHttpResponse(ctx, keepAlive, url); - NettyRequestFacade requestFacade = new NettyRequestFacade(request, ctx, serviceDeployer); - - executor.execute(() -> { - - // business handler - try { - nettyHttpHandler.handle(requestFacade, nettyHttpResponse); - - } catch (IOException e) { - logger.error( - "", e.getCause().getMessage(), "dubbo rest rest http request handler error", e.getMessage(), e); - } finally { - // write response - try { - nettyHttpResponse.addOutputHeaders(RestHeaderEnum.CONNECTION.getHeader(), "close"); - nettyHttpResponse.finish(); - } catch (IOException e) { - logger.error( - "", - e.getCause().getMessage(), - "dubbo rest rest http response flush error", - e.getMessage(), - e); - } - } - }); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/UnSharedHandlerCreator.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/UnSharedHandlerCreator.java deleted file mode 100644 index 98b127c5579..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/UnSharedHandlerCreator.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.netty; - -import org.apache.dubbo.common.URL; - -import java.util.List; - -import io.netty.channel.ChannelHandler; - -/** - * FOR create netty un shared (no @Shared) handler - */ -public interface UnSharedHandlerCreator { - - List getUnSharedHandlers(URL url); -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/ssl/SslContexts.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/ssl/SslContexts.java deleted file mode 100644 index d1c2be29732..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/ssl/SslContexts.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.netty.ssl; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.ssl.AuthPolicy; -import org.apache.dubbo.common.ssl.Cert; -import org.apache.dubbo.common.ssl.CertManager; -import org.apache.dubbo.common.ssl.ProviderCert; - -import javax.net.ssl.SSLException; - -import java.io.IOException; -import java.io.InputStream; -import java.security.Provider; -import java.security.Security; - -import io.netty.handler.ssl.ClientAuth; -import io.netty.handler.ssl.OpenSsl; -import io.netty.handler.ssl.SslContext; -import io.netty.handler.ssl.SslContextBuilder; -import io.netty.handler.ssl.SslProvider; - -import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE_STREAM; - -public class SslContexts { - - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SslContexts.class); - - public static SslContext buildServerSslContext(ProviderCert providerConnectionConfig) { - SslContextBuilder sslClientContextBuilder; - InputStream serverKeyCertChainPathStream = null; - InputStream serverPrivateKeyPathStream = null; - InputStream serverTrustCertStream = null; - try { - serverKeyCertChainPathStream = providerConnectionConfig.getKeyCertChainInputStream(); - serverPrivateKeyPathStream = providerConnectionConfig.getPrivateKeyInputStream(); - serverTrustCertStream = providerConnectionConfig.getTrustCertInputStream(); - String password = providerConnectionConfig.getPassword(); - if (password != null) { - sslClientContextBuilder = - SslContextBuilder.forServer(serverKeyCertChainPathStream, serverPrivateKeyPathStream, password); - } else { - sslClientContextBuilder = - SslContextBuilder.forServer(serverKeyCertChainPathStream, serverPrivateKeyPathStream); - } - - if (serverTrustCertStream != null) { - sslClientContextBuilder.trustManager(serverTrustCertStream); - if (providerConnectionConfig.getAuthPolicy() == AuthPolicy.CLIENT_AUTH) { - sslClientContextBuilder.clientAuth(ClientAuth.REQUIRE); - } else { - sslClientContextBuilder.clientAuth(ClientAuth.OPTIONAL); - } - } - } catch (Exception e) { - throw new IllegalArgumentException("Could not find certificate file or the certificate is invalid.", e); - } finally { - safeCloseStream(serverTrustCertStream); - safeCloseStream(serverKeyCertChainPathStream); - safeCloseStream(serverPrivateKeyPathStream); - } - try { - return sslClientContextBuilder.sslProvider(findSslProvider()).build(); - } catch (SSLException e) { - throw new IllegalStateException("Build SslSession failed.", e); - } - } - - public static SslContext buildClientSslContext(URL url) { - CertManager certManager = - url.getOrDefaultFrameworkModel().getBeanFactory().getBean(CertManager.class); - Cert consumerConnectionConfig = certManager.getConsumerConnectionConfig(url); - if (consumerConnectionConfig == null) { - return null; - } - - SslContextBuilder builder = SslContextBuilder.forClient(); - InputStream clientTrustCertCollectionPath = null; - InputStream clientCertChainFilePath = null; - InputStream clientPrivateKeyFilePath = null; - try { - clientTrustCertCollectionPath = consumerConnectionConfig.getTrustCertInputStream(); - if (clientTrustCertCollectionPath != null) { - builder.trustManager(clientTrustCertCollectionPath); - } - - clientCertChainFilePath = consumerConnectionConfig.getKeyCertChainInputStream(); - clientPrivateKeyFilePath = consumerConnectionConfig.getPrivateKeyInputStream(); - if (clientCertChainFilePath != null && clientPrivateKeyFilePath != null) { - String password = consumerConnectionConfig.getPassword(); - if (password != null) { - builder.keyManager(clientCertChainFilePath, clientPrivateKeyFilePath, password); - } else { - builder.keyManager(clientCertChainFilePath, clientPrivateKeyFilePath); - } - } - } catch (Exception e) { - throw new IllegalArgumentException("Could not find certificate file or find invalid certificate.", e); - } finally { - safeCloseStream(clientTrustCertCollectionPath); - safeCloseStream(clientCertChainFilePath); - safeCloseStream(clientPrivateKeyFilePath); - } - try { - return builder.sslProvider(findSslProvider()).build(); - } catch (SSLException e) { - throw new IllegalStateException("Build SslSession failed.", e); - } - } - - /** - * Returns OpenSSL if available, otherwise returns the JDK provider. - */ - private static SslProvider findSslProvider() { - if (OpenSsl.isAvailable()) { - logger.debug("Using OPENSSL provider."); - return SslProvider.OPENSSL; - } - if (checkJdkProvider()) { - logger.debug("Using JDK provider."); - return SslProvider.JDK; - } - throw new IllegalStateException( - "Could not find any valid TLS provider, please check your dependency or deployment environment, " - + "usually netty-tcnative, Conscrypt, or Jetty NPN/ALPN is needed."); - } - - private static boolean checkJdkProvider() { - Provider[] jdkProviders = Security.getProviders("SSLContext.TLS"); - return (jdkProviders != null && jdkProviders.length > 0); - } - - private static void safeCloseStream(InputStream stream) { - if (stream == null) { - return; - } - try { - stream.close(); - } catch (IOException e) { - logger.warn(TRANSPORT_FAILED_CLOSE_STREAM, "", "", "Failed to close a stream.", e); - } - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/ssl/SslServerTlsHandler.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/ssl/SslServerTlsHandler.java deleted file mode 100644 index 93a87baf782..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/ssl/SslServerTlsHandler.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.rpc.protocol.rest.netty.ssl; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.ssl.AuthPolicy; -import org.apache.dubbo.common.ssl.CertManager; -import org.apache.dubbo.common.ssl.ProviderCert; - -import javax.net.ssl.SSLSession; - -import java.util.List; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelPipeline; -import io.netty.handler.codec.ByteToMessageDecoder; -import io.netty.handler.ssl.SslContext; -import io.netty.handler.ssl.SslHandler; -import io.netty.handler.ssl.SslHandshakeCompletionEvent; - -import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; - -public class SslServerTlsHandler extends ByteToMessageDecoder { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SslServerTlsHandler.class); - - private final URL url; - - private final boolean sslDetected; - - public SslServerTlsHandler(URL url) { - this.url = url; - this.sslDetected = false; - } - - public SslServerTlsHandler(URL url, boolean sslDetected) { - this.url = url; - this.sslDetected = sslDetected; - } - - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - logger.error( - INTERNAL_ERROR, - "unknown error in remoting module", - "", - "TLS negotiation failed when trying to accept new connection.", - cause); - } - - @Override - public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { - if (evt instanceof SslHandshakeCompletionEvent) { - SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt; - if (handshakeEvent.isSuccess()) { - SSLSession session = - ctx.pipeline().get(SslHandler.class).engine().getSession(); - logger.info("TLS negotiation succeed with: " + session.getPeerHost()); - // Remove after handshake success. - ctx.pipeline().remove(this); - } else { - logger.error( - INTERNAL_ERROR, - "", - "", - "TLS negotiation failed when trying to accept new connection.", - handshakeEvent.cause()); - ctx.close(); - } - } - super.userEventTriggered(ctx, evt); - } - - @Override - protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List list) - throws Exception { - // Will use the first five bytes to detect a protocol. - if (byteBuf.readableBytes() < 5) { - return; - } - - if (sslDetected) { - return; - } - - CertManager certManager = - url.getOrDefaultFrameworkModel().getBeanFactory().getBean(CertManager.class); - ProviderCert providerConnectionConfig = certManager.getProviderConnectionConfig( - url, channelHandlerContext.channel().remoteAddress()); - - if (providerConnectionConfig == null) { - channelHandlerContext.pipeline().remove(this); - return; - } - - if (isSsl(byteBuf)) { - SslContext sslContext = SslContexts.buildServerSslContext(providerConnectionConfig); - enableSsl(channelHandlerContext, sslContext); - return; - } - - if (providerConnectionConfig.getAuthPolicy() == AuthPolicy.NONE) { - channelHandlerContext.pipeline().remove(this); - return; - } - - logger.error(INTERNAL_ERROR, "", "", "TLS negotiation failed when trying to accept new connection."); - channelHandlerContext.close(); - } - - private boolean isSsl(ByteBuf buf) { - return SslHandler.isEncrypted(buf); - } - - private void enableSsl(ChannelHandlerContext ctx, SslContext sslContext) { - ChannelPipeline p = ctx.pipeline(); - ctx.pipeline().addAfter(ctx.name(), null, sslContext.newHandler(ctx.alloc())); - p.addLast("unificationA", new SslServerTlsHandler(url, true)); - p.remove(this); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pair/InvokerAndRestMethodMetadataPair.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pair/InvokerAndRestMethodMetadataPair.java deleted file mode 100644 index 2b11f75a16b..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pair/InvokerAndRestMethodMetadataPair.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.rpc.protocol.rest.pair; - -import org.apache.dubbo.metadata.rest.RestMethodMetadata; -import org.apache.dubbo.rpc.Invoker; - -import java.lang.reflect.Method; -import java.util.Arrays; - -/** - * for invoker & restMethodMetadata pair - */ -public class InvokerAndRestMethodMetadataPair { - - Invoker invoker; - RestMethodMetadata restMethodMetadata; - - public InvokerAndRestMethodMetadataPair(Invoker invoker, RestMethodMetadata restMethodMetadata) { - this.invoker = invoker; - this.restMethodMetadata = restMethodMetadata; - } - - public Invoker getInvoker() { - return invoker; - } - - public RestMethodMetadata getRestMethodMetadata() { - return restMethodMetadata; - } - - public static InvokerAndRestMethodMetadataPair pair(Invoker invoker, RestMethodMetadata restMethodMetadata) { - return new InvokerAndRestMethodMetadataPair(invoker, restMethodMetadata); - } - - /** - * same interface & same method desc - * - * @param beforeMetadata - * @return - */ - public boolean compareServiceMethod(InvokerAndRestMethodMetadataPair beforeMetadata) { - - Class currentServiceInterface = this.invoker.getInterface(); - Class beforeServiceInterface = beforeMetadata.getInvoker().getInterface(); - - if (!currentServiceInterface.equals(beforeServiceInterface)) { - return false; - } - - Method beforeServiceMethod = beforeMetadata.getRestMethodMetadata().getReflectMethod(); - - Method currentReflectMethod = this.restMethodMetadata.getReflectMethod(); - - if (beforeServiceMethod.getName().equals(currentReflectMethod.getName()) // method name - // method param types - && Arrays.toString(beforeServiceMethod.getParameterTypes()) - .equals(Arrays.toString(currentReflectMethod.getParameterTypes()))) { - return true; - } - - return false; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pair/MessageCodecResultPair.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pair/MessageCodecResultPair.java deleted file mode 100644 index 9f1deeaac69..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pair/MessageCodecResultPair.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.pair; - -import org.apache.dubbo.metadata.rest.media.MediaType; - -/** - * for http message codec result - */ -public class MessageCodecResultPair { - /** - * has coded - */ - boolean coded; - - /** - * codec type - */ - MediaType mediaType; - - public MessageCodecResultPair(boolean coded, MediaType mediaType) { - this.coded = coded; - this.mediaType = mediaType; - } - - public boolean isCoded() { - return coded; - } - - public MediaType getMediaType() { - return mediaType; - } - - public static MessageCodecResultPair pair(boolean coded, MediaType mediaType) { - return new MessageCodecResultPair(coded, mediaType); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pu/RestHttp1Detector.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pu/RestHttp1Detector.java deleted file mode 100644 index 3e083e14cd6..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pu/RestHttp1Detector.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.pu; - -import org.apache.dubbo.remoting.api.AbstractHttpProtocolDetector; -import org.apache.dubbo.remoting.buffer.ChannelBuffer; -import org.apache.dubbo.rpc.model.FrameworkModel; - -/** - * rest http protocol detector - */ -public class RestHttp1Detector extends AbstractHttpProtocolDetector { - private static final char[][] HTTP_METHODS_PREFIX = getHttpMethodsPrefix(); - - private FrameworkModel frameworkModel; - - public RestHttp1Detector(FrameworkModel frameworkModel) { - this.frameworkModel = frameworkModel; - } - - @Override - public Result detect(ChannelBuffer in) { - - int i = in.readableBytes(); - - // length judge - if (i < SIMPLE_HTTP.length()) { - return Result.unrecognized(); - } - - if (prefixMatch(HTTP_METHODS_PREFIX, in, 3)) { - return Result.recognized(); - } - - return Result.unrecognized(); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pu/RestHttp1WireProtocol.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pu/RestHttp1WireProtocol.java deleted file mode 100644 index 6d661cdba36..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pu/RestHttp1WireProtocol.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.pu; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.remoting.ChannelHandler; -import org.apache.dubbo.remoting.api.AbstractWireProtocol; -import org.apache.dubbo.remoting.api.pu.ChannelHandlerPretender; -import org.apache.dubbo.remoting.api.pu.ChannelOperator; -import org.apache.dubbo.rpc.model.FrameworkModel; -import org.apache.dubbo.rpc.model.ScopeModelAware; -import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; -import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; -import org.apache.dubbo.rpc.protocol.rest.netty.RestHttpRequestDecoder; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import io.netty.handler.codec.http.HttpObjectAggregator; -import io.netty.handler.codec.http.HttpRequestDecoder; -import io.netty.handler.codec.http.HttpResponseEncoder; - -import static org.apache.dubbo.common.constants.CommonConstants.REST_SERVICE_DEPLOYER_URL_ATTRIBUTE_KEY; - -@Activate(order = Integer.MAX_VALUE) -public class RestHttp1WireProtocol extends AbstractWireProtocol implements ScopeModelAware { - - private static final ServiceDeployer emptyServiceDeployer = new ServiceDeployer(); - - public RestHttp1WireProtocol(FrameworkModel frameworkModel) { - super(new RestHttp1Detector(frameworkModel)); - } - - @Override - public void configServerProtocolHandler(URL url, ChannelOperator operator) { - - // h1 upgrade to don`t response 101 ,cause there is no h1 stream handler - // TODO add h1 stream handler - - // pathAndInvokerMapper, exceptionMapper getFrom url - ServiceDeployer serviceDeployer = (ServiceDeployer) url.getAttribute(REST_SERVICE_DEPLOYER_URL_ATTRIBUTE_KEY); - - // maybe current request is qos http or no rest service export - if (serviceDeployer == null) { - serviceDeployer = emptyServiceDeployer; - } - - List channelHandlers = Arrays.asList( - new HttpRequestDecoder( - url.getParameter( - RestConstant.MAX_INITIAL_LINE_LENGTH_PARAM, RestConstant.MAX_INITIAL_LINE_LENGTH), - url.getParameter(RestConstant.MAX_HEADER_SIZE_PARAM, RestConstant.MAX_HEADER_SIZE), - url.getParameter(RestConstant.MAX_CHUNK_SIZE_PARAM, RestConstant.MAX_CHUNK_SIZE)), - new HttpObjectAggregator( - url.getParameter(RestConstant.MAX_REQUEST_SIZE_PARAM, RestConstant.MAX_REQUEST_SIZE)), - new HttpResponseEncoder(), - new RestHttpRequestDecoder(url, serviceDeployer)); - - List handlers = new ArrayList<>(); - handlers.add(new ChannelHandlerPretender(channelHandlers)); - operator.configChannelHandler(handlers); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/request/NettyRequestFacade.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/request/NettyRequestFacade.java deleted file mode 100644 index 3fba2d33a42..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/request/NettyRequestFacade.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.request; - -import org.apache.dubbo.common.utils.IOUtils; -import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; - -import io.netty.buffer.ByteBuf; -import io.netty.buffer.ByteBufInputStream; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.socket.nio.NioSocketChannel; -import io.netty.handler.codec.http.FullHttpRequest; -import io.netty.handler.codec.http.HttpContent; - -/** - * netty request facade - */ -public class NettyRequestFacade extends RequestFacade { - - private ChannelHandlerContext context; - - public NettyRequestFacade(Object request, ChannelHandlerContext context) { - super((FullHttpRequest) request); - this.context = context; - } - - public NettyRequestFacade(Object request, ChannelHandlerContext context, ServiceDeployer serviceDeployer) { - super((FullHttpRequest) request, serviceDeployer); - this.context = context; - } - - protected void initHeaders() { - for (Map.Entry header : request.headers()) { - - String key = header.getKey(); - - ArrayList tmpHeaders = headers.get(key); - - if (tmpHeaders == null) { - tmpHeaders = new ArrayList<>(); - headers.put(key, tmpHeaders); - } - - tmpHeaders.add(header.getValue()); - } - } - - @Override - public String getHeader(String name) { - - List values = headers.get(name); - - if (values == null && name != null) { - values = headers.get(name.toLowerCase()); - } - - if (values == null || values.isEmpty()) { - return null; - } else { - return values.get(0); - } - } - - @Override - public Enumeration getHeaders(String name) { - - List list = headers.get(name); - - if (list == null) { - list = new ArrayList<>(); - } - - ListIterator stringListIterator = list.listIterator(); - - return new Enumeration() { - @Override - public boolean hasMoreElements() { - return stringListIterator.hasNext(); - } - - @Override - public String nextElement() { - return stringListIterator.next(); - } - }; - } - - @Override - public Enumeration getHeaderNames() { - - Iterator strings = headers.keySet().iterator(); - - return new Enumeration() { - @Override - public boolean hasMoreElements() { - return strings.hasNext(); - } - - @Override - public String nextElement() { - return strings.next(); - } - }; - } - - @Override - public String getMethod() { - return request.method().name(); - } - - @Override - public String getPath() { - return path; - } - - @Override - public String getContextPath() { - // TODO add ContextPath - return null; - } - - @Override - public String getRequestURI() { - return request.uri(); - } - - @Override - public String getParameter(String name) { - ArrayList strings = parameters.get(name); - - String value = null; - if (strings != null && !strings.isEmpty()) { - value = strings.get(0); - } - return value; - } - - @Override - public Enumeration getParameterNames() { - - Iterator iterator = parameters.keySet().iterator(); - - return new Enumeration() { - @Override - public boolean hasMoreElements() { - return iterator.hasNext(); - } - - @Override - public String nextElement() { - return iterator.next(); - } - }; - } - - @Override - public String[] getParameterValues(String name) { - - if (!parameters.containsKey(name)) { - - return null; - } - return parameters.get(name).toArray(new String[0]); - } - - @Override - public Map getParameterMap() { - HashMap map = new HashMap<>(); - parameters.entrySet().forEach(entry -> { - map.put(entry.getKey(), entry.getValue().toArray(new String[0])); - }); - return map; - } - - @Override - public String getRemoteAddr() { - return getChannel().remoteAddress().getHostString(); - } - - @Override - public String getRemoteHost() { - return getRemoteAddr() + ":" + getRemotePort(); - } - - @Override - public int getRemotePort() { - return getChannel().remoteAddress().getPort(); - } - - @Override - public String getLocalAddr() { - return getChannel().localAddress().getHostString(); - } - - @Override - public String getLocalHost() { - return getRemoteAddr() + ":" + getLocalPort(); - } - - private NioSocketChannel getChannel() { - return (NioSocketChannel) context.channel(); - } - - @Override - public int getLocalPort() { - return getChannel().localAddress().getPort(); - } - - @Override - public byte[] getInputStream() throws IOException { - - return body; - } - - protected void parseBody() { - ByteBuf byteBuf = ((HttpContent) request).content(); - - if (byteBuf.readableBytes() > 0) { - - try { - body = IOUtils.toByteArray(new ByteBufInputStream(byteBuf)); - } catch (IOException e) { - - } - } - } - - public ChannelHandlerContext getNettyChannelContext() { - return context; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/request/RequestFacade.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/request/RequestFacade.java deleted file mode 100644 index c3c4ac5bb8a..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/request/RequestFacade.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.request; - -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; -import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; -import org.apache.dubbo.rpc.protocol.rest.util.DataParseUtils; - -import java.io.IOException; -import java.net.URLDecoder; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; - -import static org.apache.dubbo.rpc.protocol.rest.constans.RestConstant.DEFAULT_CHARSET; - -/** - * request facade for different request - * - * @param - */ -public abstract class RequestFacade { - protected Map> headers = new HashMap<>(); - protected Map> parameters = new HashMap<>(); - - protected String path; - protected T request; - protected byte[] body = new byte[0]; - protected ServiceDeployer serviceDeployer; - - public RequestFacade(T request) { - this.request = request; - initHeaders(); - initParameters(); - parseBody(); - } - - public RequestFacade(T request, ServiceDeployer serviceDeployer) { - this(request); - this.serviceDeployer = serviceDeployer; - } - - protected void initHeaders() {} - - protected void initParameters() { - String requestURI = getRequestURI(); - String decodedRequestURI = null; - - try { - String enc = DEFAULT_CHARSET; - ArrayList charset = headers.get(RestConstant.ACCEPT_CHARSET); - // take the highest priority charset - String[] parsed = DataParseUtils.parseAcceptCharset(charset); - if (parsed != null && parsed.length > 0) { - enc = parsed[0].toUpperCase(); - } - decodedRequestURI = URLDecoder.decode(requestURI, enc); - } catch (Throwable t) { - // do nothing, try best to deliver - } - - if (StringUtils.isNotEmpty(decodedRequestURI)) { - requestURI = decodedRequestURI; - } - - if (requestURI != null && requestURI.contains("?")) { - - String queryString = requestURI.substring(requestURI.indexOf("?") + 1); - path = requestURI.substring(0, requestURI.indexOf("?")); - - String[] split = queryString.split("&"); - - for (String params : split) { - // key a= ;value b==c - int index = params.indexOf("="); - if (index <= 0) { - continue; - } - - String name = params.substring(0, index); - String value = params.substring(index + 1); - if (!StringUtils.isEmpty(name)) { - ArrayList values = parameters.get(name); - - if (values == null) { - values = new ArrayList<>(); - parameters.put(name, values); - } - values.add(value); - } - } - } else { - path = requestURI; - } - } - - public T getRequest() { - return request; - } - - public abstract String getHeader(String name); - - public abstract Enumeration getHeaders(String name); - - public abstract Enumeration getHeaderNames(); - - public abstract String getMethod(); - - public abstract String getPath(); - - public abstract String getContextPath(); - - public abstract String getRequestURI(); - - public abstract String getParameter(String name); - - public abstract Enumeration getParameterNames(); - - public abstract String[] getParameterValues(String name); - - public abstract Map getParameterMap(); - - public abstract String getRemoteAddr(); - - public abstract String getRemoteHost(); - - public abstract int getRemotePort(); - - public abstract String getLocalAddr(); - - public abstract String getLocalHost(); - - public abstract int getLocalPort(); - - public abstract byte[] getInputStream() throws IOException; - - protected abstract void parseBody(); - - public ServiceDeployer getServiceDeployer() { - return serviceDeployer; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/support/ContentType.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/support/ContentType.java deleted file mode 100644 index 8e586b5e159..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/support/ContentType.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.support; - -import javax.ws.rs.core.MediaType; - -public class ContentType { - - public static final String APPLICATION_JSON_UTF_8 = - MediaType.APPLICATION_JSON + "; " + MediaType.CHARSET_PARAMETER + "=UTF-8"; - public static final String TEXT_XML_UTF_8 = MediaType.TEXT_XML + "; " + MediaType.CHARSET_PARAMETER + "=UTF-8"; - public static final String TEXT_PLAIN_UTF_8 = MediaType.TEXT_PLAIN + "; " + MediaType.CHARSET_PARAMETER + "=UTF-8"; -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/ConstraintViolationExceptionConvert.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/ConstraintViolationExceptionConvert.java deleted file mode 100644 index 0663703e699..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/ConstraintViolationExceptionConvert.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.util; - -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.protocol.rest.RestConstraintViolation; -import org.apache.dubbo.rpc.protocol.rest.ViolationReport; - -import javax.validation.ConstraintViolation; -import javax.validation.ConstraintViolationException; - -public class ConstraintViolationExceptionConvert { - - public static Object handleConstraintViolationException(RpcException rpcException) { - ConstraintViolationException cve = (ConstraintViolationException) rpcException.getCause(); - ViolationReport report = new ViolationReport(); - for (ConstraintViolation cv : cve.getConstraintViolations()) { - report.addConstraintViolation(new RestConstraintViolation( - cv.getPropertyPath().toString(), - cv.getMessage(), - cv.getInvalidValue() == null ? "null" : cv.getInvalidValue().toString())); - } - return report; - } - - public static boolean needConvert(RpcException e) { - return isConstraintViolationException(e); - } - - private static boolean isConstraintViolationException(RpcException e) { - try { - return e.getCause() instanceof ConstraintViolationException; - } catch (Throwable throwable) { - return false; - } - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/DataParseUtils.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/DataParseUtils.java deleted file mode 100644 index 489d99b9053..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/DataParseUtils.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.util; - -import org.apache.dubbo.common.lang.Nullable; -import org.apache.dubbo.common.utils.CollectionUtils; -import org.apache.dubbo.common.utils.JsonUtils; -import org.apache.dubbo.common.utils.StringUtils; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Type; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Comparator; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.StringTokenizer; -import java.util.TreeMap; - -import static org.apache.dubbo.rpc.protocol.rest.constans.RestConstant.WEIGHT_IDENTIFIER; - -public class DataParseUtils { - - public static Object stringTypeConvert(Class targetType, String value) { - - if (StringUtils.isEmpty(value)) { - return null; - } - - if (targetType == Boolean.class || targetType == boolean.class) { - return Boolean.valueOf(value); - } - - if (targetType == String.class) { - return value; - } - - if (Number.class.isAssignableFrom(targetType)) { - return NumberUtils.parseNumber(value, targetType); - } - - if (targetType != null && targetType.isPrimitive()) { - return NumberUtils.parseNumber(value, targetType); - } - - return value; - } - - public static boolean isTextType(Class targetType) { - if (targetType == null) { - return false; - } - - return targetType == Boolean.class - || targetType == boolean.class - || targetType == String.class - || Number.class.isAssignableFrom(targetType) - || targetType.isPrimitive(); - } - - /** - * content-type text - * - * @param object - * @param outputStream - * @throws IOException - */ - public static void writeTextContent(Object object, OutputStream outputStream) throws IOException { - outputStream.write(objectTextConvertToByteArray(object)); - } - - /** - * content-type json - * - * @param object - * @param outputStream - * @throws Exception - */ - public static void writeJsonContent(Object object, OutputStream outputStream) throws Exception { - outputStream.write(JsonUtils.toJson(object).getBytes(StandardCharsets.UTF_8)); - } - - /** - * content-type form - * - * @param formData - * @param outputStream - * @throws Exception - */ - public static void writeFormContent(Map formData, OutputStream outputStream) throws Exception { - outputStream.write(serializeForm(formData, Charset.defaultCharset()).getBytes()); - } - - // TODO file multipart - - public static String serializeForm(Map formData, Charset charset) { - StringBuilder builder = new StringBuilder(); - formData.forEach((name, values) -> { - if (name == null) { - - return; - } - ((List) values).forEach(value -> { - try { - if (builder.length() != 0) { - builder.append('&'); - } - builder.append(URLEncoder.encode((String) name, charset.name())); - if (value != null) { - builder.append('='); - builder.append(URLEncoder.encode(String.valueOf(value), charset.name())); - } - } catch (UnsupportedEncodingException ex) { - throw new IllegalStateException(ex); - } - }); - }); - - return builder.toString(); - } - - public static byte[] objectTextConvertToByteArray(Object object) { - Class objectClass = object.getClass(); - - if (objectClass == Boolean.class || objectClass == boolean.class) { - return object.toString().getBytes(); - } - - if (objectClass == String.class) { - return ((String) object).getBytes(); - } - - if (objectClass.isAssignableFrom(Number.class) || objectClass.isPrimitive()) { - return (byte[]) NumberUtils.numberToBytes((Number) object); - } - - return object.toString().getBytes(); - } - - public static Object jsonConvert(Type targetType, byte[] body) throws Exception { - return JsonUtils.toJavaObject(new String(body, StandardCharsets.UTF_8), targetType); - } - - public static Object multipartFormConvert(byte[] body, Charset charset, Class targetType) throws Exception { - String[] pairs = tokenizeToStringArray(new String(body, StandardCharsets.UTF_8), "&"); - Object result = MultiValueCreator.providerCreateMultiValueMap(targetType); - for (String pair : pairs) { - int idx = pair.indexOf('='); - if (idx == -1) { - MultiValueCreator.add(result, URLDecoder.decode(pair, charset.name()), null); - } else { - String name = URLDecoder.decode(pair.substring(0, idx), charset.name()); - String value = URLDecoder.decode(pair.substring(idx + 1), charset.name()); - MultiValueCreator.add(result, name, value); - } - } - - return result; - } - - public static Object multipartFormConvert(byte[] body, Class targetType) throws Exception { - return multipartFormConvert(body, Charset.defaultCharset(), targetType); - } - - public static String[] tokenizeToStringArray(String str, String delimiters) { - return tokenizeToStringArray(str, delimiters, true, true); - } - - public static String[] tokenizeToStringArray( - String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) { - if (str == null) { - return null; - } else { - StringTokenizer st = new StringTokenizer(str, delimiters); - ArrayList tokens = new ArrayList(); - - while (true) { - String token; - do { - if (!st.hasMoreTokens()) { - return toStringArray(tokens); - } - - token = st.nextToken(); - if (trimTokens) { - token = token.trim(); - } - } while (ignoreEmptyTokens && token.length() <= 0); - - tokens.add(token); - } - } - } - - public static String[] toStringArray(Collection collection) { - return collection == null ? null : collection.toArray(new String[collection.size()]); - } - - @Nullable - public static String[] parseAcceptCharset(List acceptCharsets) { - if (CollectionUtils.isEmpty(acceptCharsets)) { - return new String[0]; - } - - SortedMap> encodings = new TreeMap<>(Comparator.reverseOrder()); - float defaultWeight = 1.0f; - for (String acceptCharset : acceptCharsets) { - String[] charsets = acceptCharset.split(","); - for (String charset : charsets) { - charset = charset.trim(); - float weight = defaultWeight; - String enc = charset; - if (charset.contains(WEIGHT_IDENTIFIER)) { - String[] split = charset.split(WEIGHT_IDENTIFIER); - enc = split[0]; - weight = Float.parseFloat(split[1]); - } - encodings.computeIfAbsent(weight, k -> new HashSet<>()).add(enc); - } - } - - List result = new ArrayList<>(); - encodings.values().forEach(result::addAll); - return result.toArray(new String[0]); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/HttpHeaderUtil.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/HttpHeaderUtil.java deleted file mode 100644 index 5388e7b27ed..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/HttpHeaderUtil.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.util; - -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.remoting.http.RequestTemplate; -import org.apache.dubbo.remoting.http.RestResult; -import org.apache.dubbo.rpc.AppResponse; -import org.apache.dubbo.rpc.RpcContext; -import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.protocol.rest.RestHeaderEnum; -import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; -import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; -import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; - -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class HttpHeaderUtil { - - /** - * convert attachment to Map> - * - * @param attachmentMap - * @return - */ - public static Map> createAttachments(Map attachmentMap) { - Map> attachments = new HashMap<>(); - int size = 0; - for (Map.Entry entry : attachmentMap.entrySet()) { - String key = entry.getKey(); - String value = String.valueOf(entry.getValue()); - - if (value != null) { - size += value.getBytes(StandardCharsets.UTF_8).length; - } - - List strings = attachments.get(key); - if (strings == null) { - strings = new ArrayList<>(); - attachments.put(key, strings); - } - strings.add(value); - } - - return attachments; - } - - /** - * add consumer attachment to request - * - * @param requestTemplate - * @param attachmentMap - */ - public static void addRequestAttachments(RequestTemplate requestTemplate, Map attachmentMap) { - Map> attachments = createAttachments(attachmentMap); - - attachments.entrySet().forEach(attachment -> { - requestTemplate.addHeaders(appendPrefixToAttachRealHeader(attachment.getKey()), attachment.getValue()); - }); - } - - /** - * add provider attachment to response - * - * @param nettyHttpResponse - */ - public static void addResponseAttachments(NettyHttpResponse nettyHttpResponse) { - Map> attachments = - createAttachments(RpcContext.getServerContext().getObjectAttachments()); - - attachments.entrySet().stream().forEach(attachment -> { - nettyHttpResponse - .getOutputHeaders() - .put(appendPrefixToAttachRealHeader(attachment.getKey()), attachment.getValue()); - }); - } - - /** - * parse rest request header attachment & header - * - * @param rpcInvocation - * @param requestFacade - */ - public static void parseRequestHeader(RpcInvocation rpcInvocation, RequestFacade requestFacade) { - - Enumeration headerNames = requestFacade.getHeaderNames(); - - while (headerNames.hasMoreElements()) { - String header = headerNames.nextElement(); - - if (!isRestAttachHeader(header)) { - // attribute - rpcInvocation.put(header, requestFacade.getHeader(header)); - continue; - } - - // attachment - rpcInvocation.setAttachment(subRestAttachRealHeaderPrefix(header.trim()), requestFacade.getHeader(header)); - } - } - - /** - * for judge rest header or rest attachment - * - * @param header - * @return - */ - public static boolean isRestAttachHeader(String header) { - - if (StringUtils.isEmpty(header) || !header.startsWith(RestHeaderEnum.REST_HEADER_PREFIX.getHeader())) { - return false; - } - - return true; - } - - /** - * for substring attachment prefix - * - * @param header - * @return - */ - public static String subRestAttachRealHeaderPrefix(String header) { - - return header.substring(RestHeaderEnum.REST_HEADER_PREFIX.getHeader().length()); - } - - /** - * append prefix to rest header distinguish from normal header - * - * @param header - * @return - */ - public static String appendPrefixToAttachRealHeader(String header) { - - return RestHeaderEnum.REST_HEADER_PREFIX.getHeader() + header; - } - - /** - * parse request attribute - * @param rpcInvocation - * @param request - */ - public static void parseRequestAttribute(RpcInvocation rpcInvocation, RequestFacade request) { - int localPort = request.getLocalPort(); - String localAddr = request.getLocalAddr(); - int remotePort = request.getRemotePort(); - String remoteAddr = request.getRemoteAddr(); - - rpcInvocation.put(RestConstant.REMOTE_ADDR, remoteAddr); - rpcInvocation.put(RestConstant.LOCAL_ADDR, localAddr); - rpcInvocation.put(RestConstant.REMOTE_PORT, remotePort); - rpcInvocation.put(RestConstant.LOCAL_PORT, localPort); - } - - /** - * parse request - * @param rpcInvocation - * @param request - */ - public static void parseRequest(RpcInvocation rpcInvocation, RequestFacade request) { - parseRequestHeader(rpcInvocation, request); - parseRequestAttribute(rpcInvocation, request); - } - - /** - * parse rest response header to appResponse attribute & attachment - * @param appResponse - * @param restResult - */ - public static void parseResponseHeader(AppResponse appResponse, RestResult restResult) { - - Map> headers = restResult.headers(); - if (headers == null || headers.isEmpty()) { - return; - } - - headers.entrySet().stream().forEach(entry -> { - String header = entry.getKey(); - if (isRestAttachHeader(header)) { - // attachment - appResponse.setAttachment(subRestAttachRealHeaderPrefix(header), entry.getValue()); - } else { - // attribute - appResponse.setAttribute(header, entry.getValue()); - } - }); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/MediaTypeUtil.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/MediaTypeUtil.java deleted file mode 100644 index 57093dc2e55..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/MediaTypeUtil.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.util; - -import org.apache.dubbo.metadata.rest.media.MediaType; -import org.apache.dubbo.rpc.protocol.rest.exception.UnSupportContentTypeException; -import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodecManager; - -import java.util.Arrays; -import java.util.List; - -public class MediaTypeUtil { - - private static final List mediaTypes = MediaType.getSupportMediaTypes(); - - /** - * return first match , if any multiple content-type ,acquire mediaType by targetClass type .if contentTypes is empty - * - * @param contentTypes - * @return - */ - public static MediaType convertMediaType(Class targetType, String... contentTypes) { - - if (contentTypes == null || contentTypes.length == 0) { - return HttpMessageCodecManager.typeSupport(targetType); - } - - for (String contentType : contentTypes) { - for (MediaType mediaType : mediaTypes) { - - if (contentType != null && contentType.contains(mediaType.value)) { - return mediaType; - } - } - - if (contentType != null && contentType.contains(MediaType.ALL_VALUE.value)) { - return HttpMessageCodecManager.typeSupport(targetType); - } - } - - throw new UnSupportContentTypeException(Arrays.toString(contentTypes)); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/MultiValueCreator.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/MultiValueCreator.java deleted file mode 100644 index 31e9112ff2b..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/MultiValueCreator.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.util; - -import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; -import org.apache.dubbo.common.logger.LoggerFactory; - -import java.lang.reflect.Method; -import java.util.Map; - -public class MultiValueCreator { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MultiValueCreator.class); - - private static final String SPRING_MultiValueMapImpl = "org.springframework.util.LinkedMultiValueMap"; - private static final String SPRING_MultiValueMap = "org.springframework.util.MultiValueMap"; - private static final String JAVAX_MultiValueMapImpl = "org.jboss.resteasy.specimpl.MultivaluedMapImpl"; - private static final String JAVAX_MultiValueMap = "javax.ws.rs.core.MultivaluedMap"; - - private static Class springMultiValueMapImplClass = null; - private static Class springMultiValueMapClass = null; - private static Method springMultiValueMapAdd = null; - - private static Class jaxrsMultiValueMapImplClass = null; - private static Class jaxrsMultiValueMapClass = null; - - private static Method jaxrsMultiValueMapAdd = null; - - static { - springMultiValueMapClass = ReflectUtils.findClassTryException(SPRING_MultiValueMap); - springMultiValueMapImplClass = ReflectUtils.findClassTryException(SPRING_MultiValueMapImpl); - springMultiValueMapAdd = ReflectUtils.getMethodByName(springMultiValueMapImplClass, "add"); - - jaxrsMultiValueMapClass = ReflectUtils.findClassTryException(JAVAX_MultiValueMap); - jaxrsMultiValueMapImplClass = ReflectUtils.findClassTryException(JAVAX_MultiValueMapImpl); - jaxrsMultiValueMapAdd = ReflectUtils.getMethodByName(jaxrsMultiValueMapImplClass, "add"); - } - - public static Object providerCreateMultiValueMap(Class targetType) { - try { - if (typeJudge(springMultiValueMapClass, targetType)) { - return springMultiValueMapImplClass.getDeclaredConstructor().newInstance(); - } else if (typeJudge(jaxrsMultiValueMapClass, targetType)) { - return jaxrsMultiValueMapImplClass.getDeclaredConstructor().newInstance(); - } - } catch (Exception e) { - logger.error( - "", - e.getMessage(), - "current param type is: " + targetType + "and support type is : " + springMultiValueMapClass + "or" - + jaxrsMultiValueMapClass, - "dubbo rest form content-type param construct error,un support param type: ", - e); - } - - return null; - } - - private static boolean typeJudge(Class parent, Class targetType) { - if (parent == null) { - return false; - } - - if (!Map.class.isAssignableFrom(targetType)) { - return true; - } - - return parent.isAssignableFrom(targetType) || parent.equals(targetType); - } - - public static void add(Object multiValueMap, String key, Object value) { - try { - if (multiValueMap == null) { - return; - } - - Method multiValueMapAdd = null; - if (springMultiValueMapImplClass.equals(multiValueMap.getClass())) { - multiValueMapAdd = springMultiValueMapAdd; - } else if (jaxrsMultiValueMapImplClass.equals(multiValueMap.getClass())) { - multiValueMapAdd = jaxrsMultiValueMapAdd; - } - - ReflectUtils.invokeAndTryCatch(multiValueMap, multiValueMapAdd, new Object[] {key, value}); - } catch (Exception e) { - logger.error("", e.getMessage(), "", "dubbo rest form content-type param add data error: ", e); - } - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/NoAnnotationBodyParseUtil.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/NoAnnotationBodyParseUtil.java deleted file mode 100644 index 02461cc0d7b..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/NoAnnotationBodyParseUtil.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.util; - -import org.apache.dubbo.metadata.rest.media.MediaType; -import org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider.ProviderParseContext; -import org.apache.dubbo.rpc.protocol.rest.exception.ParamParseException; -import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodecManager; -import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; - -public class NoAnnotationBodyParseUtil { - - public static Object[] doParse(ProviderParseContext parseContext) { - RequestFacade request = parseContext.getRequestFacade(); - try { - Class objectArraysType = Object[].class; - MediaType mediaType = - MediaTypeUtil.convertMediaType(objectArraysType, MediaType.APPLICATION_JSON_VALUE.value); - Object[] params = (Object[]) HttpMessageCodecManager.httpMessageDecode( - request.getInputStream(), objectArraysType, objectArraysType, mediaType); - return params; - } catch (Throwable e) { - throw new ParamParseException("dubbo rest protocol provider body param parser error: " + e.getMessage()); - } - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/NumberUtils.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/NumberUtils.java deleted file mode 100644 index d59680fdd03..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/NumberUtils.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.util; - -import org.apache.dubbo.common.utils.Assert; -import org.apache.dubbo.common.utils.StringUtils; - -import java.math.BigDecimal; -import java.math.BigInteger; - -public class NumberUtils { - - public static T parseNumber(String text, Class targetClass) { - Assert.notNull(text, "Text must not be null"); - Assert.notNull(targetClass, "Target class must not be null"); - String trimmed = trimAllWhitespace(text); - - if (Byte.class == targetClass || byte.class == targetClass) { - return (T) (isHexNumber(trimmed) ? Byte.decode(trimmed) : Byte.valueOf(trimmed)); - } else if (Short.class == targetClass || short.class == targetClass) { - return (T) (isHexNumber(trimmed) ? Short.decode(trimmed) : Short.valueOf(trimmed)); - } else if (Integer.class == targetClass || int.class == targetClass) { - return (T) (isHexNumber(trimmed) ? Integer.decode(trimmed) : Integer.valueOf(trimmed)); - } else if (Long.class == targetClass || long.class == targetClass) { - return (T) (isHexNumber(trimmed) ? Long.decode(trimmed) : Long.valueOf(trimmed)); - } else if (BigInteger.class == targetClass) { - return (T) (isHexNumber(trimmed) ? decodeBigInteger(trimmed) : new BigInteger(trimmed)); - } else if (Float.class == targetClass || float.class == targetClass) { - return (T) Float.valueOf(trimmed); - } else if (Double.class == targetClass || double.class == targetClass) { - return (T) Double.valueOf(trimmed); - } else if (BigDecimal.class == targetClass || Number.class == targetClass) { - return (T) new BigDecimal(trimmed); - } else { - throw new IllegalArgumentException( - "Cannot convert String [" + text + "] to target class [" + targetClass.getName() + "]"); - } - } - - private static boolean isHexNumber(String value) { - int index = (value.startsWith("-") ? 1 : 0); - return (value.startsWith("0x", index) || value.startsWith("0X", index) || value.startsWith("#", index)); - } - - private static BigInteger decodeBigInteger(String value) { - int radix = 10; - int index = 0; - boolean negative = false; - - // Handle minus sign, if present. - if (value.startsWith("-")) { - negative = true; - index++; - } - - // Handle radix specifier, if present. - if (value.startsWith("0x", index) || value.startsWith("0X", index)) { - index += 2; - radix = 16; - } else if (value.startsWith("#", index)) { - index++; - radix = 16; - } else if (value.startsWith("0", index) && value.length() > 1 + index) { - index++; - radix = 8; - } - - BigInteger result = new BigInteger(value.substring(index), radix); - return (negative ? result.negate() : result); - } - - public static String trimAllWhitespace(String str) { - if (StringUtils.isEmpty(str)) { - return str; - } - - int len = str.length(); - StringBuilder sb = new StringBuilder(str.length()); - for (int i = 0; i < len; i++) { - char c = str.charAt(i); - if (!Character.isWhitespace(c)) { - sb.append(c); - } - } - return sb.toString(); - } - - public static Object numberToBytes(Number number) { - - if (number instanceof Byte) { - // Use default encoding. - return Byte.toString(number.byteValue()).getBytes(); - } else if (number instanceof Double) { - return Double.toString(number.doubleValue()).getBytes(); - } else if (number instanceof Float) { - return Float.toString(number.floatValue()).getBytes(); - } else if (number instanceof Integer) { - return Float.toString(number.intValue()).getBytes(); - } else if (number instanceof Long) { - return Long.toString(number.longValue()).getBytes(); - } else if (number instanceof Short) { - return Short.toString(number.shortValue()).getBytes(); - } else if (number instanceof BigDecimal) { - return BigDecimal.class.cast(number).toString().getBytes(); - } - - return number; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/ReflectUtils.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/ReflectUtils.java deleted file mode 100644 index 627ad1c195e..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/ReflectUtils.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.util; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class ReflectUtils { - - public static Class findClass(String name, ClassLoader classLoader) throws ClassNotFoundException { - - return classLoader.loadClass(name); - } - - public static Class findClass(String name) throws ClassNotFoundException { - - return findClass(Thread.currentThread().getContextClassLoader(), name); - } - - public static Class findClassAndTryCatch(String name, ClassLoader classLoader) { - - try { - return findClass(name, classLoader); - } catch (Throwable e) { - - } - return null; - } - - public static Class findClass(ClassLoader classLoader, String... name) throws ClassNotFoundException { - - String[] names = name; - - Class tmp; - for (String s : names) { - tmp = findClassAndTryCatch(s, classLoader); - if (tmp == null) { - continue; - } else { - return tmp; - } - } - throw new ClassNotFoundException(); - } - - public static Class findClassTryException(ClassLoader classLoader, String... name) { - - try { - return findClass(classLoader, name); - } catch (Exception e) { - - } - return null; - } - - public static List getMethodByNameList(Class clazz, String name) { - - return getMethodByNameList(clazz, name, false); - } - - public static List getMethodByNameList(Class clazz, String name, boolean declare) { - // prevent duplicate method - Set methods = new HashSet<>(); - - try { - filterMethod(name, methods, clazz.getDeclaredMethods()); - - } catch (Exception e) { - - } - - if (!declare) { - return new ArrayList<>(methods); - } - - try { - filterMethod(name, methods, clazz.getMethods()); - } catch (Exception e) { - - } - - return new ArrayList<>(methods); - } - - public static List> getConstructList(Class clazz) { - // prevent duplicate method - Set> methods = new HashSet<>(); - - try { - filterConstructMethod(methods, clazz.getDeclaredConstructors()); - } catch (Exception e) { - } - - try { - filterConstructMethod(methods, clazz.getConstructors()); - } catch (Exception e) { - - } - return new ArrayList>(methods); - } - - private static void filterConstructMethod(Set> methods, Constructor[] declaredMethods) { - for (Constructor constructor : declaredMethods) { - methods.add(constructor); - } - } - - private static void filterMethod(String name, Set methodList, Method[] methods) { - for (Method declaredMethod : methods) { - if (!name.equals(declaredMethod.getName())) { - continue; - } - declaredMethod.setAccessible(true); - methodList.add(declaredMethod); - } - } - - public static Method getMethodByName(Class clazz, String name) { - - List methodByNameList = getMethodByNameList(clazz, name, true); - if (methodByNameList.isEmpty()) { - return null; - } else { - return methodByNameList.get(0); - } - } - - public static Class findClassTryException(String... name) { - return findClassTryException(Thread.currentThread().getContextClassLoader(), name); - } - - public static Object invoke(Object object, Method method, Object[] params) - throws InvocationTargetException, IllegalAccessException { - return method.invoke(object, params); - } - - public static Object invokeAndTryCatch(Object object, Method method, Object[] params) { - try { - return invoke(object, method, params); - } catch (Exception e) { - - } - - return null; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.config.CommonConfigPostProcessor b/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.config.CommonConfigPostProcessor deleted file mode 100644 index 4906a99b7dd..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.config.CommonConfigPostProcessor +++ /dev/null @@ -1 +0,0 @@ -feign-provider=org.apache.dubbo.rpc.protocol.rest.config.FeignClientAnnotationConfigPostProcessor diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.api.WireProtocol b/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.api.WireProtocol deleted file mode 100644 index 97cf5839f51..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.api.WireProtocol +++ /dev/null @@ -1 +0,0 @@ -rest=org.apache.dubbo.rpc.protocol.rest.pu.RestHttp1WireProtocol diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol b/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol deleted file mode 100644 index d492da9787d..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol +++ /dev/null @@ -1 +0,0 @@ -rest=org.apache.dubbo.rpc.protocol.rest.RestProtocol \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionPreBuildIntercept b/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionPreBuildIntercept deleted file mode 100644 index e277b45107b..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionPreBuildIntercept +++ /dev/null @@ -1,6 +0,0 @@ -must-intercept=org.apache.dubbo.rpc.protocol.rest.annotation.consumer.inercept.AddMustAttachmentIntercept -attachment=org.apache.dubbo.rpc.protocol.rest.annotation.consumer.inercept.AttachmentIntercept -serialize=org.apache.dubbo.rpc.protocol.rest.annotation.consumer.inercept.SerializeBodyIntercept -path=org.apache.dubbo.rpc.protocol.rest.annotation.consumer.inercept.PathVariableIntercept -header=org.apache.dubbo.rpc.protocol.rest.annotation.consumer.inercept.RequestHeaderIntercept -paramparse=org.apache.dubbo.rpc.protocol.rest.annotation.consumer.inercept.ParamParseIntercept diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer.BaseConsumerParamParser b/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer.BaseConsumerParamParser deleted file mode 100644 index 44bcfc15c38..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer.BaseConsumerParamParser +++ /dev/null @@ -1,5 +0,0 @@ -consumer-body=org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer.BodyConsumerParamParser -consumer-header=org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer.HeaderConsumerParamParser -consumer-req=org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer.ReqOrResConsumerParamParser -consumer-parameter=org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer.ParameterConsumerParamParser -consumer-form=org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer.FormConsumerParamParser diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider.BaseProviderParamParser b/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider.BaseProviderParamParser deleted file mode 100644 index 8c6a561d6c8..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider.BaseProviderParamParser +++ /dev/null @@ -1,5 +0,0 @@ -body=org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider.BodyProviderParamParser -header=org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider.HeaderProviderParamParser -path=org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider.PathProviderParamParser -param=org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider.ParamProviderParamParser -no-annotation=org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider.NoAnnotationParamProviderParamParser diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.filter.RestRequestFilter b/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.filter.RestRequestFilter deleted file mode 100644 index 030cb2d3c5b..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.filter.RestRequestFilter +++ /dev/null @@ -1,2 +0,0 @@ -resteasy=org.apache.dubbo.rpc.protocol.rest.extension.resteasy.filter.ResteasyRequestContainerFilterAdapter -invoke=org.apache.dubbo.rpc.protocol.rest.filter.ServiceInvokeRestFilter diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.filter.RestResponseFilter b/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.filter.RestResponseFilter deleted file mode 100644 index dbafe2fcdec..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.filter.RestResponseFilter +++ /dev/null @@ -1 +0,0 @@ -resteasy=org.apache.dubbo.rpc.protocol.rest.extension.resteasy.filter.ResteasyResponseContainerFilterAdapter diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.filter.RestResponseInterceptor b/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.filter.RestResponseInterceptor deleted file mode 100644 index b72ba510114..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.filter.RestResponseInterceptor +++ /dev/null @@ -1,3 +0,0 @@ -resteasy=org.apache.dubbo.rpc.protocol.rest.extension.resteasy.intercept.ResteasyWriterInterceptorAdapter -invoke=org.apache.dubbo.rpc.protocol.rest.filter.ServiceInvokeRestResponseInterceptor -resteasy-resStatus=org.apache.dubbo.rpc.protocol.rest.extension.resteasy.intercept.ResteasyStatusCodeInterceptor diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodec b/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodec deleted file mode 100644 index 5a4daf81349..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodec +++ /dev/null @@ -1,7 +0,0 @@ -multiValue=org.apache.dubbo.rpc.protocol.rest.message.codec.MultiValueCodec -text=org.apache.dubbo.rpc.protocol.rest.message.codec.TextCodec -json=org.apache.dubbo.rpc.protocol.rest.message.codec.JsonCodec -string=org.apache.dubbo.rpc.protocol.rest.message.codec.StringCodec -byteArray=org.apache.dubbo.rpc.protocol.rest.message.codec.ByteArrayCodec -xml=org.apache.dubbo.rpc.protocol.rest.message.codec.XMLCodec -resteasyResponseCodec=org.apache.dubbo.rpc.protocol.rest.message.codec.ResteasyResponseCodec diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/DataParseUtilsTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/DataParseUtilsTest.java deleted file mode 100644 index fb6fc795058..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/DataParseUtilsTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest; - -import org.apache.dubbo.rpc.protocol.rest.util.DataParseUtils; - -import java.io.ByteArrayOutputStream; -import java.util.Arrays; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public class DataParseUtilsTest { - @Test - void testJsonConvert() throws Exception { - - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - DataParseUtils.writeJsonContent(User.getInstance(), byteArrayOutputStream); - - Assertions.assertEquals( - "{\"age\":18,\"id\":404,\"name\":\"dubbo\"}".getBytes().length, - byteArrayOutputStream.toByteArray().length); - } - - @Test - void testStr() { - Object convert = DataParseUtils.stringTypeConvert(boolean.class, "true"); - - Assertions.assertEquals(Boolean.TRUE, convert); - - convert = DataParseUtils.stringTypeConvert(Boolean.class, "true"); - - Assertions.assertEquals(Boolean.TRUE, convert); - - convert = DataParseUtils.stringTypeConvert(String.class, "true"); - - Assertions.assertEquals("true", convert); - - convert = DataParseUtils.stringTypeConvert(int.class, "1"); - - Assertions.assertEquals(1, convert); - - convert = DataParseUtils.stringTypeConvert(Integer.class, "1"); - - Assertions.assertEquals(1, convert); - } - - @Test - void testParseAcceptCharset() { - String[] parsed = DataParseUtils.parseAcceptCharset(Arrays.asList("iso-8859-1")); - Assertions.assertTrue(Arrays.equals(parsed, new String[] {"iso-8859-1"})); - parsed = DataParseUtils.parseAcceptCharset(Arrays.asList("utf-8, iso-8859-1;q=0.5")); - Assertions.assertTrue(Arrays.equals(parsed, new String[] {"utf-8", "iso-8859-1"})); - parsed = DataParseUtils.parseAcceptCharset(Arrays.asList("utf-8, iso-8859-1;q=0.5, *;q=0.1", "utf-16;q=0.5")); - Assertions.assertEquals("utf-8", parsed[0]); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/DemoService.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/DemoService.java deleted file mode 100644 index 53cbc758e96..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/DemoService.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest; - -import javax.ws.rs.Consumes; -import javax.ws.rs.FormParam; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.netty.handler.codec.http.DefaultFullHttpRequest; -import org.jboss.resteasy.annotations.Form; - -@Path("/demoService") -public interface DemoService { - @GET - @Path("/hello") - Integer hello(@QueryParam("a") Integer a, @QueryParam("b") Integer b); - - @GET - @Path("/error") - @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) - @Produces({javax.ws.rs.core.MediaType.TEXT_PLAIN}) - String error(); - - @POST - @Path("/say") - @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) - String sayHello(String name); - - @POST - @Path("number") - Long testFormBody(@FormParam("number") Long number); - - boolean isCalled(); - - @GET - @Path("/primitive") - int primitiveInt(@QueryParam("a") int a, @QueryParam("b") int b); - - @GET - @Path("/primitiveLong") - long primitiveLong(@QueryParam("a") long a, @QueryParam("b") Long b); - - @GET - @Path("/primitiveByte") - long primitiveByte(@QueryParam("a") byte a, @QueryParam("b") Long b); - - @POST - @Path("/primitiveShort") - long primitiveShort(@QueryParam("a") short a, @QueryParam("b") Long b, int c); - - @GET - @Path("/request") - void request(DefaultFullHttpRequest defaultFullHttpRequest); - - @GET - @Path("testMapParam") - @Produces({MediaType.TEXT_PLAIN}) - @Consumes({MediaType.TEXT_PLAIN}) - String testMapParam(@QueryParam("test") Map params); - - @GET - @Path("testMapHeader") - @Produces({MediaType.TEXT_PLAIN}) - @Consumes({MediaType.TEXT_PLAIN}) - String testMapHeader(@HeaderParam("test") Map headers); - - @POST - @Path("testMapForm") - @Produces({MediaType.APPLICATION_JSON}) - @Consumes({MediaType.APPLICATION_FORM_URLENCODED}) - List testMapForm(MultivaluedMap params); - - @POST - @Path("/header") - @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) - String header(@HeaderParam("header") String header); - - @POST - @Path("/headerInt") - @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) - int headerInt(@HeaderParam("header") int header); - - @POST - @Path("/noStringParam") - @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) - String noStringParam(@QueryParam("param") String param); - - @POST - @Path("/noStringHeader") - @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) - String noStringHeader(@HeaderParam("header") String header); - - @POST - @Path("/noIntHeader") - @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) - int noIntHeader(int header); - - @POST - @Path("/noIntParam") - @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) - int noIntParam(int header); - - @POST - @Path("/noBodyArg") - @Consumes({MediaType.APPLICATION_JSON}) - User noBodyArg(User user); - - @POST - @Path("/list") - List list(List users); - - @POST - @Path("/set") - Set set(Set users); - - @POST - @Path("/array") - User[] array(User[] users); - - @POST - @Path("/stringMap") - Map stringMap(Map userMap); - - @POST - @Path("/map") - Map userMap(Map userMap); - - @POST - @Path("/formBody") - User formBody(@Form User user); -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/DemoServiceImpl.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/DemoServiceImpl.java deleted file mode 100644 index 69c5cbc710b..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/DemoServiceImpl.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest; - -import org.apache.dubbo.rpc.RpcContext; - -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.netty.handler.codec.http.DefaultFullHttpRequest; - -@Path("/demoService") -public class DemoServiceImpl implements DemoService { - private static Map context; - private boolean called; - - @POST - @Path("/say") - @Consumes({MediaType.TEXT_PLAIN}) - @Override - public String sayHello(String name) { - called = true; - return "Hello, " + name; - } - - @Override - public Long testFormBody(Long number) { - return number; - } - - public boolean isCalled() { - return called; - } - - @Override - public int primitiveInt(int a, int b) { - return a + b; - } - - @Override - public long primitiveLong(long a, Long b) { - return a + b; - } - - @Override - public long primitiveByte(byte a, Long b) { - return a + b; - } - - @Override - public long primitiveShort(short a, Long b, int c) { - return a + b; - } - - @Override - public void request(DefaultFullHttpRequest defaultFullHttpRequest) {} - - @Override - public String testMapParam(Map params) { - return params.get("param"); - } - - @Override - public String testMapHeader(Map headers) { - return headers.get("header"); - } - - @Override - public List testMapForm(MultivaluedMap params) { - return params.get("form"); - } - - @Override - public String header(String header) { - return header; - } - - @Override - public int headerInt(int header) { - return header; - } - - @Override - public String noStringParam(String param) { - return param; - } - - @Override - public String noStringHeader(String header) { - return header; - } - - @POST - @Path("/noIntHeader") - @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) - @Override - public int noIntHeader(@HeaderParam("header") int header) { - return header; - } - - @POST - @Path("/noIntParam") - @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) - @Override - public int noIntParam(@QueryParam("header") int header) { - return header; - } - - @Override - public User noBodyArg(User user) { - return user; - } - - @GET - @Path("/hello") - @Override - public Integer hello(@QueryParam("a") Integer a, @QueryParam("b") Integer b) { - context = RpcContext.getServerAttachment().getObjectAttachments(); - return a + b; - } - - @GET - @Path("/error") - @Override - public String error() { - throw new RuntimeException("test error"); - } - - public static Map getAttachments() { - return context; - } - - @Override - public List list(List users) { - return users; - } - - @Override - public Set set(Set users) { - return users; - } - - @Override - public User[] array(User[] users) { - return users; - } - - @Override - public Map stringMap(Map userMap) { - return userMap; - } - - @Override - public Map userMap(Map userMap) { - return userMap; - } - - @Override - public User formBody(User user) { - user.setName("formBody"); - return user; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/ExceptionMapperTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/ExceptionMapperTest.java deleted file mode 100644 index 330439ab608..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/ExceptionMapperTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest; - -import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionHandler; -import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionHandlerResult; -import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionMapper; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public class ExceptionMapperTest { - private final ExceptionMapper exceptionMapper = new ExceptionMapper(); - - @Test - void testRegister() { - - exceptionMapper.registerMapper(TestExceptionHandler.class); - - ExceptionHandlerResult result = exceptionMapper.exceptionToResult(new RuntimeException("test")); - - Assertions.assertEquals("test", result.getEntity()); - } - - @Test - void testExceptionNoArgConstruct() { - - Assertions.assertThrows(RuntimeException.class, () -> { - exceptionMapper.registerMapper(TestExceptionHandlerException.class); - }); - } - - public class TestExceptionHandler implements ExceptionHandler { - - @Override - public Object result(RuntimeException exception) { - return exception.getMessage(); - } - } - - class TestExceptionHandlerException implements ExceptionHandler { - - @Override - public Object result(RuntimeException exception) { - return exception.getMessage(); - } - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/FeignClientRestProtocolTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/FeignClientRestProtocolTest.java deleted file mode 100644 index 89cc9bc27c9..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/FeignClientRestProtocolTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.rpc.Exporter; -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.FrameworkModel; -import org.apache.dubbo.rpc.model.ModuleServiceRepository; -import org.apache.dubbo.rpc.model.ProviderModel; -import org.apache.dubbo.rpc.model.ServiceDescriptor; -import org.apache.dubbo.rpc.protocol.rest.mvc.feign.FeignClientController; -import org.apache.dubbo.rpc.protocol.rest.mvc.feign.FeignClientControllerImpl; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public class FeignClientRestProtocolTest { - private Protocol protocol = - ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest"); - private ProxyFactory proxy = - ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - private final ModuleServiceRepository repository = - ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); - - @AfterEach - public void tearDown() { - protocol.destroy(); - FrameworkModel.destroyAll(); - } - - @Test - void testRestProtocol() { - URL url = URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort() - + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.mvc.feign.FeignClientController"); - - FeignClientController server = new FeignClientControllerImpl(); - - url = this.registerProvider(url, server, DemoService.class); - - Exporter exporter = - protocol.export(proxy.getInvoker(server, FeignClientController.class, url)); - - FeignClientController feignClientController = - this.proxy.getProxy(protocol.refer(FeignClientController.class, url)); - - Assertions.assertEquals("hello, feign", feignClientController.hello()); - exporter.unexport(); - } - - private URL registerProvider(URL url, Object impl, Class interfaceClass) { - ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass); - ProviderModel providerModel = new ProviderModel(url.getServiceKey(), impl, serviceDescriptor, null, null); - repository.registerProvider(providerModel); - return url.setServiceModel(providerModel); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/HttpMessageCodecManagerTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/HttpMessageCodecManagerTest.java deleted file mode 100644 index 06c0ff5e181..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/HttpMessageCodecManagerTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest; - -import org.apache.dubbo.metadata.rest.media.MediaType; -import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodecManager; -import org.apache.dubbo.rpc.protocol.rest.message.codec.XMLCodec; -import org.apache.dubbo.rpc.protocol.rest.pair.MessageCodecResultPair; -import org.apache.dubbo.rpc.protocol.rest.rest.RegistrationResult; - -import java.io.ByteArrayOutputStream; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public class HttpMessageCodecManagerTest { - - @Test - void testCodec() throws Exception { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - - RegistrationResult registrationResult = new RegistrationResult(); - registrationResult.setId(1l); - HttpMessageCodecManager.httpMessageEncode( - byteArrayOutputStream, registrationResult, null, MediaType.TEXT_XML, null); - - Object o = HttpMessageCodecManager.httpMessageDecode( - byteArrayOutputStream.toByteArray(), - RegistrationResult.class, - RegistrationResult.class, - MediaType.TEXT_XML); - - Assertions.assertEquals(registrationResult, o); - - byteArrayOutputStream = new ByteArrayOutputStream(); - MessageCodecResultPair messageCodecResultPair = HttpMessageCodecManager.httpMessageEncode( - byteArrayOutputStream, null, null, null, RegistrationResult.class); - - MediaType mediaType = messageCodecResultPair.getMediaType(); - - Assertions.assertEquals(MediaType.APPLICATION_JSON_VALUE, mediaType); - - XMLCodec xmlCodec = new XMLCodec(); - - Assertions.assertEquals(false, xmlCodec.typeSupport(null)); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/JaxrsRestProtocolTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/JaxrsRestProtocolTest.java deleted file mode 100644 index e68969817d5..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/JaxrsRestProtocolTest.java +++ /dev/null @@ -1,804 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.metadata.rest.PathMatcher; -import org.apache.dubbo.metadata.rest.RestMethodMetadata; -import org.apache.dubbo.metadata.rest.ServiceRestMetadata; -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.Result; -import org.apache.dubbo.rpc.RpcContext; -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.model.ApplicationModel; -import org.apache.dubbo.rpc.model.FrameworkModel; -import org.apache.dubbo.rpc.model.ModuleServiceRepository; -import org.apache.dubbo.rpc.model.ProviderModel; -import org.apache.dubbo.rpc.model.ServiceDescriptor; -import org.apache.dubbo.rpc.protocol.rest.annotation.metadata.MetadataResolver; -import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; -import org.apache.dubbo.rpc.protocol.rest.exception.DoublePathCheckException; -import org.apache.dubbo.rpc.protocol.rest.exception.ResteasyExceptionMapper; -import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionHandler; -import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionMapper; -import org.apache.dubbo.rpc.protocol.rest.filter.TraceRequestAndResponseFilter; -import org.apache.dubbo.rpc.protocol.rest.rest.AnotherUserRestService; -import org.apache.dubbo.rpc.protocol.rest.rest.AnotherUserRestServiceImpl; -import org.apache.dubbo.rpc.protocol.rest.rest.HttpMethodService; -import org.apache.dubbo.rpc.protocol.rest.rest.HttpMethodServiceImpl; -import org.apache.dubbo.rpc.protocol.rest.rest.RestDemoForTestException; -import org.apache.dubbo.rpc.protocol.rest.rest.RestDemoService; -import org.apache.dubbo.rpc.protocol.rest.rest.RestDemoServiceImpl; -import org.apache.dubbo.rpc.protocol.rest.rest.TestGetInvokerService; -import org.apache.dubbo.rpc.protocol.rest.rest.TestGetInvokerServiceImpl; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; - -import org.hamcrest.CoreMatchers; -import org.jboss.resteasy.specimpl.MultivaluedMapImpl; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -import static org.apache.dubbo.remoting.Constants.SERVER_KEY; -import static org.apache.dubbo.rpc.protocol.rest.Constants.EXTENSION_KEY; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; - -class JaxrsRestProtocolTest { - private final Protocol protocol = - ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest"); - private final ProxyFactory proxy = - ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - private final int availablePort = NetUtils.getAvailablePort(); - private final URL exportUrl = URL.valueOf( - "rest://127.0.0.1:" + availablePort + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.DemoService"); - private final ModuleServiceRepository repository = - ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); - private final ExceptionMapper exceptionMapper = new ExceptionMapper(); - private static final String SERVER = "netty4"; - - @AfterEach - public void tearDown() { - protocol.destroy(); - FrameworkModel.destroyAll(); - } - - @Test - void testRestProtocol() { - URL url = URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort() - + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.DemoService"); - - DemoServiceImpl server = new DemoServiceImpl(); - - url = this.registerProvider(url, server, DemoService.class); - - Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, url)); - Invoker invoker = protocol.refer(DemoService.class, url); - Assertions.assertFalse(server.isCalled()); - - DemoService client = proxy.getProxy(invoker); - String result = client.sayHello("haha"); - Assertions.assertTrue(server.isCalled()); - Assertions.assertEquals("Hello, haha", result); - - String header = client.header("header test"); - Assertions.assertEquals("header test", header); - - Assertions.assertEquals(1, client.headerInt(1)); - invoker.destroy(); - exporter.unexport(); - } - - @Test - void testAnotherUserRestProtocolByDifferentRestClient() { - testAnotherUserRestProtocol(org.apache.dubbo.remoting.Constants.OK_HTTP); - testAnotherUserRestProtocol(org.apache.dubbo.remoting.Constants.APACHE_HTTP_CLIENT); - testAnotherUserRestProtocol(org.apache.dubbo.remoting.Constants.URL_CONNECTION); - } - - void testAnotherUserRestProtocol(String restClient) { - URL url = URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort() - + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.rest.AnotherUserRestService&" - + org.apache.dubbo.remoting.Constants.CLIENT_KEY + "=" + restClient); - - AnotherUserRestServiceImpl server = new AnotherUserRestServiceImpl(); - - url = this.registerProvider(url, server, DemoService.class); - - Exporter exporter = - protocol.export(proxy.getInvoker(server, AnotherUserRestService.class, url)); - Invoker invoker = protocol.refer(AnotherUserRestService.class, url); - - AnotherUserRestService client = proxy.getProxy(invoker); - User result = client.getUser(123l); - - Assertions.assertEquals(123l, result.getId()); - - result.setName("dubbo"); - Assertions.assertEquals(123l, client.registerUser(result).getId()); - - Assertions.assertEquals("context", client.getContext()); - - byte[] bytes = {1, 2, 3, 4}; - Assertions.assertTrue(Arrays.equals(bytes, client.bytes(bytes))); - - Assertions.assertEquals(1l, client.number(1l)); - - HashMap map = new HashMap<>(); - map.put("headers", "h1"); - Assertions.assertEquals("h1", client.headerMap(map)); - Assertions.assertEquals(null, client.headerMap(null)); - - invoker.destroy(); - exporter.unexport(); - } - - @Test - void testRestProtocolWithContextPath() { - DemoServiceImpl server = new DemoServiceImpl(); - Assertions.assertFalse(server.isCalled()); - int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("rest://127.0.0.1:" + port - + "/a/b/c?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.DemoService"); - - url = this.registerProvider(url, server, DemoService.class); - - Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, url)); - - url = URL.valueOf("rest://127.0.0.1:" + port - + "/a/b/c/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.DemoService"); - Invoker invoker = protocol.refer(DemoService.class, url); - DemoService client = proxy.getProxy(invoker); - String result = client.sayHello("haha"); - Assertions.assertTrue(server.isCalled()); - Assertions.assertEquals("Hello, haha", result); - invoker.destroy(); - exporter.unexport(); - } - - @Test - void testExport() { - DemoService server = new DemoServiceImpl(); - - URL url = this.registerProvider(exportUrl, server, DemoService.class); - - RpcContext.getClientAttachment().setAttachment("timeout", "20000"); - Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, url)); - - DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, url)); - - Integer echoString = demoService.hello(1, 2); - assertThat(echoString, is(3)); - - exporter.unexport(); - } - - @Test - void testNettyServer() { - DemoService server = new DemoServiceImpl(); - - URL url = this.registerProvider(exportUrl, server, DemoService.class); - - URL nettyUrl = url.addParameter(SERVER_KEY, SERVER); - Exporter exporter = - protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, nettyUrl)); - - DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); - - Integer echoString = demoService.hello(10, 10); - assertThat(echoString, is(20)); - - exporter.unexport(); - } - - @Disabled - @Test - void testServletWithoutWebConfig() { - Assertions.assertThrows(RpcException.class, () -> { - DemoService server = new DemoServiceImpl(); - - URL url = this.registerProvider(exportUrl, server, DemoService.class); - - URL servletUrl = url.addParameter(SERVER_KEY, "servlet"); - - protocol.export(proxy.getInvoker(server, DemoService.class, servletUrl)); - }); - } - - @Test - void testErrorHandler() { - Assertions.assertThrows(RpcException.class, () -> { - exceptionMapper.unRegisterMapper(RuntimeException.class); - DemoService server = new DemoServiceImpl(); - - URL url = this.registerProvider(exportUrl, server, DemoService.class); - - URL nettyUrl = url.addParameter(SERVER_KEY, SERVER); - Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); - - DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); - - demoService.error(); - }); - } - - @Test - void testInvoke() { - DemoService server = new DemoServiceImpl(); - - URL url = this.registerProvider(exportUrl, server, DemoService.class); - - Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, url)); - - RpcInvocation rpcInvocation = new RpcInvocation( - "hello", DemoService.class.getName(), "", new Class[] {Integer.class, Integer.class}, new Integer[] { - 2, 3 - }); - - Result result = exporter.getInvoker().invoke(rpcInvocation); - assertThat(result.getValue(), CoreMatchers.is(5)); - } - - @Test - void testFilter() { - DemoService server = new DemoServiceImpl(); - - URL url = this.registerProvider(exportUrl, server, DemoService.class); - - URL nettyUrl = url.addParameter(SERVER_KEY, SERVER) - .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.support.LoggingFilter"); - Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); - - DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); - - Integer result = demoService.hello(1, 2); - - assertThat(result, is(3)); - - exporter.unexport(); - } - - @Disabled - @Test - void testRpcContextFilter() { - DemoService server = new DemoServiceImpl(); - - URL url = this.registerProvider(exportUrl, server, DemoService.class); - - // use RpcContextFilter - URL nettyUrl = url.addParameter(SERVER_KEY, SERVER) - .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.RpcContextFilter"); - Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); - - DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); - - // make sure null and base64 encoded string can work - RpcContext.getClientAttachment().setAttachment("key1", null); - RpcContext.getClientAttachment().setAttachment("key2", "value"); - RpcContext.getClientAttachment().setAttachment("key3", "=value"); - RpcContext.getClientAttachment().setAttachment("key4", "YWJjZGVmCg=="); - RpcContext.getClientAttachment().setAttachment("key5", "val=ue"); - Integer result = demoService.hello(1, 2); - - assertThat(result, is(3)); - - Map attachment = DemoServiceImpl.getAttachments(); - assertThat(attachment.get("key1"), nullValue()); - assertThat(attachment.get("key2"), equalTo("value")); - assertThat(attachment.get("key3"), equalTo("=value")); - assertThat(attachment.get("key4"), equalTo("YWJjZGVmCg==")); - assertThat(attachment.get("key5"), equalTo("val=ue")); - - exporter.unexport(); - } - - @Disabled - @Test - void testRegFail() { - Assertions.assertThrows(RuntimeException.class, () -> { - DemoService server = new DemoServiceImpl(); - - URL url = this.registerProvider(exportUrl, server, DemoService.class); - - URL nettyUrl = url.addParameter(EXTENSION_KEY, "com.not.existing.Filter"); - protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); - }); - } - - @Test - void testDefaultPort() { - assertThat(protocol.getDefaultPort(), is(80)); - } - - @Test - void testExceptionMapper() { - - DemoService server = new DemoServiceImpl(); - - URL url = this.registerProvider(exportUrl, server, DemoService.class); - - URL exceptionUrl = url.addParameter(EXTENSION_KEY, TestExceptionMapper.class.getName()); - - protocol.export(proxy.getInvoker(server, DemoService.class, exceptionUrl)); - - DemoService referDemoService = this.proxy.getProxy(protocol.refer(DemoService.class, exceptionUrl)); - - Assertions.assertEquals("test-exception", referDemoService.error()); - } - - @Test - void testRestExceptionMapper() { - - DemoService server = new DemoServiceImpl(); - - URL url = this.registerProvider(exportUrl, server, DemoService.class); - - URL exceptionUrl = url.addParameter(EXTENSION_KEY, ResteasyExceptionMapper.class.getName()); - - protocol.export(proxy.getInvoker(server, DemoService.class, exceptionUrl)); - - DemoService referDemoService = this.proxy.getProxy(protocol.refer(DemoService.class, exceptionUrl)); - - Assertions.assertEquals("test-exception", referDemoService.error()); - } - - @Test - void testFormConsumerParser() { - DemoService server = new DemoServiceImpl(); - URL nettyUrl = this.registerProvider(exportUrl, server, DemoService.class); - - Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); - - DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); - - Long number = demoService.testFormBody(18l); - Assertions.assertEquals(18l, number); - - exporter.unexport(); - } - - @Test - void test404() { - Assertions.assertThrows(RpcException.class, () -> { - DemoService server = new DemoServiceImpl(); - URL nettyUrl = this.registerProvider(exportUrl, server, DemoService.class); - - Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); - - URL referUrl = URL.valueOf("rest://127.0.0.1:" + availablePort - + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.rest.RestDemoForTestException"); - - RestDemoForTestException restDemoForTestException = - this.proxy.getProxy(protocol.refer(RestDemoForTestException.class, referUrl)); - - restDemoForTestException.test404(); - - exporter.unexport(); - }); - } - - @Test - void test400() { - Assertions.assertThrows(RpcException.class, () -> { - DemoService server = new DemoServiceImpl(); - URL nettyUrl = this.registerProvider(exportUrl, server, DemoService.class); - - Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); - - URL referUrl = URL.valueOf("rest://127.0.0.1:" + availablePort - + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.rest.RestDemoForTestException"); - - RestDemoForTestException restDemoForTestException = - this.proxy.getProxy(protocol.refer(RestDemoForTestException.class, referUrl)); - - restDemoForTestException.test400("abc", "edf"); - - exporter.unexport(); - }); - } - - @Test - void testPrimitive() { - DemoService server = new DemoServiceImpl(); - - URL url = this.registerProvider(exportUrl, server, DemoService.class); - - URL nettyUrl = url.addParameter(SERVER_KEY, SERVER) - .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.support.LoggingFilter"); - Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); - - DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); - - Integer result = demoService.primitiveInt(1, 2); - Long resultLong = demoService.primitiveLong(1, 2l); - long resultByte = demoService.primitiveByte((byte) 1, 2l); - long resultShort = demoService.primitiveShort((short) 1, 2l, 1); - - assertThat(result, is(3)); - assertThat(resultShort, is(3l)); - assertThat(resultLong, is(3l)); - assertThat(resultByte, is(3l)); - - exporter.unexport(); - } - - @Test - void testDoubleCheckException() { - - Assertions.assertThrows(DoublePathCheckException.class, () -> { - DemoService server = new DemoServiceImpl(); - - Invoker invoker = proxy.getInvoker(server, DemoService.class, exportUrl); - - PathAndInvokerMapper pathAndInvokerMapper = new PathAndInvokerMapper(); - - ServiceRestMetadata serviceRestMetadata = - MetadataResolver.resolveConsumerServiceMetadata(DemoService.class, exportUrl, ""); - - Map pathContainPathVariableToServiceMap = - serviceRestMetadata.getPathUnContainPathVariableToServiceMap(); - - Invoker invokerNew = - proxy.getInvoker(new TestInterface() {}, TestInterface.class, exportUrl); - - pathAndInvokerMapper.addPathAndInvoker(pathContainPathVariableToServiceMap, invoker); - pathAndInvokerMapper.addPathAndInvoker(pathContainPathVariableToServiceMap, invokerNew); - }); - } - - public static interface TestInterface {} - - @Test - void testMapParam() { - DemoService server = new DemoServiceImpl(); - - URL url = this.registerProvider(exportUrl, server, DemoService.class); - - URL nettyUrl = url.addParameter(SERVER_KEY, SERVER) - .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.support.LoggingFilter"); - Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); - - DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); - - Map params = new HashMap<>(); - params.put("param", "P1"); - ; - - Map headers = new HashMap<>(); - headers.put("header", "H1"); - - Assertions.assertEquals("P1", demoService.testMapParam(params)); - Assertions.assertEquals("H1", demoService.testMapHeader(headers)); - - MultivaluedMapImpl forms = new MultivaluedMapImpl<>(); - forms.put("form", Arrays.asList("F1")); - - Assertions.assertEquals(Arrays.asList("F1"), demoService.testMapForm(forms)); - exporter.unexport(); - } - - @Test - void testNoArgParam() { - DemoService server = new DemoServiceImpl(); - - URL url = this.registerProvider(exportUrl, server, DemoService.class); - - URL nettyUrl = url.addParameter(SERVER_KEY, SERVER) - .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.support.LoggingFilter"); - Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); - - DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); - - Assertions.assertEquals(null, demoService.noStringHeader(null)); - Assertions.assertEquals(null, demoService.noStringParam(null)); - Assertions.assertThrows(RpcException.class, () -> { - demoService.noIntHeader(1); - }); - - Assertions.assertThrows(RpcException.class, () -> { - demoService.noIntParam(1); - }); - - Assertions.assertEquals(null, demoService.noBodyArg(null)); - exporter.unexport(); - } - - @Test - void testToken() { - DemoService server = new DemoServiceImpl(); - - URL url = this.registerProvider(exportUrl, server, DemoService.class); - - URL nettyUrl = url.addParameter(RestConstant.TOKEN_KEY, "TOKEN"); - Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); - - DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); - - Assertions.assertEquals("Hello, hello", demoService.sayHello("hello")); - exporter.unexport(); - } - - @Test - void testHttpMethods() { - testHttpMethod(org.apache.dubbo.remoting.Constants.OK_HTTP); - testHttpMethod(org.apache.dubbo.remoting.Constants.APACHE_HTTP_CLIENT); - testHttpMethod(org.apache.dubbo.remoting.Constants.URL_CONNECTION); - } - - void testHttpMethod(String restClient) { - HttpMethodService server = new HttpMethodServiceImpl(); - - URL url = URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort() - + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.rest.HttpMethodService&" - + org.apache.dubbo.remoting.Constants.CLIENT_KEY + "=" + restClient); - url = this.registerProvider(url, server, HttpMethodService.class); - Exporter exporter = protocol.export(proxy.getInvoker(server, HttpMethodService.class, url)); - - HttpMethodService demoService = this.proxy.getProxy(protocol.refer(HttpMethodService.class, url)); - - String expect = "hello"; - Assertions.assertEquals(null, demoService.sayHelloHead()); - Assertions.assertEquals(expect, demoService.sayHelloDelete("hello")); - Assertions.assertEquals(expect, demoService.sayHelloGet("hello")); - Assertions.assertEquals(expect, demoService.sayHelloOptions("hello")); - // Assertions.assertEquals(expect, demoService.sayHelloPatch("hello")); - Assertions.assertEquals(expect, demoService.sayHelloPost("hello")); - Assertions.assertEquals(expect, demoService.sayHelloPut("hello")); - exporter.unexport(); - } - - public static class TestExceptionMapper implements ExceptionHandler { - - @Override - public String result(RuntimeException e) { - return "test-exception"; - } - } - - @Test - void test405() { - int availablePort = NetUtils.getAvailablePort(); - URL url = URL.valueOf("rest://127.0.0.1:" + availablePort - + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.rest.RestDemoService&"); - - RestDemoServiceImpl server = new RestDemoServiceImpl(); - - url = this.registerProvider(url, server, RestDemoService.class); - - Exporter exporter = protocol.export(proxy.getInvoker(server, RestDemoService.class, url)); - - URL consumer = URL.valueOf("rest://127.0.0.1:" + availablePort - + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.rest.RestDemoForTestException&"); - - consumer = this.registerProvider(consumer, server, RestDemoForTestException.class); - - Invoker invoker = protocol.refer(RestDemoForTestException.class, consumer); - - RestDemoForTestException client = proxy.getProxy(invoker); - - Assertions.assertThrows(RpcException.class, () -> { - client.testMethodDisallowed("aaa"); - }); - - invoker.destroy(); - exporter.unexport(); - } - - @Test - void testGetInvoker() { - Assertions.assertDoesNotThrow(() -> { - URL exportUrl = URL.valueOf("rest://127.0.0.1:" + availablePort - + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.rest.TestGetInvokerService"); - - TestGetInvokerService server = new TestGetInvokerServiceImpl(); - - URL url = this.registerProvider(exportUrl, server, DemoService.class); - - Exporter exporter = - protocol.export(proxy.getInvoker(server, TestGetInvokerService.class, url)); - - TestGetInvokerService invokerService = - this.proxy.getProxy(protocol.refer(TestGetInvokerService.class, url)); - - String invoker = invokerService.getInvoker(); - Assertions.assertEquals("success", invoker); - - exporter.unexport(); - }); - } - - @Test - void testContainerRequestFilter() { - DemoService server = new DemoServiceImpl(); - - URL url = this.registerProvider(exportUrl, server, DemoService.class); - - URL nettyUrl = url.addParameter(SERVER_KEY, "netty") - .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.filter.TestContainerRequestFilter"); - - Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); - - DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); - - Assertions.assertEquals("return-success", demoService.sayHello("hello")); - exporter.unexport(); - } - - @Test - void testIntercept() { - DemoService server = new DemoServiceImpl(); - - URL url = this.registerProvider(exportUrl, server, DemoService.class); - - URL nettyUrl = url.addParameter(SERVER_KEY, "netty") - .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.intercept.DynamicTraceInterceptor"); - - Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); - - DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); - - Assertions.assertEquals("intercept", demoService.sayHello("hello")); - exporter.unexport(); - } - - @Test - void testResponseFilter() { - DemoService server = new DemoServiceImpl(); - - URL url = this.registerProvider(exportUrl, server, DemoService.class); - - URL nettyUrl = url.addParameter(SERVER_KEY, "netty") - .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.filter.TraceFilter"); - - Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); - - DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); - - Assertions.assertEquals("response-filter", demoService.sayHello("hello")); - exporter.unexport(); - } - - @Test - void testCollectionResult() { - DemoService server = new DemoServiceImpl(); - - URL url = this.registerProvider(exportUrl, server, DemoService.class); - - URL nettyUrl = url.addParameter(SERVER_KEY, "netty"); - - Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); - - DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); - - Assertions.assertEquals( - User.getInstance(), - demoService.list(Arrays.asList(User.getInstance())).get(0)); - - HashSet objects = new HashSet<>(); - objects.add(User.getInstance()); - Assertions.assertEquals(User.getInstance(), new ArrayList<>(demoService.set(objects)).get(0)); - - Assertions.assertEquals(User.getInstance(), demoService.array(objects.toArray(new User[0]))[0]); - - Map map = new HashMap<>(); - map.put("map", User.getInstance()); - Assertions.assertEquals(User.getInstance(), demoService.stringMap(map).get("map")); - - Map maps = new HashMap<>(); - maps.put(User.getInstance(), User.getInstance()); - Assertions.assertEquals(User.getInstance(), demoService.userMap(maps).get(User.getInstance())); - exporter.unexport(); - } - - @Test - void testReExport() { - DemoService server = new DemoServiceImpl(); - - URL url = this.registerProvider(exportUrl, server, DemoService.class); - - URL nettyUrl = url.addParameter(SERVER_KEY, "netty"); - - Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); - nettyUrl = url.addParameter("SERVER_KEY", "netty"); - exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); - - exporter.unexport(); - } - - @Test - void testBody() { - - Assertions.assertThrowsExactly(RpcException.class, () -> { - DemoService server = new DemoServiceImpl(); - - URL url = this.registerProvider(exportUrl, server, DemoService.class); - - URL nettyUrl = url.addParameter(org.apache.dubbo.remoting.Constants.PAYLOAD_KEY, 1024); - - Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); - - DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); - - List users = new ArrayList<>(); - for (int i = 0; i < 10000; i++) { - users.add(User.getInstance()); - } - - demoService.list(users); - - exporter.unexport(); - }); - } - - @Test - void testRequestAndResponseFilter() { - DemoService server = new DemoServiceImpl(); - - URL exportUrl = URL.valueOf("rest://127.0.0.1:" + availablePort - + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.DemoService&extension=" - + TraceRequestAndResponseFilter.class.getName()); - - URL nettyUrl = this.registerProvider(exportUrl, server, DemoService.class); - - Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); - - DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); - - Assertions.assertEquals("header-result", demoService.sayHello("hello")); - exporter.unexport(); - } - - @Test - void testFormBody() { - DemoService server = new DemoServiceImpl(); - - URL url = this.registerProvider(exportUrl, server, DemoService.class); - - URL nettyUrl = url.addParameter(SERVER_KEY, SERVER); - - Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); - - DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); - - User user = demoService.formBody(User.getInstance()); - - Assertions.assertEquals("formBody", user.getName()); - exporter.unexport(); - } - - private URL registerProvider(URL url, Object impl, Class interfaceClass) { - ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass); - ProviderModel providerModel = new ProviderModel(url.getServiceKey(), impl, serviceDescriptor, null, null); - repository.registerProvider(providerModel); - return url.setServiceModel(providerModel); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/JsonCompatibilityCheckTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/JsonCompatibilityCheckTest.java deleted file mode 100644 index e714e601077..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/JsonCompatibilityCheckTest.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.rpc.protocol.rest; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.rpc.Exporter; -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.ModuleServiceRepository; -import org.apache.dubbo.rpc.model.ProviderModel; -import org.apache.dubbo.rpc.model.ServiceDescriptor; -import org.apache.dubbo.rpc.protocol.rest.compatibility.RestDemoService; -import org.apache.dubbo.rpc.protocol.rest.compatibility.RestDemoServiceImpl; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import static org.apache.dubbo.rpc.protocol.rest.constans.RestConstant.JSON_CHECK_LEVEL; -import static org.apache.dubbo.rpc.protocol.rest.constans.RestConstant.JSON_CHECK_LEVEL_DISABLED; -import static org.apache.dubbo.rpc.protocol.rest.constans.RestConstant.JSON_CHECK_LEVEL_STRICT; -import static org.apache.dubbo.rpc.protocol.rest.constans.RestConstant.JSON_CHECK_LEVEL_WARN; - -public class JsonCompatibilityCheckTest { - - private final int availablePort = NetUtils.getAvailablePort(); - private final URL exportUrl = URL.valueOf("rest://127.0.0.1:" + availablePort - + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.compatibility.RestDemoService"); - private final ModuleServiceRepository repository = - ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); - - private final Protocol protocol = - ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest"); - private final ProxyFactory proxy = - ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - - @Test - public void testJsonCheckDisabled() { - - RestDemoService server = new RestDemoServiceImpl(); - - URL url = this.registerProvider(exportUrl, server, RestDemoService.class); - - url = url.addParameter(JSON_CHECK_LEVEL, JSON_CHECK_LEVEL_DISABLED); - - Exporter exporter = protocol.export(proxy.getInvoker(server, RestDemoService.class, url)); - - exporter.unexport(); - } - - @Test - public void testJsonCheckWarn() { - RestDemoService server = new RestDemoServiceImpl(); - - URL url = this.registerProvider(exportUrl, server, RestDemoService.class); - - url = url.addParameter(JSON_CHECK_LEVEL, JSON_CHECK_LEVEL_WARN); - - Exporter exporter = protocol.export(proxy.getInvoker(server, RestDemoService.class, url)); - - exporter.unexport(); - } - - @Test - public void testJsonCheckStrict() { - RestDemoService server = new RestDemoServiceImpl(); - - URL url = this.registerProvider(exportUrl, server, RestDemoService.class); - - URL newUrl = url.addParameter(JSON_CHECK_LEVEL, JSON_CHECK_LEVEL_STRICT); - - Assertions.assertThrowsExactly(IllegalStateException.class, () -> { - Exporter exporter = null; - try { - exporter = protocol.export(proxy.getInvoker(server, RestDemoService.class, newUrl)); - } finally { - if (exporter != null) exporter.unexport(); - } - }); - } - - private URL registerProvider(URL url, Object impl, Class interfaceClass) { - ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass); - ProviderModel providerModel = new ProviderModel(url.getServiceKey(), impl, serviceDescriptor, null, null); - repository.registerProvider(providerModel); - return url.setServiceModel(providerModel); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/MediaTypeUtilTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/MediaTypeUtilTest.java deleted file mode 100644 index 84db93b5168..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/MediaTypeUtilTest.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest; - -import org.apache.dubbo.metadata.rest.media.MediaType; -import org.apache.dubbo.rpc.protocol.rest.exception.UnSupportContentTypeException; -import org.apache.dubbo.rpc.protocol.rest.util.MediaTypeUtil; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public class MediaTypeUtilTest { - - @Test - void testException() { - - Assertions.assertThrows(UnSupportContentTypeException.class, () -> { - MediaTypeUtil.convertMediaType(null, "aaaaa"); - }); - } - - @Test - void testConvertMediaType() { - MediaType mediaType = - MediaTypeUtil.convertMediaType(null, new String[] {MediaType.APPLICATION_JSON_VALUE.value}); - - Assertions.assertEquals(MediaType.APPLICATION_JSON_VALUE, mediaType); - - mediaType = MediaTypeUtil.convertMediaType(int.class, null); - - Assertions.assertEquals(MediaType.TEXT_PLAIN, mediaType); - - mediaType = MediaTypeUtil.convertMediaType(null, new String[] {MediaType.ALL_VALUE.value}); - - Assertions.assertEquals(MediaType.APPLICATION_JSON_VALUE, mediaType); - - mediaType = MediaTypeUtil.convertMediaType(String.class, new String[] {MediaType.TEXT_XML.value}); - - Assertions.assertEquals(MediaType.TEXT_XML, mediaType); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/NettyRequestFacadeTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/NettyRequestFacadeTest.java deleted file mode 100644 index c923fb1d8b3..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/NettyRequestFacadeTest.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest; - -import org.apache.dubbo.rpc.protocol.rest.request.NettyRequestFacade; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.List; -import java.util.Map; - -import io.netty.handler.codec.http.DefaultFullHttpRequest; -import io.netty.handler.codec.http.HttpMethod; -import io.netty.handler.codec.http.HttpVersion; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.Is.is; - -public class NettyRequestFacadeTest { - - @Test - void testMethod() { - - String uri = "/a/b?c=c&d=d"; - DefaultFullHttpRequest defaultFullHttpRequest = - new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri); - - defaultFullHttpRequest.headers().add("h1", "a"); - defaultFullHttpRequest.headers().add("h1", "b"); - defaultFullHttpRequest.headers().add("h2", "c"); - NettyRequestFacade nettyRequestFacade = new NettyRequestFacade(defaultFullHttpRequest, null); - - Assertions.assertArrayEquals(new String[] {"c"}, nettyRequestFacade.getParameterValues("c")); - Enumeration parameterNames = nettyRequestFacade.getParameterNames(); - - List names = new ArrayList<>(); - while (parameterNames.hasMoreElements()) { - - names.add(parameterNames.nextElement()); - } - - Assertions.assertArrayEquals(Arrays.asList("c", "d").toArray(), names.toArray()); - - Enumeration headerNames = nettyRequestFacade.getHeaderNames(); - - List heads = new ArrayList<>(); - while (headerNames.hasMoreElements()) { - - heads.add(headerNames.nextElement()); - } - - Assertions.assertArrayEquals(Arrays.asList("h1", "h2").toArray(), heads.toArray()); - - Assertions.assertEquals(uri, nettyRequestFacade.getRequestURI()); - - Assertions.assertEquals("c", nettyRequestFacade.getHeader("h2")); - - Assertions.assertEquals("d", nettyRequestFacade.getParameter("d")); - - Assertions.assertEquals("/a/b", nettyRequestFacade.getPath()); - - Assertions.assertEquals(null, nettyRequestFacade.getParameterValues("e")); - - Assertions.assertArrayEquals(new String[] {"d"}, nettyRequestFacade.getParameterValues("d")); - - Enumeration h1s = nettyRequestFacade.getHeaders("h1"); - - heads = new ArrayList<>(); - - while (h1s.hasMoreElements()) { - - heads.add(h1s.nextElement()); - } - - Assertions.assertArrayEquals(new String[] {"a", "b"}, heads.toArray()); - - Map parameterMap = nettyRequestFacade.getParameterMap(); - - Assertions.assertArrayEquals(new String[] {"c"}, parameterMap.get("c")); - Assertions.assertArrayEquals(new String[] {"d"}, parameterMap.get("d")); - - Assertions.assertEquals("GET", nettyRequestFacade.getMethod()); - } - - @Test - void testChineseDecoding() { - String uri = "/hello/world?name=%E6%9D%8E%E5%BC%BA&age=18"; - DefaultFullHttpRequest defaultFullHttpRequest = - new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri); - defaultFullHttpRequest.headers().add("Accept-Charset", "utf-8, iso-8859-1;q=0.5, *;q=0.1"); - defaultFullHttpRequest.headers().add("Accept-Charset", "utf-16;q=0.3"); - - NettyRequestFacade nettyRequestFacade = new NettyRequestFacade(defaultFullHttpRequest, null); - assertThat(nettyRequestFacade.getPath(), is("/hello/world")); - assertThat(nettyRequestFacade.getParameter("name"), is("李强")); - assertThat(nettyRequestFacade.getParameter("age"), is("18")); - - // Applying the decode method to the URI is acceptable, even if the URI is not encoded. - uri = "/hello/world?name=lily&age=18"; - defaultFullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri); - - nettyRequestFacade = new NettyRequestFacade(defaultFullHttpRequest, null); - assertThat(nettyRequestFacade.getPath(), is("/hello/world")); - assertThat(nettyRequestFacade.getParameter("name"), is("lily")); - assertThat(nettyRequestFacade.getParameter("age"), is("18")); - - // When using URLConnectionRestClient, the URI won't be encoded, but it's still acceptable. - uri = "/hello/world?name=李强&age=18"; - defaultFullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri); - - nettyRequestFacade = new NettyRequestFacade(defaultFullHttpRequest, null); - assertThat(nettyRequestFacade.getPath(), is("/hello/world")); - assertThat(nettyRequestFacade.getParameter("name"), is("李强")); - assertThat(nettyRequestFacade.getParameter("age"), is("18")); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/NoAnnotationRestProtocolTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/NoAnnotationRestProtocolTest.java deleted file mode 100644 index f5c447a3957..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/NoAnnotationRestProtocolTest.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.CommonConstants; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.utils.JsonUtils; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; -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.FrameworkModel; -import org.apache.dubbo.rpc.model.ModuleServiceRepository; -import org.apache.dubbo.rpc.model.ProviderModel; -import org.apache.dubbo.rpc.model.ServiceDescriptor; -import org.apache.dubbo.rpc.protocol.rest.noannotation.NoAnnotationDemoService; -import org.apache.dubbo.rpc.protocol.rest.noannotation.NoAnnotationDemoServiceImpl; - -import java.util.Arrays; -import java.util.List; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -class NoAnnotationRestProtocolTest { - private final Protocol protocol = - ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest"); - private final ProxyFactory proxy = - ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - private final ModuleServiceRepository repository = - ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); - - @AfterEach - public void tearDown() { - protocol.destroy(); - FrameworkModel.destroyAll(); - new JsonUtils() { - public void clearJson() { - setJson(null); - } - }.clearJson(); - SystemPropertyConfigUtils.clearSystemProperty(CommonConstants.DubboProperty.DUBBO_PREFER_JSON_FRAMEWORK_NAME); - } - - @Test - void testJson() { - List jsons = Arrays.asList("fastjson", "fastjson2", "jackson", "gson"); - for (String json : jsons) { - new JsonUtils() { - public void clearJson() { - setJson(null); - } - }.clearJson(); - SystemPropertyConfigUtils.setSystemProperty( - CommonConstants.DubboProperty.DUBBO_PREFER_JSON_FRAMEWORK_NAME, json); - testRestProtocol(); - } - } - - void testRestProtocol() { - URL url = URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort() - + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.noannotation.NoAnnotationDemoService"); - - NoAnnotationDemoServiceImpl server = new NoAnnotationDemoServiceImpl(); - - url = this.registerProvider(url, server, DemoService.class); - - Exporter exporter = - protocol.export(proxy.getInvoker(server, NoAnnotationDemoService.class, url)); - Invoker invoker = protocol.refer(NoAnnotationDemoService.class, url); - - NoAnnotationDemoService client = proxy.getProxy(invoker); - Object result = client.sayHello("haha"); - Assertions.assertEquals("Hello, haha", result); - - result = client.hello(1, 2); - Assertions.assertEquals(3, result); - - User user = client.user(User.getInstance()); - Assertions.assertEquals("invoked", user.getName()); - - Assertions.assertEquals( - User.getInstance(), - client.userList(Arrays.asList(User.getInstance())).get(0)); - - invoker.destroy(); - exporter.unexport(); - } - - @Test - void testAnotherUserRestProtocolByDifferentRestClient() { - testAnotherUserRestProtocol(org.apache.dubbo.remoting.Constants.OK_HTTP); - testAnotherUserRestProtocol(org.apache.dubbo.remoting.Constants.APACHE_HTTP_CLIENT); - testAnotherUserRestProtocol(org.apache.dubbo.remoting.Constants.URL_CONNECTION); - } - - void testAnotherUserRestProtocol(String restClient) { - URL url = URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort() - + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.noannotation.NoAnnotationDemoService&" - + org.apache.dubbo.remoting.Constants.CLIENT_KEY + "=" + restClient); - - NoAnnotationDemoService server = new NoAnnotationDemoServiceImpl(); - - url = this.registerProvider(url, server, DemoService.class); - - Exporter exporter = - protocol.export(proxy.getInvoker(server, NoAnnotationDemoService.class, url)); - Invoker invoker = protocol.refer(NoAnnotationDemoService.class, url); - - NoAnnotationDemoService client = proxy.getProxy(invoker); - String name = "no-annotation"; - String result = client.sayHello(name); - - Assertions.assertEquals("Hello, " + name, result); - - invoker.destroy(); - exporter.unexport(); - } - - private URL registerProvider(URL url, Object impl, Class interfaceClass) { - ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass); - ProviderModel providerModel = new ProviderModel(url.getServiceKey(), impl, serviceDescriptor, null, null); - repository.registerProvider(providerModel); - return url.setServiceModel(providerModel); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/NumberUtilsTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/NumberUtilsTest.java deleted file mode 100644 index 58cf56f916c..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/NumberUtilsTest.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest; - -import org.apache.dubbo.rpc.protocol.rest.util.DataParseUtils; -import org.apache.dubbo.rpc.protocol.rest.util.NumberUtils; - -import java.math.BigDecimal; -import java.math.BigInteger; -import java.nio.charset.StandardCharsets; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public class NumberUtilsTest { - void testParseNumber(String numberStr) { - int integer = NumberUtils.parseNumber(numberStr, Integer.class); - - Assertions.assertEquals(1, integer); - - integer = NumberUtils.parseNumber(numberStr, int.class); - - Assertions.assertEquals(1, integer); - - long a = NumberUtils.parseNumber(numberStr, Long.class); - - Assertions.assertEquals(1, a); - - a = NumberUtils.parseNumber(numberStr, long.class); - - Assertions.assertEquals(1, a); - - byte b = NumberUtils.parseNumber(numberStr, Byte.class); - - Assertions.assertEquals(1, b); - - b = NumberUtils.parseNumber(numberStr, byte.class); - - Assertions.assertEquals(1, b); - - short c = NumberUtils.parseNumber(numberStr, Short.class); - - Assertions.assertEquals(1, c); - - c = NumberUtils.parseNumber(numberStr, short.class); - - Assertions.assertEquals(1, c); - - BigInteger f = NumberUtils.parseNumber(numberStr, BigInteger.class); - - Assertions.assertEquals(1, f.intValue()); - } - - @Test - void testNumberToBytes() { - byte[] except = {49}; - byte[] bytes = (byte[]) DataParseUtils.objectTextConvertToByteArray(Integer.valueOf("1")); - - Assertions.assertArrayEquals(except, bytes); - - bytes = (byte[]) DataParseUtils.objectTextConvertToByteArray(NumberUtils.parseNumber("1", int.class)); - - Assertions.assertArrayEquals(except, bytes); - - except = new byte[] {49}; - bytes = (byte[]) DataParseUtils.objectTextConvertToByteArray(Byte.valueOf("1")); - - Assertions.assertArrayEquals(except, bytes); - - except = new byte[] {49}; - bytes = (byte[]) DataParseUtils.objectTextConvertToByteArray(Short.valueOf("1")); - - Assertions.assertArrayEquals(except, bytes); - - except = new byte[] {49}; - bytes = (byte[]) DataParseUtils.objectTextConvertToByteArray(Long.valueOf("1")); - - Assertions.assertArrayEquals(except, bytes); - - except = new byte[] {49}; - bytes = (byte[]) DataParseUtils.objectTextConvertToByteArray(BigDecimal.valueOf(1)); - - Assertions.assertArrayEquals(except, bytes); - - except = new byte[] {116, 114, 117, 101}; - bytes = (byte[]) DataParseUtils.objectTextConvertToByteArray(Boolean.TRUE); - - Assertions.assertArrayEquals(except, bytes); - - except = new byte[] {116, 114, 117, 101}; - bytes = (byte[]) DataParseUtils.objectTextConvertToByteArray(true); - - Assertions.assertArrayEquals(except, bytes); - - bytes = (byte[]) DataParseUtils.objectTextConvertToByteArray(User.getInstance()); - - except = User.getInstance().toString().getBytes(StandardCharsets.UTF_8); - Assertions.assertArrayEquals(except, bytes); - } - - @Test - void testNumberStr() { - testParseNumber("1"); - testParseNumber("0X0001"); - testParseNumber("0x0001"); - testParseNumber("#1"); - } - - @Test - void testUnHexNumber() { - String numberStr = "1"; - double e = NumberUtils.parseNumber(numberStr, Double.class); - - Assertions.assertEquals(1.0, e); - - e = NumberUtils.parseNumber(numberStr, double.class); - - Assertions.assertEquals(1.0, e); - - BigDecimal g = NumberUtils.parseNumber(numberStr, BigDecimal.class); - - Assertions.assertEquals(1, g.intValue()); - - int integer = NumberUtils.parseNumber(numberStr, int.class); - - Assertions.assertEquals(1, integer); - } - - @Test - void testNegative() { - - Integer integer = NumberUtils.parseNumber("-0X1", int.class); - Assertions.assertEquals(-1, integer); - - BigInteger bigInteger = NumberUtils.parseNumber("-0X1", BigInteger.class); - Assertions.assertEquals(-1, bigInteger.intValue()); - } - - @Test - void testException() { - - Assertions.assertThrowsExactly(IllegalArgumentException.class, () -> { - Object abc = NumberUtils.parseNumber("abc", Object.class); - }); - - Assertions.assertThrowsExactly(IllegalArgumentException.class, () -> { - Object abc = NumberUtils.parseNumber(null, Object.class); - }); - - Assertions.assertThrowsExactly(IllegalArgumentException.class, () -> { - Object abc = NumberUtils.parseNumber("1", null); - }); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/ResteasyResponseTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/ResteasyResponseTest.java deleted file mode 100644 index bebde643999..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/ResteasyResponseTest.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.rpc.protocol.rest; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.rpc.Protocol; -import org.apache.dubbo.rpc.ProxyFactory; -import org.apache.dubbo.rpc.model.*; -import org.apache.dubbo.rpc.protocol.rest.rest.RestDemoService; -import org.apache.dubbo.rpc.protocol.rest.rest.RestDemoServiceImpl; - -import javax.ws.rs.core.Response; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import static org.apache.dubbo.remoting.Constants.SERVER_KEY; - -public class ResteasyResponseTest { - - private Protocol protocol = - ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest"); - private ProxyFactory proxy = - ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - private final int availablePort = NetUtils.getAvailablePort(); - private final URL exportUrl = URL.valueOf("rest://127.0.0.1:" + availablePort - + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.rest.RestDemoService"); - private final ModuleServiceRepository repository = - ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); - private static final String SERVER = "netty4"; - - @AfterEach - public void tearDown() { - protocol.destroy(); - FrameworkModel.destroyAll(); - } - - @Test - void testResponse() { - RestDemoService server = new RestDemoServiceImpl(); - URL url = this.registerProvider(exportUrl, server, RestDemoService.class); - - URL nettyUrl = url.addParameter(SERVER_KEY, SERVER).addParameter("timeout", 3000000); - - protocol.export(proxy.getInvoker(new RestDemoServiceImpl(), RestDemoService.class, nettyUrl)); - - RestDemoService demoService = this.proxy.getProxy(protocol.refer(RestDemoService.class, nettyUrl)); - - Response response = demoService.findUserById(10); - - Assertions.assertNotNull(response); - } - - @Test - void testResponseCustomStatusCode() { - RestDemoService server = new RestDemoServiceImpl(); - URL url = this.registerProvider(exportUrl, server, RestDemoService.class); - - URL nettyUrl = url.addParameter(SERVER_KEY, "netty").addParameter("timeout", 3000000); - - protocol.export(proxy.getInvoker(new RestDemoServiceImpl(), RestDemoService.class, nettyUrl)); - - RestDemoService demoService = this.proxy.getProxy(protocol.refer(RestDemoService.class, nettyUrl)); - - Response response = demoService.deleteUserById("uid"); - - Assertions.assertEquals(response.getStatus(), 200); - } - - private URL registerProvider(URL url, Object impl, Class interfaceClass) { - ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass); - ProviderModel providerModel = new ProviderModel(url.getServiceKey(), impl, serviceDescriptor, null, null); - repository.registerProvider(providerModel); - return url.setServiceModel(providerModel); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/RpcExceptionMapperTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/RpcExceptionMapperTest.java deleted file mode 100644 index fdb3ffdf2f5..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/RpcExceptionMapperTest.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.rpc.protocol.rest; - -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionHandler; - -import javax.validation.ConstraintViolation; -import javax.validation.ConstraintViolationException; - -import java.util.LinkedList; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Answers; -import org.mockito.internal.util.collections.Sets; - -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - -class RpcExceptionMapperTest { - - private ExceptionHandler exceptionMapper; - - @BeforeEach - public void setUp() { - this.exceptionMapper = new RpcExceptionMapper(); - } - - @Test - void testConstraintViolationException() { - ConstraintViolationException violationException = mock(ConstraintViolationException.class); - ConstraintViolation violation = mock(ConstraintViolation.class, Answers.RETURNS_DEEP_STUBS); - given(violationException.getConstraintViolations()).willReturn(Sets.newSet(violation)); - RpcException rpcException = new RpcException("violation", violationException); - - Object response = exceptionMapper.result(rpcException); - - assertThat(response, not(nullValue())); - assertThat(response, instanceOf(ViolationReport.class)); - } - - @Test - void testNormalException() { - RpcException rpcException = new RpcException(); - Object response = exceptionMapper.result(rpcException); - - assertThat(response, not(nullValue())); - assertThat(response, instanceOf(String.class)); - } - - @Test - void testBuildException() { - - RestConstraintViolation restConstraintViolation = new RestConstraintViolation(); - String message = "message"; - restConstraintViolation.setMessage(message); - String path = "path"; - restConstraintViolation.setPath(path); - String value = "value"; - restConstraintViolation.setValue(value); - - Assertions.assertEquals(message, restConstraintViolation.getMessage()); - Assertions.assertEquals(path, restConstraintViolation.getPath()); - Assertions.assertEquals(value, restConstraintViolation.getValue()); - } - - @Test - public void testViolationReport() { - - ViolationReport violationReport = new ViolationReport(); - - RestConstraintViolation restConstraintViolation = new RestConstraintViolation("path", "message", "value"); - - violationReport.addConstraintViolation(restConstraintViolation); - - Assertions.assertEquals(1, violationReport.getConstraintViolations().size()); - - violationReport = new ViolationReport(); - - violationReport.setConstraintViolations(new LinkedList<>()); - - Assertions.assertEquals(0, violationReport.getConstraintViolations().size()); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/ServiceConfigTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/ServiceConfigTest.java deleted file mode 100644 index 8fab22157fb..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/ServiceConfigTest.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.remoting.http.RequestTemplate; -import org.apache.dubbo.remoting.http.config.HttpClientConfig; -import org.apache.dubbo.remoting.http.restclient.OKHttpRestClient; -import org.apache.dubbo.rpc.Exporter; -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.FrameworkModel; -import org.apache.dubbo.rpc.model.ModuleServiceRepository; -import org.apache.dubbo.rpc.model.ProviderModel; -import org.apache.dubbo.rpc.model.ServiceDescriptor; -import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; -import org.apache.dubbo.rpc.protocol.rest.mvc.SpringControllerService; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public class ServiceConfigTest { - - private final Protocol protocol = - ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest"); - private final ProxyFactory proxy = - ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - private final ModuleServiceRepository repository = - ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); - - @AfterEach - public void tearDown() { - protocol.destroy(); - FrameworkModel.destroyAll(); - } - - @Test - void testControllerService() throws Exception { - - int availablePort = NetUtils.getAvailablePort(); - URL url = URL.valueOf("rest://127.0.0.1:" + availablePort - + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.mvc.SpringControllerService"); - - SpringControllerService server = new SpringControllerService(); - - url = this.registerProvider(url, server, SpringControllerService.class); - - Exporter exporter = - protocol.export(proxy.getInvoker(server, SpringControllerService.class, url)); - - OKHttpRestClient okHttpRestClient = new OKHttpRestClient(new HttpClientConfig()); - - RequestTemplate requestTemplate = new RequestTemplate(null, "GET", "127.0.0.1:" + availablePort); - requestTemplate.path("/controller/sayHello?say=dubbo"); - requestTemplate.addHeader(RestConstant.CONTENT_TYPE, "text/plain"); - requestTemplate.addHeader(RestConstant.ACCEPT, "text/plain"); - requestTemplate.addHeader(RestHeaderEnum.VERSION.getHeader(), "1.0.0"); - - byte[] body = okHttpRestClient.send(requestTemplate).get().getBody(); - - Assertions.assertEquals("dubbo", new String(body)); - exporter.unexport(); - } - - private URL registerProvider(URL url, Object impl, Class interfaceClass) { - ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass); - ProviderModel providerModel = new ProviderModel(url.getServiceKey(), impl, serviceDescriptor, null, null); - repository.registerProvider(providerModel); - return url.setServiceModel(providerModel); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/SpringMvcRestProtocolTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/SpringMvcRestProtocolTest.java deleted file mode 100644 index 0c80b818e16..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/SpringMvcRestProtocolTest.java +++ /dev/null @@ -1,447 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.utils.NetUtils; -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.Result; -import org.apache.dubbo.rpc.RpcContext; -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.model.ApplicationModel; -import org.apache.dubbo.rpc.model.FrameworkModel; -import org.apache.dubbo.rpc.model.ModuleServiceRepository; -import org.apache.dubbo.rpc.model.ProviderModel; -import org.apache.dubbo.rpc.model.ServiceDescriptor; -import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionHandler; -import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionMapper; -import org.apache.dubbo.rpc.protocol.rest.mvc.SpringDemoServiceImpl; -import org.apache.dubbo.rpc.protocol.rest.mvc.SpringRestDemoService; -import org.apache.dubbo.rpc.protocol.rest.rest.AnotherUserRestService; -import org.apache.dubbo.rpc.protocol.rest.rest.AnotherUserRestServiceImpl; - -import java.util.Arrays; -import java.util.Map; - -import org.hamcrest.CoreMatchers; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.springframework.aop.framework.AdvisedSupport; -import org.springframework.aop.framework.AopProxy; -import org.springframework.aop.framework.ProxyCreatorSupport; -import org.springframework.util.LinkedMultiValueMap; - -import static org.apache.dubbo.remoting.Constants.SERVER_KEY; -import static org.apache.dubbo.rpc.protocol.rest.Constants.EXTENSION_KEY; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; - -public class SpringMvcRestProtocolTest { - private Protocol protocol = - ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest"); - private ProxyFactory proxy = - ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - - private static URL getUrl() { - return URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort() - + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.mvc.SpringRestDemoService"); - } - - private static final String SERVER = "netty4"; - - private final ModuleServiceRepository repository = - ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); - - private final ExceptionMapper exceptionMapper = new ExceptionMapper(); - - @AfterEach - public void tearDown() { - protocol.destroy(); - FrameworkModel.destroyAll(); - } - - public SpringRestDemoService getServerImpl() { - return new SpringDemoServiceImpl(); - } - - public Class getServerClass() { - return SpringRestDemoService.class; - } - - public Exporter getExport(URL url, SpringRestDemoService server) { - url = url.addParameter(SERVER_KEY, SERVER); - return protocol.export(proxy.getInvoker(server, getServerClass(), url)); - } - - public Exporter getExceptionHandlerExport(URL url, SpringRestDemoService server) { - url = url.addParameter(SERVER_KEY, SERVER); - url = url.addParameter(EXTENSION_KEY, TestExceptionMapper.class.getName()); - return protocol.export(proxy.getInvoker(server, getServerClass(), url)); - } - - @Test - void testRestProtocol() { - URL url = URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort() - + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.mvc.SpringRestDemoService"); - - SpringRestDemoService server = getServerImpl(); - - url = this.registerProvider(url, server, getServerClass()); - - Exporter exporter = getExport(url, server); - Invoker invoker = protocol.refer(SpringRestDemoService.class, url); - Assertions.assertFalse(server.isCalled()); - - SpringRestDemoService client = proxy.getProxy(invoker); - String result = client.sayHello("haha"); - Assertions.assertTrue(server.isCalled()); - Assertions.assertEquals("Hello, haha", result); - - String header = client.testHeader("header"); - Assertions.assertEquals("header", header); - - String headerInt = client.testHeaderInt(1); - Assertions.assertEquals("1", headerInt); - invoker.destroy(); - exporter.unexport(); - } - - @Test - void testAnotherUserRestProtocol() { - URL url = URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort() - + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.rest.AnotherUserRestService"); - - AnotherUserRestServiceImpl server = new AnotherUserRestServiceImpl(); - - url = this.registerProvider(url, server, SpringRestDemoService.class); - - Exporter exporter = - protocol.export(proxy.getInvoker(server, AnotherUserRestService.class, url)); - Invoker invoker = protocol.refer(AnotherUserRestService.class, url); - - AnotherUserRestService client = proxy.getProxy(invoker); - User result = client.getUser(123l); - - Assertions.assertEquals(123l, result.getId()); - - result.setName("dubbo"); - Assertions.assertEquals(123l, client.registerUser(result).getId()); - - Assertions.assertEquals("context", client.getContext()); - - byte[] bytes = {1, 2, 3, 4}; - Assertions.assertTrue(Arrays.equals(bytes, client.bytes(bytes))); - - Assertions.assertEquals(1l, client.number(1l)); - - invoker.destroy(); - exporter.unexport(); - } - - @Test - void testRestProtocolWithContextPath() { - SpringRestDemoService server = getServerImpl(); - Assertions.assertFalse(server.isCalled()); - int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("rest://127.0.0.1:" + port - + "/a/b/c?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.mvc.SpringRestDemoService"); - - url = this.registerProvider(url, server, SpringRestDemoService.class); - - Exporter exporter = getExport(url, server); - - url = URL.valueOf("rest://127.0.0.1:" + port - + "/a/b/c/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.mvc.SpringRestDemoService"); - Invoker invoker = protocol.refer(SpringRestDemoService.class, url); - SpringRestDemoService client = proxy.getProxy(invoker); - String result = client.sayHello("haha"); - Assertions.assertTrue(server.isCalled()); - Assertions.assertEquals("Hello, haha", result); - invoker.destroy(); - exporter.unexport(); - } - - @Test - void testExport() { - SpringRestDemoService server = getServerImpl(); - - URL url = this.registerProvider(getUrl(), server, SpringRestDemoService.class); - - RpcContext.getClientAttachment().setAttachment("timeout", "200"); - Exporter exporter = getExport(url, server); - - SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, url)); - - Integer echoString = demoService.hello(1, 2); - assertThat(echoString, is(3)); - - exporter.unexport(); - } - - @Test - void testNettyServer() { - SpringRestDemoService server = getServerImpl(); - - URL nettyUrl = this.registerProvider(getUrl(), server, SpringRestDemoService.class); - - Exporter exporter = getExport(nettyUrl, server); - - SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl)); - - Integer echoString = demoService.hello(10, 10); - assertThat(echoString, is(20)); - - exporter.unexport(); - } - - @Disabled - @Test - void testServletWithoutWebConfig() { - Assertions.assertThrows(RpcException.class, () -> { - SpringRestDemoService server = getServerImpl(); - - URL url = this.registerProvider(getUrl(), server, SpringRestDemoService.class); - - URL servletUrl = url.addParameter(SERVER_KEY, "servlet"); - - protocol.export(proxy.getInvoker(server, getServerClass(), servletUrl)); - }); - } - - @Test - void testErrorHandler() { - Assertions.assertThrows(RpcException.class, () -> { - exceptionMapper.unRegisterMapper(RuntimeException.class); - SpringRestDemoService server = getServerImpl(); - - URL nettyUrl = this.registerProvider(getUrl(), server, SpringRestDemoService.class); - - Exporter exporter = getExport(nettyUrl, server); - - SpringRestDemoService demoService = - this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl)); - - demoService.error(); - }); - } - - @Test - void testInvoke() { - SpringRestDemoService server = getServerImpl(); - - URL url = this.registerProvider(getUrl(), server, SpringRestDemoService.class); - - Exporter exporter = getExport(url, server); - - RpcInvocation rpcInvocation = new RpcInvocation( - "hello", - SpringRestDemoService.class.getName(), - "", - new Class[] {Integer.class, Integer.class}, - new Integer[] {2, 3}); - - Result result = exporter.getInvoker().invoke(rpcInvocation); - assertThat(result.getValue(), CoreMatchers.is(5)); - } - - @Test - void testFilter() { - SpringRestDemoService server = getServerImpl(); - - URL url = this.registerProvider(getUrl(), server, SpringRestDemoService.class); - - Exporter exporter = getExport(url, server); - - SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, url)); - - Integer result = demoService.hello(1, 2); - - assertThat(result, is(3)); - - exporter.unexport(); - } - - @Disabled - @Test - void testRpcContextFilter() { - SpringRestDemoService server = getServerImpl(); - - URL nettyUrl = this.registerProvider(getUrl(), server, SpringRestDemoService.class); - - // use RpcContextFilter - // URL nettyUrl = url.addParameter(SERVER_KEY, "netty") - // .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.RpcContextFilter"); - Exporter exporter = getExport(nettyUrl, server); - - SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl)); - - // make sure null and base64 encoded string can work - RpcContext.getClientAttachment().setAttachment("key1", null); - RpcContext.getClientAttachment().setAttachment("key2", "value"); - RpcContext.getClientAttachment().setAttachment("key3", "=value"); - RpcContext.getClientAttachment().setAttachment("key4", "YWJjZGVmCg=="); - RpcContext.getClientAttachment().setAttachment("key5", "val=ue"); - Integer result = demoService.hello(1, 2); - - assertThat(result, is(3)); - - Map attachment = org.apache.dubbo.rpc.protocol.rest.mvc.SpringDemoServiceImpl.getAttachments(); - assertThat(attachment.get("key1"), nullValue()); - assertThat(attachment.get("key2"), equalTo("value")); - assertThat(attachment.get("key3"), equalTo("=value")); - assertThat(attachment.get("key4"), equalTo("YWJjZGVmCg==")); - assertThat(attachment.get("key5"), equalTo("val=ue")); - - exporter.unexport(); - } - - @Disabled - @Test - void testRegFail() { - Assertions.assertThrows(RuntimeException.class, () -> { - SpringRestDemoService server = getServerImpl(); - - URL url = this.registerProvider(getUrl(), server, SpringRestDemoService.class); - - URL nettyUrl = url.addParameter(EXTENSION_KEY, "com.not.existing.Filter"); - Exporter exporter = getExport(nettyUrl, server); - }); - } - - @Test - void testDefaultPort() { - assertThat(protocol.getDefaultPort(), is(80)); - } - - @Test - void testExceptionMapper() { - - SpringRestDemoService server = getServerImpl(); - - URL exceptionUrl = this.registerProvider(getUrl(), server, SpringRestDemoService.class); - - Exporter exporter = getExceptionHandlerExport(exceptionUrl, server); - - SpringRestDemoService referDemoService = - this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, exceptionUrl)); - - Assertions.assertEquals("test-exception", referDemoService.error()); - - exporter.unexport(); - } - - @Test - void testFormConsumerParser() { - SpringRestDemoService server = getServerImpl(); - - URL nettyUrl = this.registerProvider(getUrl(), server, SpringRestDemoService.class); - - Exporter exporter = getExport(nettyUrl, server); - - SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl)); - - User user = new User(); - user.setAge(18); - user.setName("dubbo"); - user.setId(404l); - String name = demoService.testFormBody(user); - Assertions.assertEquals("dubbo", name); - - LinkedMultiValueMap forms = new LinkedMultiValueMap<>(); - forms.put("form", Arrays.asList("F1")); - - Assertions.assertEquals(Arrays.asList("F1"), demoService.testFormMapBody(forms)); - - exporter.unexport(); - } - - @Test - void testPrimitive() { - SpringRestDemoService server = getServerImpl(); - - URL nettyUrl = this.registerProvider(getUrl(), server, SpringRestDemoService.class); - - Exporter exporter = getExport(nettyUrl, server); - - SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl)); - - Integer result = demoService.primitiveInt(1, 2); - Long resultLong = demoService.primitiveLong(1, 2l); - long resultByte = demoService.primitiveByte((byte) 1, 2l); - long resultShort = demoService.primitiveShort((short) 1, 2l, 1); - - assertThat(result, is(3)); - assertThat(resultShort, is(3l)); - assertThat(resultLong, is(3l)); - assertThat(resultByte, is(3l)); - - exporter.unexport(); - } - - @Test - void testProxyDoubleCheck() { - - ProxyCreatorSupport proxyCreatorSupport = new ProxyCreatorSupport(); - AdvisedSupport advisedSupport = new AdvisedSupport(); - advisedSupport.setTarget(getServerImpl()); - AopProxy aopProxy = proxyCreatorSupport.getAopProxyFactory().createAopProxy(advisedSupport); - Object proxy = aopProxy.getProxy(); - SpringRestDemoService server = (SpringRestDemoService) proxy; - - URL nettyUrl = this.registerProvider(getUrl(), server, SpringRestDemoService.class); - - Exporter exporter = getExport(nettyUrl, server); - - SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl)); - - Integer result = demoService.primitiveInt(1, 2); - Long resultLong = demoService.primitiveLong(1, 2l); - long resultByte = demoService.primitiveByte((byte) 1, 2l); - long resultShort = demoService.primitiveShort((short) 1, 2l, 1); - - assertThat(result, is(3)); - assertThat(resultShort, is(3l)); - assertThat(resultLong, is(3l)); - assertThat(resultByte, is(3l)); - - exporter.unexport(); - } - - public static class TestExceptionMapper implements ExceptionHandler { - - @Override - public String result(RuntimeException e) { - return "test-exception"; - } - } - - private URL registerProvider(URL url, Object impl, Class interfaceClass) { - ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass); - ProviderModel providerModel = new ProviderModel(url.getServiceKey(), impl, serviceDescriptor, null, null); - repository.registerProvider(providerModel); - return url.setServiceModel(providerModel); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/User.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/User.java deleted file mode 100644 index b877e2072c4..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/User.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest; - -import java.io.Serializable; -import java.util.Objects; - -/** - * User Entity - * - * @since 2.7.6 - */ -public class User implements Serializable { - - private Long id; - - private String name; - - private Integer age; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Integer getAge() { - return age; - } - - public void setAge(Integer age) { - this.age = age; - } - - public static User getInstance() { - User user = new User(); - user.setAge(18); - user.setName("dubbo"); - user.setId(404l); - return user; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - User user = (User) o; - return Objects.equals(id, user.id) && Objects.equals(name, user.name) && Objects.equals(age, user.age); - } - - @Override - public int hashCode() { - return Objects.hash(id, name, age); - } - - @Override - public String toString() { - return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/compatibility/Apple.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/compatibility/Apple.java deleted file mode 100644 index 4185dd59448..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/compatibility/Apple.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.compatibility; - -public class Apple implements Fruit { - - @Override - public String sayName() { - return "This is apple"; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/compatibility/Fruit.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/compatibility/Fruit.java deleted file mode 100644 index a05779be619..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/compatibility/Fruit.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.rpc.protocol.rest.compatibility; - -public interface Fruit { - String sayName(); -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/compatibility/RestDemoService.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/compatibility/RestDemoService.java deleted file mode 100644 index b0b9b370179..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/compatibility/RestDemoService.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.compatibility; - -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.core.MediaType; - -@Path("rest") -public interface RestDemoService { - @GET - @Path("hello") - @Consumes({MediaType.APPLICATION_JSON}) - String sayHello(String name); - - @GET - @Path("hi") - @Consumes({MediaType.APPLICATION_JSON}) - String sayHi(); - - @GET - @Path("fruit") - @Consumes({MediaType.APPLICATION_JSON}) - Fruit sayFruit(); - - @GET - @Path("apple") - @Consumes({MediaType.APPLICATION_JSON}) - Apple sayApple(); -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/compatibility/RestDemoServiceImpl.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/compatibility/RestDemoServiceImpl.java deleted file mode 100644 index f1b94f4455e..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/compatibility/RestDemoServiceImpl.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.rpc.protocol.rest.compatibility; - -public class RestDemoServiceImpl implements RestDemoService { - @Override - public String sayHello(String name) { - return "hello"; - } - - @Override - public String sayHi() { - return "hi"; - } - - @Override - public Fruit sayFruit() { - return new Apple(); - } - - @Override - public Apple sayApple() { - return new Apple(); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/exception/ResteasyExceptionMapper.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/exception/ResteasyExceptionMapper.java deleted file mode 100644 index cf540416d46..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/exception/ResteasyExceptionMapper.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.exception; - -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.ExceptionMapper; - -public class ResteasyExceptionMapper implements ExceptionMapper { - @Override - public Response toResponse(RuntimeException exception) { - return Response.status(200).entity("test-exception").build(); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/filter/TestContainerRequestFilter.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/filter/TestContainerRequestFilter.java deleted file mode 100644 index f7305bac58b..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/filter/TestContainerRequestFilter.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.filter; - -import javax.annotation.Priority; -import javax.ws.rs.Priorities; -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerRequestFilter; -import javax.ws.rs.core.Response; - -import java.io.IOException; - -@Priority(Priorities.USER) -public class TestContainerRequestFilter implements ContainerRequestFilter { - @Override - public void filter(ContainerRequestContext requestContext) throws IOException { - - requestContext.abortWith(Response.status(200).entity("return-success").build()); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/filter/TraceFilter.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/filter/TraceFilter.java deleted file mode 100644 index cc2a0717b14..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/filter/TraceFilter.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.filter; - -import javax.annotation.Priority; -import javax.ws.rs.Priorities; -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerRequestFilter; -import javax.ws.rs.container.ContainerResponseContext; -import javax.ws.rs.container.ContainerResponseFilter; - -import java.io.IOException; - -@Priority(Priorities.USER) -public class TraceFilter implements ContainerRequestFilter, ContainerResponseFilter { - - @Override - public void filter(ContainerRequestContext requestContext) throws IOException { - System.out.println( - "Request filter invoked: " + requestContext.getUriInfo().getAbsolutePath()); - } - - @Override - public void filter( - ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) - throws IOException { - containerResponseContext.setEntity("response-filter"); - System.out.println("Response filter invoked."); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/filter/TraceRequestAndResponseFilter.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/filter/TraceRequestAndResponseFilter.java deleted file mode 100644 index 68373279416..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/filter/TraceRequestAndResponseFilter.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.filter; - -import javax.annotation.Priority; -import javax.ws.rs.Priorities; -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerRequestFilter; -import javax.ws.rs.container.ContainerResponseContext; -import javax.ws.rs.container.ContainerResponseFilter; - -import java.io.IOException; - -@Priority(Priorities.USER) -public class TraceRequestAndResponseFilter implements ContainerRequestFilter, ContainerResponseFilter { - - @Override - public void filter(ContainerRequestContext requestContext) throws IOException { - - requestContext.getHeaders().add("test-response", "header-result"); - } - - @Override - public void filter( - ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) - throws IOException { - - String headerString = containerRequestContext.getHeaderString("test-response"); - containerResponseContext.setEntity(headerString); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerApiListingResourceTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerApiListingResourceTest.java deleted file mode 100644 index 3bca8798061..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerApiListingResourceTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.integration.swagger; - -import javax.servlet.ServletConfig; -import javax.servlet.ServletContext; -import javax.ws.rs.core.Application; -import javax.ws.rs.core.Response; - -import java.net.URI; -import java.util.HashSet; -import java.util.Set; - -import io.swagger.models.Swagger; -import org.jboss.resteasy.spi.ResteasyUriInfo; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -class DubboSwaggerApiListingResourceTest { - - private Application app; - private ServletConfig sc; - - @Test - void test() throws Exception { - - DubboSwaggerApiListingResource resource = new DubboSwaggerApiListingResource(); - - app = mock(Application.class); - sc = mock(ServletConfig.class); - Set> sets = new HashSet>(); - sets.add(SwaggerService.class); - - when(sc.getServletContext()).thenReturn(mock(ServletContext.class)); - when(app.getClasses()).thenReturn(sets); - - Response response = resource.getListingJson(app, sc, null, new ResteasyUriInfo(new URI("http://rest.test"))); - - Assertions.assertNotNull(response); - Swagger swagger = (Swagger) response.getEntity(); - Assertions.assertEquals("SwaggerService", swagger.getTags().get(0).getName()); - Assertions.assertEquals( - "/demoService/hello", swagger.getPaths().keySet().toArray()[0].toString()); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/SwaggerService.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/SwaggerService.java deleted file mode 100644 index 6c35edc89c3..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/SwaggerService.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.integration.swagger; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.QueryParam; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; - -@Path("/demoService") -@Api(value = "SwaggerService") -public interface SwaggerService { - @GET - @Path("/hello") - @ApiOperation(value = "hello") - Integer hello(@QueryParam("a") Integer a, @QueryParam("b") Integer b); -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/intercept/DynamicTraceInterceptor.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/intercept/DynamicTraceInterceptor.java deleted file mode 100644 index 66c62ecda93..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/intercept/DynamicTraceInterceptor.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.rpc.protocol.rest.intercept; - -import javax.annotation.Priority; -import javax.ws.rs.Priorities; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.ext.ReaderInterceptor; -import javax.ws.rs.ext.ReaderInterceptorContext; -import javax.ws.rs.ext.WriterInterceptor; -import javax.ws.rs.ext.WriterInterceptorContext; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; - -@Priority(Priorities.USER) -public class DynamicTraceInterceptor implements ReaderInterceptor, WriterInterceptor { - - public DynamicTraceInterceptor() {} - - @Override - public Object aroundReadFrom(ReaderInterceptorContext readerInterceptorContext) - throws IOException, WebApplicationException { - System.out.println("Dynamic reader interceptor invoked"); - return readerInterceptorContext.proceed(); - } - - @Override - public void aroundWriteTo(WriterInterceptorContext writerInterceptorContext) - throws IOException, WebApplicationException { - System.out.println("Dynamic writer interceptor invoked"); - writerInterceptorContext.getOutputStream().write("intercept".getBytes(StandardCharsets.UTF_8)); - writerInterceptorContext.proceed(); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/SpringControllerService.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/SpringControllerService.java deleted file mode 100644 index bf761196d46..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/SpringControllerService.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.mvc; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -@RequestMapping("/controller") -public class SpringControllerService { - - @GetMapping("/sayHello") - public String sayHello(String say) { - return say; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/SpringDemoServiceImpl.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/SpringDemoServiceImpl.java deleted file mode 100644 index f5d92787c0c..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/SpringDemoServiceImpl.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.mvc; - -import org.apache.dubbo.rpc.RpcContext; -import org.apache.dubbo.rpc.protocol.rest.User; - -import java.util.List; -import java.util.Map; - -import org.springframework.util.LinkedMultiValueMap; - -public class SpringDemoServiceImpl implements SpringRestDemoService { - private static Map context; - private boolean called; - - @Override - public String sayHello(String name) { - called = true; - return "Hello, " + name; - } - - @Override - public boolean isCalled() { - return called; - } - - @Override - public String testFormBody(User user) { - return user.getName(); - } - - @Override - public List testFormMapBody(LinkedMultiValueMap map) { - return map.get("form"); - } - - @Override - public String testHeader(String header) { - return header; - } - - @Override - public String testHeaderInt(int header) { - return String.valueOf(header); - } - - @Override - public Integer hello(Integer a, Integer b) { - context = RpcContext.getServerAttachment().getObjectAttachments(); - return a + b; - } - - @Override - public String error() { - throw new RuntimeException(); - } - - public static Map getAttachments() { - return context; - } - - @Override - public int primitiveInt(int a, int b) { - return a + b; - } - - @Override - public long primitiveLong(long a, Long b) { - return a + b; - } - - @Override - public long primitiveByte(byte a, Long b) { - return a + b; - } - - @Override - public long primitiveShort(short a, Long b, int c) { - return a + b; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/SpringRestDemoService.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/SpringRestDemoService.java deleted file mode 100644 index b2bcd08e0fd..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/SpringRestDemoService.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.mvc; - -import org.apache.dubbo.rpc.protocol.rest.User; - -import java.util.List; - -import org.springframework.http.MediaType; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; - -@RequestMapping("/demoService") -public interface SpringRestDemoService { - @RequestMapping(value = "/hello", method = RequestMethod.GET) - Integer hello(@RequestParam Integer a, @RequestParam Integer b); - - @RequestMapping(value = "/error", method = RequestMethod.GET) - String error(); - - @RequestMapping(value = "/sayHello", method = RequestMethod.POST, consumes = MediaType.TEXT_PLAIN_VALUE) - String sayHello(String name); - - boolean isCalled(); - - @RequestMapping( - value = "/testFormBody", - method = RequestMethod.POST, - consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) - String testFormBody(@RequestBody User user); - - @RequestMapping( - value = "/testFormMapBody", - method = RequestMethod.POST, - consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) - List testFormMapBody(@RequestBody LinkedMultiValueMap map); - - @RequestMapping(value = "/testHeader", method = RequestMethod.POST, consumes = MediaType.TEXT_PLAIN_VALUE) - String testHeader(@RequestHeader String header); - - @RequestMapping(value = "/testHeaderInt", method = RequestMethod.GET, consumes = MediaType.TEXT_PLAIN_VALUE) - String testHeaderInt(@RequestHeader int header); - - @RequestMapping(method = RequestMethod.GET, value = "/primitive") - int primitiveInt(@RequestParam("a") int a, @RequestParam("b") int b); - - @RequestMapping(method = RequestMethod.GET, value = "/primitiveLong") - long primitiveLong(@RequestParam("a") long a, @RequestParam("b") Long b); - - @RequestMapping(method = RequestMethod.GET, value = "/primitiveByte") - long primitiveByte(@RequestParam("a") byte a, @RequestParam("b") Long b); - - @RequestMapping(method = RequestMethod.POST, value = "/primitiveShort") - long primitiveShort(@RequestParam("a") short a, @RequestParam("b") Long b, @RequestBody int c); -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/feign/FeignClientController.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/feign/FeignClientController.java deleted file mode 100644 index 1d8d046793e..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/feign/FeignClientController.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.mvc.feign; - -import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -@FeignClient(path = "/feign") -@RequestMapping("/context") -public interface FeignClientController { - - @RequestMapping(value = "/hello", method = RequestMethod.GET) - String hello(); -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/feign/FeignClientControllerImpl.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/feign/FeignClientControllerImpl.java deleted file mode 100644 index a7d4387c89d..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/feign/FeignClientControllerImpl.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.mvc.feign; - -public class FeignClientControllerImpl implements FeignClientController { - - @Override - public String hello() { - return "hello, feign"; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/noannotation/NoAnnotationDemoService.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/noannotation/NoAnnotationDemoService.java deleted file mode 100644 index 267c1106b4a..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/noannotation/NoAnnotationDemoService.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.noannotation; - -import org.apache.dubbo.rpc.protocol.rest.User; - -import java.util.List; - -public interface NoAnnotationDemoService { - Integer hello(Integer a, Integer b); - - String error(); - - String sayHello(String name); - - User user(User user); - - List userList(List users); -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/noannotation/NoAnnotationDemoServiceImpl.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/noannotation/NoAnnotationDemoServiceImpl.java deleted file mode 100644 index e29313375aa..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/noannotation/NoAnnotationDemoServiceImpl.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.noannotation; - -import org.apache.dubbo.rpc.protocol.rest.User; - -import java.util.List; - -public class NoAnnotationDemoServiceImpl implements NoAnnotationDemoService { - - @Override - public Integer hello(Integer a, Integer b) { - return a + b; - } - - @Override - public String error() { - return null; - } - - @Override - public String sayHello(String name) { - return "Hello, " + name; - } - - @Override - public User user(User user) { - user.setName("invoked"); - return user; - } - - @Override - public List userList(List users) { - return users; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/AnotherUserRestService.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/AnotherUserRestService.java deleted file mode 100644 index 0eed7872e5c..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/AnotherUserRestService.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.rest; - -import org.apache.dubbo.rpc.protocol.rest.User; - -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; - -import java.util.Map; - -@Path("u") -@Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) -public interface AnotherUserRestService { - - @GET - @Path("{id : \\d+}") - @Produces({MediaType.APPLICATION_JSON}) - User getUser(@PathParam("id") Long id); - - @POST - @Path("register") - @Produces("text/xml; charset=UTF-8") - RegistrationResult registerUser(User user); - - @GET - @Path("context") - @Produces({MediaType.APPLICATION_JSON}) - String getContext(); - - @POST - @Path("bytes") - @Produces({MediaType.APPLICATION_JSON}) - byte[] bytes(byte[] bytes); - - @POST - @Path("number") - @Produces({MediaType.APPLICATION_JSON}) - Long number(Long number); - - @POST - @Path("headerMap") - @Produces({MediaType.APPLICATION_JSON}) - String headerMap(@HeaderParam("headers") Map headers); -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/AnotherUserRestServiceImpl.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/AnotherUserRestServiceImpl.java deleted file mode 100644 index 3e99f97bae9..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/AnotherUserRestServiceImpl.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.rest; - -import org.apache.dubbo.rpc.protocol.rest.User; - -import java.util.Map; - -public class AnotherUserRestServiceImpl implements AnotherUserRestService { - - @Override - public User getUser(Long id) { - - User user = new User(); - user.setId(id); - return user; - } - - @Override - public RegistrationResult registerUser(User user) { - return new RegistrationResult(user.getId()); - } - - @Override - public String getContext() { - - return "context"; - } - - @Override - public byte[] bytes(byte[] bytes) { - return bytes; - } - - @Override - public Long number(Long number) { - return number; - } - - @Override - public String headerMap(Map headers) { - return headers.get("headers"); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/HttpMethodService.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/HttpMethodService.java deleted file mode 100644 index 88696140a7f..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/HttpMethodService.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.rest; - -import javax.ws.rs.*; - -@Path("/demoService") -public interface HttpMethodService { - - @POST - @Path("/sayPost") - @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) - String sayHelloPost(@QueryParam("name") String name); - - @DELETE - @Path("/sayDelete") - @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) - String sayHelloDelete(@QueryParam("name") String name); - - @HEAD - @Path("/sayHead") - @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) - String sayHelloHead(); - - @GET - @Path("/sayGet") - @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) - String sayHelloGet(@QueryParam("name") String name); - - @PUT - @Path("/sayPut") - @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) - String sayHelloPut(@QueryParam("name") String name); - - @PATCH - @Path("/sayPatch") - @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) - String sayHelloPatch(@QueryParam("name") String name); - - @OPTIONS - @Path("/sayOptions") - @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) - String sayHelloOptions(@QueryParam("name") String name); -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/HttpMethodServiceImpl.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/HttpMethodServiceImpl.java deleted file mode 100644 index 7dee6606c2c..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/HttpMethodServiceImpl.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.rest; - -public class HttpMethodServiceImpl implements HttpMethodService { - - @Override - public String sayHelloPost(String name) { - return name; - } - - @Override - public String sayHelloDelete(String name) { - return name; - } - - @Override - public String sayHelloHead() { - return "hello"; - } - - @Override - public String sayHelloGet(String name) { - return name; - } - - @Override - public String sayHelloPut(String name) { - return name; - } - - @Override - public String sayHelloPatch(String name) { - return name; - } - - @Override - public String sayHelloOptions(String name) { - return name; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RegistrationResult.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RegistrationResult.java deleted file mode 100644 index 12b0e5627dd..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RegistrationResult.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.rest; - -import javax.xml.bind.annotation.XmlRootElement; - -import java.io.Serializable; -import java.util.Objects; - -/** - * DTO to customize the returned message - */ -@XmlRootElement -public class RegistrationResult implements Serializable { - - private Long id; - - public RegistrationResult() {} - - public RegistrationResult(Long id) { - this.id = id; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - RegistrationResult that = (RegistrationResult) o; - return Objects.equals(id, that.id); - } - - @Override - public int hashCode() { - return Objects.hash(id); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RestDemoForTestException.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RestDemoForTestException.java deleted file mode 100644 index 5ef5293a6dc..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RestDemoForTestException.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.rest; - -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; - -@Path("/demoService") -public interface RestDemoForTestException { - - @POST - @Path("/noFound") - @Produces(MediaType.TEXT_PLAIN) - String test404(); - - @GET - @Consumes({MediaType.TEXT_PLAIN}) - @Path("/hello") - Integer test400(@QueryParam("a") String a, @QueryParam("b") String b); - - @POST - @Path("{uid}") - String testMethodDisallowed(@PathParam("uid") String uid); -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RestDemoService.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RestDemoService.java deleted file mode 100644 index 728ce078849..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RestDemoService.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.rest; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.FormParam; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -@Path("/demoService") -public interface RestDemoService { - @GET - @Path("/hello") - Integer hello(@QueryParam("a") Integer a, @QueryParam("b") Integer b); - - @GET - @Path("/findUserById") - Response findUserById(@QueryParam("id") Integer id); - - @GET - @Path("/error") - String error(); - - @POST - @Path("/say") - @Consumes({MediaType.TEXT_PLAIN}) - String sayHello(String name); - - @POST - @Path("number") - @Produces({MediaType.APPLICATION_FORM_URLENCODED}) - @Consumes({MediaType.APPLICATION_FORM_URLENCODED}) - Long testFormBody(@FormParam("number") Long number); - - boolean isCalled(); - - @DELETE - @Path("{uid}") - String deleteUserByUid(@PathParam("uid") String uid); - - @DELETE - @Path("/deleteUserById/{uid}") - public Response deleteUserById(@PathParam("uid") String uid); -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RestDemoServiceImpl.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RestDemoServiceImpl.java deleted file mode 100644 index 63a4734e852..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RestDemoServiceImpl.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.rest; - -import org.apache.dubbo.rpc.RpcContext; - -import javax.ws.rs.core.Response; - -import java.util.HashMap; -import java.util.Map; - -import org.jboss.resteasy.specimpl.BuiltResponse; - -public class RestDemoServiceImpl implements RestDemoService { - private static Map context; - private boolean called; - - @Override - public String sayHello(String name) { - called = true; - return "Hello, " + name; - } - - @Override - public Long testFormBody(Long number) { - return number; - } - - public boolean isCalled() { - return called; - } - - @Override - public String deleteUserByUid(String uid) { - return uid; - } - - @Override - public Integer hello(Integer a, Integer b) { - context = RpcContext.getServerAttachment().getObjectAttachments(); - return a + b; - } - - @Override - public Response findUserById(Integer id) { - Map content = new HashMap<>(); - content.put("username", "jack"); - content.put("id", id); - - return BuiltResponse.ok(content).build(); - } - - @Override - public String error() { - throw new RuntimeException(); - } - - @Override - public Response deleteUserById(String uid) { - return Response.status(300).entity("deleted").build(); - } - - public static Map getAttachments() { - return context; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/TestGetInvokerService.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/TestGetInvokerService.java deleted file mode 100644 index 994b7a285ad..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/TestGetInvokerService.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.rest; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; - -@Path("/test") -public interface TestGetInvokerService { - - @GET - @Path("/getInvoker") - String getInvoker(); -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/TestGetInvokerServiceImpl.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/TestGetInvokerServiceImpl.java deleted file mode 100644 index e04757afcfd..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/TestGetInvokerServiceImpl.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.rpc.protocol.rest.rest; - -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.RpcContext; -import org.apache.dubbo.rpc.protocol.rest.RestRPCInvocationUtil; -import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; - -import java.lang.reflect.Method; - -import org.junit.jupiter.api.Assertions; - -public class TestGetInvokerServiceImpl implements TestGetInvokerService { - - @Override - public String getInvoker() { - Object request = RpcContext.getServiceContext().getRequest(); - RequestFacade requestFacade = (RequestFacade) request; - Invoker invokerByRequest = RestRPCInvocationUtil.getInvokerByRequest((RequestFacade) request); - - Method hello = null; - Method hashcode = null; - try { - hello = TestGetInvokerServiceImpl.class.getDeclaredMethod("getInvoker"); - hashcode = TestGetInvokerServiceImpl.class.getDeclaredMethod("hashcode"); - - } catch (NoSuchMethodException e) { - - } - - Invoker invokerByServiceInvokeMethod = - RestRPCInvocationUtil.getInvokerByServiceInvokeMethod(hello, requestFacade.getServiceDeployer()); - - Invoker invoker = - RestRPCInvocationUtil.getInvokerByServiceInvokeMethod(hashcode, requestFacade.getServiceDeployer()); - - Assertions.assertEquals(invokerByRequest, invokerByServiceInvokeMethod); - Assertions.assertNull(invoker); - - return "success"; - } -} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/resources/log4j2-test.xml b/dubbo-rpc/dubbo-rpc-rest/src/test/resources/log4j2-test.xml deleted file mode 100644 index ba99f52cc2d..00000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/resources/log4j2-test.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TriHttp2RemoteFlowController.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TriHttp2RemoteFlowController.java index b29439fe3e2..aa5339317d5 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TriHttp2RemoteFlowController.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TriHttp2RemoteFlowController.java @@ -306,7 +306,7 @@ private final class FlowState implements StreamByteDistributor.StreamState { FlowState(Http2Stream stream) { this.stream = stream; - pendingWriteQueue = new ArrayDeque(2); + pendingWriteQueue = new ArrayDeque<>(2); } /** diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp2Protocol.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp2Protocol.java index ea088c9af19..4e91dabb35c 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp2Protocol.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp2Protocol.java @@ -31,8 +31,10 @@ import org.apache.dubbo.remoting.http12.netty4.h2.NettyHttp2FrameCodec; import org.apache.dubbo.remoting.http12.netty4.h2.NettyHttp2ProtocolSelectorHandler; import org.apache.dubbo.remoting.utils.UrlUtils; +import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ScopeModelAware; +import org.apache.dubbo.rpc.protocol.tri.h12.HttpServerAfterUpgradeHandler; import org.apache.dubbo.rpc.protocol.tri.h12.TripleProtocolDetector; import org.apache.dubbo.rpc.protocol.tri.h12.http1.DefaultHttp11ServerTransportListenerFactory; import org.apache.dubbo.rpc.protocol.tri.h12.http2.GenericHttp2ServerTransportListenerFactory; @@ -48,14 +50,18 @@ import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; +import io.netty.handler.codec.http.HttpServerUpgradeHandler; +import io.netty.handler.codec.http2.Http2CodecUtil; import io.netty.handler.codec.http2.Http2FrameCodec; import io.netty.handler.codec.http2.Http2FrameCodecBuilder; import io.netty.handler.codec.http2.Http2FrameLogger; import io.netty.handler.codec.http2.Http2MultiplexHandler; +import io.netty.handler.codec.http2.Http2ServerUpgradeCodec; import io.netty.handler.codec.http2.Http2Settings; import io.netty.handler.codec.http2.Http2StreamChannel; import io.netty.handler.flush.FlushConsolidationHandler; import io.netty.handler.logging.LogLevel; +import io.netty.util.AsciiString; import static org.apache.dubbo.rpc.Constants.H2_SETTINGS_ENABLE_PUSH_KEY; import static org.apache.dubbo.rpc.Constants.H2_SETTINGS_HEADER_TABLE_SIZE_KEY; @@ -143,20 +149,66 @@ public void configServerProtocolHandler(URL url, ChannelOperator operator) { } private void configurerHttp1Handlers(URL url, List handlers) { - handlers.add(new ChannelHandlerPretender(new HttpServerCodec())); + final HttpServerCodec sourceCodec = new HttpServerCodec(); + handlers.add(new ChannelHandlerPretender(sourceCodec)); + // Triple protocol http1 upgrade support + handlers.add(new ChannelHandlerPretender(new HttpServerUpgradeHandler( + sourceCodec, + protocol -> { + if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) { + Configuration config = + ConfigurationUtils.getGlobalConfiguration(url.getOrDefaultApplicationModel()); + return new Http2ServerUpgradeCodec( + buildHttp2FrameCodec(config, url.getOrDefaultApplicationModel()), + new HttpServerAfterUpgradeHandler(), + new HttpWriteQueueHandler(), + new FlushConsolidationHandler(64, true), + new TripleServerConnectionHandler(), + buildHttp2MultiplexHandler(url), + new TripleTailHandler()); + } + // Not upgrade request + return null; + }, + Integer.MAX_VALUE))); + // If the upgrade was successful, remove the message from the output list + // so that it's not propagated to the next handler. This request will + // be propagated as a user event instead. handlers.add(new ChannelHandlerPretender(new HttpObjectAggregator(Integer.MAX_VALUE))); handlers.add(new ChannelHandlerPretender(new NettyHttp1Codec())); handlers.add(new ChannelHandlerPretender(new NettyHttp1ConnectionHandler( url, frameworkModel, DefaultHttp11ServerTransportListenerFactory.INSTANCE))); } + private Http2MultiplexHandler buildHttp2MultiplexHandler(URL url) { + return new Http2MultiplexHandler(new ChannelInitializer() { + @Override + protected void initChannel(Http2StreamChannel ch) { + final ChannelPipeline p = ch.pipeline(); + p.addLast(new NettyHttp2FrameCodec()); + p.addLast(new NettyHttp2ProtocolSelectorHandler( + url, frameworkModel, GenericHttp2ServerTransportListenerFactory.INSTANCE)); + } + }); + } + private void configurerHttp2Handlers(URL url, List handlers) { Configuration config = ConfigurationUtils.getGlobalConfiguration(url.getOrDefaultApplicationModel()); - final Http2FrameCodec codec = TripleHttp2FrameCodecBuilder.forServer() + final Http2FrameCodec codec = buildHttp2FrameCodec(config, url.getOrDefaultApplicationModel()); + final Http2MultiplexHandler handler = buildHttp2MultiplexHandler(url); + handlers.add(new ChannelHandlerPretender(new HttpWriteQueueHandler())); + handlers.add(new ChannelHandlerPretender(codec)); + handlers.add(new ChannelHandlerPretender(new FlushConsolidationHandler(64, true))); + handlers.add(new ChannelHandlerPretender(new TripleServerConnectionHandler())); + handlers.add(new ChannelHandlerPretender(handler)); + handlers.add(new ChannelHandlerPretender(new TripleTailHandler())); + } + + private Http2FrameCodec buildHttp2FrameCodec(Configuration config, ApplicationModel applicationModel) { + return TripleHttp2FrameCodecBuilder.forServer() .customizeConnection((connection) -> connection .remote() - .flowController( - new TriHttp2RemoteFlowController(connection, url.getOrDefaultApplicationModel()))) + .flowController(new TriHttp2RemoteFlowController(connection, applicationModel))) .gracefulShutdownTimeoutMillis(10000) .initialSettings(new Http2Settings() .headerTableSize( @@ -168,20 +220,5 @@ private void configurerHttp2Handlers(URL url, List handlers) { config.getInt(H2_SETTINGS_MAX_HEADER_LIST_SIZE_KEY, DEFAULT_MAX_HEADER_LIST_SIZE))) .frameLogger(SERVER_LOGGER) .build(); - final Http2MultiplexHandler handler = new Http2MultiplexHandler(new ChannelInitializer() { - @Override - protected void initChannel(Http2StreamChannel ch) { - final ChannelPipeline p = ch.pipeline(); - p.addLast(new NettyHttp2FrameCodec()); - p.addLast(new NettyHttp2ProtocolSelectorHandler( - url, frameworkModel, GenericHttp2ServerTransportListenerFactory.INSTANCE)); - } - }); - handlers.add(new ChannelHandlerPretender(new HttpWriteQueueHandler())); - handlers.add(new ChannelHandlerPretender(codec)); - handlers.add(new ChannelHandlerPretender(new FlushConsolidationHandler(64, true))); - handlers.add(new ChannelHandlerPretender(new TripleServerConnectionHandler())); - handlers.add(new ChannelHandlerPretender(handler)); - handlers.add(new ChannelHandlerPretender(new TripleTailHandler())); } } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleScopeModelInitializer.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleScopeModelInitializer.java new file mode 100644 index 00000000000..1811821438e --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleScopeModelInitializer.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.rpc.protocol.tri; + +import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; +import org.apache.dubbo.rpc.model.ApplicationModel; +import org.apache.dubbo.rpc.model.FrameworkModel; +import org.apache.dubbo.rpc.model.ModuleModel; +import org.apache.dubbo.rpc.model.ScopeModelInitializer; +import org.apache.dubbo.rpc.protocol.tri.rest.mapping.DefaultRequestMappingRegistry; +import org.apache.dubbo.rpc.protocol.tri.route.DefaultRequestRouter; + +public class TripleScopeModelInitializer implements ScopeModelInitializer { + + @Override + public void initializeFrameworkModel(FrameworkModel frameworkModel) { + ScopeBeanFactory beanFactory = frameworkModel.getBeanFactory(); + beanFactory.registerBean(DefaultRequestMappingRegistry.class); + beanFactory.registerBean(DefaultRequestRouter.class); + } + + @Override + public void initializeApplicationModel(ApplicationModel applicationModel) {} + + @Override + public void initializeModuleModel(ModuleModel moduleModel) {} +} diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/AbstractServerCallListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/AbstractServerCallListener.java index 28a5a9fbf4d..42bb5fa4355 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/AbstractServerCallListener.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/AbstractServerCallListener.java @@ -67,6 +67,10 @@ public void invoke() { try { final long stInMillis = System.currentTimeMillis(); final Result response = invoker.invoke(invocation); + if (response.hasException()) { + onResponseException(response.getException()); + return; + } response.whenCompleteWithContext((r, t) -> { if (responseObserver instanceof AttachmentHolder) { ((AttachmentHolder) responseObserver).setResponseAttachments(response.getObjectAttachments()); @@ -75,8 +79,8 @@ public void invoke() { responseObserver.onError(t); return; } - if (response.hasException()) { - onResponseException(response.getException()); + if (r.hasException()) { + onResponseException(r.getException()); return; } final long cost = System.currentTimeMillis() - stInMillis; diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/AbstractServerTransportListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/AbstractServerTransportListener.java index 9839625823a..970aa88fa7b 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/AbstractServerTransportListener.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/AbstractServerTransportListener.java @@ -65,7 +65,7 @@ public abstract class AbstractServerTransportListener
f.invoke(invoker, inv)); diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/HttpServerAfterUpgradeHandler.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/HttpServerAfterUpgradeHandler.java new file mode 100644 index 00000000000..30c89087d50 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/HttpServerAfterUpgradeHandler.java @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.rpc.protocol.tri.h12; + +import io.netty.channel.ChannelHandler.Sharable; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.handler.codec.http.HttpServerUpgradeHandler; +import io.netty.handler.codec.http2.DefaultHttp2DataFrame; +import io.netty.handler.codec.http2.DefaultHttp2Headers; +import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame; +import io.netty.handler.codec.http2.Http2CodecUtil; +import io.netty.handler.codec.http2.Http2FrameCodec; +import io.netty.handler.codec.http2.Http2FrameStream; +import io.netty.handler.codec.http2.Http2Headers; +import io.netty.handler.codec.http2.InboundHttpToHttp2Adapter; + +import static io.netty.handler.codec.http.HttpResponseStatus.OK; + +/** + * If an upgrade occurred, the program need send a simple response via HTTP/2 on stream 1 (the stream specifically reserved + * for cleartext HTTP upgrade). However, {@link Http2FrameCodec} send 'upgradeRequest' to upgraded channel handlers by + * {@link InboundHttpToHttp2Adapter} (As it noted that this may behave strangely). So we need to distinguish the 'upgradeRequest' + * and send the response.
+ * + * @see HttpServerUpgradeHandler + * @see Http2FrameCodec + * @see InboundHttpToHttp2Adapter + * @since 3.3.0 + */ +@Sharable +public class HttpServerAfterUpgradeHandler extends ChannelInboundHandlerAdapter { + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + if (msg instanceof DefaultHttp2HeadersFrame) { + DefaultHttp2HeadersFrame headersFrame = (DefaultHttp2HeadersFrame) msg; + if (headersFrame.stream().id() == Http2CodecUtil.HTTP_UPGRADE_STREAM_ID && headersFrame.isEndStream()) { + // upgradeRequest + sendResponse(ctx, headersFrame.stream()); + return; + } + } + super.channelRead(ctx, msg); + } + + /** + * Send a frame for the response status + */ + private static void sendResponse(ChannelHandlerContext ctx, Http2FrameStream stream) { + Http2Headers headers = new DefaultHttp2Headers().status(OK.codeAsText()); + ctx.write(new DefaultHttp2HeadersFrame(headers).stream(stream)); + ctx.write(new DefaultHttp2DataFrame(true).stream(stream)); + } +} diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcHttp2ServerTransportListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcHttp2ServerTransportListener.java index 63c5ee2cbcf..0399c643342 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcHttp2ServerTransportListener.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcHttp2ServerTransportListener.java @@ -26,6 +26,7 @@ import org.apache.dubbo.remoting.http12.exception.UnimplementedException; import org.apache.dubbo.remoting.http12.h2.H2StreamChannel; import org.apache.dubbo.remoting.http12.h2.Http2Header; +import org.apache.dubbo.remoting.http12.h2.Http2InputMessage; import org.apache.dubbo.remoting.http12.h2.Http2TransportListener; import org.apache.dubbo.remoting.http12.message.MethodMetadata; import org.apache.dubbo.remoting.http12.message.StreamingDecoder; @@ -34,7 +35,6 @@ import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.tri.DescriptorUtils; import org.apache.dubbo.rpc.protocol.tri.RpcInvocationBuildContext; -import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum; import org.apache.dubbo.rpc.protocol.tri.compressor.DeCompressor; import org.apache.dubbo.rpc.protocol.tri.compressor.Identity; import org.apache.dubbo.rpc.protocol.tri.h12.HttpMessageListener; @@ -120,14 +120,22 @@ protected RpcInvocation onBuildRpcInvocationCompletion(RpcInvocation invocation) getContext().getServiceDescriptor().getInterfaceName(), getContext().getMethodName())); } - String consumerAppKey = - getHttpMetadata().headers().getFirst(TripleHeaderEnum.CONSUMER_APP_NAME_KEY.getHeader()); - if (null != consumerAppKey) { - invocation.put(TripleHeaderEnum.CONSUMER_APP_NAME_KEY, consumerAppKey); - } return invocation; } + @Override + protected void onError(Http2InputMessage message, Throwable throwable) { + try { + message.close(); + } catch (Exception e) { + throwable.addSuppressed(e); + } + onError(throwable); + } + + @Override + protected void onFinally(Http2InputMessage message) {} + @Override protected GrpcStreamingDecoder getStreamingDecoder() { return (GrpcStreamingDecoder) super.getStreamingDecoder(); diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http1/DefaultHttp11ServerTransportListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http1/DefaultHttp11ServerTransportListener.java index 11f3012c22a..950a2d93506 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http1/DefaultHttp11ServerTransportListener.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http1/DefaultHttp11ServerTransportListener.java @@ -27,6 +27,7 @@ import org.apache.dubbo.remoting.http12.h1.Http1ServerChannelObserver; import org.apache.dubbo.remoting.http12.h1.Http1ServerStreamChannelObserver; import org.apache.dubbo.remoting.http12.h1.Http1ServerTransportListener; +import org.apache.dubbo.remoting.http12.h1.Http1ServerUnaryChannelObserver; import org.apache.dubbo.remoting.http12.message.DefaultListeningDecoder; import org.apache.dubbo.remoting.http12.message.MediaType; import org.apache.dubbo.remoting.http12.message.codec.JsonCodec; @@ -58,7 +59,7 @@ public DefaultHttp11ServerTransportListener(HttpChannel httpChannel, URL url, Fr executorSupport = ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()) .getExecutorSupport(url); this.httpChannel = httpChannel; - serverChannelObserver = new Http1ServerChannelObserver(httpChannel); + serverChannelObserver = new Http1ServerUnaryChannelObserver(httpChannel); serverChannelObserver.setResponseEncoder(JsonCodec.INSTANCE); } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/GenericHttp2ServerTransportListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/GenericHttp2ServerTransportListener.java index 326e09ede3e..4fee48dfb43 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/GenericHttp2ServerTransportListener.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/GenericHttp2ServerTransportListener.java @@ -86,6 +86,7 @@ protected Executor initializeExecutor(Http2Header metadata) { return new SerializingExecutor(executorSupport.getExecutor(metadata)); } + @Override protected void doOnMetadata(Http2Header metadata) { if (metadata.isEndStream()) { if (!HttpMethods.supportBody(metadata.method())) { @@ -164,7 +165,7 @@ protected void onMetadataCompletion(Http2Header metadata) { @Override protected void onDataCompletion(Http2InputMessage message) { if (message.isEndStream()) { - serverCallListener.onComplete(); + getStreamingDecoder().close(); } } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer b/dubbo-rpc/dubbo-rpc-triple/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer new file mode 100644 index 00000000000..65af7ec2222 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer @@ -0,0 +1 @@ +dubbo-rpc-triple=org.apache.dubbo.rpc.protocol.tri.TripleScopeModelInitializer diff --git a/dubbo-rpc/pom.xml b/dubbo-rpc/pom.xml index 14fe5010206..dc21d034bd5 100644 --- a/dubbo-rpc/pom.xml +++ b/dubbo-rpc/pom.xml @@ -31,7 +31,6 @@ dubbo-rpc-api dubbo-rpc-dubbo dubbo-rpc-injvm - dubbo-rpc-rest dubbo-rpc-triple diff --git a/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2ObjectInput.java b/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2ObjectInput.java index a167ea3983c..52d486ec67d 100644 --- a/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2ObjectInput.java +++ b/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2ObjectInput.java @@ -91,7 +91,7 @@ public String readUTF() throws IOException { @Override public byte[] readBytes() throws IOException { - int length = is.read(); + int length = readLength(); byte[] bytes = new byte[length]; int read = is.read(bytes, 0, length); if (read != length) { diff --git a/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2ObjectOutput.java b/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2ObjectOutput.java index f596b8db4a6..0240e009d72 100644 --- a/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2ObjectOutput.java +++ b/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2ObjectOutput.java @@ -89,13 +89,13 @@ public void writeUTF(String v) throws IOException { @Override public void writeBytes(byte[] b) throws IOException { - os.write(b.length); + writeLength(b.length); os.write(b); } @Override public void writeBytes(byte[] b, int off, int len) throws IOException { - os.write(len); + writeLength(len); os.write(b, off, len); } diff --git a/dubbo-spring-boot/dubbo-spring-boot-interceptor/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-interceptor/pom.xml index 6585f611e45..9e3f238ff82 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-interceptor/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-interceptor/pom.xml @@ -46,6 +46,12 @@ spring-boot-starter-web true + + org.apache.dubbo + dubbo-rpc-api + ${project.version} + true + diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-nacos-spring-boot-starter/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-nacos-spring-boot-starter/pom.xml index 49ea3b67beb..563a89ee080 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-nacos-spring-boot-starter/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-nacos-spring-boot-starter/pom.xml @@ -1,19 +1,19 @@ 4.0.0 diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-zookeeper-curator5-spring-boot-starter/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-zookeeper-curator5-spring-boot-starter/pom.xml index 7fd88c83383..f15ce669ee5 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-zookeeper-curator5-spring-boot-starter/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-zookeeper-curator5-spring-boot-starter/pom.xml @@ -1,19 +1,19 @@ 4.0.0 @@ -31,7 +31,7 @@ 5.1.0 - 3.8.3 + 3.8.4 @@ -44,6 +44,20 @@ org.apache.zookeeper zookeeper ${zookeeper_version} + + + io.netty + * + + + ch.qos.logback + logback-core + + + ch.qos.logback + logback-classic + + diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-zookeeper-spring-boot-starter/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-zookeeper-spring-boot-starter/pom.xml index ca4350360f2..b55854054f8 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-zookeeper-spring-boot-starter/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-zookeeper-spring-boot-starter/pom.xml @@ -1,19 +1,19 @@ 4.0.0 diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/pom.xml index 5af7140e930..5fbfc4bffdb 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/pom.xml @@ -36,8 +36,8 @@ - 1.12.3 - 1.2.3 + 1.12.5 + 1.2.5 1.34.1 2.17.2 0.16.0 diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-starters/pom.xml index 897a01556a7..736e23590b9 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/pom.xml @@ -1,19 +1,19 @@ 4.0.0 diff --git a/dubbo-spring-boot/pom.xml b/dubbo-spring-boot/pom.xml index a555e7b6b41..ba3a5e4cd53 100644 --- a/dubbo-spring-boot/pom.xml +++ b/dubbo-spring-boot/pom.xml @@ -41,7 +41,7 @@ 2.7.18 - 1.14.12 + 1.14.14 4.11.0 diff --git a/dubbo-test/dubbo-dependencies-all/pom.xml b/dubbo-test/dubbo-dependencies-all/pom.xml index dc961a62890..307a81e88b0 100644 --- a/dubbo-test/dubbo-dependencies-all/pom.xml +++ b/dubbo-test/dubbo-dependencies-all/pom.xml @@ -124,11 +124,6 @@ dubbo-metadata-api ${project.version} - - org.apache.dubbo - dubbo-metadata-rest - ${project.version} - org.apache.dubbo dubbo-metadata-report-zookeeper @@ -251,11 +246,6 @@ ${project.version} - - org.apache.dubbo - dubbo-plugin-proxy-bytebuddy - ${project.version} - org.apache.dubbo dubbo-rest-jaxrs @@ -305,11 +295,6 @@ dubbo-remoting-api ${project.version} - - org.apache.dubbo - dubbo-remoting-http - ${project.version} - org.apache.dubbo dubbo-remoting-http12 @@ -357,11 +342,6 @@ dubbo-rpc-injvm ${project.version} - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - org.apache.dubbo diff --git a/dubbo-test/dubbo-test-check/pom.xml b/dubbo-test/dubbo-test-check/pom.xml index 442b5b84a3d..1508247fad7 100644 --- a/dubbo-test/dubbo-test-check/pom.xml +++ b/dubbo-test/dubbo-test-check/pom.xml @@ -31,7 +31,7 @@ 4.2.0 3.7.2 4.2.0 - 1.26.0 + 1.26.1 1.9.3 1.4.0 2.12.3 diff --git a/dubbo-test/dubbo-test-common/pom.xml b/dubbo-test/dubbo-test-common/pom.xml index d759f057449..01e0f41f7a2 100644 --- a/dubbo-test/dubbo-test-common/pom.xml +++ b/dubbo-test/dubbo-test-common/pom.xml @@ -31,6 +31,11 @@ + + + javax.ws.rs + javax.ws.rs-api + org.apache.zookeeper zookeeper @@ -50,11 +55,6 @@ dubbo-rpc-api ${project.version} - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - org.apache.dubbo dubbo-test-check diff --git a/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/SysProps.java b/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/SysProps.java index dcfafc37f8e..6c9f5c1001a 100644 --- a/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/SysProps.java +++ b/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/SysProps.java @@ -24,7 +24,7 @@ */ public class SysProps { - private static Map map = new LinkedHashMap(); + private static Map map = new LinkedHashMap<>(); public static void reset() { map.clear(); diff --git a/dubbo-test/dubbo-test-modules/src/test/java/org/apache/dubbo/dependency/FileTest.java b/dubbo-test/dubbo-test-modules/src/test/java/org/apache/dubbo/dependency/FileTest.java index 5f9f02e3cca..baac484a844 100644 --- a/dubbo-test/dubbo-test-modules/src/test/java/org/apache/dubbo/dependency/FileTest.java +++ b/dubbo-test/dubbo-test-modules/src/test/java/org/apache/dubbo/dependency/FileTest.java @@ -389,15 +389,20 @@ void checkDubboAllShade() throws DocumentException { } @Test - void checkDubboAllTransform() throws DocumentException { + void checkDubboTransform() throws DocumentException { File baseFile = getBaseFile(); List spis = new LinkedList<>(); readSPI(baseFile, spis); String dubboAllPath = "dubbo-distribution" + File.separator + "dubbo-all" + File.separator + "pom.xml"; + String dubboAllShadedPath = + "dubbo-distribution" + File.separator + "dubbo-all-shaded" + File.separator + "pom.xml"; + String dubboCoreSPIPath = "dubbo-distribution" + File.separator + "dubbo-core-spi" + File.separator + "pom.xml"; SAXReader reader = new SAXReader(); Document dubboAll = reader.read(new File(baseFile, dubboAllPath)); + Document dubboAllShaded = reader.read(new File(baseFile, dubboAllShadedPath)); + Document dubboCoreSPI = reader.read(new File(baseFile, dubboCoreSPIPath)); List transformsInDubboAll = dubboAll.getRootElement().element("build").element("plugins").elements("plugin").stream() @@ -415,6 +420,38 @@ void checkDubboAllTransform() throws DocumentException { .map(resource -> resource.substring(resource.lastIndexOf("/") + 1)) .collect(Collectors.toList()); + List transformsInDubboAllShaded = + dubboAllShaded.getRootElement().element("build").element("plugins").elements("plugin").stream() + .filter(ele -> ele.elementText("artifactId").equals("maven-shade-plugin")) + .map(ele -> ele.element("executions")) + .map(ele -> ele.elements("execution")) + .flatMap(Collection::stream) + .filter(ele -> ele.elementText("phase").equals("package")) + .map(ele -> ele.element("configuration")) + .map(ele -> ele.element("transformers")) + .map(ele -> ele.elements("transformer")) + .flatMap(Collection::stream) + .map(ele -> ele.elementText("resource")) + .map(String::trim) + .map(resource -> resource.substring(resource.lastIndexOf("/") + 1)) + .collect(Collectors.toList()); + + List transformsInDubboCoreSPI = + dubboCoreSPI.getRootElement().element("build").element("plugins").elements("plugin").stream() + .filter(ele -> ele.elementText("artifactId").equals("maven-shade-plugin")) + .map(ele -> ele.element("executions")) + .map(ele -> ele.elements("execution")) + .flatMap(Collection::stream) + .filter(ele -> ele.elementText("phase").equals("package")) + .map(ele -> ele.element("configuration")) + .map(ele -> ele.element("transformers")) + .map(ele -> ele.elements("transformer")) + .flatMap(Collection::stream) + .map(ele -> ele.elementText("resource")) + .map(String::trim) + .map(resource -> resource.substring(resource.lastIndexOf("/") + 1)) + .collect(Collectors.toList()); + List expectedSpis = new LinkedList<>(spis); expectedSpis.removeAll(transformsInDubboAll); Assertions.assertTrue( @@ -430,6 +467,44 @@ void checkDubboAllTransform() throws DocumentException { "Class without `@SPI` declaration should not be added to dubbo-all(dubbo-distribution" + File.separator + "dubbo-all" + File.separator + "pom.xml in shade plugin) to being transformed. Found spis: " + unexpectedSpis); + + expectedSpis = new LinkedList<>(spis); + expectedSpis.removeAll(transformsInDubboAllShaded); + Assertions.assertTrue( + expectedSpis.isEmpty(), + "Newly created SPI interface must be added to dubbo-all-shaded(dubbo-distribution" + File.separator + + "dubbo-all-shaded" + File.separator + + "pom.xml in shade plugin) to being transformed. Found spis: " + + expectedSpis); + + unexpectedSpis = new LinkedList<>(transformsInDubboAllShaded); + unexpectedSpis.removeAll(spis); + Assertions.assertTrue( + unexpectedSpis.isEmpty(), + "Class without `@SPI` declaration should not be added to dubbo-all-shaded(dubbo-distribution" + + File.separator + + "dubbo-all-shaded" + File.separator + + "pom.xml in shade plugin) to being transformed. Found spis: " + + unexpectedSpis); + + expectedSpis = new LinkedList<>(spis); + expectedSpis.removeAll(transformsInDubboCoreSPI); + Assertions.assertTrue( + expectedSpis.isEmpty(), + "Newly created SPI interface must be added to dubbo-core-spi(dubbo-distribution" + File.separator + + "dubbo-core-spi" + File.separator + + "pom.xml in shade plugin) to being transformed. Found spis: " + + expectedSpis); + + unexpectedSpis = new LinkedList<>(transformsInDubboCoreSPI); + unexpectedSpis.removeAll(spis); + Assertions.assertTrue( + unexpectedSpis.isEmpty(), + "Class without `@SPI` declaration should not be added to dubbo-core-spi(dubbo-distribution" + + File.separator + + "dubbo-core-spi" + File.separator + + "pom.xml in shade plugin) to being transformed. Found spis: " + + unexpectedSpis); } @Test diff --git a/dubbo-test/dubbo-test-spring/pom.xml b/dubbo-test/dubbo-test-spring/pom.xml index 3ba048cc35d..b248dcaae2e 100644 --- a/dubbo-test/dubbo-test-spring/pom.xml +++ b/dubbo-test/dubbo-test-spring/pom.xml @@ -99,11 +99,6 @@ dubbo-rpc-dubbo ${project.version} - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - org.apache.dubbo dubbo-config-spring diff --git a/dubbo-test/dubbo-test-spring3.2/pom.xml b/dubbo-test/dubbo-test-spring3.2/pom.xml index d209e06c380..f57ae9167c3 100644 --- a/dubbo-test/dubbo-test-spring3.2/pom.xml +++ b/dubbo-test/dubbo-test-spring3.2/pom.xml @@ -28,7 +28,7 @@ true - 3.2.18.RELEASE + 5.3.34 diff --git a/dubbo-test/dubbo-test-spring4.1/pom.xml b/dubbo-test/dubbo-test-spring4.1/pom.xml index 4467ba76372..3a35d3e37ec 100644 --- a/dubbo-test/dubbo-test-spring4.1/pom.xml +++ b/dubbo-test/dubbo-test-spring4.1/pom.xml @@ -28,7 +28,7 @@ true - 4.1.9.RELEASE + 5.3.34 diff --git a/dubbo-test/dubbo-test-spring4.2/pom.xml b/dubbo-test/dubbo-test-spring4.2/pom.xml index e900558060a..7dfa978e14f 100644 --- a/dubbo-test/dubbo-test-spring4.2/pom.xml +++ b/dubbo-test/dubbo-test-spring4.2/pom.xml @@ -28,7 +28,7 @@ true - 4.2.4.RELEASE + 5.3.34 diff --git a/pom.xml b/pom.xml index 4dafbf47e67..b93069ee272 100644 --- a/pom.xml +++ b/pom.xml @@ -129,16 +129,16 @@ true - 3.3.0 + 3.4.1 3.2.5 3.2.5 2.8.2 - 3.12.1 - 3.3.0 + 3.13.0 + 3.3.1 3.6.3 9.4.54.v20240208 3.3.1 - 0.8.11 + 0.8.12 1.6.0 3.4.1 3.1.0 @@ -152,7 +152,7 @@ 1.0.0 2.38.0 - 3.3.0-beta.2-SNAPSHOT + 3.3.0-beta.3-SNAPSHOT @@ -280,7 +280,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.5.2 + 3.5.3 false