diff --git a/.artifacts b/.artifacts index cd6334693d0..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 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/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/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/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 12490c4d9ea..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 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-spring/pom.xml b/dubbo-config/dubbo-config-spring/pom.xml index 0c14921e6e3..b49df8dc0c9 100644 --- a/dubbo-config/dubbo-config-spring/pom.xml +++ b/dubbo-config/dubbo-config-spring/pom.xml @@ -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/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-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 1b2d730c85a..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 @@ -133,11 +133,6 @@ dubbo-filter-validation ${project.version} - - org.apache.dubbo - dubbo-remoting-http - ${project.version} - com.alibaba 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 da5c091b118..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 @@ -133,12 +133,6 @@ dubbo-filter-validation ${project.version} - - org.apache.dubbo - dubbo-remoting-http - ${project.version} - - com.alibaba fastjson 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-distribution/dubbo-all-shaded/pom.xml b/dubbo-distribution/dubbo-all-shaded/pom.xml index b0591156921..a27f148cef6 100644 --- a/dubbo-distribution/dubbo-all-shaded/pom.xml +++ b/dubbo-distribution/dubbo-all-shaded/pom.xml @@ -363,13 +363,6 @@ compile true - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - compile - true - org.apache.dubbo @@ -507,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 @@ -631,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 @@ -708,30 +688,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 @@ -762,9 +718,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 @@ -921,9 +874,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 @@ -935,10 +885,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-all/pom.xml b/dubbo-distribution/dubbo-all/pom.xml index 19fd7dbbfc3..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 @@ -343,13 +336,6 @@ compile true - - org.apache.dubbo - dubbo-remoting-http - ${project.version} - compile - true - org.apache.dubbo dubbo-remoting-http12 @@ -415,13 +401,6 @@ compile true - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - compile - true - org.apache.dubbo @@ -528,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 @@ -553,7 +531,6 @@ 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 @@ -563,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 @@ -686,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 @@ -763,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 @@ -817,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 @@ -976,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 @@ -990,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-core-spi/pom.xml b/dubbo-distribution/dubbo-core-spi/pom.xml index 6ef9c5d928e..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 @@ -324,30 +312,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 @@ -378,9 +342,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 @@ -537,9 +498,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 @@ -551,10 +509,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-metadata/dubbo-metadata-processor/pom.xml b/dubbo-metadata/dubbo-metadata-processor/pom.xml index fe6041612b2..bf8b63c8dbf 100644 --- a/dubbo-metadata/dubbo-metadata-processor/pom.xml +++ b/dubbo-metadata/dubbo-metadata-processor/pom.xml @@ -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-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-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-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 5536e6c83e6..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 fa7cb5ab3ab..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/config/HttpClientConfig.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.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 maxIdleConnections = 20; - - private int keepAliveDuration = 30 * 1000; - - 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; - } - - public int getMaxIdleConnections() { - - return maxIdleConnections; - } - - public void setMaxIdleConnections(int maxIdleConnections) { - - this.maxIdleConnections = maxIdleConnections; - } - - public int getKeepAliveDuration() { - - return keepAliveDuration; - } - - public void setKeepAliveDuration(int keepAliveDuration) { - - this.keepAliveDuration = keepAliveDuration; - } -} 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 762be4b2cd2..00000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/restclient/OKHttpRestClient.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.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.ConnectionPool; -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) { - - return new OkHttpClient.Builder() - .readTimeout(httpClientConfig.getReadTimeout(), TimeUnit.SECONDS) - .writeTimeout(httpClientConfig.getWriteTimeout(), TimeUnit.SECONDS) - .connectTimeout(httpClientConfig.getConnectTimeout(), TimeUnit.SECONDS) - .connectionPool(new ConnectionPool( - httpClientConfig.getMaxIdleConnections(), - httpClientConfig.getKeepAliveDuration(), - TimeUnit.SECONDS)) - .build(); - } -} 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 0f2358cee07..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 dc71cd862dc..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/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-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 3c10fc699ec..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 fcf7faf5f57..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 6350eaaf155..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 deacffa63a9..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/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-test/dubbo-dependencies-all/pom.xml b/dubbo-test/dubbo-dependencies-all/pom.xml index 8bfc74434b3..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 @@ -300,11 +295,6 @@ dubbo-remoting-api ${project.version} - - org.apache.dubbo - dubbo-remoting-http - ${project.version} - org.apache.dubbo dubbo-remoting-http12 @@ -352,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-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-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