From 0d91d419a8b25a9917a03dc68a3eb5069ac856ea Mon Sep 17 00:00:00 2001 From: Albumen Kevin Date: Thu, 19 Oct 2023 15:25:40 +0800 Subject: [PATCH] Remove direct dependency of alibaba dubbo (#13218) * Remove direct dependency of alibaba dubbo * disable in ExtensionLoader * Fix license * Fix test * Fix case * Fix test --- .../common/compact/Dubbo2ActivateUtils.java | 169 +++++++ .../common/compact/Dubbo2CompactUtils.java | 118 +++++ .../compact/Dubbo2GenericExceptionUtils.java | 129 +++++ .../common/constants/CommonConstants.java | 5 +- .../common/extension/ExtensionLoader.java | 41 +- .../extension/support/ActivateComparator.java | 16 +- .../extension/support/WrapperComparator.java | 12 +- .../utils/ServiceAnnotationResolver.java | 11 +- .../dubbo/config/ReferenceConfigBase.java | 4 +- .../common/extension/ExtensionLoaderTest.java | 10 - .../support/ActivateComparatorTest.java | 11 +- .../common/utils/AnnotationUtilsTest.java | 28 +- ...bbo.common.extension.activate.ActivateExt1 | 2 - dubbo-compatible/pom.xml | 11 + .../dubbo/common/extension/Activate.java | 0 .../dubbo/config/annotation/Reference.java | 0 .../dubbo/config/annotation/Service.java | 0 .../com/alibaba/dubbo/rpc/RpcException.java | 0 .../dubbo/rpc/service/EchoService.java | 0 .../dubbo/rpc/service/GenericException.java | 0 .../dubbo/rpc/service/GenericService.java | 0 .../dubbo/common/extension/ExtensionTest.java | 26 + .../extension/activate/ActivateExt1.java | 25 + .../activate/impl/ActivateExt1Impl1.java | 28 ++ .../activate/impl/OldActivateExt1Impl2.java | 0 .../activate/impl/OldActivateExt1Impl3.java | 0 .../support/ActivateComparatorTest.java | 60 +++ .../common/extension/support/Filter0.java | 23 + .../common/extension/support/Filter1.java | 23 + .../common/extension/support/Filter2.java | 23 + .../common/extension/support/Filter3.java | 23 + .../common/extension/support/Filter4.java | 23 + .../common/extension/support/OldFilter0.java | 0 .../common/extension/support/OldFilter5.java | 0 .../extension/support/Order0Filter0.java | 24 + .../extension/support/Order0Filter1.java | 24 + .../extension/support/Order0Filter2.java | 24 + .../common/utils/AnnotationUtilsTest.java | 393 +++++++++++++++ .../apache/dubbo/config/spring/api/Box.java | 23 + .../dubbo/config/spring/api/DemoService.java | 28 ++ .../dubbo/config/spring/api/HelloService.java | 22 + .../ServiceAnnotationTestConfiguration.java | 109 ++++ .../DubboComponentScanRegistrarTest.java | 129 +++++ .../DubboConfigConfigurationTest.java | 94 ++++ .../annotation/EnableDubboConfigTest.java | 140 ++++++ .../context/annotation/EnableDubboTest.java | 150 ++++++ .../consumer/ConsumerConfiguration.java | 140 ++++++ .../test/TestConsumerConfiguration.java | 121 +++++ .../provider/DefaultHelloService.java | 38 ++ .../annotation/provider/DemoServiceImpl.java | 52 ++ .../annotation/provider/HelloServiceImpl.java | 35 ++ .../provider/ProviderConfiguration.java | 120 +++++ .../dubbo/config/spring/filter/MockDao.java | 24 + .../config/spring/filter/MockDaoImpl.java | 24 + .../config/spring/filter/MockFilter.java | 66 +++ .../dubbo/generic/GenericServiceTest.java | 6 +- .../AbstractAnnotationProcessingTest.java | 65 +++ .../AnnotationProcessingTestProcessor.java | 76 +++ .../CompilerInvocationInterceptor.java | 45 ++ .../ArrayTypeDefinitionBuilderTest.java | 125 +++++ .../CollectionTypeDefinitionBuilderTest.java | 105 ++++ .../EnumTypeDefinitionBuilderTest.java | 69 +++ .../GeneralTypeDefinitionBuilderTest.java | 67 +++ .../builder/MapTypeDefinitionBuilderTest.java | 139 ++++++ .../PrimitiveTypeDefinitionBuilderTest.java | 131 +++++ .../builder/ServiceDefinitionBuilderTest.java | 83 ++++ .../SimpleTypeDefinitionBuilderTest.java | 146 ++++++ .../processing/model/ArrayTypeModel.java | 36 ++ .../processing/model/CollectionTypeModel.java | 42 ++ .../annotation/processing/model/Color.java | 46 ++ .../processing/model/MapTypeModel.java | 41 ++ .../annotation/processing/model/Model.java | 89 ++++ .../processing/model/PrimitiveTypeModel.java | 73 +++ .../processing/model/SimpleTypeModel.java | 161 ++++++ ...AnnotatedMethodParameterProcessorTest.java | 59 +++ .../processing/util/AnnotationUtilsTest.java | 231 +++++++++ .../processing/util/FieldUtilsTest.java | 259 ++++++++++ .../processing/util/LoggerUtilsTest.java | 50 ++ .../processing/util/MemberUtilsTest.java | 113 +++++ .../processing/util/MethodUtilsTest.java | 196 ++++++++ .../util/ServiceAnnotationUtilsTest.java | 138 +++++ .../processing/util/TypeUtilsTest.java | 470 ++++++++++++++++++ .../metadata/rest/DefaultRestService.java | 69 +++ .../dubbo/metadata/rest/RestService.java | 42 ++ .../metadata/rest/SpringRestService.java | 95 ++++ .../metadata/rest/StandardRestService.java | 107 ++++ .../org/apache/dubbo/metadata/rest/User.java | 62 +++ .../apache/dubbo/metadata/tools/Ancestor.java | 35 ++ .../apache/dubbo/metadata/tools/Compiler.java | 120 +++++ .../dubbo/metadata/tools/CompilerTest.java | 37 ++ .../tools/DefaultRestServiceTest.java | 45 ++ .../metadata/tools/DefaultTestService.java | 63 +++ .../metadata/tools/GenericTestService.java | 38 ++ .../apache/dubbo/metadata/tools/Parent.java | 63 +++ .../dubbo/metadata/tools/RestServiceTest.java | 42 ++ .../metadata/tools/SpringRestServiceTest.java | 39 ++ .../tools/StandardRestServiceTest.java | 39 ++ .../dubbo/metadata/tools/TestProcessor.java | 50 ++ .../dubbo/metadata/tools/TestService.java | 54 ++ .../dubbo/metadata/tools/TestServiceImpl.java | 51 ++ .../rpc/filter/GenericImplFilterTest.java | 64 +++ .../apache/dubbo/rpc/support/DemoService.java | 64 +++ .../org/apache/dubbo/rpc/support/Person.java | 52 ++ .../org/apache/dubbo/rpc/support/Type.java | 21 + .../test/resources/META-INF/config.properties | 36 ++ .../resources/META-INF/default.properties | 4 + .../META-INF/dubbb-consumer.properties | 12 + .../META-INF/dubbb-provider.properties | 24 + .../META-INF/dubbo-consumer.properties | 13 + .../META-INF/dubbo-provider.properties | 24 + ...bbo.common.extension.activate.ActivateExt1 | 2 + ...che.dubbo.common.extension.support.Filter0 | 5 + .../internal/org.apache.dubbo.rpc.Filter | 1 + .../ReferenceAnnotationBeanPostProcessor.java | 12 +- .../ServiceAnnotationPostProcessor.java | 30 +- .../spring/util/DubboAnnotationUtils.java | 4 +- .../context/annotation/EnableDubboTest.java | 16 +- .../test/TestConsumerConfiguration.java | 17 +- .../annotation/provider/HelloServiceImpl.java | 2 +- .../AbstractServiceRestMetadataResolver.java | 9 +- .../processing/util/AnnotationUtilsTest.java | 24 +- .../util/ServiceAnnotationUtilsTest.java | 4 +- .../metadata/tools/GenericTestService.java | 2 +- .../dubbo/metadata/tools/TestServiceImpl.java | 6 - .../org/apache/dubbo/rpc/AppResponse.java | 17 +- .../dubbo/rpc/filter/GenericFilter.java | 17 +- .../dubbo/rpc/filter/GenericImplFilter.java | 8 +- .../dubbo/rpc/proxy/AbstractProxyFactory.java | 13 +- .../rpc/support/Dubbo2RpcExceptionUtils.java | 73 +++ .../rpc/filter/GenericImplFilterTest.java | 36 +- 130 files changed, 7178 insertions(+), 147 deletions(-) create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2ActivateUtils.java create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2CompactUtils.java create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2GenericExceptionUtils.java rename {dubbo-common => dubbo-compatible}/src/main/java/com/alibaba/dubbo/common/extension/Activate.java (100%) rename {dubbo-common => dubbo-compatible}/src/main/java/com/alibaba/dubbo/config/annotation/Reference.java (100%) rename {dubbo-common => dubbo-compatible}/src/main/java/com/alibaba/dubbo/config/annotation/Service.java (100%) rename {dubbo-rpc/dubbo-rpc-api => dubbo-compatible}/src/main/java/com/alibaba/dubbo/rpc/RpcException.java (100%) rename {dubbo-common => dubbo-compatible}/src/main/java/com/alibaba/dubbo/rpc/service/EchoService.java (100%) rename {dubbo-common => dubbo-compatible}/src/main/java/com/alibaba/dubbo/rpc/service/GenericException.java (100%) rename {dubbo-common => dubbo-compatible}/src/main/java/com/alibaba/dubbo/rpc/service/GenericService.java (100%) create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/activate/ActivateExt1.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateExt1Impl1.java rename {dubbo-common => dubbo-compatible}/src/test/java/org/apache/dubbo/common/extension/activate/impl/OldActivateExt1Impl2.java (100%) rename {dubbo-common => dubbo-compatible}/src/test/java/org/apache/dubbo/common/extension/activate/impl/OldActivateExt1Impl3.java (100%) create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/ActivateComparatorTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter0.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter1.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter2.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter3.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter4.java rename {dubbo-common => dubbo-compatible}/src/test/java/org/apache/dubbo/common/extension/support/OldFilter0.java (100%) rename {dubbo-common => dubbo-compatible}/src/test/java/org/apache/dubbo/common/extension/support/OldFilter5.java (100%) create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter0.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter1.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter2.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/common/utils/AnnotationUtilsTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/api/Box.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/api/DemoService.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/api/HelloService.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationTestConfiguration.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScanRegistrarTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfigurationTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfigTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/ConsumerConfiguration.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/test/TestConsumerConfiguration.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DefaultHelloService.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DemoServiceImpl.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/HelloServiceImpl.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/ProviderConfiguration.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/filter/MockDao.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/filter/MockDaoImpl.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/filter/MockFilter.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/AbstractAnnotationProcessingTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/AnnotationProcessingTestProcessor.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/CompilerInvocationInterceptor.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ArrayTypeDefinitionBuilderTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/CollectionTypeDefinitionBuilderTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/EnumTypeDefinitionBuilderTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/GeneralTypeDefinitionBuilderTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/MapTypeDefinitionBuilderTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/PrimitiveTypeDefinitionBuilderTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ServiceDefinitionBuilderTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/SimpleTypeDefinitionBuilderTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/ArrayTypeModel.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/CollectionTypeModel.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/Color.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/MapTypeModel.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/Model.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/PrimitiveTypeModel.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/SimpleTypeModel.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/rest/AnnotatedMethodParameterProcessorTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtilsTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/FieldUtilsTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/LoggerUtilsTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MemberUtilsTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MethodUtilsTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtilsTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/TypeUtilsTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/DefaultRestService.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/RestService.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/User.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/Ancestor.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/Compiler.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/CompilerTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/DefaultRestServiceTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/DefaultTestService.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/GenericTestService.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/Parent.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/RestServiceTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/SpringRestServiceTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/StandardRestServiceTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestProcessor.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestService.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestServiceImpl.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/rpc/support/DemoService.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/rpc/support/Person.java create mode 100644 dubbo-compatible/src/test/java/org/apache/dubbo/rpc/support/Type.java create mode 100644 dubbo-compatible/src/test/resources/META-INF/config.properties create mode 100644 dubbo-compatible/src/test/resources/META-INF/default.properties create mode 100644 dubbo-compatible/src/test/resources/META-INF/dubbb-consumer.properties create mode 100644 dubbo-compatible/src/test/resources/META-INF/dubbb-provider.properties create mode 100644 dubbo-compatible/src/test/resources/META-INF/dubbo-consumer.properties create mode 100644 dubbo-compatible/src/test/resources/META-INF/dubbo-provider.properties create mode 100644 dubbo-compatible/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.extension.activate.ActivateExt1 create mode 100644 dubbo-compatible/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.extension.support.Filter0 create mode 100644 dubbo-compatible/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter create mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/Dubbo2RpcExceptionUtils.java diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2ActivateUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2ActivateUtils.java new file mode 100644 index 0000000000..448aae4a74 --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2ActivateUtils.java @@ -0,0 +1,169 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.compact; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; + +public class Dubbo2ActivateUtils { + private static final Class ACTIVATE_CLASS; + private static final Method GROUP_METHOD; + private static final Method VALUE_METHOD; + private static final Method BEFORE_METHOD; + private static final Method AFTER_METHOD; + private static final Method ORDER_METHOD; + private static final Method ON_CLASS_METHOD; + + static { + ACTIVATE_CLASS = loadClass(); + GROUP_METHOD = loadMethod("group"); + VALUE_METHOD = loadMethod("value"); + BEFORE_METHOD = loadMethod("before"); + AFTER_METHOD = loadMethod("after"); + ORDER_METHOD = loadMethod("order"); + ON_CLASS_METHOD = loadMethod("onClass"); + } + + @SuppressWarnings("unchecked") + private static Class loadClass() { + try { + Class clazz = Class.forName("com.alibaba.dubbo.common.extension.Activate"); + if (clazz.isAnnotation()) { + return (Class) clazz; + } else { + return null; + } + } catch (Throwable e) { + return null; + } + } + + public static boolean isActivateLoaded() { + return ACTIVATE_CLASS != null; + } + + public static Class getActivateClass() { + return ACTIVATE_CLASS; + } + + private static Method loadMethod(String name) { + if (ACTIVATE_CLASS == null) { + return null; + } + try { + return ACTIVATE_CLASS.getMethod(name); + } catch (Throwable e) { + return null; + } + } + + public static String[] getGroup(Annotation annotation) { + if (GROUP_METHOD == null) { + return null; + } + try { + Object result = GROUP_METHOD.invoke(annotation); + if (result instanceof String[]) { + return (String[]) result; + } else { + return null; + } + } catch (Throwable e) { + return null; + } + } + + public static String[] getValue(Annotation annotation) { + if (VALUE_METHOD == null) { + return null; + } + try { + Object result = VALUE_METHOD.invoke(annotation); + if (result instanceof String[]) { + return (String[]) result; + } else { + return null; + } + } catch (Throwable e) { + return null; + } + } + + public static String[] getBefore(Annotation annotation) { + if (BEFORE_METHOD == null) { + return null; + } + try { + Object result = BEFORE_METHOD.invoke(annotation); + if (result instanceof String[]) { + return (String[]) result; + } else { + return null; + } + } catch (Throwable e) { + return null; + } + } + + public static String[] getAfter(Annotation annotation) { + if (AFTER_METHOD == null) { + return null; + } + try { + Object result = AFTER_METHOD.invoke(annotation); + if (result instanceof String[]) { + return (String[]) result; + } else { + return null; + } + } catch (Throwable e) { + return null; + } + } + + public static int getOrder(Annotation annotation) { + if (ORDER_METHOD == null) { + return 0; + } + try { + Object result = ORDER_METHOD.invoke(annotation); + if (result instanceof Integer) { + return (Integer) result; + } else { + return 0; + } + } catch (Throwable e) { + return 0; + } + } + + public static String[] getOnClass(Annotation annotation) { + if (ON_CLASS_METHOD == null) { + return null; + } + try { + Object result = ON_CLASS_METHOD.invoke(annotation); + if (result instanceof String[]) { + return (String[]) result; + } else { + return null; + } + } catch (Throwable e) { + return null; + } + } +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2CompactUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2CompactUtils.java new file mode 100644 index 0000000000..c3a3952e0a --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2CompactUtils.java @@ -0,0 +1,118 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.compact; + +import org.apache.dubbo.common.constants.CommonConstants; +import org.apache.dubbo.common.utils.StringUtils; + +import java.lang.annotation.Annotation; + +public class Dubbo2CompactUtils { + private static volatile boolean enabled = true; + private static final Class REFERENCE_CLASS; + private static final Class SERVICE_CLASS; + private static final Class ECHO_SERVICE_CLASS; + private static final Class GENERIC_SERVICE_CLASS; + + static { + initEnabled(); + REFERENCE_CLASS = loadAnnotation("com.alibaba.dubbo.config.annotation.Reference"); + SERVICE_CLASS = loadAnnotation("com.alibaba.dubbo.config.annotation.Service"); + ECHO_SERVICE_CLASS = loadClass("com.alibaba.dubbo.rpc.service.EchoService"); + GENERIC_SERVICE_CLASS = loadClass("com.alibaba.dubbo.rpc.service.GenericService"); + } + + private static void initEnabled() { + try { + String fromProp = System.getProperty(CommonConstants.DUBBO2_COMPACT_ENABLE); + if (StringUtils.isNotEmpty(fromProp)) { + enabled = Boolean.parseBoolean(fromProp); + return; + } + String fromEnv = System.getenv(CommonConstants.DUBBO2_COMPACT_ENABLE); + if (StringUtils.isNotEmpty(fromEnv)) { + enabled = Boolean.parseBoolean(fromEnv); + return; + } + fromEnv = System.getenv(StringUtils.toOSStyleKey(CommonConstants.DUBBO2_COMPACT_ENABLE)); + enabled = !StringUtils.isNotEmpty(fromEnv) || Boolean.parseBoolean(fromEnv); + } catch (Throwable t) { + enabled = true; + } + } + + public static boolean isEnabled() { + return enabled; + } + + public static void setEnabled(boolean enabled) { + Dubbo2CompactUtils.enabled = enabled; + } + + private static Class loadClass(String name) { + try { + return Class.forName(name); + } catch (Throwable e) { + return null; + } + } + + @SuppressWarnings("unchecked") + private static Class loadAnnotation(String name) { + try { + Class clazz = Class.forName(name); + if (clazz.isAnnotation()) { + return (Class) clazz; + } else { + return null; + } + } catch (Throwable e) { + return null; + } + } + public static boolean isReferenceClassLoaded() { + return REFERENCE_CLASS != null; + } + + public static Class getReferenceClass() { + return REFERENCE_CLASS; + } + + public static boolean isServiceClassLoaded() { + return SERVICE_CLASS != null; + } + + public static Class getServiceClass() { + return SERVICE_CLASS; + } + + public static boolean isEchoServiceClassLoaded() { + return ECHO_SERVICE_CLASS != null; + } + + public static Class getEchoServiceClass() { + return ECHO_SERVICE_CLASS; + } + + public static boolean isGenericServiceClassLoaded() { + return GENERIC_SERVICE_CLASS != null; + } + + public static Class getGenericServiceClass() { + return GENERIC_SERVICE_CLASS; + } +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2GenericExceptionUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2GenericExceptionUtils.java new file mode 100644 index 0000000000..0e4e28d2e0 --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2GenericExceptionUtils.java @@ -0,0 +1,129 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.compact; + +import org.apache.dubbo.rpc.service.GenericException; + +import java.lang.reflect.Constructor; + +public class Dubbo2GenericExceptionUtils { + private static final Class GENERIC_EXCEPTION_CLASS; + private static final Constructor GENERIC_EXCEPTION_CONSTRUCTOR; + private static final Constructor GENERIC_EXCEPTION_CONSTRUCTOR_S; + private static final Constructor GENERIC_EXCEPTION_CONSTRUCTOR_S_S; + private static final Constructor GENERIC_EXCEPTION_CONSTRUCTOR_T; + private static final Constructor GENERIC_EXCEPTION_CONSTRUCTOR_S_T_S_S; + + static { + GENERIC_EXCEPTION_CLASS = loadClass(); + GENERIC_EXCEPTION_CONSTRUCTOR = loadConstructor(); + GENERIC_EXCEPTION_CONSTRUCTOR_S = loadConstructor(String.class); + GENERIC_EXCEPTION_CONSTRUCTOR_S_S = loadConstructor(String.class, String.class); + GENERIC_EXCEPTION_CONSTRUCTOR_T = loadConstructor(Throwable.class); + GENERIC_EXCEPTION_CONSTRUCTOR_S_T_S_S = loadConstructor(String.class, Throwable.class, String.class, String.class); + } + + @SuppressWarnings("unchecked") + private static Class loadClass() { + try { + Class clazz = Class.forName("com.alibaba.dubbo.rpc.service.GenericException"); + if (GenericException.class.isAssignableFrom(clazz)) { + return (Class) clazz; + } else { + return null; + } + } catch (Throwable e) { + return null; + } + } + + private static Constructor loadConstructor(Class... parameterTypes) { + if (GENERIC_EXCEPTION_CLASS == null) { + return null; + } + try { + return GENERIC_EXCEPTION_CLASS.getConstructor(parameterTypes); + } catch (Throwable e) { + return null; + } + } + + public static boolean isGenericExceptionClassLoaded() { + return GENERIC_EXCEPTION_CLASS != null && GENERIC_EXCEPTION_CONSTRUCTOR != null + && GENERIC_EXCEPTION_CONSTRUCTOR_S != null && GENERIC_EXCEPTION_CONSTRUCTOR_S_S != null + && GENERIC_EXCEPTION_CONSTRUCTOR_T != null && GENERIC_EXCEPTION_CONSTRUCTOR_S_T_S_S != null; + } + + public static Class getGenericExceptionClass() { + return GENERIC_EXCEPTION_CLASS; + } + + public static org.apache.dubbo.rpc.service.GenericException newGenericException() { + if (GENERIC_EXCEPTION_CONSTRUCTOR == null) { + return null; + } + try { + return GENERIC_EXCEPTION_CONSTRUCTOR.newInstance(); + } catch (Throwable e) { + return null; + } + } + + public static org.apache.dubbo.rpc.service.GenericException newGenericException(String exceptionMessage) { + if (GENERIC_EXCEPTION_CONSTRUCTOR_S == null) { + return null; + } + try { + return GENERIC_EXCEPTION_CONSTRUCTOR_S.newInstance(exceptionMessage); + } catch (Throwable e) { + return null; + } + } + + public static org.apache.dubbo.rpc.service.GenericException newGenericException(String exceptionClass, String exceptionMessage) { + if (GENERIC_EXCEPTION_CONSTRUCTOR_S_S == null) { + return null; + } + try { + return GENERIC_EXCEPTION_CONSTRUCTOR_S_S.newInstance(exceptionClass, exceptionMessage); + } catch (Throwable e) { + return null; + } + } + + public static org.apache.dubbo.rpc.service.GenericException newGenericException(Throwable cause) { + if (GENERIC_EXCEPTION_CONSTRUCTOR_T == null) { + return null; + } + try { + return GENERIC_EXCEPTION_CONSTRUCTOR_T.newInstance(cause); + } catch (Throwable e) { + return null; + } + } + + public static org.apache.dubbo.rpc.service.GenericException newGenericException(String message, Throwable cause, String exceptionClass, String exceptionMessage) { + if (GENERIC_EXCEPTION_CONSTRUCTOR_S_T_S_S == null) { + return null; + } + try { + return GENERIC_EXCEPTION_CONSTRUCTOR_S_T_S_S.newInstance(message, cause, exceptionClass, exceptionMessage); + } catch (Throwable e) { + return null; + } + } +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java index 03b93bbce3..8b96f96b69 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java @@ -32,7 +32,7 @@ public interface CommonConstants { String PROVIDER = "provider"; String CONSUMER = "consumer"; - + String CALLBACK = "callback"; String APPLICATION_KEY = "application"; @@ -644,4 +644,7 @@ public interface CommonConstants { String DUBBO_PACKABLE_METHOD_FACTORY = "dubbo.application.parameters." + PACKABLE_METHOD_FACTORY_KEY; String DUBBO_MANUAL_REGISTER_KEY = "dubbo.application.manual-register"; + + String DUBBO2_COMPACT_ENABLE = "dubbo.compact.enable"; + } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionLoader.java b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionLoader.java index be0f96d247..bea5d7c474 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionLoader.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionLoader.java @@ -19,6 +19,8 @@ package org.apache.dubbo.common.extension; import org.apache.dubbo.common.Extension; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.beans.support.InstantiationStrategy; +import org.apache.dubbo.common.compact.Dubbo2ActivateUtils; +import org.apache.dubbo.common.compact.Dubbo2CompactUtils; import org.apache.dubbo.common.context.Lifecycle; import org.apache.dubbo.common.extension.support.ActivateComparator; import org.apache.dubbo.common.extension.support.WrapperComparator; @@ -47,6 +49,7 @@ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.lang.annotation.Annotation; import java.lang.ref.SoftReference; import java.lang.reflect.Constructor; import java.lang.reflect.Method; @@ -366,9 +369,10 @@ public class ExtensionLoader { if (activate instanceof Activate) { activateGroup = ((Activate) activate).group(); activateValue = ((Activate) activate).value(); - } else if (activate instanceof com.alibaba.dubbo.common.extension.Activate) { - activateGroup = ((com.alibaba.dubbo.common.extension.Activate) activate).group(); - activateValue = ((com.alibaba.dubbo.common.extension.Activate) activate).value(); + } else if (Dubbo2CompactUtils.isEnabled() && Dubbo2ActivateUtils.isActivateLoaded() + && Dubbo2ActivateUtils.getActivateClass().isAssignableFrom(activate.getClass())) { + activateGroup = Dubbo2ActivateUtils.getGroup((Annotation) activate); + activateValue = Dubbo2ActivateUtils.getValue((Annotation) activate); } else { continue; } @@ -1004,16 +1008,18 @@ public class ExtensionLoader { private void loadDirectory(Map> extensionClasses, LoadingStrategy strategy, String type) throws InterruptedException { loadDirectoryInternal(extensionClasses, strategy, type); - try { - String oldType = type.replace("org.apache", "com.alibaba"); - if (oldType.equals(type)) { - return; - } - //if class not found,skip try to load resources - ClassUtils.forName(oldType); - loadDirectoryInternal(extensionClasses, strategy, oldType); - } catch (ClassNotFoundException classNotFoundException) { + if (Dubbo2CompactUtils.isEnabled()) { + try { + String oldType = type.replace("org.apache", "com.alibaba"); + if (oldType.equals(type)) { + return; + } + //if class not found,skip try to load resources + ClassUtils.forName(oldType); + loadDirectoryInternal(extensionClasses, strategy, oldType); + } catch (ClassNotFoundException classNotFoundException) { + } } } @@ -1273,8 +1279,9 @@ public class ExtensionLoader { if (activate instanceof Activate) { onClass = ((Activate) activate).onClass(); - } else if (activate instanceof com.alibaba.dubbo.common.extension.Activate) { - onClass = ((com.alibaba.dubbo.common.extension.Activate) activate).onClass(); + } else if (Dubbo2CompactUtils.isEnabled() && Dubbo2ActivateUtils.isActivateLoaded() + && Dubbo2ActivateUtils.getActivateClass().isAssignableFrom(activate.getClass())) { + onClass = Dubbo2ActivateUtils.getOnClass(activate); } boolean isActive = true; @@ -1322,10 +1329,10 @@ public class ExtensionLoader { Activate activate = clazz.getAnnotation(Activate.class); if (activate != null) { cachedActivates.put(name, activate); - } else { + } else if (Dubbo2CompactUtils.isEnabled() && Dubbo2ActivateUtils.isActivateLoaded()){ // support com.alibaba.dubbo.common.extension.Activate - com.alibaba.dubbo.common.extension.Activate oldActivate = clazz.getAnnotation( - com.alibaba.dubbo.common.extension.Activate.class); + Annotation oldActivate = clazz.getAnnotation( + Dubbo2ActivateUtils.getActivateClass()); if (oldActivate != null) { cachedActivates.put(name, oldActivate); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/support/ActivateComparator.java b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/support/ActivateComparator.java index d8386f116c..73016dcae9 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/support/ActivateComparator.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/support/ActivateComparator.java @@ -16,12 +16,15 @@ */ package org.apache.dubbo.common.extension.support; +import org.apache.dubbo.common.compact.Dubbo2ActivateUtils; +import org.apache.dubbo.common.compact.Dubbo2CompactUtils; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.extension.ExtensionDirector; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.common.utils.ArrayUtils; +import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; @@ -150,12 +153,13 @@ public class ActivateComparator implements Comparator> { info.before = activate.before(); info.after = activate.after(); info.order = activate.order(); - } else if (clazz.isAnnotationPresent(com.alibaba.dubbo.common.extension.Activate.class)) { - com.alibaba.dubbo.common.extension.Activate activate = clazz.getAnnotation( - com.alibaba.dubbo.common.extension.Activate.class); - info.before = activate.before(); - info.after = activate.after(); - info.order = activate.order(); + } else if (Dubbo2CompactUtils.isEnabled() && Dubbo2ActivateUtils.isActivateLoaded() && + clazz.isAnnotationPresent(Dubbo2ActivateUtils.getActivateClass())) { + Annotation activate = clazz.getAnnotation( + Dubbo2ActivateUtils.getActivateClass()); + info.before = Dubbo2ActivateUtils.getBefore(activate); + info.after = Dubbo2ActivateUtils.getAfter(activate); + info.order = Dubbo2ActivateUtils.getOrder(activate); } else { info.order = 0; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/support/WrapperComparator.java b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/support/WrapperComparator.java index ced9357221..4fb19bf22b 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/support/WrapperComparator.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/support/WrapperComparator.java @@ -16,9 +16,12 @@ */ package org.apache.dubbo.common.extension.support; +import org.apache.dubbo.common.compact.Dubbo2ActivateUtils; +import org.apache.dubbo.common.compact.Dubbo2CompactUtils; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.extension.Wrapper; +import java.lang.annotation.Annotation; import java.util.Comparator; /** @@ -63,11 +66,12 @@ public class WrapperComparator implements Comparator { // TODO: backward compatibility Activate activate = clazz.getAnnotation(Activate.class); info.order = activate.order(); - } else if (clazz.isAnnotationPresent(com.alibaba.dubbo.common.extension.Activate.class)) { + } else if (Dubbo2CompactUtils.isEnabled() && Dubbo2ActivateUtils.isActivateLoaded() && + clazz.isAnnotationPresent(Dubbo2ActivateUtils.getActivateClass())) { // TODO: backward compatibility - com.alibaba.dubbo.common.extension.Activate activate = clazz.getAnnotation( - com.alibaba.dubbo.common.extension.Activate.class); - info.order = activate.order(); + Annotation activate = clazz.getAnnotation( + Dubbo2ActivateUtils.getActivateClass()); + info.order = Dubbo2ActivateUtils.getOrder(activate); } else if (clazz.isAnnotationPresent(Wrapper.class)) { Wrapper wrapper = clazz.getAnnotation(Wrapper.class); info.order = wrapper.order(); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ServiceAnnotationResolver.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ServiceAnnotationResolver.java index 8fc8bc69a6..3bc86a869e 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ServiceAnnotationResolver.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ServiceAnnotationResolver.java @@ -16,6 +16,7 @@ */ package org.apache.dubbo.common.utils; +import org.apache.dubbo.common.compact.Dubbo2CompactUtils; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.config.annotation.Service; @@ -45,7 +46,15 @@ public class ServiceAnnotationResolver { * * @since 2.7.9 */ - public static List> SERVICE_ANNOTATION_CLASSES = unmodifiableList(asList(DubboService.class, Service.class, com.alibaba.dubbo.config.annotation.Service.class)); + public static List> SERVICE_ANNOTATION_CLASSES = loadServiceAnnotationClasses(); + + private static List> loadServiceAnnotationClasses() { + if (Dubbo2CompactUtils.isEnabled() && Dubbo2CompactUtils.isServiceClassLoaded()) { + return unmodifiableList(asList(DubboService.class, Service.class, Dubbo2CompactUtils.getServiceClass())); + } else { + return unmodifiableList(asList(DubboService.class, Service.class)); + } + } private final Annotation serviceAnnotation; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/ReferenceConfigBase.java b/dubbo-common/src/main/java/org/apache/dubbo/config/ReferenceConfigBase.java index e2115e5cde..962b74c2f6 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/ReferenceConfigBase.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/ReferenceConfigBase.java @@ -17,6 +17,7 @@ package org.apache.dubbo.config; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.compact.Dubbo2CompactUtils; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.RegexProperties; import org.apache.dubbo.common.utils.StringUtils; @@ -227,7 +228,8 @@ public abstract class ReferenceConfigBase extends AbstractReferenceConfig { public static Class determineInterfaceClass(String generic, String interfaceName, ClassLoader classLoader) { if (ProtocolUtils.isGeneric(generic)) { - return com.alibaba.dubbo.rpc.service.GenericService.class; + return Dubbo2CompactUtils.isEnabled() && Dubbo2CompactUtils.isGenericServiceClassLoaded() ? + Dubbo2CompactUtils.getGenericServiceClass() : GenericService.class; } try { if (StringUtils.isNotEmpty(interfaceName)) { diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoaderTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoaderTest.java index 2e2b2a0884..bbf27a61e1 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoaderTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoaderTest.java @@ -24,8 +24,6 @@ import org.apache.dubbo.common.convert.StringToIntegerConverter; import org.apache.dubbo.common.extension.activate.ActivateExt1; import org.apache.dubbo.common.extension.activate.impl.ActivateExt1Impl1; import org.apache.dubbo.common.extension.activate.impl.GroupActivateExtImpl; -import org.apache.dubbo.common.extension.activate.impl.OldActivateExt1Impl2; -import org.apache.dubbo.common.extension.activate.impl.OldActivateExt1Impl3; import org.apache.dubbo.common.extension.activate.impl.OrderActivateExtImpl1; import org.apache.dubbo.common.extension.activate.impl.OrderActivateExtImpl2; import org.apache.dubbo.common.extension.activate.impl.ValueActivateExtImpl; @@ -568,14 +566,6 @@ class ExtensionLoaderTest { Assertions.assertEquals(1, list.size()); assertSame(list.get(0).getClass(), GroupActivateExtImpl.class); - // test old @Activate group - url = url.addParameter(GROUP_KEY, "old_group"); - list = getExtensionLoader(ActivateExt1.class) - .getActivateExtension(url, new String[]{}, "old_group"); - Assertions.assertEquals(2, list.size()); - Assertions.assertTrue(list.get(0).getClass() == OldActivateExt1Impl2.class - || list.get(0).getClass() == OldActivateExt1Impl3.class); - // test value url = url.removeParameter(GROUP_KEY); url = url.addParameter(GROUP_KEY, "value"); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/ActivateComparatorTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/ActivateComparatorTest.java index 2b0bbad296..6bf8cdfbf1 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/ActivateComparatorTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/ActivateComparatorTest.java @@ -41,21 +41,18 @@ class ActivateComparatorTest { Filter2 f2 = new Filter2(); Filter3 f3 = new Filter3(); Filter4 f4 = new Filter4(); - OldFilter5 f5 = new OldFilter5(); List> filters = new ArrayList<>(); filters.add(f1.getClass()); filters.add(f2.getClass()); filters.add(f3.getClass()); filters.add(f4.getClass()); - filters.add(f5.getClass()); Collections.sort(filters, activateComparator); Assertions.assertEquals(f4.getClass(), filters.get(0)); - Assertions.assertEquals(f5.getClass(), filters.get(1)); - Assertions.assertEquals(f3.getClass(), filters.get(2)); - Assertions.assertEquals(f2.getClass(), filters.get(3)); - Assertions.assertEquals(f1.getClass(), filters.get(4)); + Assertions.assertEquals(f3.getClass(), filters.get(1)); + Assertions.assertEquals(f2.getClass(), filters.get(2)); + Assertions.assertEquals(f1.getClass(), filters.get(3)); } @Test @@ -83,4 +80,4 @@ class ActivateComparatorTest { Assertions.assertEquals(order0Filter2.getClass(), filters.get(1)); } } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/AnnotationUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/AnnotationUtilsTest.java index 26b1960f35..ceadeaf4f3 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/AnnotationUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/AnnotationUtilsTest.java @@ -214,28 +214,30 @@ class AnnotationUtilsTest { @Test void testIsAnnotationPresent() { assertTrue(isAnnotationPresent(A.class, true, Service.class)); - assertTrue(isAnnotationPresent(A.class, true, Service.class, com.alibaba.dubbo.config.annotation.Service.class)); +// assertTrue(isAnnotationPresent(A.class, true, Service.class, com.alibaba.dubbo.config.annotation.Service.class)); assertTrue(isAnnotationPresent(A.class, Service.class)); assertTrue(isAnnotationPresent(A.class, "org.apache.dubbo.config.annotation.Service")); - assertTrue(AnnotationUtils.isAllAnnotationPresent(A.class, Service.class, Service.class, com.alibaba.dubbo.config.annotation.Service.class)); +// assertTrue(AnnotationUtils.isAllAnnotationPresent(A.class, Service.class, Service.class, com.alibaba.dubbo.config.annotation.Service.class)); + assertTrue(AnnotationUtils.isAllAnnotationPresent(A.class, Service.class, Service.class)); assertTrue(isAnnotationPresent(A.class, Deprecated.class)); } @Test void testIsAnyAnnotationPresent() { - assertTrue(isAnyAnnotationPresent(A.class, Service.class, com.alibaba.dubbo.config.annotation.Service.class, Deprecated.class)); - assertTrue(isAnyAnnotationPresent(A.class, Service.class, com.alibaba.dubbo.config.annotation.Service.class)); +// assertTrue(isAnyAnnotationPresent(A.class, Service.class, com.alibaba.dubbo.config.annotation.Service.class, Deprecated.class)); +// assertTrue(isAnyAnnotationPresent(A.class, Service.class, com.alibaba.dubbo.config.annotation.Service.class)); assertTrue(isAnyAnnotationPresent(A.class, Service.class, Deprecated.class)); - assertTrue(isAnyAnnotationPresent(A.class, com.alibaba.dubbo.config.annotation.Service.class, Deprecated.class)); +// assertTrue(isAnyAnnotationPresent(A.class, com.alibaba.dubbo.config.annotation.Service.class, Deprecated.class)); + assertTrue(isAnyAnnotationPresent(A.class, Deprecated.class)); assertTrue(isAnyAnnotationPresent(A.class, Service.class)); - assertTrue(isAnyAnnotationPresent(A.class, com.alibaba.dubbo.config.annotation.Service.class)); +// assertTrue(isAnyAnnotationPresent(A.class, com.alibaba.dubbo.config.annotation.Service.class)); assertTrue(isAnyAnnotationPresent(A.class, Deprecated.class)); } @Test void testGetAnnotation() { assertNotNull(getAnnotation(A.class, "org.apache.dubbo.config.annotation.Service")); - assertNotNull(getAnnotation(A.class, "com.alibaba.dubbo.config.annotation.Service")); +// assertNotNull(getAnnotation(A.class, "com.alibaba.dubbo.config.annotation.Service")); assertNotNull(getAnnotation(A.class, "org.apache.dubbo.common.extension.Adaptive")); assertNull(getAnnotation(A.class, "java.lang.Deprecated")); assertNull(getAnnotation(A.class, "java.lang.String")); @@ -282,7 +284,6 @@ class AnnotationUtilsTest { } @Service(interfaceName = "java.lang.CharSequence", interfaceClass = CharSequence.class) - @com.alibaba.dubbo.config.annotation.Service(interfaceName = "java.lang.CharSequence", interfaceClass = CharSequence.class) @Adaptive(value = {"a", "b", "c"}) static class A { @@ -363,10 +364,9 @@ class AnnotationUtilsTest { } private void assertADeclaredAnnotations(List annotations, int offset) { - int size = 3 + offset; + int size = 2 + offset; assertEquals(size, annotations.size()); boolean apacheServiceFound = false; - boolean alibabaServiceFound = false; boolean adaptiveFound = false; for (Annotation annotation: annotations) { @@ -376,18 +376,12 @@ class AnnotationUtilsTest { apacheServiceFound = true; continue; } - if (!alibabaServiceFound && (annotation instanceof com.alibaba.dubbo.config.annotation.Service)) { - assertEquals("java.lang.CharSequence", ((com.alibaba.dubbo.config.annotation.Service)annotation).interfaceName()); - assertEquals(CharSequence.class, ((com.alibaba.dubbo.config.annotation.Service)annotation).interfaceClass()); - alibabaServiceFound = true; - continue; - } if (!adaptiveFound && (annotation instanceof Adaptive)) { assertArrayEquals(new String[]{"a", "b", "c"}, ((Adaptive)annotation).value()); adaptiveFound = true; continue; } } - assertTrue(apacheServiceFound && alibabaServiceFound && adaptiveFound); + assertTrue(apacheServiceFound && adaptiveFound); } } diff --git a/dubbo-common/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.extension.activate.ActivateExt1 b/dubbo-common/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.extension.activate.ActivateExt1 index be6ad66e3e..8921c2c3f4 100644 --- a/dubbo-common/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.extension.activate.ActivateExt1 +++ b/dubbo-common/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.extension.activate.ActivateExt1 @@ -2,6 +2,4 @@ group=org.apache.dubbo.common.extension.activate.impl.GroupActivateExtImpl value=org.apache.dubbo.common.extension.activate.impl.ValueActivateExtImpl order1=org.apache.dubbo.common.extension.activate.impl.OrderActivateExtImpl1 order2=org.apache.dubbo.common.extension.activate.impl.OrderActivateExtImpl2 -old1=org.apache.dubbo.common.extension.activate.impl.OldActivateExt1Impl2 -old2=org.apache.dubbo.common.extension.activate.impl.OldActivateExt1Impl3 onClassExt=org.apache.dubbo.common.extension.activate.impl.ActivateOnClassExt1Impl diff --git a/dubbo-compatible/pom.xml b/dubbo-compatible/pom.xml index bbadadbd42..ec42b071f7 100644 --- a/dubbo-compatible/pom.xml +++ b/dubbo-compatible/pom.xml @@ -33,6 +33,11 @@ dubbo-config-spring ${project.parent.version} + + org.springframework + spring-tx + test + org.apache.dubbo dubbo-qos @@ -88,6 +93,12 @@ ${project.parent.version} test + + org.apache.dubbo + dubbo-metadata-processor + ${project.parent.version} + test + org.apache.dubbo dubbo-metadata-report-zookeeper diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/extension/Activate.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/extension/Activate.java similarity index 100% rename from dubbo-common/src/main/java/com/alibaba/dubbo/common/extension/Activate.java rename to dubbo-compatible/src/main/java/com/alibaba/dubbo/common/extension/Activate.java diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/config/annotation/Reference.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/annotation/Reference.java similarity index 100% rename from dubbo-common/src/main/java/com/alibaba/dubbo/config/annotation/Reference.java rename to dubbo-compatible/src/main/java/com/alibaba/dubbo/config/annotation/Reference.java diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/config/annotation/Service.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/annotation/Service.java similarity index 100% rename from dubbo-common/src/main/java/com/alibaba/dubbo/config/annotation/Service.java rename to dubbo-compatible/src/main/java/com/alibaba/dubbo/config/annotation/Service.java diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcException.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcException.java similarity index 100% rename from dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcException.java rename to dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcException.java diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/rpc/service/EchoService.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/service/EchoService.java similarity index 100% rename from dubbo-common/src/main/java/com/alibaba/dubbo/rpc/service/EchoService.java rename to dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/service/EchoService.java diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/rpc/service/GenericException.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/service/GenericException.java similarity index 100% rename from dubbo-common/src/main/java/com/alibaba/dubbo/rpc/service/GenericException.java rename to dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/service/GenericException.java diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/rpc/service/GenericService.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/service/GenericService.java similarity index 100% rename from dubbo-common/src/main/java/com/alibaba/dubbo/rpc/service/GenericService.java rename to dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/service/GenericService.java diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/ExtensionTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/ExtensionTest.java index f6d1b923ee..187c28905a 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/ExtensionTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/ExtensionTest.java @@ -17,9 +17,18 @@ package org.apache.dubbo.common.extension; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.extension.activate.ActivateExt1; +import org.apache.dubbo.common.extension.activate.impl.OldActivateExt1Impl2; +import org.apache.dubbo.common.extension.activate.impl.OldActivateExt1Impl3; +import org.apache.dubbo.rpc.model.ApplicationModel; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import java.util.List; + +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.junit.jupiter.api.Assertions.fail; class ExtensionTest { @@ -41,4 +50,21 @@ class ExtensionTest { fail(); } } + + private ExtensionLoader getExtensionLoader(Class type) { + return ApplicationModel.defaultModel().getExtensionDirector().getExtensionLoader(type); + } + + @Test + void testLoadActivateExtension() { + // test default + URL url = URL.valueOf("test://localhost/test") + .addParameter(GROUP_KEY, "old_group"); + List list = getExtensionLoader(ActivateExt1.class) + .getActivateExtension(url, new String[]{}, "old_group"); + Assertions.assertEquals(2, list.size()); + Assertions.assertTrue(list.get(0).getClass() == OldActivateExt1Impl2.class + || list.get(0).getClass() == OldActivateExt1Impl3.class); + + } } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/activate/ActivateExt1.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/activate/ActivateExt1.java new file mode 100644 index 0000000000..c00a988577 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/activate/ActivateExt1.java @@ -0,0 +1,25 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.common.extension.activate; + +import org.apache.dubbo.common.extension.SPI; + +@SPI("impl1") +public interface ActivateExt1 { + String echo(String msg); +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateExt1Impl1.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateExt1Impl1.java new file mode 100644 index 0000000000..fe3e082d49 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateExt1Impl1.java @@ -0,0 +1,28 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.common.extension.activate.impl; + +import org.apache.dubbo.common.extension.Activate; +import org.apache.dubbo.common.extension.activate.ActivateExt1; + +@Activate(order = 1, group = {"default_group"}) +public class ActivateExt1Impl1 implements ActivateExt1 { + public String echo(String msg) { + return msg; + } +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/OldActivateExt1Impl2.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/activate/impl/OldActivateExt1Impl2.java similarity index 100% rename from dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/OldActivateExt1Impl2.java rename to dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/activate/impl/OldActivateExt1Impl2.java diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/OldActivateExt1Impl3.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/activate/impl/OldActivateExt1Impl3.java similarity index 100% rename from dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/OldActivateExt1Impl3.java rename to dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/activate/impl/OldActivateExt1Impl3.java diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/ActivateComparatorTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/ActivateComparatorTest.java new file mode 100644 index 0000000000..1c1cf7dc80 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/ActivateComparatorTest.java @@ -0,0 +1,60 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.extension.support; + +import org.apache.dubbo.rpc.model.ApplicationModel; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +class ActivateComparatorTest { + + private ActivateComparator activateComparator; + + @BeforeEach + public void setup() { + activateComparator = new ActivateComparator(ApplicationModel.defaultModel().getExtensionDirector()); + } + + @Test + void testActivateComparator(){ + Filter1 f1 = new Filter1(); + Filter2 f2 = new Filter2(); + Filter3 f3 = new Filter3(); + Filter4 f4 = new Filter4(); + OldFilter5 f5 = new OldFilter5(); + List> filters = new ArrayList<>(); + filters.add(f1.getClass()); + filters.add(f2.getClass()); + filters.add(f3.getClass()); + filters.add(f4.getClass()); + filters.add(f5.getClass()); + + Collections.sort(filters, activateComparator); + + Assertions.assertEquals(f4.getClass(), filters.get(0)); + Assertions.assertEquals(f5.getClass(), filters.get(1)); + Assertions.assertEquals(f3.getClass(), filters.get(2)); + Assertions.assertEquals(f2.getClass(), filters.get(3)); + Assertions.assertEquals(f1.getClass(), filters.get(4)); + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter0.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter0.java new file mode 100644 index 0000000000..612440894d --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter0.java @@ -0,0 +1,23 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.extension.support; + +import org.apache.dubbo.common.extension.SPI; + +@SPI +public interface Filter0 { +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter1.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter1.java new file mode 100644 index 0000000000..5f30dd650e --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter1.java @@ -0,0 +1,23 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.extension.support; + +import org.apache.dubbo.common.extension.Activate; + +@Activate +public class Filter1 implements Filter0{ +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter2.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter2.java new file mode 100644 index 0000000000..df93fa6eaf --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter2.java @@ -0,0 +1,23 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.extension.support; + +import org.apache.dubbo.common.extension.Activate; + +@Activate(before = "_1") +public class Filter2 implements Filter0{ +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter3.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter3.java new file mode 100644 index 0000000000..c02aaa13c2 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter3.java @@ -0,0 +1,23 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.extension.support; + +import org.apache.dubbo.common.extension.Activate; + +@Activate(after = "_4") +public class Filter3 implements Filter0{ +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter4.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter4.java new file mode 100644 index 0000000000..353874bc9a --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter4.java @@ -0,0 +1,23 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.extension.support; + +import org.apache.dubbo.common.extension.Activate; + +@Activate(before = "_2") +public class Filter4 implements Filter0{ +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/OldFilter0.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/OldFilter0.java similarity index 100% rename from dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/OldFilter0.java rename to dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/OldFilter0.java diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/OldFilter5.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/OldFilter5.java similarity index 100% rename from dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/OldFilter5.java rename to dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/OldFilter5.java diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter0.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter0.java new file mode 100644 index 0000000000..634e92f12f --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter0.java @@ -0,0 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.common.extension.support; + +import org.apache.dubbo.common.extension.SPI; + +@SPI +public interface Order0Filter0 { +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter1.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter1.java new file mode 100644 index 0000000000..cf23ffee94 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter1.java @@ -0,0 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.common.extension.support; + +import org.apache.dubbo.common.extension.Activate; + +@Activate +public class Order0Filter1 implements Order0Filter0 { +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter2.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter2.java new file mode 100644 index 0000000000..b09ed993a9 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter2.java @@ -0,0 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.common.extension.support; + +import org.apache.dubbo.common.extension.Activate; + +@Activate +public class Order0Filter2 implements Order0Filter0 { +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/utils/AnnotationUtilsTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/utils/AnnotationUtilsTest.java new file mode 100644 index 0000000000..26b1960f35 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/utils/AnnotationUtilsTest.java @@ -0,0 +1,393 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.utils; + +import org.apache.dubbo.common.extension.Adaptive; +import org.apache.dubbo.config.annotation.DubboService; +import org.apache.dubbo.config.annotation.Service; + +import org.junit.jupiter.api.Test; + +import java.lang.annotation.Annotation; +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import static java.util.Arrays.asList; +import static org.apache.dubbo.common.utils.AnnotationUtils.excludedType; +import static org.apache.dubbo.common.utils.AnnotationUtils.filterDefaultValues; +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.findMetaAnnotations; +import static org.apache.dubbo.common.utils.AnnotationUtils.getAllDeclaredAnnotations; +import static org.apache.dubbo.common.utils.AnnotationUtils.getAllMetaAnnotations; +import static org.apache.dubbo.common.utils.AnnotationUtils.getAnnotation; +import static org.apache.dubbo.common.utils.AnnotationUtils.getAttribute; +import static org.apache.dubbo.common.utils.AnnotationUtils.getAttributes; +import static org.apache.dubbo.common.utils.AnnotationUtils.getDeclaredAnnotations; +import static org.apache.dubbo.common.utils.AnnotationUtils.getDefaultValue; +import static org.apache.dubbo.common.utils.AnnotationUtils.getMetaAnnotations; +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.AnnotationUtils.isAnyAnnotationPresent; +import static org.apache.dubbo.common.utils.AnnotationUtils.isSameType; +import static org.apache.dubbo.common.utils.AnnotationUtils.isType; +import static org.apache.dubbo.common.utils.MethodUtils.findMethod; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * {@link AnnotationUtils} Test + * + * @since 2.7.6 + */ +class AnnotationUtilsTest { + + @Test + void testIsType() { + // null checking + assertFalse(isType(null)); + // Method checking + assertFalse(isType(findMethod(A.class, "execute"))); + // Class checking + assertTrue(isType(A.class)); + } + + @Test + void testIsSameType() { + assertTrue(isSameType(A.class.getAnnotation(Service.class), Service.class)); + assertFalse(isSameType(A.class.getAnnotation(Service.class), Deprecated.class)); + assertFalse(isSameType(A.class.getAnnotation(Service.class), null)); + assertFalse(isSameType(null, Deprecated.class)); + assertFalse(isSameType(null, null)); + } + + @Test + void testExcludedType() { + assertFalse(excludedType(Service.class).test(A.class.getAnnotation(Service.class))); + assertTrue(excludedType(Service.class).test(A.class.getAnnotation(Deprecated.class))); + } + + @Test + void testGetAttribute() { + Annotation annotation = A.class.getAnnotation(Service.class); + assertEquals("java.lang.CharSequence", getAttribute(annotation, "interfaceName")); + assertEquals(CharSequence.class, getAttribute(annotation, "interfaceClass")); + assertEquals("", getAttribute(annotation, "version")); + assertEquals("", getAttribute(annotation, "group")); + assertEquals("", getAttribute(annotation, "path")); + assertEquals(true, getAttribute(annotation, "export")); + assertEquals(false, getAttribute(annotation, "deprecated")); + } + + @Test + void testGetAttributesMap() { + Annotation annotation = A.class.getAnnotation(Service.class); + Map attributes = getAttributes(annotation, false); + assertEquals("java.lang.CharSequence", attributes.get("interfaceName")); + assertEquals(CharSequence.class, attributes.get("interfaceClass")); + assertEquals("", attributes.get("group")); + assertEquals(getDefaultValue(annotation, "export"), attributes.get("export")); + + Map filteredAttributes = filterDefaultValues(annotation, attributes); + assertEquals(2, filteredAttributes.size()); + assertEquals("java.lang.CharSequence", filteredAttributes.get("interfaceName")); + assertEquals(CharSequence.class, filteredAttributes.get("interfaceClass")); + assertFalse(filteredAttributes.containsKey("group")); + assertFalse(filteredAttributes.containsKey("export")); + + Map nonDefaultAttributes = getAttributes(annotation, true); + assertEquals(nonDefaultAttributes, filteredAttributes); + } + + @Test + void testGetValue() { + Adaptive adaptive = A.class.getAnnotation(Adaptive.class); + String[] value = getValue(adaptive); + assertEquals(asList("a", "b", "c"), asList(value)); + } + + @Test + void testGetDeclaredAnnotations() { + List annotations = getDeclaredAnnotations(A.class); + assertADeclaredAnnotations(annotations, 0); + + annotations = getDeclaredAnnotations(A.class, a -> isSameType(a, Service.class)); + assertEquals(1, annotations.size()); + Service service = (Service) annotations.get(0); + assertEquals("java.lang.CharSequence", service.interfaceName()); + assertEquals(CharSequence.class, service.interfaceClass()); + } + + @Test + void testGetAllDeclaredAnnotations() { + List annotations = getAllDeclaredAnnotations(A.class); + assertADeclaredAnnotations(annotations, 0); + + annotations = getAllDeclaredAnnotations(B.class); + assertTrue(isSameType(annotations.get(0), Service5.class)); + assertADeclaredAnnotations(annotations, 1); + + annotations = new LinkedList<>(getAllDeclaredAnnotations(C.class)); + assertTrue(isSameType(annotations.get(0), MyAdaptive.class)); + assertTrue(isSameType(annotations.get(1), Service5.class)); + assertADeclaredAnnotations(annotations, 2); + + annotations = getAllDeclaredAnnotations(findMethod(A.class, "execute")); + MyAdaptive myAdaptive = (MyAdaptive) annotations.get(0); + assertArrayEquals(new String[]{"e"}, myAdaptive.value()); + + annotations = getAllDeclaredAnnotations(findMethod(B.class, "execute")); + Adaptive adaptive = (Adaptive) annotations.get(0); + assertArrayEquals(new String[]{"f"}, adaptive.value()); + } + + @Test + void testGetMetaAnnotations() { + List metaAnnotations = getMetaAnnotations(Service.class, a -> isSameType(a, Inherited.class)); + assertEquals(1, metaAnnotations.size()); + assertEquals(Inherited.class, metaAnnotations.get(0).annotationType()); + + metaAnnotations = getMetaAnnotations(Service.class); + HashSet set1 = new HashSet<>(); + metaAnnotations.forEach(t -> set1.add(t.annotationType())); + HashSet set2 = new HashSet<>(); + set2.add(Inherited.class); + set2.add(Deprecated.class); + assertEquals(2, metaAnnotations.size()); + assertEquals(set1, set2); + } + + @Test + void testGetAllMetaAnnotations() { + List metaAnnotations = getAllMetaAnnotations(Service5.class); + int offset = 0; + + HashSet set1 = new HashSet<>(); + metaAnnotations.forEach(t -> set1.add(t.annotationType())); + HashSet set2 = new HashSet<>(); + set2.add(Inherited.class); + set2.add(DubboService.class); + set2.add(Service4.class); + set2.add(Service3.class); + set2.add(Service2.class); + assertEquals(9, metaAnnotations.size()); + assertEquals(set1, set2); + + metaAnnotations = getAllMetaAnnotations(MyAdaptive.class); + HashSet set3 = new HashSet<>(); + metaAnnotations.forEach(t -> set3.add(t.annotationType())); + HashSet set4 = new HashSet<>(); + metaAnnotations.forEach(t -> set3.add(t.annotationType())); + set4.add(Inherited.class); + set4.add(Adaptive.class); + assertEquals(2, metaAnnotations.size()); + assertEquals(set3, set4); + } + + + @Test + void testIsAnnotationPresent() { + assertTrue(isAnnotationPresent(A.class, true, Service.class)); + assertTrue(isAnnotationPresent(A.class, true, Service.class, com.alibaba.dubbo.config.annotation.Service.class)); + assertTrue(isAnnotationPresent(A.class, Service.class)); + assertTrue(isAnnotationPresent(A.class, "org.apache.dubbo.config.annotation.Service")); + assertTrue(AnnotationUtils.isAllAnnotationPresent(A.class, Service.class, Service.class, com.alibaba.dubbo.config.annotation.Service.class)); + assertTrue(isAnnotationPresent(A.class, Deprecated.class)); + } + + @Test + void testIsAnyAnnotationPresent() { + assertTrue(isAnyAnnotationPresent(A.class, Service.class, com.alibaba.dubbo.config.annotation.Service.class, Deprecated.class)); + assertTrue(isAnyAnnotationPresent(A.class, Service.class, com.alibaba.dubbo.config.annotation.Service.class)); + assertTrue(isAnyAnnotationPresent(A.class, Service.class, Deprecated.class)); + assertTrue(isAnyAnnotationPresent(A.class, com.alibaba.dubbo.config.annotation.Service.class, Deprecated.class)); + assertTrue(isAnyAnnotationPresent(A.class, Service.class)); + assertTrue(isAnyAnnotationPresent(A.class, com.alibaba.dubbo.config.annotation.Service.class)); + assertTrue(isAnyAnnotationPresent(A.class, Deprecated.class)); + } + + @Test + void testGetAnnotation() { + assertNotNull(getAnnotation(A.class, "org.apache.dubbo.config.annotation.Service")); + assertNotNull(getAnnotation(A.class, "com.alibaba.dubbo.config.annotation.Service")); + assertNotNull(getAnnotation(A.class, "org.apache.dubbo.common.extension.Adaptive")); + assertNull(getAnnotation(A.class, "java.lang.Deprecated")); + assertNull(getAnnotation(A.class, "java.lang.String")); + assertNull(getAnnotation(A.class, "NotExistedClass")); + } + + @Test + void testFindAnnotation() { + Service service = findAnnotation(A.class, Service.class); + assertEquals("java.lang.CharSequence", service.interfaceName()); + assertEquals(CharSequence.class, service.interfaceClass()); + + service = findAnnotation(B.class, Service.class); + assertEquals(CharSequence.class, service.interfaceClass()); + } + + @Test + void testFindMetaAnnotations() { + List services = findMetaAnnotations(B.class, DubboService.class); + assertEquals(1, services.size()); + + DubboService service = services.get(0); + assertEquals("", service.interfaceName()); + assertEquals(Cloneable.class, service.interfaceClass()); + + services = findMetaAnnotations(Service5.class, DubboService.class); + assertEquals(1, services.size()); + + service = services.get(0); + assertEquals("", service.interfaceName()); + assertEquals(Cloneable.class, service.interfaceClass()); + } + + @Test + void testFindMetaAnnotation() { + DubboService service = findMetaAnnotation(B.class, DubboService.class); + assertEquals(Cloneable.class, service.interfaceClass()); + + service = findMetaAnnotation(B.class, "org.apache.dubbo.config.annotation.DubboService"); + assertEquals(Cloneable.class, service.interfaceClass()); + + service = findMetaAnnotation(Service5.class, DubboService.class); + assertEquals(Cloneable.class, service.interfaceClass()); + } + + @Service(interfaceName = "java.lang.CharSequence", interfaceClass = CharSequence.class) + @com.alibaba.dubbo.config.annotation.Service(interfaceName = "java.lang.CharSequence", interfaceClass = CharSequence.class) + @Adaptive(value = {"a", "b", "c"}) + static class A { + + @MyAdaptive("e") + public void execute() { + + } + + + } + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target({ElementType.TYPE}) + @Inherited + @DubboService(interfaceClass = Cloneable.class) + @interface Service2 { + + + } + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target({ElementType.TYPE}) + @Inherited + @Service2 + @interface Service3 { + + + } + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target({ElementType.TYPE}) + @Inherited + @Service3 + @interface Service4 { + + + } + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target({ElementType.TYPE}) + @Inherited + @Service4 + @interface Service5 { + + + } + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target({ElementType.TYPE, ElementType.METHOD}) + @Inherited + @Adaptive + @interface MyAdaptive { + + String[] value() default {}; + + } + + @Service5 + static class B extends A { + + @Adaptive("f") + @Override + public void execute() { + + } + + + } + + @MyAdaptive + static class C extends B { + + } + + private void assertADeclaredAnnotations(List annotations, int offset) { + int size = 3 + offset; + assertEquals(size, annotations.size()); + boolean apacheServiceFound = false; + boolean alibabaServiceFound = false; + boolean adaptiveFound = false; + + for (Annotation annotation: annotations) { + if (!apacheServiceFound && (annotation instanceof Service)) { + assertEquals("java.lang.CharSequence", ((Service)annotation).interfaceName()); + assertEquals(CharSequence.class, ((Service)annotation).interfaceClass()); + apacheServiceFound = true; + continue; + } + if (!alibabaServiceFound && (annotation instanceof com.alibaba.dubbo.config.annotation.Service)) { + assertEquals("java.lang.CharSequence", ((com.alibaba.dubbo.config.annotation.Service)annotation).interfaceName()); + assertEquals(CharSequence.class, ((com.alibaba.dubbo.config.annotation.Service)annotation).interfaceClass()); + alibabaServiceFound = true; + continue; + } + if (!adaptiveFound && (annotation instanceof Adaptive)) { + assertArrayEquals(new String[]{"a", "b", "c"}, ((Adaptive)annotation).value()); + adaptiveFound = true; + continue; + } + } + assertTrue(apacheServiceFound && alibabaServiceFound && adaptiveFound); + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/api/Box.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/api/Box.java new file mode 100644 index 0000000000..ed168fc37a --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/api/Box.java @@ -0,0 +1,23 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.config.spring.api; + +public interface Box { + + String getName(); + +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/api/DemoService.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/api/DemoService.java new file mode 100644 index 0000000000..84fd939716 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/api/DemoService.java @@ -0,0 +1,28 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.config.spring.api; + +/** + * DemoService + */ +public interface DemoService { + + String sayName(String name); + + Box getBox(); + +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/api/HelloService.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/api/HelloService.java new file mode 100644 index 0000000000..3cc5416096 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/api/HelloService.java @@ -0,0 +1,22 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.config.spring.api; + +public interface HelloService { + String sayHello(String name); +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationTestConfiguration.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationTestConfiguration.java new file mode 100644 index 0000000000..59f1385a13 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationTestConfiguration.java @@ -0,0 +1,109 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.config.spring.beans.factory.annotation; + + +import org.apache.dubbo.config.ApplicationConfig; +import org.apache.dubbo.config.ProtocolConfig; +import org.apache.dubbo.config.RegistryConfig; +import org.apache.dubbo.config.annotation.Service; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; +import org.springframework.context.annotation.PropertySource; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionException; +import org.springframework.transaction.TransactionStatus; + +/** + * {@link Service} Bean + * + * @since 2.6.5 + */ +@PropertySource("classpath:/META-INF/default.properties") +public class ServiceAnnotationTestConfiguration { + + /** + * Current application configuration, to replace XML config: + * + * <dubbo:application name="dubbo-demo-application"/> + * + * + * @return {@link ApplicationConfig} Bean + */ + @Bean("dubbo-demo-application") + public ApplicationConfig applicationConfig() { + ApplicationConfig applicationConfig = new ApplicationConfig(); + applicationConfig.setName("dubbo-demo-application"); + return applicationConfig; + } + + /** + * Current registry center configuration, to replace XML config: + * + * <dubbo:registry id="my-registry" address="N/A"/> + * + * + * @return {@link RegistryConfig} Bean + */ + @Bean("my-registry") + public RegistryConfig registryConfig() { + RegistryConfig registryConfig = new RegistryConfig(); + registryConfig.setAddress("N/A"); + return registryConfig; + } + + /** + * Current protocol configuration, to replace XML config: + * + * <dubbo:protocol name="dubbo" port="12345"/> + * + * + * @return {@link ProtocolConfig} Bean + */ + @Bean//("dubbo") + public ProtocolConfig protocolConfig() { + ProtocolConfig protocolConfig = new ProtocolConfig(); + protocolConfig.setName("dubbo"); + protocolConfig.setPort(12345); + return protocolConfig; + } + + @Primary + @Bean + public PlatformTransactionManager platformTransactionManager() { + return new PlatformTransactionManager() { + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException { + return null; + } + + @Override + public void commit(TransactionStatus status) throws TransactionException { + + } + + @Override + public void rollback(TransactionStatus status) throws TransactionException { + + } + }; + } + +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScanRegistrarTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScanRegistrarTest.java new file mode 100644 index 0000000000..6ad42e80c7 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScanRegistrarTest.java @@ -0,0 +1,129 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.config.spring.context.annotation; + +import org.apache.dubbo.config.bootstrap.DubboBootstrap; +import org.apache.dubbo.config.spring.api.DemoService; +import org.apache.dubbo.config.spring.context.annotation.consumer.ConsumerConfiguration; +import org.apache.dubbo.config.spring.context.annotation.provider.DemoServiceImpl; +import org.apache.dubbo.config.spring.context.annotation.provider.ProviderConfiguration; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.aop.support.AopUtils; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.transaction.annotation.Transactional; + +import static org.springframework.core.annotation.AnnotationUtils.findAnnotation; + +/** + * {@link DubboComponentScanRegistrar} Test + * + * @since 2.5.8 + */ +class DubboComponentScanRegistrarTest { + + @BeforeEach + public void setUp() { + DubboBootstrap.reset(); + } + + @AfterEach + public void tearDown() { + } + + @Test + void test() { + + AnnotationConfigApplicationContext providerContext = new AnnotationConfigApplicationContext(); + + providerContext.register(ProviderConfiguration.class); + + providerContext.refresh(); + + DemoService demoService = providerContext.getBean(DemoService.class); + + String value = demoService.sayName("Mercy"); + + Assertions.assertEquals("Hello,Mercy", value); + + Class beanClass = AopUtils.getTargetClass(demoService); + + // DemoServiceImpl with @Transactional + Assertions.assertEquals(DemoServiceImpl.class, beanClass); + + // Test @Transactional is present or not + Assertions.assertNotNull(findAnnotation(beanClass, Transactional.class)); + + + // consumer app + AnnotationConfigApplicationContext consumerContext = new AnnotationConfigApplicationContext(); + + consumerContext.register(ConsumerConfiguration.class); + + consumerContext.refresh(); + + ConsumerConfiguration consumerConfiguration = consumerContext.getBean(ConsumerConfiguration.class); + + demoService = consumerConfiguration.getDemoService(); + + value = demoService.sayName("Mercy"); + + Assertions.assertEquals("Hello,Mercy", value); + + ConsumerConfiguration.Child child = consumerContext.getBean(ConsumerConfiguration.Child.class); + + // From Child + + demoService = child.getDemoServiceFromChild(); + + Assertions.assertNotNull(demoService); + + value = demoService.sayName("Mercy"); + + Assertions.assertEquals("Hello,Mercy", value); + + // From Parent + + demoService = child.getDemoServiceFromParent(); + + Assertions.assertNotNull(demoService); + + value = demoService.sayName("Mercy"); + + Assertions.assertEquals("Hello,Mercy", value); + + // From Ancestor + + demoService = child.getDemoServiceFromAncestor(); + + Assertions.assertNotNull(demoService); + + value = demoService.sayName("Mercy"); + + Assertions.assertEquals("Hello,Mercy", value); + + providerContext.close(); + consumerContext.close(); + + + } + + +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfigurationTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfigurationTest.java new file mode 100644 index 0000000000..f4b705315e --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfigurationTest.java @@ -0,0 +1,94 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.config.spring.context.annotation; + +import org.apache.dubbo.config.ApplicationConfig; +import org.apache.dubbo.config.ModuleConfig; +import org.apache.dubbo.config.ProtocolConfig; +import org.apache.dubbo.config.RegistryConfig; +import org.apache.dubbo.config.bootstrap.DubboBootstrap; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.core.io.support.ResourcePropertySource; + +import java.io.IOException; + +/** + * {@link DubboConfigConfiguration} Test + * + * @since 2.5.8 + */ +class DubboConfigConfigurationTest { + + private AnnotationConfigApplicationContext context; + + @BeforeEach + public void before() throws IOException { + DubboBootstrap.reset(); + + context = new AnnotationConfigApplicationContext(); + ResourcePropertySource propertySource = new ResourcePropertySource("META-INF/config.properties"); + context.getEnvironment().getPropertySources().addFirst(propertySource); + + } + + @AfterEach + public void after() { + context.close(); + } + + @Test + void testSingle() throws IOException { + + context.register(DubboConfigConfiguration.Single.class); + context.refresh(); + + // application + ApplicationConfig applicationConfig = context.getBean("applicationBean", ApplicationConfig.class); + Assertions.assertEquals("dubbo-demo-application", applicationConfig.getName()); + + // module + ModuleConfig moduleConfig = context.getBean("moduleBean", ModuleConfig.class); + Assertions.assertEquals("dubbo-demo-module", moduleConfig.getName()); + + // registry + RegistryConfig registryConfig = context.getBean(RegistryConfig.class); + Assertions.assertEquals("zookeeper://192.168.99.100:32770", registryConfig.getAddress()); + + // protocol + ProtocolConfig protocolConfig = context.getBean(ProtocolConfig.class); + Assertions.assertEquals("dubbo", protocolConfig.getName()); + Assertions.assertEquals(Integer.valueOf(20880), protocolConfig.getPort()); + } + + @Test + void testMultiple() { + context.register(DubboConfigConfiguration.Multiple.class); + context.refresh(); + + RegistryConfig registry1 = context.getBean("registry1", RegistryConfig.class); + Assertions.assertEquals(2181, registry1.getPort()); + + RegistryConfig registry2 = context.getBean("registry2", RegistryConfig.class); + Assertions.assertEquals(2182, registry2.getPort()); + } + +} \ No newline at end of file diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfigTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfigTest.java new file mode 100644 index 0000000000..803241d535 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfigTest.java @@ -0,0 +1,140 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.config.spring.context.annotation; + +import org.apache.dubbo.config.ApplicationConfig; +import org.apache.dubbo.config.ConsumerConfig; +import org.apache.dubbo.config.ModuleConfig; +import org.apache.dubbo.config.MonitorConfig; +import org.apache.dubbo.config.ProtocolConfig; +import org.apache.dubbo.config.ProviderConfig; +import org.apache.dubbo.config.RegistryConfig; +import org.apache.dubbo.config.bootstrap.DubboBootstrap; +import org.apache.dubbo.config.context.ConfigManager; +import org.apache.dubbo.rpc.model.ApplicationModel; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.PropertySource; + +import java.util.Collection; + +import static com.alibaba.spring.util.BeanRegistrar.hasAlias; +import static org.junit.jupiter.api.Assertions.assertFalse; + + +/** + * {@link EnableDubboConfig} Test + * + * @since 2.5.8 + */ +class EnableDubboConfigTest { + + @BeforeEach + public void setUp() { + DubboBootstrap.reset(); + } + + @AfterEach + public void tearDown() { + DubboBootstrap.reset(); + } + + //@Test + public void testSingle() { + + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + context.register(TestConfig.class); + context.refresh(); + + // application + ApplicationConfig applicationConfig = context.getBean("applicationBean", ApplicationConfig.class); + Assertions.assertEquals("dubbo-demo-application", applicationConfig.getName()); + + // module + ModuleConfig moduleConfig = context.getBean("moduleBean", ModuleConfig.class); + Assertions.assertEquals("dubbo-demo-module", moduleConfig.getName()); + + // registry + RegistryConfig registryConfig = context.getBean(RegistryConfig.class); + Assertions.assertEquals("zookeeper://192.168.99.100:32770", registryConfig.getAddress()); + + // protocol + ProtocolConfig protocolConfig = context.getBean(ProtocolConfig.class); + Assertions.assertEquals("dubbo", protocolConfig.getName()); + Assertions.assertEquals(Integer.valueOf(20880), protocolConfig.getPort()); + + // monitor + MonitorConfig monitorConfig = context.getBean(MonitorConfig.class); + Assertions.assertEquals("zookeeper://127.0.0.1:32770", monitorConfig.getAddress()); + + // provider + ProviderConfig providerConfig = context.getBean(ProviderConfig.class); + Assertions.assertEquals("127.0.0.1", providerConfig.getHost()); + + + // consumer + ConsumerConfig consumerConfig = context.getBean(ConsumerConfig.class); + Assertions.assertEquals("netty", consumerConfig.getClient()); + + // asserts aliases + assertFalse(hasAlias(context, "org.apache.dubbo.config.RegistryConfig#0", "zookeeper")); + assertFalse(hasAlias(context, "org.apache.dubbo.config.MonitorConfig#0", "zookeeper")); + } + + //@Test + public void testMultiple() { + + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + context.register(TestMultipleConfig.class); + context.refresh(); + + RegistryConfig registry1 = context.getBean("registry1", RegistryConfig.class); + Assertions.assertEquals(2181, registry1.getPort()); + + RegistryConfig registry2 = context.getBean("registry2", RegistryConfig.class); + Assertions.assertEquals(2182, registry2.getPort()); + + ConfigManager configManager = ApplicationModel.defaultModel().getApplicationConfigManager(); + Collection protocolConfigs = configManager.getProtocols(); + Assertions.assertEquals(3, protocolConfigs.size()); + + configManager.getProtocol("dubbo").get(); + configManager.getProtocol("rest").get(); + configManager.getProtocol("thrift").get(); + + + // asserts aliases +// assertTrue(hasAlias(context, "applicationBean2", "dubbo-demo-application2")); +// assertTrue(hasAlias(context, "applicationBean3", "dubbo-demo-application3")); + + } + + @EnableDubboConfig + @PropertySource("META-INF/config.properties") + private static class TestMultipleConfig { + + } + + @EnableDubboConfig(multiple = false) + @PropertySource("META-INF/config.properties") + private static class TestConfig { + + } +} \ No newline at end of file diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboTest.java new file mode 100644 index 0000000000..729d5ec5f0 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboTest.java @@ -0,0 +1,150 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.config.spring.context.annotation; + +import org.apache.dubbo.config.RegistryConfig; +import org.apache.dubbo.config.bootstrap.DubboBootstrap; +import org.apache.dubbo.config.spring.api.DemoService; +import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationTestConfiguration; +import org.apache.dubbo.config.spring.context.annotation.consumer.test.TestConsumerConfiguration; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Import; +import org.springframework.context.annotation.Primary; +import org.springframework.context.annotation.PropertySource; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionException; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.annotation.EnableTransactionManagement; +/** + * {@link EnableDubbo} Test + * + * @since 2.5.8 + */ +class EnableDubboTest { + + private AnnotationConfigApplicationContext context; + + @BeforeEach + public void setUp() { + context = new AnnotationConfigApplicationContext(); + DubboBootstrap.reset(); + } + + @AfterEach + public void tearDown() { + context.close(); + DubboBootstrap.reset(); + } + + @Test + void testConsumer() { + + context.register(TestProviderConfiguration.class, TestConsumerConfiguration.class); + context.refresh(); + + TestConsumerConfiguration consumerConfiguration = context.getBean(TestConsumerConfiguration.class); + + DemoService demoService = consumerConfiguration.getDemoService(); + String value = demoService.sayName("Mercy"); + Assertions.assertEquals("Hello,Mercy", value); + + DemoService autowiredDemoService = consumerConfiguration.getAutowiredDemoService(); + Assertions.assertEquals("Hello,Mercy", autowiredDemoService.sayName("Mercy")); + + DemoService autowiredReferDemoService = consumerConfiguration.getAutowiredReferDemoService(); + Assertions.assertEquals("Hello,Mercy", autowiredReferDemoService.sayName("Mercy")); + + TestConsumerConfiguration.Child child = context.getBean(TestConsumerConfiguration.Child.class); + + // From Child + + demoService = child.getDemoServiceFromChild(); + + Assertions.assertNotNull(demoService); + + value = demoService.sayName("Mercy"); + + Assertions.assertEquals("Hello,Mercy", value); + + // From Parent + + demoService = child.getDemoServiceFromParent(); + + Assertions.assertNotNull(demoService); + + value = demoService.sayName("Mercy"); + + Assertions.assertEquals("Hello,Mercy", value); + + // From Ancestor + + demoService = child.getDemoServiceFromAncestor(); + + Assertions.assertNotNull(demoService); + + value = demoService.sayName("Mercy"); + + Assertions.assertEquals("Hello,Mercy", value); + + // Test my-registry2 bean presentation + RegistryConfig registryConfig = context.getBean("my-registry", RegistryConfig.class); + + // Test multiple binding + Assertions.assertEquals("N/A", registryConfig.getAddress()); + + } + + @EnableDubbo(scanBasePackages = "org.apache.dubbo.config.spring.context.annotation.provider") + @ComponentScan(basePackages = "org.apache.dubbo.config.spring.context.annotation.provider") + @PropertySource("classpath:/META-INF/dubbo-provider.properties") + @Import(ServiceAnnotationTestConfiguration.class) + @EnableTransactionManagement + public static class TestProviderConfiguration { + + @Primary + @Bean + public PlatformTransactionManager platformTransactionManager() { + return new PlatformTransactionManager() { + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException { + return null; + } + + @Override + public void commit(TransactionStatus status) throws TransactionException { + + } + + @Override + public void rollback(TransactionStatus status) throws TransactionException { + + } + }; + } + } + + +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/ConsumerConfiguration.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/ConsumerConfiguration.java new file mode 100644 index 0000000000..9fd7b2e1b7 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/ConsumerConfiguration.java @@ -0,0 +1,140 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.config.spring.context.annotation.consumer; + +import org.apache.dubbo.config.ApplicationConfig; +import org.apache.dubbo.config.RegistryConfig; +import org.apache.dubbo.config.annotation.Reference; +import org.apache.dubbo.config.spring.api.DemoService; +import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; + +@Configuration("consumerConfiguration") +@DubboComponentScan( + basePackageClasses = ConsumerConfiguration.class +) +@PropertySource("META-INF/default.properties") +public class ConsumerConfiguration { + + private static final String remoteURL = "dubbo://127.0.0.1:12345?version=2.5.7"; + + /** + * Current application configuration, to replace XML config: + * + * <dubbo:application name="dubbo-demo-application"/> + * + * + * @return {@link ApplicationConfig} Bean + */ + @Bean("dubbo-demo-application") + public ApplicationConfig applicationConfig() { + ApplicationConfig applicationConfig = new ApplicationConfig(); + applicationConfig.setName("dubbo-demo-application"); + return applicationConfig; + } + + /** + * Current registry center configuration, to replace XML config: + * + * <dubbo:registry address="N/A"/> + * + * + * @return {@link RegistryConfig} Bean + */ + @Bean + public RegistryConfig registryConfig() { + RegistryConfig registryConfig = new RegistryConfig(); + registryConfig.setAddress("N/A"); + return registryConfig; + } + + @Autowired + private DemoService demoServiceFromAncestor; + + @Reference(version = "2.5.7", url = remoteURL) + private DemoService demoService; + + public DemoService getDemoService() { + return demoService; + } + + public void setDemoService(DemoService demoService) { + this.demoService = demoService; + } + + + @Bean + public Child c() { + return new Child(); + } + + public static abstract class Ancestor { + + @Reference(version = "2.5.7", url = remoteURL) + private DemoService demoServiceFromAncestor; + + public DemoService getDemoServiceFromAncestor() { + return demoServiceFromAncestor; + } + + public void setDemoServiceFromAncestor(DemoService demoServiceFromAncestor) { + this.demoServiceFromAncestor = demoServiceFromAncestor; + } + } + + public static abstract class Parent extends Ancestor { + + private DemoService demoServiceFromParent; + + public DemoService getDemoServiceFromParent() { + return demoServiceFromParent; + } + + @Reference(version = "2.5.7", url = remoteURL) + public void setDemoServiceFromParent(DemoService demoServiceFromParent) { + this.demoServiceFromParent = demoServiceFromParent; + } + + } + + public static class Child extends Parent { + + @Autowired + private DemoService demoService; + + @Reference(version = "2.5.7", url = remoteURL) + private DemoService demoServiceFromChild; + + + public DemoService getDemoService() { + return demoService; + } + + public DemoService getDemoServiceFromChild() { + return demoServiceFromChild; + } + + public void setDemoServiceFromChild(DemoService demoServiceFromChild) { + this.demoServiceFromChild = demoServiceFromChild; + } + } + +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/test/TestConsumerConfiguration.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/test/TestConsumerConfiguration.java new file mode 100644 index 0000000000..5869d95e89 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/test/TestConsumerConfiguration.java @@ -0,0 +1,121 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.config.spring.context.annotation.consumer.test; + +import org.apache.dubbo.config.annotation.DubboReference; +import org.apache.dubbo.config.annotation.Reference; +import org.apache.dubbo.config.spring.api.DemoService; +import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.PropertySource; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +/** + * Test Consumer Configuration + * + * @since 2.5.7 + */ +@EnableDubbo(scanBasePackageClasses = TestConsumerConfiguration.class) +@PropertySource("classpath:/META-INF/dubbb-consumer.properties") +@EnableTransactionManagement +public class TestConsumerConfiguration { + + private static final String remoteURL = "dubbo://127.0.0.1:12345?version=2.5.7"; + + @Reference(id = "demoService", + version = "2.5.7", + url = remoteURL, + application = "dubbo-demo-application", + filter = "mymock") + private DemoService demoService; + + @Autowired + @Qualifier("demoServiceImpl") + private DemoService autowiredDemoService; + + @Autowired + @Qualifier("demoService") + private DemoService autowiredReferDemoService; + + public DemoService getAutowiredDemoService() { + return autowiredDemoService; + } + + public DemoService getAutowiredReferDemoService() { + return autowiredReferDemoService; + } + + public DemoService getDemoService() { + return demoService; + } + + public void setDemoService(DemoService demoService) { + this.demoService = demoService; + } + + + @Bean + public Child c() { + return new Child(); + } + + public static abstract class Ancestor { + + @DubboReference(version = "2.5.7", url = remoteURL,filter = "mymock", application = "dubbo-demo-application") + private DemoService demoServiceFromAncestor; + + public DemoService getDemoServiceFromAncestor() { + return demoServiceFromAncestor; + } + + public void setDemoServiceFromAncestor(DemoService demoServiceFromAncestor) { + this.demoServiceFromAncestor = demoServiceFromAncestor; + } + } + + public static abstract class Parent extends Ancestor { + + private DemoService demoServiceFromParent; + + public DemoService getDemoServiceFromParent() { + return demoServiceFromParent; + } + + @com.alibaba.dubbo.config.annotation.Reference(version = "2.5.7", url = remoteURL, filter = "mymock", application = "dubbo-demo-application") + public void setDemoServiceFromParent(DemoService demoServiceFromParent) { + this.demoServiceFromParent = demoServiceFromParent; + } + + } + + public static class Child extends Parent { + + @Reference(version = "2.5.7", url = remoteURL, filter = "mymock", application = "dubbo-demo-application") + private DemoService demoServiceFromChild; + + public DemoService getDemoServiceFromChild() { + return demoServiceFromChild; + } + + public void setDemoServiceFromChild(DemoService demoServiceFromChild) { + this.demoServiceFromChild = demoServiceFromChild; + } + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DefaultHelloService.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DefaultHelloService.java new file mode 100644 index 0000000000..c4df6f4340 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DefaultHelloService.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.config.spring.context.annotation.provider; + +import org.apache.dubbo.config.annotation.DubboService; +import org.apache.dubbo.config.spring.api.HelloService; + +import org.springframework.stereotype.Service; + +/** + * Default {@link HelloService} annotation with Spring's {@link Service} + * and Dubbo's {@link org.apache.dubbo.config.annotation.Service} + * + */ +@Service +@DubboService +public class DefaultHelloService implements HelloService { + + @Override + public String sayHello(String name) { + return "Greeting, " + name; + } + +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DemoServiceImpl.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DemoServiceImpl.java new file mode 100644 index 0000000000..8ee2a8a09f --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DemoServiceImpl.java @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.config.spring.context.annotation.provider; + +import org.apache.dubbo.config.annotation.Method; +import org.apache.dubbo.config.spring.api.Box; +import org.apache.dubbo.config.spring.api.DemoService; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + + +/** + * {@link DemoService} Service implementation + * + * @since 2.5.8 + */ +@org.apache.dubbo.config.annotation.Service( + version = "2.5.7", + application = "${demo.service.application}", + protocol = "${demo.service.protocol}", + registry = "${demo.service.registry}", + methods = @Method(timeout = 100,name = "sayName") +) +@Service +@Transactional +public class DemoServiceImpl implements DemoService { + + @Override + public String sayName(String name) { + return "Hello," + name; + } + + @Override + public Box getBox() { + throw new UnsupportedOperationException("For Purposes!"); + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/HelloServiceImpl.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/HelloServiceImpl.java new file mode 100644 index 0000000000..d21cdc23ce --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/HelloServiceImpl.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.config.spring.context.annotation.provider; + +import org.apache.dubbo.config.spring.api.HelloService; + +import com.alibaba.dubbo.config.annotation.Service; + +/** + * {@link HelloService} Implementation just annotating Dubbo's {@link Service} + * + * @since 2.5.9 + */ +@Service(interfaceName = "org.apache.dubbo.config.spring.api.HelloService", version = "2") +public class HelloServiceImpl implements HelloService { + + @Override + public String sayHello(String name) { + return "Hello, " + name; + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/ProviderConfiguration.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/ProviderConfiguration.java new file mode 100644 index 0000000000..59e0cb3d77 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/ProviderConfiguration.java @@ -0,0 +1,120 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.config.spring.context.annotation.provider; + +import org.apache.dubbo.config.ApplicationConfig; +import org.apache.dubbo.config.ProtocolConfig; +import org.apache.dubbo.config.RegistryConfig; +import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; +import org.springframework.context.annotation.PropertySource; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionException; +import org.springframework.transaction.annotation.EnableTransactionManagement; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; + +import java.util.UUID; + +@DubboComponentScan(basePackages = "org.apache.dubbo.config.spring.context.annotation.provider") +@PropertySource("classpath:/META-INF/default.properties") +@EnableTransactionManagement +public class ProviderConfiguration { + + /** + * Current application configuration, to replace XML config: + * + * <dubbo:application name="dubbo-demo-application"/> + * + * + * @return {@link ApplicationConfig} Bean + */ + @Bean("dubbo-demo-application") + public ApplicationConfig applicationConfig() { + ApplicationConfig applicationConfig = new ApplicationConfig(); + applicationConfig.setName("dubbo-demo-application"); + return applicationConfig; + } + + /** + * Current registry center configuration, to replace XML config: + * + * <dubbo:registry id="my-registry" address="N/A"/> + * + * + * @return {@link RegistryConfig} Bean + */ + @Bean("my-registry") + public RegistryConfig registryConfig() { + RegistryConfig registryConfig = new RegistryConfig(); + registryConfig.setAddress("N/A"); + return registryConfig; + } + + /** + * Current protocol configuration, to replace XML config: + * + * <dubbo:protocol name="dubbo" port="12345"/> + * + * + * @return {@link ProtocolConfig} Bean + */ + @Bean("dubbo") + public ProtocolConfig protocolConfig() { + ProtocolConfig protocolConfig = new ProtocolConfig(); + protocolConfig.setName("dubbo"); + protocolConfig.setPort(12345); + return protocolConfig; + } + + @Primary + @Bean + public PlatformTransactionManager platformTransactionManager() { + return new AbstractPlatformTransactionManager() { + private Logger logger = LoggerFactory.getLogger("TestPlatformTransactionManager"); + + @Override + protected Object doGetTransaction() throws TransactionException { + String transaction = "transaction_" + UUID.randomUUID().toString(); + logger.info("Create transaction: " + transaction); + return transaction; + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException { + logger.info("Begin transaction: " + transaction); + } + + @Override + protected void doCommit(DefaultTransactionStatus status) throws TransactionException { + logger.info("Commit transaction: " + status.getTransaction()); + } + + @Override + protected void doRollback(DefaultTransactionStatus status) throws TransactionException { + logger.info("Rollback transaction: " + status.getTransaction()); + } + }; + } + +} + diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/filter/MockDao.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/filter/MockDao.java new file mode 100644 index 0000000000..9006995903 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/filter/MockDao.java @@ -0,0 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.config.spring.filter; + +/** + * MockDao + */ +public interface MockDao { + +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/filter/MockDaoImpl.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/filter/MockDaoImpl.java new file mode 100644 index 0000000000..d8f6f9cd75 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/filter/MockDaoImpl.java @@ -0,0 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.config.spring.filter; + +/** + * MockDaoImpl + */ +public class MockDaoImpl implements MockDao { + +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/filter/MockFilter.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/filter/MockFilter.java new file mode 100644 index 0000000000..e41d734c60 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/filter/MockFilter.java @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.config.spring.filter; + +import org.apache.dubbo.rpc.Filter; +import org.apache.dubbo.rpc.Invocation; +import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.Protocol; +import org.apache.dubbo.rpc.Result; +import org.apache.dubbo.rpc.RpcException; +import org.apache.dubbo.rpc.cluster.LoadBalance; + +/** + * MockFilter + */ +public class MockFilter implements Filter { + + private LoadBalance loadBalance; + + private Protocol protocol; + + private MockDao mockDao; + + public MockDao getMockDao() { + return mockDao; + } + + public void setMockDao(MockDao mockDao) { + this.mockDao = mockDao; + } + + public LoadBalance getLoadBalance() { + return loadBalance; + } + + public void setLoadBalance(LoadBalance loadBalance) { + this.loadBalance = loadBalance; + } + + public Protocol getProtocol() { + return protocol; + } + + public void setProtocol(Protocol protocol) { + this.protocol = protocol; + } + + public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { + return invoker.invoke(invocation); + } + +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/generic/GenericServiceTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/generic/GenericServiceTest.java index a2848f9565..3ec36e00f4 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/generic/GenericServiceTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/generic/GenericServiceTest.java @@ -19,6 +19,7 @@ package org.apache.dubbo.generic; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.compact.Dubbo2CompactUtils; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.config.bootstrap.DubboBootstrap; @@ -109,12 +110,13 @@ class GenericServiceTest { Exporter exporter = protocol.export(proxyFactory.getInvoker(server, DemoService.class, url)); // simulate normal invoke - ReferenceConfig oldReferenceConfig = new ReferenceConfig<>(); + ReferenceConfig oldReferenceConfig = new ReferenceConfig<>(); oldReferenceConfig.setGeneric(true); oldReferenceConfig.setInterface(DemoService.class.getName()); oldReferenceConfig.refresh(); Invoker invoker = protocol.refer(oldReferenceConfig.getInterfaceClass(), url); - com.alibaba.dubbo.rpc.service.GenericService client = (com.alibaba.dubbo.rpc.service.GenericService) proxyFactory.getProxy(invoker, true); + GenericService client = (GenericService) proxyFactory.getProxy(invoker, true); + Assertions.assertInstanceOf(Dubbo2CompactUtils.getGenericServiceClass(), client); Object result = client.$invoke("sayHello", new String[]{"java.lang.String"}, new Object[]{"haha"}); Assertions.assertEquals("hello haha", result); diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/AbstractAnnotationProcessingTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/AbstractAnnotationProcessingTest.java new file mode 100644 index 0000000000..abe91275d4 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/AbstractAnnotationProcessingTest.java @@ -0,0 +1,65 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.metadata.annotation.processing; + +import org.apache.dubbo.metadata.annotation.processing.util.TypeUtils; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; + +import javax.annotation.processing.ProcessingEnvironment; +import javax.lang.model.element.TypeElement; +import javax.lang.model.util.Elements; +import javax.lang.model.util.Types; +import java.lang.annotation.Annotation; +import java.util.Set; + +/** + * Abstract {@link Annotation} Processing Test case + * + * @since 2.7.6 + */ +@ExtendWith(CompilerInvocationInterceptor.class) +public abstract class AbstractAnnotationProcessingTest { + + static ThreadLocal testInstanceHolder = new ThreadLocal<>(); + + protected ProcessingEnvironment processingEnv; + + protected Elements elements; + + protected Types types; + + @BeforeEach + public final void init() { + testInstanceHolder.set(this); + } + + @AfterEach + public final void destroy() { + testInstanceHolder.remove(); + } + + protected abstract void addCompiledClasses(Set> classesToBeCompiled); + + protected abstract void beforeEach(); + + protected TypeElement getType(Class type) { + return TypeUtils.getType(processingEnv, type); + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/AnnotationProcessingTestProcessor.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/AnnotationProcessingTestProcessor.java new file mode 100644 index 0000000000..a02432711b --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/AnnotationProcessingTestProcessor.java @@ -0,0 +1,76 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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; + +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.InvocationInterceptor; +import org.junit.jupiter.api.extension.ReflectiveInvocationContext; + +import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.RoundEnvironment; +import javax.annotation.processing.SupportedAnnotationTypes; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.TypeElement; +import java.lang.reflect.Method; +import java.util.Set; + +import static javax.lang.model.SourceVersion.latestSupported; + +@SupportedAnnotationTypes("*") +public class AnnotationProcessingTestProcessor extends AbstractProcessor { + + private final AbstractAnnotationProcessingTest abstractAnnotationProcessingTest; + private final InvocationInterceptor.Invocation invocation; + + private final ReflectiveInvocationContext invocationContext; + + private final ExtensionContext extensionContext; + + public AnnotationProcessingTestProcessor(AbstractAnnotationProcessingTest abstractAnnotationProcessingTest, InvocationInterceptor.Invocation invocation, + ReflectiveInvocationContext invocationContext, + ExtensionContext extensionContext) { + this.abstractAnnotationProcessingTest = abstractAnnotationProcessingTest; + this.invocation = invocation; + this.invocationContext = invocationContext; + this.extensionContext = extensionContext; + } + + @Override + public boolean process(Set annotations, RoundEnvironment roundEnv) { + if (!roundEnv.processingOver()) { + prepare(); + abstractAnnotationProcessingTest.beforeEach(); + try { + invocation.proceed(); + } catch (Throwable throwable) { + throw new RuntimeException(throwable); + } + } + return false; + } + + private void prepare() { + abstractAnnotationProcessingTest.processingEnv = super.processingEnv; + abstractAnnotationProcessingTest.elements = super.processingEnv.getElementUtils(); + abstractAnnotationProcessingTest.types = super.processingEnv.getTypeUtils(); + } + + @Override + public SourceVersion getSupportedSourceVersion() { + return latestSupported(); + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/CompilerInvocationInterceptor.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/CompilerInvocationInterceptor.java new file mode 100644 index 0000000000..fe97b4b4b8 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/CompilerInvocationInterceptor.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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; + +import org.apache.dubbo.metadata.tools.Compiler; + +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.InvocationInterceptor; +import org.junit.jupiter.api.extension.ReflectiveInvocationContext; + +import java.lang.reflect.Method; +import java.util.LinkedHashSet; +import java.util.Set; + +import static org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest.testInstanceHolder; + +public class CompilerInvocationInterceptor implements InvocationInterceptor { + + @Override + public void interceptTestMethod(Invocation invocation, + ReflectiveInvocationContext invocationContext, + ExtensionContext extensionContext) throws Throwable { + Set> classesToBeCompiled = new LinkedHashSet<>(); + AbstractAnnotationProcessingTest abstractAnnotationProcessingTest = testInstanceHolder.get(); + classesToBeCompiled.add(getClass()); + abstractAnnotationProcessingTest.addCompiledClasses(classesToBeCompiled); + Compiler compiler = new Compiler(); + compiler.processors(new AnnotationProcessingTestProcessor(abstractAnnotationProcessingTest, invocation, invocationContext, extensionContext)); + compiler.compile(classesToBeCompiled.toArray(new Class[0])); + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ArrayTypeDefinitionBuilderTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ArrayTypeDefinitionBuilderTest.java new file mode 100644 index 0000000000..cd84396e6d --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ArrayTypeDefinitionBuilderTest.java @@ -0,0 +1,125 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.metadata.annotation.processing.builder; + +import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; +import org.apache.dubbo.metadata.annotation.processing.model.ArrayTypeModel; +import org.apache.dubbo.metadata.definition.model.TypeDefinition; + +import org.junit.jupiter.api.Test; + +import javax.annotation.processing.ProcessingEnvironment; +import javax.lang.model.element.ElementKind; +import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.function.BiConsumer; +import java.util.stream.Stream; + +import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * {@link ArrayTypeDefinitionBuilder} Test + * + * @since 2.7.6 + */ +class ArrayTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { + + private ArrayTypeDefinitionBuilder builder; + + private TypeElement testType; + + private VariableElement integersField; + + private VariableElement stringsField; + + private VariableElement primitiveTypeModelsField; + + private VariableElement modelsField; + + private VariableElement colorsField; + + @Override + protected void addCompiledClasses(Set> classesToBeCompiled) { + classesToBeCompiled.add(ArrayTypeModel.class); + } + + @Override + protected void beforeEach() { + builder = new ArrayTypeDefinitionBuilder(); + testType = getType(ArrayTypeModel.class); + integersField = findField(testType, "integers"); + stringsField = findField(testType, "strings"); + primitiveTypeModelsField = findField(testType, "primitiveTypeModels"); + modelsField = findField(testType, "models"); + colorsField = findField(testType, "colors"); + } + + @Test + void testAccept() { + assertTrue(builder.accept(processingEnv, integersField.asType())); + assertTrue(builder.accept(processingEnv, stringsField.asType())); + assertTrue(builder.accept(processingEnv, primitiveTypeModelsField.asType())); + assertTrue(builder.accept(processingEnv, modelsField.asType())); + assertTrue(builder.accept(processingEnv, colorsField.asType())); + } + + @Test + void testBuild() { + + buildAndAssertTypeDefinition(processingEnv, integersField, "int[]", "int", builder); + + buildAndAssertTypeDefinition(processingEnv, stringsField, "java.lang.String[]", "java.lang.String", builder); + + buildAndAssertTypeDefinition(processingEnv, primitiveTypeModelsField, + "org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel[]", + "org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel", builder); + + buildAndAssertTypeDefinition(processingEnv, modelsField, + "org.apache.dubbo.metadata.annotation.processing.model.Model[]", + "org.apache.dubbo.metadata.annotation.processing.model.Model", builder, (def, subDef) -> { + TypeElement subType = elements.getTypeElement(subDef.getType()); + assertEquals(ElementKind.CLASS, subType.getKind()); + }); + + buildAndAssertTypeDefinition(processingEnv, colorsField, + "org.apache.dubbo.metadata.annotation.processing.model.Color[]", + "org.apache.dubbo.metadata.annotation.processing.model.Color", builder, (def, subDef) -> { + TypeElement subType = elements.getTypeElement(subDef.getType()); + assertEquals(ElementKind.ENUM, subType.getKind()); + }); + + } + + static void buildAndAssertTypeDefinition(ProcessingEnvironment processingEnv, VariableElement field, + String expectedType, String compositeType, TypeBuilder builder, + BiConsumer... assertions) { + Map typeCache = new HashMap<>(); + TypeDefinition typeDefinition = TypeDefinitionBuilder.build(processingEnv, field, typeCache); + String subTypeName = typeDefinition.getItems().get(0); + TypeDefinition subTypeDefinition = typeCache.get(subTypeName); + assertEquals(expectedType, typeDefinition.getType()); +// assertEquals(field.getSimpleName().toString(), typeDefinition.get$ref()); + assertEquals(compositeType, subTypeDefinition.getType()); +// assertEquals(builder.getClass().getName(), typeDefinition.getTypeBuilderName()); + Stream.of(assertions).forEach(assertion -> assertion.accept(typeDefinition, subTypeDefinition)); + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/CollectionTypeDefinitionBuilderTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/CollectionTypeDefinitionBuilderTest.java new file mode 100644 index 0000000000..e99d417784 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/CollectionTypeDefinitionBuilderTest.java @@ -0,0 +1,105 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.metadata.annotation.processing.builder; + +import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; +import org.apache.dubbo.metadata.annotation.processing.model.CollectionTypeModel; + +import org.junit.jupiter.api.Test; + +import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; +import java.util.Set; + +import static org.apache.dubbo.metadata.annotation.processing.builder.ArrayTypeDefinitionBuilderTest.buildAndAssertTypeDefinition; +import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * {@link CollectionTypeDefinitionBuilder} Test + * + * @since 2.7.6 + */ +class CollectionTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { + + private CollectionTypeDefinitionBuilder builder; + + private VariableElement stringsField; + + private VariableElement colorsField; + + private VariableElement primitiveTypeModelsField; + + private VariableElement modelsField; + + private VariableElement modelArraysField; + + @Override + protected void addCompiledClasses(Set> classesToBeCompiled) { + classesToBeCompiled.add(CollectionTypeModel.class); + } + + @Override + protected void beforeEach() { + builder = new CollectionTypeDefinitionBuilder(); + TypeElement testType = getType(CollectionTypeModel.class); + stringsField = findField( testType, "strings"); + colorsField = findField( testType, "colors"); + primitiveTypeModelsField = findField( testType, "primitiveTypeModels"); + modelsField = findField( testType, "models"); + modelArraysField = findField( testType, "modelArrays"); + + assertEquals("strings", stringsField.getSimpleName().toString()); + assertEquals("colors", colorsField.getSimpleName().toString()); + assertEquals("primitiveTypeModels", primitiveTypeModelsField.getSimpleName().toString()); + assertEquals("models", modelsField.getSimpleName().toString()); + assertEquals("modelArrays", modelArraysField.getSimpleName().toString()); + } + + @Test + void testAccept() { + assertTrue(builder.accept(processingEnv, stringsField.asType())); + assertTrue(builder.accept(processingEnv, colorsField.asType())); + assertTrue(builder.accept(processingEnv, primitiveTypeModelsField.asType())); + assertTrue(builder.accept(processingEnv, modelsField.asType())); + assertTrue(builder.accept(processingEnv, modelArraysField.asType())); + } + + @Test + void testBuild() { + + buildAndAssertTypeDefinition(processingEnv, stringsField, "java.util.Collection", "java.lang.String", builder); + + buildAndAssertTypeDefinition(processingEnv, colorsField, "java.util.List", + "org.apache.dubbo.metadata.annotation.processing.model.Color", builder); + + buildAndAssertTypeDefinition(processingEnv, primitiveTypeModelsField, + "java.util.Queue", + "org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel", builder); + + buildAndAssertTypeDefinition(processingEnv, modelsField, + "java.util.Deque", + "org.apache.dubbo.metadata.annotation.processing.model.Model", builder); + + buildAndAssertTypeDefinition(processingEnv, modelArraysField, + "java.util.Set", + "org.apache.dubbo.metadata.annotation.processing.model.Model[]", builder); + + + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/EnumTypeDefinitionBuilderTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/EnumTypeDefinitionBuilderTest.java new file mode 100644 index 0000000000..49572e708e --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/EnumTypeDefinitionBuilderTest.java @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.metadata.annotation.processing.builder; + +import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; +import org.apache.dubbo.metadata.annotation.processing.model.Color; +import org.apache.dubbo.metadata.definition.model.TypeDefinition; + +import org.junit.jupiter.api.Test; + +import javax.lang.model.element.TypeElement; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import static java.util.Arrays.asList; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * {@link EnumTypeDefinitionBuilder} Test + * + * @since 2.7.6 + */ +class EnumTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { + + private EnumTypeDefinitionBuilder builder; + + @Override + protected void addCompiledClasses(Set> classesToBeCompiled) { + classesToBeCompiled.add(Color.class); + } + + @Override + protected void beforeEach() { + builder = new EnumTypeDefinitionBuilder(); + } + + @Test + void testAccept() { + TypeElement typeElement = getType(Color.class); + assertTrue(builder.accept(processingEnv, typeElement.asType())); + } + + @Test + void testBuild() { + TypeElement typeElement = getType(Color.class); + Map typeCache = new HashMap<>(); + TypeDefinition typeDefinition = TypeDefinitionBuilder.build(processingEnv, typeElement, typeCache); + assertEquals(Color.class.getName(), typeDefinition.getType()); + assertEquals(asList("RED", "YELLOW", "BLUE"), typeDefinition.getEnums()); +// assertEquals(typeDefinition.getTypeBuilderName(), builder.getClass().getName()); + } + +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/GeneralTypeDefinitionBuilderTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/GeneralTypeDefinitionBuilderTest.java new file mode 100644 index 0000000000..8ca703aa32 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/GeneralTypeDefinitionBuilderTest.java @@ -0,0 +1,67 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.builder; + +import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; +import org.apache.dubbo.metadata.annotation.processing.model.ArrayTypeModel; +import org.apache.dubbo.metadata.annotation.processing.model.CollectionTypeModel; +import org.apache.dubbo.metadata.annotation.processing.model.Color; +import org.apache.dubbo.metadata.annotation.processing.model.Model; +import org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel; +import org.apache.dubbo.metadata.annotation.processing.model.SimpleTypeModel; + +import org.junit.jupiter.api.Test; + +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * {@link GeneralTypeDefinitionBuilder} Test + * + * @since 2.7.6 + */ +class GeneralTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { + + private GeneralTypeDefinitionBuilder builder; + + @Override + protected void addCompiledClasses(Set> classesToBeCompiled) { + classesToBeCompiled.add(Model.class); + } + + @Override + protected void beforeEach() { + builder = new GeneralTypeDefinitionBuilder(); + } + + @Test + void testAccept() { + assertTrue(builder.accept(processingEnv, getType(Model.class).asType())); + assertTrue(builder.accept(processingEnv, getType(PrimitiveTypeModel.class).asType())); + assertTrue(builder.accept(processingEnv, getType(SimpleTypeModel.class).asType())); + assertTrue(builder.accept(processingEnv, getType(ArrayTypeModel.class).asType())); + assertTrue(builder.accept(processingEnv, getType(CollectionTypeModel.class).asType())); + assertFalse(builder.accept(processingEnv, getType(Color.class).asType())); + } + + @Test + void testBuild() { + + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/MapTypeDefinitionBuilderTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/MapTypeDefinitionBuilderTest.java new file mode 100644 index 0000000000..4f48684606 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/MapTypeDefinitionBuilderTest.java @@ -0,0 +1,139 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.builder; + +import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; +import org.apache.dubbo.metadata.annotation.processing.model.MapTypeModel; +import org.apache.dubbo.metadata.definition.model.TypeDefinition; + +import org.junit.jupiter.api.Test; + +import javax.annotation.processing.ProcessingEnvironment; +import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.function.BiConsumer; +import java.util.stream.Stream; + +import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * {@link MapTypeDefinitionBuilder} Test + * + * @since 2.7.6 + */ +class MapTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { + + private MapTypeDefinitionBuilder builder; + + private VariableElement stringsField; + + private VariableElement colorsField; + + private VariableElement primitiveTypeModelsField; + + private VariableElement modelsField; + + private VariableElement modelArraysField; + + @Override + protected void addCompiledClasses(Set> classesToBeCompiled) { + classesToBeCompiled.add(MapTypeModel.class); + } + + @Override + protected void beforeEach() { + builder = new MapTypeDefinitionBuilder(); + TypeElement testType = getType(MapTypeModel.class); + stringsField = findField(testType, "strings"); + colorsField = findField(testType, "colors"); + primitiveTypeModelsField = findField(testType, "primitiveTypeModels"); + modelsField = findField(testType, "models"); + modelArraysField = findField(testType, "modelArrays"); + + assertEquals("strings", stringsField.getSimpleName().toString()); + assertEquals("colors", colorsField.getSimpleName().toString()); + assertEquals("primitiveTypeModels", primitiveTypeModelsField.getSimpleName().toString()); + assertEquals("models", modelsField.getSimpleName().toString()); + assertEquals("modelArrays", modelArraysField.getSimpleName().toString()); + } + + @Test + void testAccept() { + assertTrue(builder.accept(processingEnv, stringsField.asType())); + assertTrue(builder.accept(processingEnv, colorsField.asType())); + assertTrue(builder.accept(processingEnv, primitiveTypeModelsField.asType())); + assertTrue(builder.accept(processingEnv, modelsField.asType())); + assertTrue(builder.accept(processingEnv, modelArraysField.asType())); + } + + @Test + void testBuild() { + + buildAndAssertTypeDefinition(processingEnv, stringsField, + "java.util.Map", + "java.lang.String", + "java.lang.String", + builder); + + buildAndAssertTypeDefinition(processingEnv, colorsField, + "java.util.SortedMap", + "java.lang.String", + "org.apache.dubbo.metadata.annotation.processing.model.Color", + builder); + + buildAndAssertTypeDefinition(processingEnv, primitiveTypeModelsField, + "java.util.NavigableMap", + "org.apache.dubbo.metadata.annotation.processing.model.Color", + "org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel", + builder); + + buildAndAssertTypeDefinition(processingEnv, modelsField, + "java.util.HashMap", + "java.lang.String", + "org.apache.dubbo.metadata.annotation.processing.model.Model", + builder); + + buildAndAssertTypeDefinition(processingEnv, modelArraysField, + "java.util.TreeMap", + "org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel", + "org.apache.dubbo.metadata.annotation.processing.model.Model[]", + builder); + } + + static void buildAndAssertTypeDefinition(ProcessingEnvironment processingEnv, VariableElement field, + String expectedType, String keyType, String valueType, + TypeBuilder builder, + BiConsumer... assertions) { + Map typeCache = new HashMap<>(); + TypeDefinition typeDefinition = TypeDefinitionBuilder.build(processingEnv, field, typeCache); + String keyTypeName = typeDefinition.getItems().get(0); + TypeDefinition keyTypeDefinition = typeCache.get(keyTypeName); + String valueTypeName = typeDefinition.getItems().get(1); + TypeDefinition valueTypeDefinition = typeCache.get(valueTypeName); + assertEquals(expectedType, typeDefinition.getType()); +// assertEquals(field.getSimpleName().toString(), typeDefinition.get$ref()); + assertEquals(keyType, keyTypeDefinition.getType()); + assertEquals(valueType, valueTypeDefinition.getType()); +// assertEquals(builder.getClass().getName(), typeDefinition.getTypeBuilderName()); + Stream.of(assertions).forEach(assertion -> assertion.accept(typeDefinition, keyTypeDefinition)); + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/PrimitiveTypeDefinitionBuilderTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/PrimitiveTypeDefinitionBuilderTest.java new file mode 100644 index 0000000000..3c9774cf6c --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/PrimitiveTypeDefinitionBuilderTest.java @@ -0,0 +1,131 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.builder; + +import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; +import org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel; +import org.apache.dubbo.metadata.definition.model.TypeDefinition; + +import org.junit.jupiter.api.Test; + +import javax.annotation.processing.ProcessingEnvironment; +import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * {@link PrimitiveTypeDefinitionBuilder} Test + * + * @since 2.7.6 + */ +class PrimitiveTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { + + private PrimitiveTypeDefinitionBuilder builder; + + private VariableElement zField; + + private VariableElement bField; + + private VariableElement cField; + + private VariableElement sField; + + private VariableElement iField; + + private VariableElement lField; + + private VariableElement fField; + + private VariableElement dField; + + @Override + protected void addCompiledClasses(Set> classesToBeCompiled) { + classesToBeCompiled.add(PrimitiveTypeModel.class); + } + + @Override + protected void beforeEach() { + + builder = new PrimitiveTypeDefinitionBuilder(); + + TypeElement testType = getType(PrimitiveTypeModel.class); + + zField = findField( testType, "z"); + bField = findField( testType, "b"); + cField = findField( testType, "c"); + sField = findField( testType, "s"); + iField = findField( testType, "i"); + lField = findField( testType, "l"); + fField = findField( testType, "f"); + dField = findField( testType, "d"); + + assertEquals("boolean", zField.asType().toString()); + assertEquals("byte", bField.asType().toString()); + assertEquals("char", cField.asType().toString()); + assertEquals("short", sField.asType().toString()); + assertEquals("int", iField.asType().toString()); + assertEquals("long", lField.asType().toString()); + assertEquals("float", fField.asType().toString()); + assertEquals("double", dField.asType().toString()); + } + + @Test + void testAccept() { + assertTrue(builder.accept(processingEnv, zField.asType())); + assertTrue(builder.accept(processingEnv, bField.asType())); + assertTrue(builder.accept(processingEnv, cField.asType())); + assertTrue(builder.accept(processingEnv, sField.asType())); + assertTrue(builder.accept(processingEnv, iField.asType())); + assertTrue(builder.accept(processingEnv, lField.asType())); + assertTrue(builder.accept(processingEnv, fField.asType())); + assertTrue(builder.accept(processingEnv, dField.asType())); + } + + @Test + void testBuild() { + buildAndAssertTypeDefinition(processingEnv, zField, builder); + buildAndAssertTypeDefinition(processingEnv, bField, builder); + buildAndAssertTypeDefinition(processingEnv, cField, builder); + buildAndAssertTypeDefinition(processingEnv, sField, builder); + buildAndAssertTypeDefinition(processingEnv, iField, builder); + buildAndAssertTypeDefinition(processingEnv, lField, builder); + buildAndAssertTypeDefinition(processingEnv, zField, builder); + buildAndAssertTypeDefinition(processingEnv, fField, builder); + buildAndAssertTypeDefinition(processingEnv, dField, builder); + } + + static void buildAndAssertTypeDefinition(ProcessingEnvironment processingEnv, VariableElement field, TypeBuilder builder) { + Map typeCache = new HashMap<>(); + TypeDefinition typeDefinition = TypeDefinitionBuilder.build(processingEnv, field, typeCache); + assertBasicTypeDefinition(typeDefinition, field.asType().toString(), builder); +// assertEquals(field.getSimpleName().toString(), typeDefinition.get$ref()); + } + + static void assertBasicTypeDefinition(TypeDefinition typeDefinition, String type, TypeBuilder builder) { + assertEquals(type, typeDefinition.getType()); +// assertEquals(builder.getClass().getName(), typeDefinition.getTypeBuilderName()); + assertTrue(typeDefinition.getProperties().isEmpty()); + assertTrue(typeDefinition.getItems().isEmpty()); + assertTrue(typeDefinition.getEnums().isEmpty()); + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ServiceDefinitionBuilderTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ServiceDefinitionBuilderTest.java new file mode 100644 index 0000000000..9906f12975 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ServiceDefinitionBuilderTest.java @@ -0,0 +1,83 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.builder; + +import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; +import org.apache.dubbo.metadata.definition.model.ServiceDefinition; +import org.apache.dubbo.metadata.definition.model.TypeDefinition; +import org.apache.dubbo.metadata.tools.TestServiceImpl; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.Set; + +import static org.apache.dubbo.metadata.annotation.processing.builder.ServiceDefinitionBuilder.build; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * {@link ServiceDefinitionBuilder} Test + * + * @since 2.7.6 + */ +class ServiceDefinitionBuilderTest extends AbstractAnnotationProcessingTest { + + + @Override + protected void addCompiledClasses(Set> classesToBeCompiled) { + classesToBeCompiled.add(TestServiceImpl.class); + } + + @Override + protected void beforeEach() { + } + + @Test + void testBuild() { + ServiceDefinition serviceDefinition = build(processingEnv, getType(TestServiceImpl.class)); + assertEquals(TestServiceImpl.class.getTypeName(), serviceDefinition.getCanonicalName()); + assertEquals("org/apache/dubbo/metadata/tools/TestServiceImpl.class", serviceDefinition.getCodeSource()); + + // types + List typeNames = Arrays.asList( + "org.apache.dubbo.metadata.tools.TestServiceImpl", + "org.apache.dubbo.metadata.tools.GenericTestService", + "org.apache.dubbo.metadata.tools.DefaultTestService", + "org.apache.dubbo.metadata.tools.TestService", + "java.lang.AutoCloseable", + "java.io.Serializable", + "java.util.EventListener" + ); + for (String typeName : typeNames) { + String gotTypeName = getTypeName(typeName, serviceDefinition.getTypes()); + assertEquals(typeName, gotTypeName); + } + + // methods + assertEquals(14, serviceDefinition.getMethods().size()); + } + + private static String getTypeName(String type, List types) { + for (TypeDefinition typeDefinition : types) { + if (type.equals(typeDefinition.getType())) { + return typeDefinition.getType(); + } + } + return type; + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/SimpleTypeDefinitionBuilderTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/SimpleTypeDefinitionBuilderTest.java new file mode 100644 index 0000000000..08f008d394 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/SimpleTypeDefinitionBuilderTest.java @@ -0,0 +1,146 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.metadata.annotation.processing.builder; + +import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; +import org.apache.dubbo.metadata.annotation.processing.model.SimpleTypeModel; + +import org.junit.jupiter.api.Test; + +import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; +import java.util.Set; + +import static org.apache.dubbo.metadata.annotation.processing.builder.PrimitiveTypeDefinitionBuilderTest.buildAndAssertTypeDefinition; +import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; +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 SimpleTypeDefinitionBuilder} Test + * + * @since 2.7.6 + */ +class SimpleTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { + + private SimpleTypeDefinitionBuilder builder; + + private VariableElement vField; + + private VariableElement zField; + + private VariableElement cField; + + private VariableElement bField; + + private VariableElement sField; + + private VariableElement iField; + + private VariableElement lField; + + private VariableElement fField; + + private VariableElement dField; + + private VariableElement strField; + + private VariableElement bdField; + + private VariableElement biField; + + private VariableElement dtField; + + private VariableElement invalidField; + + + @Override + protected void addCompiledClasses(Set> classesToBeCompiled) { + classesToBeCompiled.add(SimpleTypeModel.class); + } + + @Override + protected void beforeEach() { + builder = new SimpleTypeDefinitionBuilder(); + TypeElement testType = getType(SimpleTypeModel.class); + vField = findField(testType, "v"); + zField = findField(testType, "z"); + cField = findField(testType, "c"); + bField = findField(testType, "b"); + sField = findField(testType, "s"); + iField = findField(testType, "i"); + lField = findField(testType, "l"); + fField = findField(testType, "f"); + dField = findField(testType, "d"); + strField = findField(testType, "str"); + bdField = findField(testType, "bd"); + biField = findField(testType, "bi"); + dtField = findField(testType, "dt"); + invalidField = findField(testType, "invalid"); + + assertEquals("java.lang.Void", vField.asType().toString()); + assertEquals("java.lang.Boolean", zField.asType().toString()); + assertEquals("java.lang.Character", cField.asType().toString()); + assertEquals("java.lang.Byte", bField.asType().toString()); + assertEquals("java.lang.Short", sField.asType().toString()); + assertEquals("java.lang.Integer", iField.asType().toString()); + assertEquals("java.lang.Long", lField.asType().toString()); + assertEquals("java.lang.Float", fField.asType().toString()); + assertEquals("java.lang.Double", dField.asType().toString()); + assertEquals("java.lang.String", strField.asType().toString()); + assertEquals("java.math.BigDecimal", bdField.asType().toString()); + assertEquals("java.math.BigInteger", biField.asType().toString()); + assertEquals("java.util.Date", dtField.asType().toString()); + assertEquals("int", invalidField.asType().toString()); + } + + @Test + void testAccept() { + assertTrue(builder.accept(processingEnv, vField.asType())); + assertTrue(builder.accept(processingEnv, zField.asType())); + assertTrue(builder.accept(processingEnv, cField.asType())); + assertTrue(builder.accept(processingEnv, bField.asType())); + assertTrue(builder.accept(processingEnv, sField.asType())); + assertTrue(builder.accept(processingEnv, iField.asType())); + assertTrue(builder.accept(processingEnv, lField.asType())); + assertTrue(builder.accept(processingEnv, fField.asType())); + assertTrue(builder.accept(processingEnv, dField.asType())); + assertTrue(builder.accept(processingEnv, strField.asType())); + assertTrue(builder.accept(processingEnv, bdField.asType())); + assertTrue(builder.accept(processingEnv, biField.asType())); + assertTrue(builder.accept(processingEnv, dtField.asType())); + // false condition + assertFalse(builder.accept(processingEnv, invalidField.asType())); + } + + @Test + void testBuild() { + buildAndAssertTypeDefinition(processingEnv, vField, builder); + buildAndAssertTypeDefinition(processingEnv, zField, builder); + buildAndAssertTypeDefinition(processingEnv, cField, builder); + buildAndAssertTypeDefinition(processingEnv, sField, builder); + buildAndAssertTypeDefinition(processingEnv, iField, builder); + buildAndAssertTypeDefinition(processingEnv, lField, builder); + buildAndAssertTypeDefinition(processingEnv, fField, builder); + buildAndAssertTypeDefinition(processingEnv, dField, builder); + buildAndAssertTypeDefinition(processingEnv, strField, builder); + buildAndAssertTypeDefinition(processingEnv, bdField, builder); + buildAndAssertTypeDefinition(processingEnv, biField, builder); + buildAndAssertTypeDefinition(processingEnv, dtField, builder); + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/ArrayTypeModel.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/ArrayTypeModel.java new file mode 100644 index 0000000000..28bf4f3111 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/ArrayTypeModel.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.metadata.annotation.processing.model; + +/** + * Array Type Model + * + * @since 2.7.6 + */ +public class ArrayTypeModel { + + private int[] integers; // Primitive type array + + private String[] strings; // Simple type array + + private PrimitiveTypeModel[] primitiveTypeModels; // Complex type array + + private Model[] models; // Hierarchical Complex type array + + private Color[] colors; // Enum type array + +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/CollectionTypeModel.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/CollectionTypeModel.java new file mode 100644 index 0000000000..e90f1c8926 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/CollectionTypeModel.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.metadata.annotation.processing.model; + +import java.util.Collection; +import java.util.Deque; +import java.util.List; +import java.util.Queue; +import java.util.Set; + +/** + * {@link Collection} Type Model + * + * @since 2.7.6 + */ +public class CollectionTypeModel { + + private Collection strings; // The composite element is simple type + + private List colors; // The composite element is Enum type + + private Queue primitiveTypeModels; // The composite element is POJO type + + private Deque models; // The composite element is hierarchical POJO type + + private Set modelArrays; // The composite element is hierarchical POJO type + +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/Color.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/Color.java new file mode 100644 index 0000000000..9fab9df62d --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/Color.java @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.metadata.annotation.processing.model; + +/** + * Color enumeration + * + * @since 2.7.6 + */ +public enum Color { + + RED(1), + YELLOW(2), + BLUE(3); + + private final int value; + + Color(int value) { + this.value = value; + } + + @Override + public String toString() { + return "Color{" + + "value=" + value + + "} " + super.toString(); + } + + public int getValue() { + return value; + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/MapTypeModel.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/MapTypeModel.java new file mode 100644 index 0000000000..087aa932ed --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/MapTypeModel.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.metadata.annotation.processing.model; + +import java.util.HashMap; +import java.util.Map; +import java.util.NavigableMap; +import java.util.SortedMap; +import java.util.TreeMap; + +/** + * {@link Map} Type model + * + * @since 2.7.6 + */ +public class MapTypeModel { + + private Map strings; // The composite element is simple type + + private SortedMap colors; // The composite element is Enum type + + private NavigableMap primitiveTypeModels; // The composite element is POJO type + + private HashMap models; // The composite element is hierarchical POJO type + + private TreeMap modelArrays; // The composite element is hierarchical POJO type +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/Model.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/Model.java new file mode 100644 index 0000000000..e3c72a5e32 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/Model.java @@ -0,0 +1,89 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.metadata.annotation.processing.model; + +import org.apache.dubbo.metadata.tools.Parent; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.concurrent.TimeUnit; + +/** + * Model Object + */ +public class Model extends Parent { + + private float f; + + private double d; + + private TimeUnit tu; + + private String str; + + private BigInteger bi; + + private BigDecimal bd; + + public float getF() { + return f; + } + + public void setF(float f) { + this.f = f; + } + + public double getD() { + return d; + } + + public void setD(double d) { + this.d = d; + } + + public TimeUnit getTu() { + return tu; + } + + public void setTu(TimeUnit tu) { + this.tu = tu; + } + + public String getStr() { + return str; + } + + public void setStr(String str) { + this.str = str; + } + + public BigInteger getBi() { + return bi; + } + + public void setBi(BigInteger bi) { + this.bi = bi; + } + + public BigDecimal getBd() { + return bd; + } + + public void setBd(BigDecimal bd) { + this.bd = bd; + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/PrimitiveTypeModel.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/PrimitiveTypeModel.java new file mode 100644 index 0000000000..c013a7403b --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/PrimitiveTypeModel.java @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.model; + +/** + * Primitive Type model + * + * @since 2.7.6 + */ +public class PrimitiveTypeModel { + + private boolean z; + + private byte b; + + private char c; + + private short s; + + private int i; + + private long l; + + private float f; + + private double d; + + public boolean isZ() { + return z; + } + + public byte getB() { + return b; + } + + public char getC() { + return c; + } + + public short getS() { + return s; + } + + public int getI() { + return i; + } + + public long getL() { + return l; + } + + public float getF() { + return f; + } + + public double getD() { + return d; + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/SimpleTypeModel.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/SimpleTypeModel.java new file mode 100644 index 0000000000..c745c927a1 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/SimpleTypeModel.java @@ -0,0 +1,161 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.model; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Date; + +/** + * Simple Type model + * + * @since 2.7.6 + */ +public class SimpleTypeModel { + + private Void v; + + private Boolean z; + + private Character c; + + private Byte b; + + private Short s; + + private Integer i; + + private Long l; + + private Float f; + + private Double d; + + private String str; + + private BigDecimal bd; + + private BigInteger bi; + + private Date dt; + + private int invalid; + + public Void getV() { + return v; + } + + public void setV(Void v) { + this.v = v; + } + + public Boolean getZ() { + return z; + } + + public void setZ(Boolean z) { + this.z = z; + } + + public Character getC() { + return c; + } + + public void setC(Character c) { + this.c = c; + } + + public Byte getB() { + return b; + } + + public void setB(Byte b) { + this.b = b; + } + + public Short getS() { + return s; + } + + public void setS(Short s) { + this.s = s; + } + + public Integer getI() { + return i; + } + + public void setI(Integer i) { + this.i = i; + } + + public Long getL() { + return l; + } + + public void setL(Long l) { + this.l = l; + } + + public Float getF() { + return f; + } + + public void setF(Float f) { + this.f = f; + } + + public Double getD() { + return d; + } + + public void setD(Double d) { + this.d = d; + } + + public String getStr() { + return str; + } + + public void setStr(String str) { + this.str = str; + } + + public BigDecimal getBd() { + return bd; + } + + public void setBd(BigDecimal bd) { + this.bd = bd; + } + + public BigInteger getBi() { + return bi; + } + + public void setBi(BigInteger bi) { + this.bi = bi; + } + + public Date getDt() { + return dt; + } + + public void setDt(Date dt) { + this.dt = dt; + } +} 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 new file mode 100644 index 0000000000..6db0efb5b5 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/rest/AnnotatedMethodParameterProcessorTest.java @@ -0,0 +1,59 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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 new file mode 100644 index 0000000000..186b06bb4f --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtilsTest.java @@ -0,0 +1,231 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.util; + +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 org.junit.jupiter.api.Test; +import org.springframework.web.bind.annotation.GetMapping; + +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; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +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.getAnnotation; +import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getAnnotations; +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; + +/** + * The {@link AnnotationUtils} Test + * + * @since 2.7.6 + */ +class AnnotationUtilsTest extends AbstractAnnotationProcessingTest { + + private TypeElement testType; + + @Override + protected void addCompiledClasses(Set> classesToBeCompiled) { + } + + @Override + protected void beforeEach() { + testType = getType(TestServiceImpl.class); + } + + @Test + void testGetAnnotation() { + AnnotationMirror serviceAnnotation = getAnnotation(testType, Service.class); + assertEquals("3.0.0", getAttribute(serviceAnnotation, "version")); + assertEquals("test", getAttribute(serviceAnnotation, "group")); + assertEquals("org.apache.dubbo.metadata.tools.TestService", getAttribute(serviceAnnotation, "interfaceName")); + + assertNull(getAnnotation(testType, (Class) null)); + assertNull(getAnnotation(testType, (String) null)); + + assertNull(getAnnotation(testType.asType(), (Class) null)); + assertNull(getAnnotation(testType.asType(), (String) null)); + + assertNull(getAnnotation((Element) null, (Class) null)); + assertNull(getAnnotation((Element) null, (String) null)); + + assertNull(getAnnotation((TypeElement) null, (Class) null)); + assertNull(getAnnotation((TypeElement) null, (String) null)); + } + + @Test + void testGetAnnotations() { + List annotations = getAnnotations(testType); + Iterator iterator = annotations.iterator(); + + assertEquals(2, annotations.size()); + assertEquals("com.alibaba.dubbo.config.annotation.Service", iterator.next().getAnnotationType().toString()); + assertEquals("org.apache.dubbo.config.annotation.Service", iterator.next().getAnnotationType().toString()); + + annotations = getAnnotations(testType, Service.class); + iterator = annotations.iterator(); + assertEquals(1, annotations.size()); + assertEquals("org.apache.dubbo.config.annotation.Service", iterator.next().getAnnotationType().toString()); + + annotations = getAnnotations(testType.asType(), Service.class); + iterator = annotations.iterator(); + assertEquals(1, annotations.size()); + assertEquals("org.apache.dubbo.config.annotation.Service", iterator.next().getAnnotationType().toString()); + + annotations = getAnnotations(testType.asType(), Service.class.getTypeName()); + iterator = annotations.iterator(); + assertEquals(1, annotations.size()); + assertEquals("org.apache.dubbo.config.annotation.Service", iterator.next().getAnnotationType().toString()); + + annotations = getAnnotations(testType, Override.class); + assertEquals(0, annotations.size()); + + annotations = getAnnotations(testType, com.alibaba.dubbo.config.annotation.Service.class); + assertEquals(1, annotations.size()); + + assertTrue(getAnnotations(null, (Class) null).isEmpty()); + assertTrue(getAnnotations(null, (String) null).isEmpty()); + assertTrue(getAnnotations(testType, (Class) null).isEmpty()); + assertTrue(getAnnotations(testType, (String) null).isEmpty()); + + assertTrue(getAnnotations(null, Service.class).isEmpty()); + assertTrue(getAnnotations(null, Service.class.getTypeName()).isEmpty()); + } + + @Test + void testGetAllAnnotations() { + + List annotations = getAllAnnotations(testType); + assertEquals(5, annotations.size()); + + annotations = getAllAnnotations(testType.asType(), annotation -> true); + assertEquals(5, annotations.size()); + + annotations = getAllAnnotations(processingEnv, TestServiceImpl.class); + assertEquals(5, annotations.size()); + + annotations = getAllAnnotations(testType.asType(), Service.class); + assertEquals(2, annotations.size()); + + annotations = getAllAnnotations(testType, Override.class); + assertEquals(0, annotations.size()); + + annotations = getAllAnnotations(testType.asType(), com.alibaba.dubbo.config.annotation.Service.class); + assertEquals(2, annotations.size()); + + assertTrue(getAllAnnotations((Element) null, (Class) null).isEmpty()); + assertTrue(getAllAnnotations((TypeMirror) null, (String) null).isEmpty()); + assertTrue(getAllAnnotations((ProcessingEnvironment) null, (Class) null).isEmpty()); + assertTrue(getAllAnnotations((ProcessingEnvironment) null, (String) null).isEmpty()); + + assertTrue(getAllAnnotations((Element) null).isEmpty()); + assertTrue(getAllAnnotations((TypeMirror) null).isEmpty()); + assertTrue(getAllAnnotations(processingEnv, (Class) null).isEmpty()); + assertTrue(getAllAnnotations(processingEnv, (String) null).isEmpty()); + + + assertTrue(getAllAnnotations(testType, (Class) null).isEmpty()); + assertTrue(getAllAnnotations(testType.asType(), (Class) null).isEmpty()); + + assertTrue(getAllAnnotations(testType, (String) null).isEmpty()); + assertTrue(getAllAnnotations(testType.asType(), (String) null).isEmpty()); + + assertTrue(getAllAnnotations((Element) null, Service.class).isEmpty()); + assertTrue(getAllAnnotations((TypeMirror) null, Service.class.getTypeName()).isEmpty()); + } + + + @Test + void testFindAnnotation() { + + assertEquals("org.apache.dubbo.config.annotation.Service", findAnnotation(testType, Service.class).getAnnotationType().toString()); + assertEquals("com.alibaba.dubbo.config.annotation.Service", findAnnotation(testType, com.alibaba.dubbo.config.annotation.Service.class).getAnnotationType().toString()); + assertEquals("javax.ws.rs.Path", findAnnotation(testType, Path.class).getAnnotationType().toString()); + assertEquals("javax.ws.rs.Path", findAnnotation(testType.asType(), Path.class).getAnnotationType().toString()); + assertEquals("javax.ws.rs.Path", findAnnotation(testType.asType(), Path.class.getTypeName()).getAnnotationType().toString()); + assertNull(findAnnotation(testType, Override.class)); + + assertNull(findAnnotation((Element) null, (Class) null)); + assertNull(findAnnotation((Element) null, (String) null)); + assertNull(findAnnotation((TypeMirror) null, (Class) null)); + assertNull(findAnnotation((TypeMirror) null, (String) null)); + + assertNull(findAnnotation(testType, (Class) null)); + assertNull(findAnnotation(testType, (String) null)); + assertNull(findAnnotation(testType.asType(), (Class) null)); + assertNull(findAnnotation(testType.asType(), (String) null)); + } + + @Test + void testFindMetaAnnotation() { + getAllDeclaredMethods(getType(TestService.class)).forEach(method -> { + assertEquals("javax.ws.rs.HttpMethod", findMetaAnnotation(method, "javax.ws.rs.HttpMethod").getAnnotationType().toString()); + }); + } + + @Test + void testGetAttribute() { + assertEquals("org.apache.dubbo.metadata.tools.TestService", getAttribute(findAnnotation(testType, Service.class), "interfaceName")); + assertEquals("org.apache.dubbo.metadata.tools.TestService", getAttribute(findAnnotation(testType, Service.class).getElementValues(), "interfaceName")); + assertEquals("/echo", getAttribute(findAnnotation(testType, Path.class), "value")); + + 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 + void testGetValue() { + AnnotationMirror pathAnnotation = getAnnotation(getType(TestService.class), Path.class); + assertEquals("/echo", getValue(pathAnnotation)); + } + + @Test + void testIsAnnotationPresent() { + assertTrue(isAnnotationPresent(testType, "org.apache.dubbo.config.annotation.Service")); + assertTrue(isAnnotationPresent(testType, "com.alibaba.dubbo.config.annotation.Service")); + assertTrue(isAnnotationPresent(testType, "javax.ws.rs.Path")); + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/FieldUtilsTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/FieldUtilsTest.java new file mode 100644 index 0000000000..74b69cc72d --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/FieldUtilsTest.java @@ -0,0 +1,259 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.util; + +import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; +import org.apache.dubbo.metadata.annotation.processing.model.Color; +import org.apache.dubbo.metadata.annotation.processing.model.Model; +import org.apache.dubbo.metadata.tools.TestServiceImpl; + +import org.junit.jupiter.api.Test; + +import javax.lang.model.element.Element; +import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; +import javax.lang.model.type.TypeMirror; +import java.lang.reflect.Type; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.List; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import static javax.lang.model.element.Modifier.FINAL; +import static javax.lang.model.element.Modifier.PRIVATE; +import static javax.lang.model.element.Modifier.PUBLIC; +import static javax.lang.model.element.Modifier.STATIC; +import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; +import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.getAllDeclaredFields; +import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.getAllNonStaticFields; +import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.getDeclaredField; +import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.getDeclaredFields; +import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.getNonStaticFields; +import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.isEnumMemberField; +import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.isField; +import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.isNonStaticField; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * {@link FieldUtils} Test + * + * @since 2.7.6 + */ +class FieldUtilsTest extends AbstractAnnotationProcessingTest { + + private TypeElement testType; + + @Override + protected void addCompiledClasses(Set> classesToBeCompiled) { + } + + @Override + protected void beforeEach() { + testType = getType(TestServiceImpl.class); + } + + @Test + void testGetDeclaredFields() { + TypeElement type = getType(Model.class); + List fields = getDeclaredFields(type); + assertModelFields(fields); + + fields = getDeclaredFields(type.asType()); + assertModelFields(fields); + + assertTrue(getDeclaredFields((Element) null).isEmpty()); + assertTrue(getDeclaredFields((TypeMirror) null).isEmpty()); + + fields = getDeclaredFields(type, f -> "f".equals(f.getSimpleName().toString())); + assertEquals(1, fields.size()); + assertEquals("f", fields.get(0).getSimpleName().toString()); + } + + @Test + void testGetAllDeclaredFields() { + TypeElement type = getType(Model.class); + + List fields = getAllDeclaredFields(type); + + assertModelAllFields(fields); + + assertTrue(getAllDeclaredFields((Element) null).isEmpty()); + assertTrue(getAllDeclaredFields((TypeMirror) null).isEmpty()); + + fields = getAllDeclaredFields(type, f -> "f".equals(f.getSimpleName().toString())); + assertEquals(1, fields.size()); + assertEquals("f", fields.get(0).getSimpleName().toString()); + } + + @Test + void testGetDeclaredField() { + TypeElement type = getType(Model.class); + testGetDeclaredField(type, "f", float.class); + testGetDeclaredField(type, "d", double.class); + testGetDeclaredField(type, "tu", TimeUnit.class); + testGetDeclaredField(type, "str", String.class); + testGetDeclaredField(type, "bi", BigInteger.class); + testGetDeclaredField(type, "bd", BigDecimal.class); + + assertNull(getDeclaredField(type, "b")); + assertNull(getDeclaredField(type, "s")); + assertNull(getDeclaredField(type, "i")); + assertNull(getDeclaredField(type, "l")); + assertNull(getDeclaredField(type, "z")); + + assertNull(getDeclaredField((Element) null, "z")); + assertNull(getDeclaredField((TypeMirror) null, "z")); + } + + @Test + void testFindField() { + TypeElement type = getType(Model.class); + testFindField(type, "f", float.class); + testFindField(type, "d", double.class); + testFindField(type, "tu", TimeUnit.class); + testFindField(type, "str", String.class); + testFindField(type, "bi", BigInteger.class); + testFindField(type, "bd", BigDecimal.class); + testFindField(type, "b", byte.class); + testFindField(type, "s", short.class); + testFindField(type, "i", int.class); + testFindField(type, "l", long.class); + testFindField(type, "z", boolean.class); + + assertNull(findField((Element) null, "f")); + assertNull(findField((Element) null, null)); + + assertNull(findField((TypeMirror) null, "f")); + assertNull(findField((TypeMirror) null, null)); + + assertNull(findField(type, null)); + assertNull(findField(type.asType(), null)); + } + + @Test + void testIsEnumField() { + TypeElement type = getType(Color.class); + VariableElement field = findField(type, "RED"); + assertTrue(isEnumMemberField(field)); + + field = findField(type, "YELLOW"); + assertTrue(isEnumMemberField(field)); + + field = findField(type, "BLUE"); + assertTrue(isEnumMemberField(field)); + + type = getType(Model.class); + field = findField(type, "f"); + assertFalse(isEnumMemberField(field)); + + assertFalse(isEnumMemberField(null)); + } + + @Test + void testIsNonStaticField() { + TypeElement type = getType(Model.class); + assertTrue(isNonStaticField(findField(type, "f"))); + + type = getType(Color.class); + assertFalse(isNonStaticField(findField(type, "BLUE"))); + } + + @Test + void testIsField() { + TypeElement type = getType(Model.class); + assertTrue(isField(findField(type, "f"))); + assertTrue(isField(findField(type, "f"), PRIVATE)); + + type = getType(Color.class); + assertTrue(isField(findField(type, "BLUE"), PUBLIC, STATIC, FINAL)); + + + assertFalse(isField(null)); + assertFalse(isField(null, PUBLIC, STATIC, FINAL)); + } + + @Test + void testGetNonStaticFields() { + TypeElement type = getType(Model.class); + + List fields = getNonStaticFields(type); + assertModelFields(fields); + + fields = getNonStaticFields(type.asType()); + assertModelFields(fields); + + assertTrue(getAllNonStaticFields((Element) null).isEmpty()); + assertTrue(getAllNonStaticFields((TypeMirror) null).isEmpty()); + } + + @Test + void testGetAllNonStaticFields() { + TypeElement type = getType(Model.class); + + List fields = getAllNonStaticFields(type); + assertModelAllFields(fields); + + fields = getAllNonStaticFields(type.asType()); + assertModelAllFields(fields); + + assertTrue(getAllNonStaticFields((Element) null).isEmpty()); + assertTrue(getAllNonStaticFields((TypeMirror) null).isEmpty()); + } + + private void assertModelFields(List fields) { + assertEquals(6, fields.size()); + assertEquals("d", fields.get(1).getSimpleName().toString()); + assertEquals("tu", fields.get(2).getSimpleName().toString()); + assertEquals("str", fields.get(3).getSimpleName().toString()); + assertEquals("bi", fields.get(4).getSimpleName().toString()); + assertEquals("bd", fields.get(5).getSimpleName().toString()); + } + + private void assertModelAllFields(List fields) { + assertEquals(11, fields.size()); + assertEquals("f", fields.get(0).getSimpleName().toString()); + assertEquals("d", fields.get(1).getSimpleName().toString()); + assertEquals("tu", fields.get(2).getSimpleName().toString()); + assertEquals("str", fields.get(3).getSimpleName().toString()); + assertEquals("bi", fields.get(4).getSimpleName().toString()); + assertEquals("bd", fields.get(5).getSimpleName().toString()); + assertEquals("b", fields.get(6).getSimpleName().toString()); + assertEquals("s", fields.get(7).getSimpleName().toString()); + assertEquals("i", fields.get(8).getSimpleName().toString()); + assertEquals("l", fields.get(9).getSimpleName().toString()); + assertEquals("z", fields.get(10).getSimpleName().toString()); + } + + private void testGetDeclaredField(TypeElement type, String fieldName, Type fieldType) { + VariableElement field = getDeclaredField(type, fieldName); + assertField(field, fieldName, fieldType); + } + + private void testFindField(TypeElement type, String fieldName, Type fieldType) { + VariableElement field = findField(type, fieldName); + assertField(field, fieldName, fieldType); + } + + private void assertField(VariableElement field, String fieldName, Type fieldType) { + assertEquals(fieldName, field.getSimpleName().toString()); + assertEquals(fieldType.getTypeName(), field.asType().toString()); + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/LoggerUtilsTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/LoggerUtilsTest.java new file mode 100644 index 0000000000..284ccb4231 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/LoggerUtilsTest.java @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.metadata.annotation.processing.util; + +import org.junit.jupiter.api.Test; + +import static org.apache.dubbo.metadata.annotation.processing.util.LoggerUtils.info; +import static org.apache.dubbo.metadata.annotation.processing.util.LoggerUtils.warn; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * {@link LoggerUtils} Test + * + * @since 2.7.6 + */ +class LoggerUtilsTest { + + @Test + void testLogger() { + assertNotNull(LoggerUtils.LOGGER); + } + + @Test + void testInfo() { + info("Hello,World"); + info("Hello,%s", "World"); + info("%s,%s", "Hello", "World"); + } + + @Test + void testWarn() { + warn("Hello,World"); + warn("Hello,%s", "World"); + warn("%s,%s", "Hello", "World"); + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MemberUtilsTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MemberUtilsTest.java new file mode 100644 index 0000000000..59a1b4545a --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MemberUtilsTest.java @@ -0,0 +1,113 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.util; + +import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; +import org.apache.dubbo.metadata.annotation.processing.model.Model; +import org.apache.dubbo.metadata.tools.TestServiceImpl; + +import org.junit.jupiter.api.Test; + +import javax.lang.model.element.Element; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; +import java.util.List; +import java.util.Set; + +import static javax.lang.model.element.Modifier.PRIVATE; +import static javax.lang.model.util.ElementFilter.fieldsIn; +import static javax.lang.model.util.ElementFilter.methodsIn; +import static org.apache.dubbo.metadata.annotation.processing.util.MemberUtils.getAllDeclaredMembers; +import static org.apache.dubbo.metadata.annotation.processing.util.MemberUtils.getDeclaredMembers; +import static org.apache.dubbo.metadata.annotation.processing.util.MemberUtils.hasModifiers; +import static org.apache.dubbo.metadata.annotation.processing.util.MemberUtils.isPublicNonStatic; +import static org.apache.dubbo.metadata.annotation.processing.util.MemberUtils.matchParameterTypes; +import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.findMethod; +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 MemberUtils} Test + * + * @since 2.7.6 + */ +class MemberUtilsTest extends AbstractAnnotationProcessingTest { + + private TypeElement testType; + + @Override + protected void addCompiledClasses(Set> classesToBeCompiled) { + } + + @Override + protected void beforeEach() { + testType = getType(TestServiceImpl.class); + } + + @Test + void testIsPublicNonStatic() { + assertFalse(isPublicNonStatic(null)); + methodsIn(getDeclaredMembers(testType.asType())).forEach(method -> assertTrue(isPublicNonStatic(method))); + } + + @Test + void testHasModifiers() { + assertFalse(hasModifiers(null)); + List members = getAllDeclaredMembers(testType.asType()); + List fields = fieldsIn(members); + assertTrue(hasModifiers(fields.get(0), PRIVATE)); + } + + @Test + void testDeclaredMembers() { + TypeElement type = getType(Model.class); + List members = getDeclaredMembers(type.asType()); + List fields = fieldsIn(members); + assertEquals(19, members.size()); + assertEquals(6, fields.size()); + assertEquals("f", fields.get(0).getSimpleName().toString()); + assertEquals("d", fields.get(1).getSimpleName().toString()); + assertEquals("tu", fields.get(2).getSimpleName().toString()); + assertEquals("str", fields.get(3).getSimpleName().toString()); + assertEquals("bi", fields.get(4).getSimpleName().toString()); + assertEquals("bd", fields.get(5).getSimpleName().toString()); + + members = getAllDeclaredMembers(type.asType()); + fields = fieldsIn(members); + assertEquals(11, fields.size()); + assertEquals("f", fields.get(0).getSimpleName().toString()); + assertEquals("d", fields.get(1).getSimpleName().toString()); + assertEquals("tu", fields.get(2).getSimpleName().toString()); + assertEquals("str", fields.get(3).getSimpleName().toString()); + assertEquals("bi", fields.get(4).getSimpleName().toString()); + assertEquals("bd", fields.get(5).getSimpleName().toString()); + assertEquals("b", fields.get(6).getSimpleName().toString()); + assertEquals("s", fields.get(7).getSimpleName().toString()); + assertEquals("i", fields.get(8).getSimpleName().toString()); + assertEquals("l", fields.get(9).getSimpleName().toString()); + assertEquals("z", fields.get(10).getSimpleName().toString()); + } + + @Test + void testMatchParameterTypes() { + ExecutableElement method = findMethod(testType, "echo", "java.lang.String"); + assertTrue(matchParameterTypes(method.getParameters(), "java.lang.String")); + assertFalse(matchParameterTypes(method.getParameters(), "java.lang.Object")); + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MethodUtilsTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MethodUtilsTest.java new file mode 100644 index 0000000000..dca4090df5 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MethodUtilsTest.java @@ -0,0 +1,196 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.util; + +import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; +import org.apache.dubbo.metadata.annotation.processing.model.Model; +import org.apache.dubbo.metadata.tools.TestService; +import org.apache.dubbo.metadata.tools.TestServiceImpl; + +import org.junit.jupiter.api.Test; + +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.TypeElement; +import javax.lang.model.type.TypeMirror; +import java.util.List; +import java.util.Set; + +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.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getDeclaredMethods; +import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getMethodName; +import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getMethodParameterTypes; +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.MethodUtils.getReturnType; +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; + +/** + * {@link MethodUtils} Test + * + * @since 2.7.6 + */ +class MethodUtilsTest extends AbstractAnnotationProcessingTest { + + private TypeElement testType; + + @Override + protected void addCompiledClasses(Set> classesToBeCompiled) { + } + + @Override + protected void beforeEach() { + testType = getType(TestServiceImpl.class); + } + + @Test + void testDeclaredMethods() { + TypeElement type = getType(Model.class); + List methods = getDeclaredMethods(type); + assertEquals(12, methods.size()); + + methods = getAllDeclaredMethods(type); + // registerNatives() no provided in JDK 17 + assertTrue(methods.size() >= 33); + + assertTrue(getAllDeclaredMethods((TypeElement) null).isEmpty()); + assertTrue(getAllDeclaredMethods((TypeMirror) null).isEmpty()); + } + + private List doGetAllDeclaredMethods() { + return getAllDeclaredMethods(testType, Object.class); + } + + @Test + void testGetAllDeclaredMethods() { + List methods = doGetAllDeclaredMethods(); + assertEquals(14, methods.size()); + } + + @Test + void testGetPublicNonStaticMethods() { + List methods = getPublicNonStaticMethods(testType, Object.class); + assertEquals(14, methods.size()); + + methods = getPublicNonStaticMethods(testType.asType(), Object.class); + assertEquals(14, methods.size()); + } + + @Test + void testIsMethod() { + List methods = getPublicNonStaticMethods(testType, Object.class); + assertEquals(14, methods.stream().map(MethodUtils::isMethod).count()); + } + + @Test + void testIsPublicNonStaticMethod() { + List methods = getPublicNonStaticMethods(testType, Object.class); + assertEquals(14, methods.stream().map(MethodUtils::isPublicNonStaticMethod).count()); + } + + @Test + void testFindMethod() { + TypeElement type = getType(Model.class); + // Test methods from java.lang.Object + // Object#toString() + String methodName = "toString"; + ExecutableElement method = findMethod(type.asType(), methodName); + assertEquals(method.getSimpleName().toString(), methodName); + + // Object#hashCode() + methodName = "hashCode"; + method = findMethod(type.asType(), methodName); + assertEquals(method.getSimpleName().toString(), methodName); + + // Object#getClass() + methodName = "getClass"; + method = findMethod(type.asType(), methodName); + assertEquals(method.getSimpleName().toString(), methodName); + + // Object#finalize() + methodName = "finalize"; + method = findMethod(type.asType(), methodName); + assertEquals(method.getSimpleName().toString(), methodName); + + // Object#clone() + methodName = "clone"; + method = findMethod(type.asType(), methodName); + assertEquals(method.getSimpleName().toString(), methodName); + + // Object#notify() + methodName = "notify"; + method = findMethod(type.asType(), methodName); + assertEquals(method.getSimpleName().toString(), methodName); + + // Object#notifyAll() + methodName = "notifyAll"; + method = findMethod(type.asType(), methodName); + assertEquals(method.getSimpleName().toString(), methodName); + + // Object#wait(long) + methodName = "wait"; + method = findMethod(type.asType(), methodName, long.class); + assertEquals(method.getSimpleName().toString(), methodName); + + // Object#wait(long,int) + methodName = "wait"; + method = findMethod(type.asType(), methodName, long.class, int.class); + assertEquals(method.getSimpleName().toString(), methodName); + + // Object#equals(Object) + methodName = "equals"; + method = findMethod(type.asType(), methodName, Object.class); + assertEquals(method.getSimpleName().toString(), methodName); + } + + @Test + void testGetOverrideMethod() { + List methods = doGetAllDeclaredMethods(); + + ExecutableElement overrideMethod = getOverrideMethod(processingEnv, testType, methods.get(0)); + assertNull(overrideMethod); + + ExecutableElement declaringMethod = findMethod(getType(TestService.class), "echo", "java.lang.String"); + + overrideMethod = getOverrideMethod(processingEnv, testType, declaringMethod); + assertEquals(methods.get(0), overrideMethod); + } + + @Test + void testGetMethodName() { + ExecutableElement method = findMethod(testType, "echo", "java.lang.String"); + assertEquals("echo", getMethodName(method)); + assertNull(getMethodName(null)); + } + + @Test + void testReturnType() { + ExecutableElement method = findMethod(testType, "echo", "java.lang.String"); + assertEquals("java.lang.String", getReturnType(method)); + assertNull(getReturnType(null)); + } + + @Test + void testMatchParameterTypes() { + ExecutableElement method = findMethod(testType, "echo", "java.lang.String"); + assertArrayEquals(new String[]{"java.lang.String"}, getMethodParameterTypes(method)); + assertTrue(getMethodParameterTypes(null).length == 0); + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtilsTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtilsTest.java new file mode 100644 index 0000000000..1bca2bc027 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtilsTest.java @@ -0,0 +1,138 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.metadata.annotation.processing.util; + +import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; +import org.apache.dubbo.metadata.tools.DefaultTestService; +import org.apache.dubbo.metadata.tools.GenericTestService; +import org.apache.dubbo.metadata.tools.TestService; +import org.apache.dubbo.metadata.tools.TestServiceImpl; + +import org.junit.jupiter.api.Test; + +import javax.lang.model.element.TypeElement; +import java.util.LinkedHashSet; +import java.util.Set; + +import static java.util.Arrays.asList; +import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.DUBBO_SERVICE_ANNOTATION_TYPE; +import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.GROUP_ATTRIBUTE_NAME; +import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.INTERFACE_CLASS_ATTRIBUTE_NAME; +import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.INTERFACE_NAME_ATTRIBUTE_NAME; +import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.LEGACY_SERVICE_ANNOTATION_TYPE; +import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.SERVICE_ANNOTATION_TYPE; +import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.SUPPORTED_ANNOTATION_TYPES; +import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.VERSION_ATTRIBUTE_NAME; +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.isServiceAnnotationPresent; +import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.resolveServiceInterfaceName; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * {@link ServiceAnnotationUtils} Test + * + * @since 2.7.6 + */ +class ServiceAnnotationUtilsTest extends AbstractAnnotationProcessingTest { + + @Override + protected void addCompiledClasses(Set> classesToBeCompiled) { + + } + + @Override + protected void beforeEach() { + + } + + @Test + void testConstants() { + assertEquals("org.apache.dubbo.config.annotation.DubboService", DUBBO_SERVICE_ANNOTATION_TYPE); + assertEquals("org.apache.dubbo.config.annotation.Service", SERVICE_ANNOTATION_TYPE); + assertEquals("com.alibaba.dubbo.config.annotation.Service", LEGACY_SERVICE_ANNOTATION_TYPE); + assertEquals("interfaceClass", INTERFACE_CLASS_ATTRIBUTE_NAME); + assertEquals("interfaceName", INTERFACE_NAME_ATTRIBUTE_NAME); + assertEquals("group", GROUP_ATTRIBUTE_NAME); + assertEquals("version", VERSION_ATTRIBUTE_NAME); + assertEquals(new LinkedHashSet<>(asList("org.apache.dubbo.config.annotation.DubboService", "org.apache.dubbo.config.annotation.Service", "com.alibaba.dubbo.config.annotation.Service")), SUPPORTED_ANNOTATION_TYPES); + } + + @Test + void testIsServiceAnnotationPresent() { + + assertTrue(isServiceAnnotationPresent(getType(TestServiceImpl.class))); + assertTrue(isServiceAnnotationPresent(getType(GenericTestService.class))); + assertTrue(isServiceAnnotationPresent(getType(DefaultTestService.class))); + + assertFalse(isServiceAnnotationPresent(getType(TestService.class))); + } + + @Test + void testGetAnnotation() { + TypeElement type = getType(TestServiceImpl.class); + assertEquals("org.apache.dubbo.config.annotation.Service", getAnnotation(type).getAnnotationType().toString()); + + type = getType(GenericTestService.class); + assertEquals("com.alibaba.dubbo.config.annotation.Service", getAnnotation(type).getAnnotationType().toString()); + + type = getType(DefaultTestService.class); + assertEquals("org.apache.dubbo.config.annotation.Service", getAnnotation(type).getAnnotationType().toString()); + + assertThrows(IllegalArgumentException.class, () -> getAnnotation(getType(TestService.class))); + } + + @Test + void testResolveServiceInterfaceName() { + TypeElement type = getType(TestServiceImpl.class); + assertEquals("org.apache.dubbo.metadata.tools.TestService", resolveServiceInterfaceName(type, getAnnotation(type))); + + type = getType(GenericTestService.class); + assertEquals("org.apache.dubbo.metadata.tools.TestService", resolveServiceInterfaceName(type, getAnnotation(type))); + + type = getType(DefaultTestService.class); + assertEquals("org.apache.dubbo.metadata.tools.TestService", resolveServiceInterfaceName(type, getAnnotation(type))); + } + + @Test + void testGetVersion() { + TypeElement type = getType(TestServiceImpl.class); + assertEquals("3.0.0", getVersion(getAnnotation(type))); + + type = getType(GenericTestService.class); + assertEquals("2.0.0", getVersion(getAnnotation(type))); + + type = getType(DefaultTestService.class); + assertEquals("1.0.0", getVersion(getAnnotation(type))); + } + + @Test + void testGetGroup() { + TypeElement type = getType(TestServiceImpl.class); + assertEquals("test", getGroup(getAnnotation(type))); + + type = getType(GenericTestService.class); + assertEquals("generic", getGroup(getAnnotation(type))); + + type = getType(DefaultTestService.class); + assertEquals("default", getGroup(getAnnotation(type))); + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/TypeUtilsTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/TypeUtilsTest.java new file mode 100644 index 0000000000..04e86e77ff --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/TypeUtilsTest.java @@ -0,0 +1,470 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.util; + +import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; +import org.apache.dubbo.metadata.annotation.processing.model.ArrayTypeModel; +import org.apache.dubbo.metadata.annotation.processing.model.Color; +import org.apache.dubbo.metadata.annotation.processing.model.Model; +import org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel; +import org.apache.dubbo.metadata.tools.DefaultTestService; +import org.apache.dubbo.metadata.tools.GenericTestService; +import org.apache.dubbo.metadata.tools.TestServiceImpl; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import javax.lang.model.element.Element; +import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; +import javax.lang.model.type.DeclaredType; +import javax.lang.model.type.TypeKind; +import javax.lang.model.type.TypeMirror; +import java.io.File; +import java.lang.reflect.Type; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import static java.util.Arrays.asList; +import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; +import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.getDeclaredFields; +import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getAllInterfaces; +import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getAllSuperTypes; +import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getHierarchicalTypes; +import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getInterfaces; +import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getResource; +import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getResourceName; +import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getSuperType; +import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isAnnotationType; +import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isArrayType; +import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isClassType; +import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isDeclaredType; +import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isEnumType; +import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isInterfaceType; +import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isPrimitiveType; +import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isSameType; +import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isSimpleType; +import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isTypeElement; +import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.listDeclaredTypes; +import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.listTypeElements; +import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.ofDeclaredType; +import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.ofDeclaredTypes; +import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.ofTypeElement; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The {@link TypeUtils} Test + * + * @since 2.7.6 + */ +class TypeUtilsTest extends AbstractAnnotationProcessingTest { + + private TypeElement testType; + + @Override + protected void addCompiledClasses(Set> classesToBeCompiled) { + classesToBeCompiled.add(ArrayTypeModel.class); + classesToBeCompiled.add(Color.class); + } + + @Override + protected void beforeEach() { + testType = getType(TestServiceImpl.class); + } + + @Test + void testIsSimpleType() { + + assertTrue(isSimpleType(getType(Void.class))); + assertTrue(isSimpleType(getType(Boolean.class))); + assertTrue(isSimpleType(getType(Character.class))); + assertTrue(isSimpleType(getType(Byte.class))); + assertTrue(isSimpleType(getType(Short.class))); + assertTrue(isSimpleType(getType(Integer.class))); + assertTrue(isSimpleType(getType(Long.class))); + assertTrue(isSimpleType(getType(Float.class))); + assertTrue(isSimpleType(getType(Double.class))); + assertTrue(isSimpleType(getType(String.class))); + assertTrue(isSimpleType(getType(BigDecimal.class))); + assertTrue(isSimpleType(getType(BigInteger.class))); + assertTrue(isSimpleType(getType(Date.class))); + assertTrue(isSimpleType(getType(Object.class))); + + assertFalse(isSimpleType(getType(getClass()))); + assertFalse(isSimpleType((TypeElement) null)); + assertFalse(isSimpleType((TypeMirror) null)); + } + + @Test + void testIsSameType() { + assertTrue(isSameType(getType(Void.class).asType(), "java.lang.Void")); + assertFalse(isSameType(getType(String.class).asType(), "java.lang.Void")); + + assertFalse(isSameType(getType(Void.class).asType(), (Type) null)); + assertFalse(isSameType(null, (Type) null)); + + assertFalse(isSameType(getType(Void.class).asType(), (String) null)); + assertFalse(isSameType(null, (String) null)); + } + + @Test + void testIsArrayType() { + TypeElement type = getType(ArrayTypeModel.class); + assertTrue(isArrayType(findField(type.asType(), "integers").asType())); + assertTrue(isArrayType(findField(type.asType(), "strings").asType())); + assertTrue(isArrayType(findField(type.asType(), "primitiveTypeModels").asType())); + assertTrue(isArrayType(findField(type.asType(), "models").asType())); + assertTrue(isArrayType(findField(type.asType(), "colors").asType())); + + assertFalse(isArrayType((Element) null)); + assertFalse(isArrayType((TypeMirror) null)); + } + + @Test + void testIsEnumType() { + TypeElement type = getType(Color.class); + assertTrue(isEnumType(type.asType())); + + type = getType(ArrayTypeModel.class); + assertFalse(isEnumType(type.asType())); + + assertFalse(isEnumType((Element) null)); + assertFalse(isEnumType((TypeMirror) null)); + } + + @Test + void testIsClassType() { + TypeElement type = getType(ArrayTypeModel.class); + assertTrue(isClassType(type.asType())); + + type = getType(Model.class); + assertTrue(isClassType(type.asType())); + + assertFalse(isClassType((Element) null)); + assertFalse(isClassType((TypeMirror) null)); + } + + @Test + void testIsPrimitiveType() { + TypeElement type = getType(PrimitiveTypeModel.class); + getDeclaredFields(type.asType()) + .stream() + .map(VariableElement::asType) + .forEach(t -> assertTrue(isPrimitiveType(t))); + + assertFalse(isPrimitiveType(getType(ArrayTypeModel.class))); + + assertFalse(isPrimitiveType((Element) null)); + assertFalse(isPrimitiveType((TypeMirror) null)); + } + + @Test + void testIsInterfaceType() { + TypeElement type = getType(CharSequence.class); + assertTrue(isInterfaceType(type)); + assertTrue(isInterfaceType(type.asType())); + + type = getType(Model.class); + assertFalse(isInterfaceType(type)); + assertFalse(isInterfaceType(type.asType())); + + assertFalse(isInterfaceType((Element) null)); + assertFalse(isInterfaceType((TypeMirror) null)); + } + + @Test + void testIsAnnotationType() { + TypeElement type = getType(Override.class); + + assertTrue(isAnnotationType(type)); + assertTrue(isAnnotationType(type.asType())); + + type = getType(Model.class); + assertFalse(isAnnotationType(type)); + assertFalse(isAnnotationType(type.asType())); + + assertFalse(isAnnotationType((Element) null)); + assertFalse(isAnnotationType((TypeMirror) null)); + } + + @Test + void testGetHierarchicalTypes() { + Set hierarchicalTypes = getHierarchicalTypes(testType.asType(), true, true, true); + Iterator iterator = hierarchicalTypes.iterator(); + assertEquals(8, hierarchicalTypes.size()); + assertEquals("org.apache.dubbo.metadata.tools.TestServiceImpl", iterator.next().toString()); + assertEquals("org.apache.dubbo.metadata.tools.GenericTestService", iterator.next().toString()); + assertEquals("org.apache.dubbo.metadata.tools.DefaultTestService", iterator.next().toString()); + assertEquals("java.lang.Object", iterator.next().toString()); + assertEquals("org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); + assertEquals("java.lang.AutoCloseable", iterator.next().toString()); + assertEquals("java.io.Serializable", iterator.next().toString()); + assertEquals("java.util.EventListener", iterator.next().toString()); + + hierarchicalTypes = getHierarchicalTypes(testType); + iterator = hierarchicalTypes.iterator(); + assertEquals(8, hierarchicalTypes.size()); + assertEquals("org.apache.dubbo.metadata.tools.TestServiceImpl", iterator.next().toString()); + assertEquals("org.apache.dubbo.metadata.tools.GenericTestService", iterator.next().toString()); + assertEquals("org.apache.dubbo.metadata.tools.DefaultTestService", iterator.next().toString()); + assertEquals("java.lang.Object", iterator.next().toString()); + assertEquals("org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); + assertEquals("java.lang.AutoCloseable", iterator.next().toString()); + assertEquals("java.io.Serializable", iterator.next().toString()); + assertEquals("java.util.EventListener", iterator.next().toString()); + + hierarchicalTypes = getHierarchicalTypes(testType.asType(), Object.class); + iterator = hierarchicalTypes.iterator(); + assertEquals(7, hierarchicalTypes.size()); + assertEquals("org.apache.dubbo.metadata.tools.TestServiceImpl", iterator.next().toString()); + assertEquals("org.apache.dubbo.metadata.tools.GenericTestService", iterator.next().toString()); + assertEquals("org.apache.dubbo.metadata.tools.DefaultTestService", iterator.next().toString()); + assertEquals("org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); + assertEquals("java.lang.AutoCloseable", iterator.next().toString()); + assertEquals("java.io.Serializable", iterator.next().toString()); + assertEquals("java.util.EventListener", iterator.next().toString()); + + hierarchicalTypes = getHierarchicalTypes(testType.asType(), true, true, false); + iterator = hierarchicalTypes.iterator(); + assertEquals(4, hierarchicalTypes.size()); + assertEquals("org.apache.dubbo.metadata.tools.TestServiceImpl", iterator.next().toString()); + assertEquals("org.apache.dubbo.metadata.tools.GenericTestService", iterator.next().toString()); + assertEquals("org.apache.dubbo.metadata.tools.DefaultTestService", iterator.next().toString()); + assertEquals("java.lang.Object", iterator.next().toString()); + + hierarchicalTypes = getHierarchicalTypes(testType.asType(), true, false, true); + iterator = hierarchicalTypes.iterator(); + assertEquals(5, hierarchicalTypes.size()); + assertEquals("org.apache.dubbo.metadata.tools.TestServiceImpl", iterator.next().toString()); + assertEquals("org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); + assertEquals("java.lang.AutoCloseable", iterator.next().toString()); + assertEquals("java.io.Serializable", iterator.next().toString()); + assertEquals("java.util.EventListener", iterator.next().toString()); + + hierarchicalTypes = getHierarchicalTypes(testType.asType(), false, false, true); + iterator = hierarchicalTypes.iterator(); + assertEquals(4, hierarchicalTypes.size()); + assertEquals("org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); + assertEquals("java.lang.AutoCloseable", iterator.next().toString()); + assertEquals("java.io.Serializable", iterator.next().toString()); + assertEquals("java.util.EventListener", iterator.next().toString()); + + hierarchicalTypes = getHierarchicalTypes(testType.asType(), true, false, false); + iterator = hierarchicalTypes.iterator(); + assertEquals(1, hierarchicalTypes.size()); + assertEquals("org.apache.dubbo.metadata.tools.TestServiceImpl", iterator.next().toString()); + + hierarchicalTypes = getHierarchicalTypes(testType.asType(), false, false, false); + assertEquals(0, hierarchicalTypes.size()); + + assertTrue(getHierarchicalTypes((TypeElement) null).isEmpty()); + assertTrue(getHierarchicalTypes((TypeMirror) null).isEmpty()); + } + + + @Test + void testGetInterfaces() { + TypeElement type = getType(Model.class); + List interfaces = getInterfaces(type); + assertTrue(interfaces.isEmpty()); + + interfaces = getInterfaces(testType.asType()); + + assertEquals(3, interfaces.size()); + assertEquals("org.apache.dubbo.metadata.tools.TestService", interfaces.get(0).toString()); + assertEquals("java.lang.AutoCloseable", interfaces.get(1).toString()); + assertEquals("java.io.Serializable", interfaces.get(2).toString()); + + assertTrue(getInterfaces((TypeElement) null).isEmpty()); + assertTrue(getInterfaces((TypeMirror) null).isEmpty()); + } + + @Test + void testGetAllInterfaces() { + Set interfaces = getAllInterfaces(testType.asType()); + assertEquals(4, interfaces.size()); + Iterator iterator = interfaces.iterator(); + assertEquals("org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); + assertEquals("java.lang.AutoCloseable", iterator.next().toString()); + assertEquals("java.io.Serializable", iterator.next().toString()); + assertEquals("java.util.EventListener", iterator.next().toString()); + + Set allInterfaces = getAllInterfaces(testType); + assertEquals(4, interfaces.size()); + + Iterator allIterator = allInterfaces.iterator(); + assertEquals("org.apache.dubbo.metadata.tools.TestService", allIterator.next().toString()); + assertEquals("java.lang.AutoCloseable", allIterator.next().toString()); + assertEquals("java.io.Serializable", allIterator.next().toString()); + assertEquals("java.util.EventListener", allIterator.next().toString()); + + assertTrue(getAllInterfaces((TypeElement) null).isEmpty()); + assertTrue(getAllInterfaces((TypeMirror) null).isEmpty()); + } + + @Test + void testGetType() { + TypeElement element = TypeUtils.getType(processingEnv, String.class); + assertEquals(element, TypeUtils.getType(processingEnv, element.asType())); + assertEquals(element, TypeUtils.getType(processingEnv, "java.lang.String")); + + assertNull(TypeUtils.getType(processingEnv, (Type) null)); + assertNull(TypeUtils.getType(processingEnv, (TypeMirror) null)); + assertNull(TypeUtils.getType(processingEnv, (CharSequence) null)); + assertNull(TypeUtils.getType(null, (CharSequence) null)); + } + + @Test + void testGetSuperType() { + TypeElement gtsTypeElement = getSuperType(testType); + assertEquals(gtsTypeElement, getType(GenericTestService.class)); + TypeElement dtsTypeElement = getSuperType(gtsTypeElement); + assertEquals(dtsTypeElement, getType(DefaultTestService.class)); + + TypeMirror gtsType = getSuperType(testType.asType()); + assertEquals(gtsType, getType(GenericTestService.class).asType()); + TypeMirror dtsType = getSuperType(gtsType); + assertEquals(dtsType, getType(DefaultTestService.class).asType()); + + assertNull(getSuperType((TypeElement) null)); + assertNull(getSuperType((TypeMirror) null)); + } + + @Test + void testGetAllSuperTypes() { + Set allSuperTypes = getAllSuperTypes(testType); + Iterator iterator = allSuperTypes.iterator(); + assertEquals(3, allSuperTypes.size()); + assertEquals(iterator.next(), getType(GenericTestService.class)); + assertEquals(iterator.next(), getType(DefaultTestService.class)); + assertEquals(iterator.next(), getType(Object.class)); + + allSuperTypes = getAllSuperTypes(testType); + iterator = allSuperTypes.iterator(); + assertEquals(3, allSuperTypes.size()); + assertEquals(iterator.next(), getType(GenericTestService.class)); + assertEquals(iterator.next(), getType(DefaultTestService.class)); + assertEquals(iterator.next(), getType(Object.class)); + + assertTrue(getAllSuperTypes((TypeElement) null).isEmpty()); + assertTrue(getAllSuperTypes((TypeMirror) null).isEmpty()); + } + + @Test + void testIsDeclaredType() { + assertTrue(isDeclaredType(testType)); + assertTrue(isDeclaredType(testType.asType())); + assertFalse(isDeclaredType((Element) null)); + assertFalse(isDeclaredType((TypeMirror) null)); + assertFalse(isDeclaredType(types.getNullType())); + assertFalse(isDeclaredType(types.getPrimitiveType(TypeKind.BYTE))); + assertFalse(isDeclaredType(types.getArrayType(types.getPrimitiveType(TypeKind.BYTE)))); + } + + @Test + void testOfDeclaredType() { + assertEquals(testType.asType(), ofDeclaredType(testType)); + assertEquals(testType.asType(), ofDeclaredType(testType.asType())); + assertEquals(ofDeclaredType(testType), ofDeclaredType(testType.asType())); + + assertNull(ofDeclaredType((Element) null)); + assertNull(ofDeclaredType((TypeMirror) null)); + } + + @Test + void testIsTypeElement() { + assertTrue(isTypeElement(testType)); + assertTrue(isTypeElement(testType.asType())); + + assertFalse(isTypeElement((Element) null)); + assertFalse(isTypeElement((TypeMirror) null)); + } + + @Test + void testOfTypeElement() { + assertEquals(testType, ofTypeElement(testType)); + assertEquals(testType, ofTypeElement(testType.asType())); + + assertNull(ofTypeElement((Element) null)); + assertNull(ofTypeElement((TypeMirror) null)); + } + + @Test + void testOfDeclaredTypes() { + Set declaredTypes = ofDeclaredTypes(asList(getType(String.class), getType(TestServiceImpl.class), getType(Color.class))); + assertTrue(declaredTypes.contains(getType(String.class).asType())); + assertTrue(declaredTypes.contains(getType(TestServiceImpl.class).asType())); + assertTrue(declaredTypes.contains(getType(Color.class).asType())); + + assertTrue(ofDeclaredTypes(null).isEmpty()); + } + + @Test + void testListDeclaredTypes() { + List types = listDeclaredTypes(asList(testType, testType, testType)); + assertEquals(1, types.size()); + assertEquals(ofDeclaredType(testType), types.get(0)); + + types = listDeclaredTypes(asList(new Element[]{null})); + assertTrue(types.isEmpty()); + } + + @Test + void testListTypeElements() { + List typeElements = listTypeElements(asList(testType.asType(), ofDeclaredType(testType))); + assertEquals(1, typeElements.size()); + assertEquals(testType, typeElements.get(0)); + + typeElements = listTypeElements(asList(types.getPrimitiveType(TypeKind.BYTE), types.getNullType(), types.getNoType(TypeKind.NONE))); + assertTrue(typeElements.isEmpty()); + + typeElements = listTypeElements(asList(new TypeMirror[]{null})); + assertTrue(typeElements.isEmpty()); + + typeElements = listTypeElements(null); + assertTrue(typeElements.isEmpty()); + } + + @Test + @Disabled + public void testGetResource() throws URISyntaxException { + URL resource = getResource(processingEnv, testType); + assertNotNull(resource); + assertTrue(new File(resource.toURI()).exists()); + assertEquals(resource, getResource(processingEnv, testType.asType())); + assertEquals(resource, getResource(processingEnv, "org.apache.dubbo.metadata.tools.TestServiceImpl")); + + assertThrows(RuntimeException.class, () -> getResource(processingEnv, "NotFound")); + } + + @Test + void testGetResourceName() { + assertEquals("java/lang/String.class", getResourceName("java.lang.String")); + assertNull(getResourceName(null)); + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/DefaultRestService.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/DefaultRestService.java new file mode 100644 index 0000000000..844fe840f3 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/DefaultRestService.java @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.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-compatible/src/test/java/org/apache/dubbo/metadata/rest/RestService.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/RestService.java new file mode 100644 index 0000000000..65d67ab475 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/RestService.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.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-compatible/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java new file mode 100644 index 0000000000..c2daf9b104 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java @@ -0,0 +1,95 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.metadata.rest; + +import org.apache.dubbo.config.annotation.DubboService; + +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; + +import java.util.HashMap; +import java.util.Map; + +/** + * 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-compatible/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java new file mode 100644 index 0000000000..684d76fd3b --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java @@ -0,0 +1,107 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.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-compatible/src/test/java/org/apache/dubbo/metadata/rest/User.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/User.java new file mode 100644 index 0000000000..2b6c4a21ba --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/User.java @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.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-compatible/src/test/java/org/apache/dubbo/metadata/tools/Ancestor.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/Ancestor.java new file mode 100644 index 0000000000..52ccaf6ab3 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/Ancestor.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.metadata.tools; + +import java.io.Serializable; + +/** + * Ancestor + */ +public class Ancestor implements Serializable { + + private boolean z; + + public boolean isZ() { + return z; + } + + public void setZ(boolean z) { + this.z = z; + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/Compiler.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/Compiler.java new file mode 100644 index 0000000000..e2f27dd306 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/Compiler.java @@ -0,0 +1,120 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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 javax.annotation.processing.Processor; +import javax.tools.JavaCompiler; +import javax.tools.JavaFileObject; +import javax.tools.StandardJavaFileManager; +import javax.tools.StandardLocation; +import javax.tools.ToolProvider; +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.Set; + +import static java.util.Arrays.asList; + +/** + * The Java Compiler + */ +public class Compiler { + + private final File sourceDirectory; + + private final JavaCompiler javaCompiler; + + private final StandardJavaFileManager javaFileManager; + + private final Set processors = new LinkedHashSet<>(); + + public Compiler() throws IOException { + this(defaultTargetDirectory()); + } + + public Compiler(File targetDirectory) throws IOException { + this(defaultSourceDirectory(), targetDirectory); + } + + public Compiler(File sourceDirectory, File targetDirectory) throws IOException { + this.sourceDirectory = sourceDirectory; + this.javaCompiler = ToolProvider.getSystemJavaCompiler(); + this.javaFileManager = javaCompiler.getStandardFileManager(null, null, null); + this.javaFileManager.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(targetDirectory)); + this.javaFileManager.setLocation(StandardLocation.SOURCE_OUTPUT, Collections.singleton(targetDirectory)); + } + + private static File defaultSourceDirectory() { + return new File(defaultRootDirectory(), "src/test/java"); + } + + private static File defaultRootDirectory() { + return detectClassPath(Compiler.class).getParentFile().getParentFile(); + } + + private static File defaultTargetDirectory() { + File dir = new File(defaultRootDirectory(), "target/generated-classes"); + dir.mkdirs(); + return dir; + } + + private static File detectClassPath(Class targetClass) { + URL classFileURL = targetClass.getProtectionDomain().getCodeSource().getLocation(); + if ("file".equals(classFileURL.getProtocol())) { + return new File(classFileURL.getPath()); + } else { + throw new RuntimeException("No support"); + } + } + + public Compiler processors(Processor... processors) { + this.processors.addAll(asList(processors)); + return this; + } + + private Iterable getJavaFileObjects(Class... sourceClasses) { + int size = sourceClasses == null ? 0 : sourceClasses.length; + File[] javaSourceFiles = new File[size]; + for (int i = 0; i < size; i++) { + File javaSourceFile = javaSourceFile(sourceClasses[i].getName()); + javaSourceFiles[i] = javaSourceFile; + } + return javaFileManager.getJavaFileObjects(javaSourceFiles); + } + + private File javaSourceFile(String sourceClassName) { + String javaSourceFilePath = sourceClassName.replace('.', '/').concat(".java"); + return new File(sourceDirectory, javaSourceFilePath); + } + + public boolean compile(Class... sourceClasses) { + JavaCompiler.CompilationTask task = javaCompiler.getTask(null, this.javaFileManager, null, + asList("-parameters", "-Xlint:unchecked", "-nowarn", "-Xlint:deprecation"), +// null, + null, getJavaFileObjects(sourceClasses)); + if (!processors.isEmpty()) { + task.setProcessors(processors); + } + return task.call(); + } + + public JavaCompiler getJavaCompiler() { + return javaCompiler; + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/CompilerTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/CompilerTest.java new file mode 100644 index 0000000000..071e1b26c8 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/CompilerTest.java @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.junit.jupiter.api.Test; + +import java.io.IOException; + +/** + * The Compiler test case + */ +class CompilerTest { + + @Test + void testCompile() throws IOException { + Compiler compiler = new Compiler(); + compiler.compile( + TestServiceImpl.class, + DefaultTestService.class, + GenericTestService.class); + } +} + 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 new file mode 100644 index 0000000000..d7b73c4abc --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/DefaultRestServiceTest.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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 org.junit.jupiter.api.Test; + +import java.io.IOException; + +/** + * 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/DefaultTestService.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/DefaultTestService.java new file mode 100644 index 0000000000..85bce6924d --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/DefaultTestService.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.config.annotation.Service; +import org.apache.dubbo.metadata.annotation.processing.model.Model; + +import java.util.concurrent.TimeUnit; + +/** + * {@link TestService} Implementation + * + * @since 2.7.6 + */ +@Service( + interfaceName = "org.apache.dubbo.metadata.tools.TestService", + version = "1.0.0", + group = "default" +) +public class DefaultTestService implements TestService { + + private String name; + + @Override + public String echo(String message) { + return "[ECHO] " + message; + } + + @Override + public Model model(Model model) { + return model; + } + + @Override + public String testPrimitive(boolean z, int i) { + return null; + } + + @Override + public Model testEnum(TimeUnit timeUnit) { + return null; + } + + @Override + public String testArray(String[] strArray, int[] intArray, Model[] modelArray) { + return null; + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/GenericTestService.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/GenericTestService.java new file mode 100644 index 0000000000..83cf19ff2c --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/GenericTestService.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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 com.alibaba.dubbo.config.annotation.Service; + +import java.util.EventListener; + +/** + * {@link TestService} Implementation + * + * @since 2.7.6 + */ +@Service( + version = "2.0.0", + group = "generic" +) +public class GenericTestService extends DefaultTestService implements TestService, EventListener { + @Override + public String echo(String message) { + return "[ECHO] " + message; + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/Parent.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/Parent.java new file mode 100644 index 0000000000..4273a0fb70 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/Parent.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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; + +/** + * Parent + */ +public class Parent extends Ancestor { + + private byte b; + + private short s; + + private int i; + + private long l; + + public byte getB() { + return b; + } + + public void setB(byte b) { + this.b = b; + } + + public short getS() { + return s; + } + + public void setS(short s) { + this.s = s; + } + + public int getI() { + return i; + } + + public void setI(int i) { + this.i = i; + } + + public long getL() { + return l; + } + + public void setL(long l) { + this.l = l; + } +} 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 new file mode 100644 index 0000000000..5f0ed6e093 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/RestServiceTest.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.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 org.junit.jupiter.api.Test; + +import java.io.IOException; + +/** + * {@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 new file mode 100644 index 0000000000..ce17abd592 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/SpringRestServiceTest.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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 org.junit.jupiter.api.Test; + +import java.io.IOException; + +/** + * {@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 new file mode 100644 index 0000000000..e55fdf3da4 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/StandardRestServiceTest.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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 org.junit.jupiter.api.Test; + +import java.io.IOException; + +/** + * 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-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestProcessor.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestProcessor.java new file mode 100644 index 0000000000..cb8ae82354 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestProcessor.java @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.metadata.tools; + +import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.ProcessingEnvironment; +import javax.annotation.processing.Processor; +import javax.annotation.processing.RoundEnvironment; +import javax.annotation.processing.SupportedAnnotationTypes; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.TypeElement; +import java.util.Set; + +import static javax.lang.model.SourceVersion.latestSupported; + +/** + * {@link Processor} for test + * + * @since 2.7.6 + */ +@SupportedAnnotationTypes("*") +public class TestProcessor extends AbstractProcessor { + + @Override + public boolean process(Set annotations, RoundEnvironment roundEnv) { + return false; + } + + public ProcessingEnvironment getProcessingEnvironment() { + return super.processingEnv; + } + + public SourceVersion getSupportedSourceVersion(){ + return latestSupported(); + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestService.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestService.java new file mode 100644 index 0000000000..83c0ef6aff --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestService.java @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.metadata.tools; + +import org.apache.dubbo.metadata.annotation.processing.model.Model; + +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import java.util.concurrent.TimeUnit; + +/** + * Test Service + * + * @since 2.7.6 + */ +@Path("/echo") +public interface TestService { + + @GET + String echo(@PathParam("message") @DefaultValue("mercyblitz") String message); + + @POST + Model model(@PathParam("model") Model model); + + // Test primitive + @PUT + String testPrimitive(boolean z, int i); + + // Test enumeration + @PUT + Model testEnum(TimeUnit timeUnit); + + // Test Array + @GET + String testArray(String[] strArray, int[] intArray, Model[] modelArray); +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestServiceImpl.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestServiceImpl.java new file mode 100644 index 0000000000..713e8e701b --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestServiceImpl.java @@ -0,0 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.metadata.tools; + + +import org.apache.dubbo.config.annotation.Service; + +import java.io.Serializable; + +/** + * {@link TestService} Implementation + * + * @since 2.7.6 + */ +@com.alibaba.dubbo.config.annotation.Service( + interfaceName = "org.apache.dubbo.metadata.tools.TestService", + interfaceClass = TestService.class, + version = "3.0.0", + group = "test" +) +@Service( + interfaceName = "org.apache.dubbo.metadata.tools.TestService", + interfaceClass = TestService.class, + version = "3.0.0", + group = "test" +) +public class TestServiceImpl extends GenericTestService implements TestService, AutoCloseable, Serializable { + + @Override + public String echo(String message) { + return "[ECHO] " + message; + } + + @Override + public void close() throws Exception { + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java new file mode 100644 index 0000000000..874950ce80 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java @@ -0,0 +1,64 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.rpc.filter; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.compact.Dubbo2GenericExceptionUtils; +import org.apache.dubbo.rpc.AppResponse; +import org.apache.dubbo.rpc.AsyncRpcResult; +import org.apache.dubbo.rpc.Invocation; +import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.Result; +import org.apache.dubbo.rpc.RpcInvocation; +import org.apache.dubbo.rpc.model.ApplicationModel; +import org.apache.dubbo.rpc.support.DemoService; +import org.apache.dubbo.rpc.support.Person; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.when; + +class GenericImplFilterTest { + + private GenericImplFilter genericImplFilter = new GenericImplFilter(ApplicationModel.defaultModel().getDefaultModule()); + + @Test + void testInvokeWithException() throws Exception { + + RpcInvocation invocation = new RpcInvocation("getPerson", "org.apache.dubbo.rpc.support.DemoService", + "org.apache.dubbo.rpc.support.DemoService:dubbo", new Class[]{Person.class}, new Object[]{new Person("dubbo", 10)}); + + URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + + "accesslog=true&group=dubbo&version=1.1&generic=true"); + Invoker invoker = Mockito.mock(Invoker.class); + + AppResponse mockRpcResult = new AppResponse(Dubbo2GenericExceptionUtils.newGenericException(new RuntimeException("failed"))); + when(invoker.invoke(any(Invocation.class))).thenReturn(AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation)); + when(invoker.getUrl()).thenReturn(url); + when(invoker.getInterface()).thenReturn(DemoService.class); + + Result asyncResult = genericImplFilter.invoke(invoker, invocation); + Result result = asyncResult.get(); + genericImplFilter.onResponse(result, invoker, invocation); + Assertions.assertEquals(RuntimeException.class, result.getException().getClass()); + + } + +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/support/DemoService.java b/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/support/DemoService.java new file mode 100644 index 0000000000..ed595724f8 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/support/DemoService.java @@ -0,0 +1,64 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.rpc.support; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; + +public interface DemoService { + void sayHello(String name); + + String echo(String text); + + long timestamp(); + + String getThreadName(); + + int getSize(String[] strs); + + int getSize(Object[] os); + + Object invoke(String service, String method) throws Exception; + + int stringLength(String str); + + Type enumlength(Type... types); + +// Type enumlength(Type type); + +// String get(CustomArgument arg1); + + byte getbyte(byte arg); + + Person getPerson(Person person); + + String testReturnType(String str); + + List testReturnType1(String str); + + CompletableFuture testReturnType2(String str); + + CompletableFuture> testReturnType3(String str); + + CompletableFuture testReturnType4(String str); + + CompletableFuture> testReturnType5(String str); + + void $invoke(String s1, String s2); + +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/support/Person.java b/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/support/Person.java new file mode 100644 index 0000000000..d4570af5ca --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/support/Person.java @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.rpc.support; + +import java.io.Serializable; + +/** + * Person.java + */ +public class Person implements Serializable { + + private static final long serialVersionUID = 1L; + private String name; + private int age; + + public Person() {} + + public Person(String name, int age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/support/Type.java b/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/support/Type.java new file mode 100644 index 0000000000..22ded46777 --- /dev/null +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/support/Type.java @@ -0,0 +1,21 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.rpc.support; + +public enum Type { + High, Normal, Lower +} diff --git a/dubbo-compatible/src/test/resources/META-INF/config.properties b/dubbo-compatible/src/test/resources/META-INF/config.properties new file mode 100644 index 0000000000..51b587ea4f --- /dev/null +++ b/dubbo-compatible/src/test/resources/META-INF/config.properties @@ -0,0 +1,36 @@ +application.prefix = dubbo.application. +application.prefixes = dubbo.applications. +# single bean definition + +## application +dubbo.application.id = applicationBean +dubbo.application.name = dubbo-demo-application + +## module +dubbo.module.id = moduleBean +dubbo.module.name = dubbo-demo-module + +## registry +dubbo.registry.address = zookeeper://192.168.99.100:32770 +dubbo.registry.useAsConfigCenter = false +dubbo.registry.useAsMetadataCenter = false + +## protocol +dubbo.protocol.name = dubbo +dubbo.protocol.port = 20880 + +dubbo.protocols.rest.port=8080 +dubbo.protocols.thrift.port=9090 + +## monitor +dubbo.monitor.address = zookeeper://127.0.0.1:32770 + +## provider +dubbo.provider.host = 127.0.0.1 + +## consumer +dubbo.consumer.client = netty + +# multiple Bean definition +dubbo.registries.registry1.address = zookeeper://localhost:2181 +dubbo.registries.registry2.address = zookeeper://localhost:2182 diff --git a/dubbo-compatible/src/test/resources/META-INF/default.properties b/dubbo-compatible/src/test/resources/META-INF/default.properties new file mode 100644 index 0000000000..101030bba9 --- /dev/null +++ b/dubbo-compatible/src/test/resources/META-INF/default.properties @@ -0,0 +1,4 @@ +demo.service.version = 2.5.7 +demo.service.application = dubbo-demo-application +demo.service.protocol = dubbo +demo.service.registry = my-registry diff --git a/dubbo-compatible/src/test/resources/META-INF/dubbb-consumer.properties b/dubbo-compatible/src/test/resources/META-INF/dubbb-consumer.properties new file mode 100644 index 0000000000..736358a499 --- /dev/null +++ b/dubbo-compatible/src/test/resources/META-INF/dubbb-consumer.properties @@ -0,0 +1,12 @@ +# Dubbo Consumer Properties as an alternative for +# Spring XML Bean definition : META-INF/spring/dubbo-annotation-consumer.xml +demo.service.application = dubbo-demo-application +demo.service.registry = my-registry + +## Dubbo configs binding properties +### +dubbo.applications.dubbo-demo-application.name = dubbo-demo-application + +### +dubbo.registries.my-registry.address = N/A +dubbo.registries.my-registry2.address = N/A diff --git a/dubbo-compatible/src/test/resources/META-INF/dubbb-provider.properties b/dubbo-compatible/src/test/resources/META-INF/dubbb-provider.properties new file mode 100644 index 0000000000..24b479e712 --- /dev/null +++ b/dubbo-compatible/src/test/resources/META-INF/dubbb-provider.properties @@ -0,0 +1,24 @@ +# Dubbo Provider Properties as an alternative for +# Spring XML Bean definition : META-INF/spring/dubbo-annotation-provider.xml + +## Service Providers' Placeholders for org.apache.dubbo.config.spring.context.annotation.provider.DemoServiceImpl + +demo.service.application = dubbo-demo-application +demo.service.protocol = dubbo +demo.service.registry = my-registry + + +## Dubbo configs binding properties + +### +dubbo.application.id = dubbo-demo-application +dubbo.application.name = dubbo-demo-application + +### +dubbo.registry.id = my-registry +dubbo.registry.address = N/A + +### +dubbo.protocol.id = dubbo +dubbo.protocol.name = dubbo +dubbo.protocol.port = 12345 diff --git a/dubbo-compatible/src/test/resources/META-INF/dubbo-consumer.properties b/dubbo-compatible/src/test/resources/META-INF/dubbo-consumer.properties new file mode 100644 index 0000000000..f841d6a7fb --- /dev/null +++ b/dubbo-compatible/src/test/resources/META-INF/dubbo-consumer.properties @@ -0,0 +1,13 @@ +# Dubbo Consumer Properties as an alternative for +# Spring XML Bean definition : META-INF/spring/dubbo-annotation-consumer.xml +demo.service.application = dubbo-annotation-test +demo.service.registry = my-registry + +## Dubbo configs binding properties +### +# In this UT, the provider will be responsible of loading ApplicationConfig. +dubbo.applications.dubbo-demo-application.name = dubbo-demo-application + +### +dubbo.registries.my-registry.address = N/A +dubbo.registries.my-registry2.address = N/A diff --git a/dubbo-compatible/src/test/resources/META-INF/dubbo-provider.properties b/dubbo-compatible/src/test/resources/META-INF/dubbo-provider.properties new file mode 100644 index 0000000000..63c984d1ce --- /dev/null +++ b/dubbo-compatible/src/test/resources/META-INF/dubbo-provider.properties @@ -0,0 +1,24 @@ +# Dubbo Provider Properties as an alternative for +# Spring XML Bean definition : META-INF/spring/dubbo-annotation-provider.xml + +## Service Providers' Placeholders for org.apache.dubbo.config.spring.context.annotation.provider.DemoServiceImpl + +demo.service.application = dubbo-demo-application +demo.service.protocol = dubbo +demo.service.registry = my-registry + + +## Dubbo configs binding properties + +### +dubbo.application.id = dubbo-demo-application +dubbo.application.name = dubbo-demo-application + +### +dubbo.registry.id = my-registry +dubbo.registry.address = N/A + +### +dubbo.protocol.name = dubbo +dubbo.protocol.port = 12345 +dubbo.monitor.address=N/A diff --git a/dubbo-compatible/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.extension.activate.ActivateExt1 b/dubbo-compatible/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.extension.activate.ActivateExt1 new file mode 100644 index 0000000000..64f7d2ff51 --- /dev/null +++ b/dubbo-compatible/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.extension.activate.ActivateExt1 @@ -0,0 +1,2 @@ +old1=org.apache.dubbo.common.extension.activate.impl.OldActivateExt1Impl2 +old2=org.apache.dubbo.common.extension.activate.impl.OldActivateExt1Impl3 diff --git a/dubbo-compatible/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.extension.support.Filter0 b/dubbo-compatible/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.extension.support.Filter0 new file mode 100644 index 0000000000..cd818494cc --- /dev/null +++ b/dubbo-compatible/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.extension.support.Filter0 @@ -0,0 +1,5 @@ +_1=org.apache.dubbo.common.extension.support.Filter1 +_2=org.apache.dubbo.common.extension.support.Filter2 +_3=org.apache.dubbo.common.extension.support.Filter3 +_4=org.apache.dubbo.common.extension.support.Filter4 +_5=org.apache.dubbo.common.extension.support.OldFilter5 \ No newline at end of file diff --git a/dubbo-compatible/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter b/dubbo-compatible/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter new file mode 100644 index 0000000000..1adf5237ef --- /dev/null +++ b/dubbo-compatible/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter @@ -0,0 +1 @@ +mymock=org.apache.dubbo.config.spring.filter.MockFilter \ No newline at end of file diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java index f679627932..a36cd6f566 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java @@ -17,6 +17,7 @@ package org.apache.dubbo.config.spring.beans.factory.annotation; +import org.apache.dubbo.common.compact.Dubbo2CompactUtils; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ArrayUtils; @@ -121,7 +122,16 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean * {@link DubboReference @DubboReference} has been supported since 2.7.7 */ public ReferenceAnnotationBeanPostProcessor() { - super(DubboReference.class, Reference.class, com.alibaba.dubbo.config.annotation.Reference.class); + super(loadAnnotationTypes()); + } + + @SuppressWarnings("unchecked") + private static Class[] loadAnnotationTypes() { + if (Dubbo2CompactUtils.isEnabled() && Dubbo2CompactUtils.isReferenceClassLoaded()) { + return (Class[])new Class[]{DubboReference.class, Reference.class, Dubbo2CompactUtils.getReferenceClass()}; + } else { + return (Class[])new Class[]{DubboReference.class, Reference.class}; + } } @Override diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationPostProcessor.java index 279e1c1903..aa8a52cf93 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationPostProcessor.java @@ -16,6 +16,7 @@ */ package org.apache.dubbo.config.spring.beans.factory.annotation; +import org.apache.dubbo.common.compact.Dubbo2CompactUtils; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.AnnotationUtils; @@ -105,14 +106,27 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos public static final String BEAN_NAME = "dubboServiceAnnotationPostProcessor"; - private final static List> serviceAnnotationTypes = asList( - // @since 2.7.7 Add the @DubboService , the issue : https://github.com/apache/dubbo/issues/6007 - DubboService.class, - // @since 2.7.0 the substitute @com.alibaba.dubbo.config.annotation.Service - Service.class, - // @since 2.7.3 Add the compatibility for legacy Dubbo's @Service , the issue : https://github.com/apache/dubbo/issues/4330 - com.alibaba.dubbo.config.annotation.Service.class - ); + private final static List> serviceAnnotationTypes = loadServiceAnnotationTypes(); + + private static List> loadServiceAnnotationTypes() { + if (Dubbo2CompactUtils.isEnabled() && Dubbo2CompactUtils.isServiceClassLoaded()) { + return asList( + // @since 2.7.7 Add the @DubboService , the issue : https://github.com/apache/dubbo/issues/6007 + DubboService.class, + // @since 2.7.0 the substitute @com.alibaba.dubbo.config.annotation.Service + Service.class, + // @since 2.7.3 Add the compatibility for legacy Dubbo's @Service , the issue : https://github.com/apache/dubbo/issues/4330 + Dubbo2CompactUtils.getServiceClass() + ); + } else { + return asList( + // @since 2.7.7 Add the @DubboService , the issue : https://github.com/apache/dubbo/issues/6007 + DubboService.class, + // @since 2.7.0 the substitute @com.alibaba.dubbo.config.annotation.Service + Service.class + ); + } + } private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/DubboAnnotationUtils.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/DubboAnnotationUtils.java index 170bbab0ba..6a3ffb62c3 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/DubboAnnotationUtils.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/DubboAnnotationUtils.java @@ -79,8 +79,8 @@ public class DubboAnnotationUtils { // 1. get from DubboService.interfaceName() String interfaceClassName = AnnotationUtils.getAttribute(attributes, "interfaceName"); if (StringUtils.hasText(interfaceClassName)) { - if (GenericService.class.getName().equals(interfaceClassName) || - com.alibaba.dubbo.rpc.service.GenericService.class.getName().equals(interfaceClassName)) { + if ("org.apache.dubbo.rpc.service.GenericService".equals(interfaceClassName) || + "com.alibaba.dubbo.rpc.service.GenericService".equals(interfaceClassName)) { throw new IllegalStateException("@Service interfaceName() cannot be GenericService: " + interfaceClassName); } return interfaceClassName; diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboTest.java index 74898c719c..6230db4822 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboTest.java @@ -119,13 +119,13 @@ class EnableDubboTest { // From Parent - demoService = child.getDemoServiceFromParent(); - - Assertions.assertNotNull(demoService); - - value = demoService.sayName("Mercy"); - - Assertions.assertEquals("Hello,Mercy", value); +// demoService = child.getDemoServiceFromParent(); +// +// Assertions.assertNotNull(demoService); +// +// value = demoService.sayName("Mercy"); +// +// Assertions.assertEquals("Hello,Mercy", value); // From Ancestor @@ -176,4 +176,4 @@ class EnableDubboTest { } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/test/TestConsumerConfiguration.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/test/TestConsumerConfiguration.java index 5869d95e89..57b8669fe4 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/test/TestConsumerConfiguration.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/test/TestConsumerConfiguration.java @@ -90,22 +90,7 @@ public class TestConsumerConfiguration { } } - public static abstract class Parent extends Ancestor { - - private DemoService demoServiceFromParent; - - public DemoService getDemoServiceFromParent() { - return demoServiceFromParent; - } - - @com.alibaba.dubbo.config.annotation.Reference(version = "2.5.7", url = remoteURL, filter = "mymock", application = "dubbo-demo-application") - public void setDemoServiceFromParent(DemoService demoServiceFromParent) { - this.demoServiceFromParent = demoServiceFromParent; - } - - } - - public static class Child extends Parent { + public static class Child extends Ancestor { @Reference(version = "2.5.7", url = remoteURL, filter = "mymock", application = "dubbo-demo-application") private DemoService demoServiceFromChild; diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/HelloServiceImpl.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/HelloServiceImpl.java index d21cdc23ce..1841abb075 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/HelloServiceImpl.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/HelloServiceImpl.java @@ -16,9 +16,9 @@ */ package org.apache.dubbo.config.spring.context.annotation.provider; +import org.apache.dubbo.config.annotation.Service; import org.apache.dubbo.config.spring.api.HelloService; -import com.alibaba.dubbo.config.annotation.Service; /** * {@link HelloService} Implementation just annotating Dubbo's {@link Service} diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/AbstractServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/AbstractServiceRestMetadataResolver.java index ec391d9483..9d9cbfd483 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/AbstractServiceRestMetadataResolver.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/AbstractServiceRestMetadataResolver.java @@ -16,6 +16,7 @@ */ 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; @@ -91,8 +92,12 @@ public abstract class AbstractServiceRestMetadataResolver implements ServiceRest } protected final boolean isServiceAnnotationPresent(Class serviceType) { - return isAnyAnnotationPresent(serviceType, DubboService.class, Service.class, - com.alibaba.dubbo.config.annotation.Service.class); + if (Dubbo2CompactUtils.isEnabled() && Dubbo2CompactUtils.isServiceClassLoaded()) { + return isAnyAnnotationPresent(serviceType, DubboService.class, Service.class, + Dubbo2CompactUtils.getServiceClass()); + } else { + return isAnyAnnotationPresent(serviceType, DubboService.class, Service.class); + } } /** 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 186b06bb4f..79a50e304c 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 @@ -94,8 +94,8 @@ class AnnotationUtilsTest extends AbstractAnnotationProcessingTest { List annotations = getAnnotations(testType); Iterator iterator = annotations.iterator(); - assertEquals(2, annotations.size()); - assertEquals("com.alibaba.dubbo.config.annotation.Service", iterator.next().getAnnotationType().toString()); + assertEquals(1, annotations.size()); +// assertEquals("com.alibaba.dubbo.config.annotation.Service", iterator.next().getAnnotationType().toString()); assertEquals("org.apache.dubbo.config.annotation.Service", iterator.next().getAnnotationType().toString()); annotations = getAnnotations(testType, Service.class); @@ -116,8 +116,8 @@ class AnnotationUtilsTest extends AbstractAnnotationProcessingTest { annotations = getAnnotations(testType, Override.class); assertEquals(0, annotations.size()); - annotations = getAnnotations(testType, com.alibaba.dubbo.config.annotation.Service.class); - assertEquals(1, annotations.size()); +// annotations = getAnnotations(testType, com.alibaba.dubbo.config.annotation.Service.class); +// assertEquals(1, annotations.size()); assertTrue(getAnnotations(null, (Class) null).isEmpty()); assertTrue(getAnnotations(null, (String) null).isEmpty()); @@ -132,22 +132,22 @@ class AnnotationUtilsTest extends AbstractAnnotationProcessingTest { void testGetAllAnnotations() { List annotations = getAllAnnotations(testType); - assertEquals(5, annotations.size()); + assertEquals(4, annotations.size()); annotations = getAllAnnotations(testType.asType(), annotation -> true); - assertEquals(5, annotations.size()); + assertEquals(4, annotations.size()); annotations = getAllAnnotations(processingEnv, TestServiceImpl.class); - assertEquals(5, annotations.size()); + assertEquals(4, annotations.size()); annotations = getAllAnnotations(testType.asType(), Service.class); - assertEquals(2, annotations.size()); + assertEquals(3, annotations.size()); annotations = getAllAnnotations(testType, Override.class); assertEquals(0, annotations.size()); - annotations = getAllAnnotations(testType.asType(), com.alibaba.dubbo.config.annotation.Service.class); - assertEquals(2, annotations.size()); +// annotations = getAllAnnotations(testType.asType(), com.alibaba.dubbo.config.annotation.Service.class); +// assertEquals(2, annotations.size()); assertTrue(getAllAnnotations((Element) null, (Class) null).isEmpty()); assertTrue(getAllAnnotations((TypeMirror) null, (String) null).isEmpty()); @@ -175,7 +175,7 @@ class AnnotationUtilsTest extends AbstractAnnotationProcessingTest { void testFindAnnotation() { assertEquals("org.apache.dubbo.config.annotation.Service", findAnnotation(testType, Service.class).getAnnotationType().toString()); - assertEquals("com.alibaba.dubbo.config.annotation.Service", findAnnotation(testType, com.alibaba.dubbo.config.annotation.Service.class).getAnnotationType().toString()); +// assertEquals("com.alibaba.dubbo.config.annotation.Service", findAnnotation(testType, com.alibaba.dubbo.config.annotation.Service.class).getAnnotationType().toString()); assertEquals("javax.ws.rs.Path", findAnnotation(testType, Path.class).getAnnotationType().toString()); assertEquals("javax.ws.rs.Path", findAnnotation(testType.asType(), Path.class).getAnnotationType().toString()); assertEquals("javax.ws.rs.Path", findAnnotation(testType.asType(), Path.class.getTypeName()).getAnnotationType().toString()); @@ -225,7 +225,7 @@ class AnnotationUtilsTest extends AbstractAnnotationProcessingTest { @Test void testIsAnnotationPresent() { assertTrue(isAnnotationPresent(testType, "org.apache.dubbo.config.annotation.Service")); - assertTrue(isAnnotationPresent(testType, "com.alibaba.dubbo.config.annotation.Service")); +// assertTrue(isAnnotationPresent(testType, "com.alibaba.dubbo.config.annotation.Service")); assertTrue(isAnnotationPresent(testType, "javax.ws.rs.Path")); } } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtilsTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtilsTest.java index 1bca2bc027..309956ba50 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtilsTest.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtilsTest.java @@ -91,8 +91,8 @@ class ServiceAnnotationUtilsTest extends AbstractAnnotationProcessingTest { TypeElement type = getType(TestServiceImpl.class); assertEquals("org.apache.dubbo.config.annotation.Service", getAnnotation(type).getAnnotationType().toString()); - type = getType(GenericTestService.class); - assertEquals("com.alibaba.dubbo.config.annotation.Service", getAnnotation(type).getAnnotationType().toString()); +// type = getType(GenericTestService.class); +// assertEquals("com.alibaba.dubbo.config.annotation.Service", getAnnotation(type).getAnnotationType().toString()); type = getType(DefaultTestService.class); assertEquals("org.apache.dubbo.config.annotation.Service", getAnnotation(type).getAnnotationType().toString()); diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/GenericTestService.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/GenericTestService.java index 83cf19ff2c..c6f540347b 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/GenericTestService.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/GenericTestService.java @@ -17,7 +17,7 @@ package org.apache.dubbo.metadata.tools; -import com.alibaba.dubbo.config.annotation.Service; +import org.apache.dubbo.config.annotation.Service; import java.util.EventListener; diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/TestServiceImpl.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/TestServiceImpl.java index 713e8e701b..7bb1bf0c06 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/TestServiceImpl.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/TestServiceImpl.java @@ -26,12 +26,6 @@ import java.io.Serializable; * * @since 2.7.6 */ -@com.alibaba.dubbo.config.annotation.Service( - interfaceName = "org.apache.dubbo.metadata.tools.TestService", - interfaceClass = TestService.class, - version = "3.0.0", - group = "test" -) @Service( interfaceName = "org.apache.dubbo.metadata.tools.TestService", interfaceClass = TestService.class, diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AppResponse.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AppResponse.java index 8a2089ed20..a41bc386cd 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AppResponse.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AppResponse.java @@ -16,6 +16,9 @@ */ package org.apache.dubbo.rpc; +import org.apache.dubbo.common.compact.Dubbo2CompactUtils; +import org.apache.dubbo.rpc.support.Dubbo2RpcExceptionUtils; + import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; @@ -85,12 +88,14 @@ public class AppResponse implements Result { } catch (Exception e) { // ignore } - if ((exception instanceof RpcException) && !(exception instanceof com.alibaba.dubbo.rpc.RpcException)) { - com.alibaba.dubbo.rpc.RpcException recreated = - new com.alibaba.dubbo.rpc.RpcException(((RpcException) exception).getCode(), - exception.getMessage(), exception.getCause()); - recreated.setStackTrace(exception.getStackTrace()); - throw recreated; + if (Dubbo2CompactUtils.isEnabled() && Dubbo2RpcExceptionUtils.isRpcExceptionClassLoaded() + && (exception instanceof RpcException) && !Dubbo2RpcExceptionUtils.getRpcExceptionClass().isAssignableFrom(exception.getClass())) { + RpcException recreated = Dubbo2RpcExceptionUtils.newRpcException(((RpcException) exception).getCode(), + exception.getMessage(), exception.getCause()); + if (recreated != null) { + recreated.setStackTrace(exception.getStackTrace()); + throw recreated; + } } throw exception; } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java index d78a35ebaf..fa61d9b4f7 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java @@ -19,6 +19,8 @@ package org.apache.dubbo.rpc.filter; import org.apache.dubbo.common.beanutil.JavaBeanAccessor; import org.apache.dubbo.common.beanutil.JavaBeanDescriptor; import org.apache.dubbo.common.beanutil.JavaBeanSerializeUtil; +import org.apache.dubbo.common.compact.Dubbo2CompactUtils; +import org.apache.dubbo.common.compact.Dubbo2GenericExceptionUtils; import org.apache.dubbo.common.config.Configuration; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.constants.LoggerCodeConstants; @@ -291,16 +293,23 @@ public class GenericFilter implements Filter, Filter.Listener, ScopeModelAware { generic = getGenericValueFromRpcContext(); } - if (appResponse.hasException()) { + if (appResponse.hasException() && + Dubbo2CompactUtils.isEnabled() && Dubbo2GenericExceptionUtils.isGenericExceptionClassLoaded()) { Throwable appException = appResponse.getException(); if (appException instanceof GenericException) { GenericException tmp = (GenericException) appException; - appException = new com.alibaba.dubbo.rpc.service.GenericException(tmp.getMessage(), tmp.getCause(), + GenericException recreated = Dubbo2GenericExceptionUtils.newGenericException(tmp.getMessage(), tmp.getCause(), tmp.getExceptionClass(), tmp.getExceptionMessage()); + if (recreated != null) { + appException = recreated; + } appException.setStackTrace(tmp.getStackTrace()); } - if (!(appException instanceof com.alibaba.dubbo.rpc.service.GenericException)) { - appException = new com.alibaba.dubbo.rpc.service.GenericException(appException); + if (!(Dubbo2GenericExceptionUtils.getGenericExceptionClass().isAssignableFrom(appException.getClass()))) { + GenericException recreated = Dubbo2GenericExceptionUtils.newGenericException(appException); + if (recreated != null) { + appException = recreated; + } } appResponse.setException(appException); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java index e3308840e8..65c8bd16e8 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java @@ -19,6 +19,8 @@ package org.apache.dubbo.rpc.filter; import org.apache.dubbo.common.beanutil.JavaBeanAccessor; import org.apache.dubbo.common.beanutil.JavaBeanDescriptor; import org.apache.dubbo.common.beanutil.JavaBeanSerializeUtil; +import org.apache.dubbo.common.compact.Dubbo2CompactUtils; +import org.apache.dubbo.common.compact.Dubbo2GenericExceptionUtils; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; @@ -176,8 +178,10 @@ public class GenericImplFilter implements Filter, Filter.Listener { } catch (NoSuchMethodException e) { throw new RpcException(e.getMessage(), e); } - } else if (appResponse.getException() instanceof com.alibaba.dubbo.rpc.service.GenericException) { - com.alibaba.dubbo.rpc.service.GenericException exception = (com.alibaba.dubbo.rpc.service.GenericException) appResponse.getException(); + } else if (Dubbo2CompactUtils.isEnabled() && Dubbo2GenericExceptionUtils.isGenericExceptionClassLoaded() + && Dubbo2GenericExceptionUtils.getGenericExceptionClass().isAssignableFrom(appResponse.getException().getClass())) { + // TODO we should cast if is apache GenericException or not? + org.apache.dubbo.rpc.service.GenericException exception = (org.apache.dubbo.rpc.service.GenericException) appResponse.getException(); try { String className = exception.getExceptionClass(); DefaultSerializeClassChecker classChecker = moduleModel.getApplicationModel() diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.java index 269392b04b..8219bb74db 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.java @@ -16,6 +16,7 @@ */ package org.apache.dubbo.rpc.proxy; +import org.apache.dubbo.common.compact.Dubbo2CompactUtils; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ClassUtils; @@ -82,8 +83,16 @@ public abstract class AbstractProxyFactory implements ProxyFactory { // ignore } - if (GenericService.class.equals(invoker.getInterface()) || !GenericService.class.isAssignableFrom(invoker.getInterface())) { - interfaces.add(com.alibaba.dubbo.rpc.service.GenericService.class); + if (GenericService.class.isAssignableFrom(invoker.getInterface()) && + Dubbo2CompactUtils.isEnabled() && Dubbo2CompactUtils.isGenericServiceClassLoaded()) { + interfaces.add(Dubbo2CompactUtils.getGenericServiceClass()); + } + if (!GenericService.class.isAssignableFrom(invoker.getInterface())) { + if (Dubbo2CompactUtils.isEnabled() && Dubbo2CompactUtils.isGenericServiceClassLoaded()) { + interfaces.add(Dubbo2CompactUtils.getGenericServiceClass()); + } else { + interfaces.add(org.apache.dubbo.rpc.service.GenericService.class); + } } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/Dubbo2RpcExceptionUtils.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/Dubbo2RpcExceptionUtils.java new file mode 100644 index 0000000000..548e6807bc --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/Dubbo2RpcExceptionUtils.java @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.rpc.support; + +import java.lang.reflect.Constructor; + +public class Dubbo2RpcExceptionUtils { + private static final Class RPC_EXCEPTION_CLASS; + private static final Constructor RPC_EXCEPTION_CONSTRUCTOR_I_S_T; + + static { + RPC_EXCEPTION_CLASS = loadClass(); + RPC_EXCEPTION_CONSTRUCTOR_I_S_T = loadConstructor(int.class, String.class, Throwable.class); + } + + @SuppressWarnings("unchecked") + private static Class loadClass() { + try { + Class clazz = Class.forName("com.alibaba.dubbo.rpc.RpcException"); + if (org.apache.dubbo.rpc.RpcException.class.isAssignableFrom(clazz)) { + return (Class) clazz; + } else { + return null; + } + } catch (Throwable e) { + return null; + } + } + + private static Constructor loadConstructor(Class... parameterTypes) { + if (RPC_EXCEPTION_CLASS == null) { + return null; + } + try { + return RPC_EXCEPTION_CLASS.getConstructor(parameterTypes); + } catch (Throwable e) { + return null; + } + } + + public static boolean isRpcExceptionClassLoaded() { + return RPC_EXCEPTION_CLASS != null && RPC_EXCEPTION_CONSTRUCTOR_I_S_T != null; + } + + public static Class getRpcExceptionClass() { + return RPC_EXCEPTION_CLASS; + } + + public static org.apache.dubbo.rpc.RpcException newRpcException(int code, String message, Throwable cause) { + if (RPC_EXCEPTION_CONSTRUCTOR_I_S_T == null) { + return null; + } + try { + return RPC_EXCEPTION_CONSTRUCTOR_I_S_T.newInstance(code, message, cause); + } catch (Throwable e) { + return null; + } + } +} diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java index 56e6a5d1c5..ecf08b6e36 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java @@ -16,10 +16,6 @@ */ package org.apache.dubbo.rpc.filter; -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Map; - import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.AsyncRpcResult; @@ -28,14 +24,19 @@ import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; +import org.apache.dubbo.rpc.service.GenericException; import org.apache.dubbo.rpc.service.GenericService; import org.apache.dubbo.rpc.support.DemoService; import org.apache.dubbo.rpc.support.Person; + import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import com.alibaba.dubbo.rpc.service.GenericException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; @@ -75,7 +76,8 @@ class GenericImplFilterTest { } @Test - void testInvokeWithException() throws Exception { + @Disabled("Apache Generic Exception not support cast exception now") + void testInvokeWithException1() throws Exception { RpcInvocation invocation = new RpcInvocation("getPerson", "org.apache.dubbo.rpc.support.DemoService", "org.apache.dubbo.rpc.support.DemoService:dubbo", new Class[]{Person.class}, new Object[]{new Person("dubbo", 10)}); @@ -96,6 +98,28 @@ class GenericImplFilterTest { } + @Test + void testInvokeWithException2() throws Exception { + + RpcInvocation invocation = new RpcInvocation("getPerson", "org.apache.dubbo.rpc.support.DemoService", + "org.apache.dubbo.rpc.support.DemoService:dubbo", new Class[]{Person.class}, new Object[]{new Person("dubbo", 10)}); + + URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + + "accesslog=true&group=dubbo&version=1.1&generic=true"); + Invoker invoker = Mockito.mock(Invoker.class); + + AppResponse mockRpcResult = new AppResponse(new GenericException(new RuntimeException("failed"))); + when(invoker.invoke(any(Invocation.class))).thenReturn(AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation)); + when(invoker.getUrl()).thenReturn(url); + when(invoker.getInterface()).thenReturn(DemoService.class); + + Result asyncResult = genericImplFilter.invoke(invoker, invocation); + Result result = asyncResult.get(); + genericImplFilter.onResponse(result, invoker, invocation); + Assertions.assertEquals(GenericException.class, result.getException().getClass()); + + } + @Test void testInvokeWith$Invoke() throws Exception {