Remove direct dependency of alibaba dubbo (#13218)

* Remove direct dependency of alibaba dubbo

* disable in ExtensionLoader

* Fix license

* Fix test

* Fix case

* Fix test
This commit is contained in:
Albumen Kevin 2023-10-19 15:25:40 +08:00 committed by GitHub
parent 416374cd78
commit 0d91d419a8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
130 changed files with 7178 additions and 147 deletions

View File

@ -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<? extends Annotation> 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<? extends Annotation> loadClass() {
try {
Class<?> clazz = Class.forName("com.alibaba.dubbo.common.extension.Activate");
if (clazz.isAnnotation()) {
return (Class<? extends Annotation>) clazz;
} else {
return null;
}
} catch (Throwable e) {
return null;
}
}
public static boolean isActivateLoaded() {
return ACTIVATE_CLASS != null;
}
public static Class<? extends Annotation> 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;
}
}
}

View File

@ -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<? extends Annotation> REFERENCE_CLASS;
private static final Class<? extends Annotation> 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<? extends Annotation> loadAnnotation(String name) {
try {
Class<?> clazz = Class.forName(name);
if (clazz.isAnnotation()) {
return (Class<? extends Annotation>) clazz;
} else {
return null;
}
} catch (Throwable e) {
return null;
}
}
public static boolean isReferenceClassLoaded() {
return REFERENCE_CLASS != null;
}
public static Class<? extends Annotation> getReferenceClass() {
return REFERENCE_CLASS;
}
public static boolean isServiceClassLoaded() {
return SERVICE_CLASS != null;
}
public static Class<? extends Annotation> 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;
}
}

View File

@ -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<? extends org.apache.dubbo.rpc.service.GenericException> GENERIC_EXCEPTION_CLASS;
private static final Constructor<? extends org.apache.dubbo.rpc.service.GenericException> GENERIC_EXCEPTION_CONSTRUCTOR;
private static final Constructor<? extends org.apache.dubbo.rpc.service.GenericException> GENERIC_EXCEPTION_CONSTRUCTOR_S;
private static final Constructor<? extends org.apache.dubbo.rpc.service.GenericException> GENERIC_EXCEPTION_CONSTRUCTOR_S_S;
private static final Constructor<? extends org.apache.dubbo.rpc.service.GenericException> GENERIC_EXCEPTION_CONSTRUCTOR_T;
private static final Constructor<? extends org.apache.dubbo.rpc.service.GenericException> 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<? extends org.apache.dubbo.rpc.service.GenericException> loadClass() {
try {
Class<?> clazz = Class.forName("com.alibaba.dubbo.rpc.service.GenericException");
if (GenericException.class.isAssignableFrom(clazz)) {
return (Class<? extends org.apache.dubbo.rpc.service.GenericException>) clazz;
} else {
return null;
}
} catch (Throwable e) {
return null;
}
}
private static Constructor<? extends org.apache.dubbo.rpc.service.GenericException> 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<? extends org.apache.dubbo.rpc.service.GenericException> 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;
}
}
}

View File

@ -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";
}

View File

@ -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<T> {
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<T> {
private void loadDirectory(Map<String, Class<?>> 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<T> {
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<T> {
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);
}

View File

@ -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<Class<?>> {
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;
}

View File

@ -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<Object> {
// 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();

View File

@ -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<Class<? extends Annotation>> SERVICE_ANNOTATION_CLASSES = unmodifiableList(asList(DubboService.class, Service.class, com.alibaba.dubbo.config.annotation.Service.class));
public static List<Class<? extends Annotation>> SERVICE_ANNOTATION_CLASSES = loadServiceAnnotationClasses();
private static List<Class<? extends Annotation>> 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;

View File

@ -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<T> 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)) {

View File

@ -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");

View File

@ -41,21 +41,18 @@ class ActivateComparatorTest {
Filter2 f2 = new Filter2();
Filter3 f3 = new Filter3();
Filter4 f4 = new Filter4();
OldFilter5 f5 = new OldFilter5();
List<Class<?>> 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));
}
}
}
}

View File

@ -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<Annotation> 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);
}
}

View File

@ -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

View File

@ -33,6 +33,11 @@
<artifactId>dubbo-config-spring</artifactId>
<version>${project.parent.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-qos</artifactId>
@ -88,6 +93,12 @@
<version>${project.parent.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-metadata-processor</artifactId>
<version>${project.parent.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-metadata-report-zookeeper</artifactId>

View File

@ -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 <T> ExtensionLoader<T> getExtensionLoader(Class<T> 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<ActivateExt1> 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);
}
}

View File

@ -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);
}

View File

@ -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;
}
}

View File

@ -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<Class<?>> 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));
}
}

View File

@ -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 {
}

View File

@ -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{
}

View File

@ -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{
}

View File

@ -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{
}

View File

@ -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{
}

View File

@ -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 {
}

View File

@ -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 {
}

View File

@ -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 {
}

View File

@ -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<String, Object> 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<String, Object> 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<String, Object> 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<Annotation> 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<Annotation> 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<Annotation> 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<Object> set1 = new HashSet<>();
metaAnnotations.forEach(t -> set1.add(t.annotationType()));
HashSet<Object> set2 = new HashSet<>();
set2.add(Inherited.class);
set2.add(Deprecated.class);
assertEquals(2, metaAnnotations.size());
assertEquals(set1, set2);
}
@Test
void testGetAllMetaAnnotations() {
List<Annotation> metaAnnotations = getAllMetaAnnotations(Service5.class);
int offset = 0;
HashSet<Object> set1 = new HashSet<>();
metaAnnotations.forEach(t -> set1.add(t.annotationType()));
HashSet<Object> 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<Object> set3 = new HashSet<>();
metaAnnotations.forEach(t -> set3.add(t.annotationType()));
HashSet<Object> 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<DubboService> 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<Annotation> 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);
}
}

View File

@ -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();
}

View File

@ -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();
}

View File

@ -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);
}

View File

@ -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:
* <prev>
* &lt;dubbo:application name="dubbo-demo-application"/&gt;
* </prev>
*
* @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:
* <prev>
* &lt;dubbo:registry id="my-registry" address="N/A"/&gt;
* </prev>
*
* @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:
* <prev>
* &lt;dubbo:protocol name="dubbo" port="12345"/&gt;
* </prev>
*
* @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 {
}
};
}
}

View File

@ -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();
}
}

View File

@ -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());
}
}

View File

@ -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<ProtocolConfig> 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 {
}
}

View File

@ -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 {
}
};
}
}
}

View File

@ -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:
* <prev>
* &lt;dubbo:application name="dubbo-demo-application"/&gt;
* </prev>
*
* @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:
* <prev>
* &lt;dubbo:registry address="N/A"/&gt;
* </prev>
*
* @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;
}
}
}

View File

@ -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;
}
}
}

View File

@ -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;
}
}

View File

@ -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!");
}
}

View File

@ -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;
}
}

View File

@ -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:
* <prev>
* &lt;dubbo:application name="dubbo-demo-application"/&gt;
* </prev>
*
* @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:
* <prev>
* &lt;dubbo:registry id="my-registry" address="N/A"/&gt;
* </prev>
*
* @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:
* <prev>
* &lt;dubbo:protocol name="dubbo" port="12345"/&gt;
* </prev>
*
* @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());
}
};
}
}

View File

@ -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 {
}

View File

@ -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 {
}

View File

@ -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);
}
}

View File

@ -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<DemoService> exporter = protocol.export(proxyFactory.getInvoker(server, DemoService.class, url));
// simulate normal invoke
ReferenceConfig<com.alibaba.dubbo.rpc.service.GenericService> 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);

View File

@ -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<AbstractAnnotationProcessingTest> 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<Class<?>> classesToBeCompiled);
protected abstract void beforeEach();
protected TypeElement getType(Class<?> type) {
return TypeUtils.getType(processingEnv, type);
}
}

View File

@ -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<Void> invocation;
private final ReflectiveInvocationContext<Method> invocationContext;
private final ExtensionContext extensionContext;
public AnnotationProcessingTestProcessor(AbstractAnnotationProcessingTest abstractAnnotationProcessingTest, InvocationInterceptor.Invocation<Void> invocation,
ReflectiveInvocationContext<Method> invocationContext,
ExtensionContext extensionContext) {
this.abstractAnnotationProcessingTest = abstractAnnotationProcessingTest;
this.invocation = invocation;
this.invocationContext = invocationContext;
this.extensionContext = extensionContext;
}
@Override
public boolean process(Set<? extends TypeElement> 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();
}
}

View File

@ -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<Void> invocation,
ReflectiveInvocationContext<Method> invocationContext,
ExtensionContext extensionContext) throws Throwable {
Set<Class<?>> 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]));
}
}

View File

@ -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<Class<?>> 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<TypeDefinition, TypeDefinition>... assertions) {
Map<String, TypeDefinition> 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));
}
}

View File

@ -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<Class<?>> 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>", "java.lang.String", builder);
buildAndAssertTypeDefinition(processingEnv, colorsField, "java.util.List<org.apache.dubbo.metadata.annotation.processing.model.Color>",
"org.apache.dubbo.metadata.annotation.processing.model.Color", builder);
buildAndAssertTypeDefinition(processingEnv, primitiveTypeModelsField,
"java.util.Queue<org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel>",
"org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel", builder);
buildAndAssertTypeDefinition(processingEnv, modelsField,
"java.util.Deque<org.apache.dubbo.metadata.annotation.processing.model.Model>",
"org.apache.dubbo.metadata.annotation.processing.model.Model", builder);
buildAndAssertTypeDefinition(processingEnv, modelArraysField,
"java.util.Set<org.apache.dubbo.metadata.annotation.processing.model.Model[]>",
"org.apache.dubbo.metadata.annotation.processing.model.Model[]", builder);
}
}

View File

@ -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<Class<?>> 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<String, TypeDefinition> 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());
}
}

View File

@ -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<Class<?>> 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() {
}
}

View File

@ -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<Class<?>> 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>",
"java.lang.String",
"java.lang.String",
builder);
buildAndAssertTypeDefinition(processingEnv, colorsField,
"java.util.SortedMap<java.lang.String,org.apache.dubbo.metadata.annotation.processing.model.Color>",
"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>",
"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>",
"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[]>",
"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<TypeDefinition, TypeDefinition>... assertions) {
Map<String, TypeDefinition> 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));
}
}

View File

@ -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<Class<?>> 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<String, TypeDefinition> 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());
}
}

View File

@ -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<Class<?>> 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<String> 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<TypeDefinition> types) {
for (TypeDefinition typeDefinition : types) {
if (type.equals(typeDefinition.getType())) {
return typeDefinition.getType();
}
}
return type;
}
}

View File

@ -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<Class<?>> 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);
}
}

View File

@ -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
}

View File

@ -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<String> strings; // The composite element is simple type
private List<Color> colors; // The composite element is Enum type
private Queue<PrimitiveTypeModel> primitiveTypeModels; // The composite element is POJO type
private Deque<Model> models; // The composite element is hierarchical POJO type
private Set<Model[]> modelArrays; // The composite element is hierarchical POJO type
}

View File

@ -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;
}
}

View File

@ -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<String, String> strings; // The composite element is simple type
private SortedMap<String, Color> colors; // The composite element is Enum type
private NavigableMap<Color, PrimitiveTypeModel> primitiveTypeModels; // The composite element is POJO type
private HashMap<String, Model> models; // The composite element is hierarchical POJO type
private TreeMap<PrimitiveTypeModel, Model[]> modelArrays; // The composite element is hierarchical POJO type
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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());
}
}

View File

@ -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<Class<?>> 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<AnnotationMirror> annotations = getAnnotations(testType);
Iterator<AnnotationMirror> 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<AnnotationMirror> 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"));
}
}

View File

@ -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<Class<?>> classesToBeCompiled) {
}
@Override
protected void beforeEach() {
testType = getType(TestServiceImpl.class);
}
@Test
void testGetDeclaredFields() {
TypeElement type = getType(Model.class);
List<VariableElement> 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<VariableElement> 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<VariableElement> 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<VariableElement> 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<VariableElement> 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<VariableElement> 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());
}
}

View File

@ -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");
}
}

View File

@ -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<Class<?>> 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<? extends Element> members = getAllDeclaredMembers(testType.asType());
List<VariableElement> fields = fieldsIn(members);
assertTrue(hasModifiers(fields.get(0), PRIVATE));
}
@Test
void testDeclaredMembers() {
TypeElement type = getType(Model.class);
List<? extends Element> members = getDeclaredMembers(type.asType());
List<VariableElement> 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"));
}
}

View File

@ -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<Class<?>> classesToBeCompiled) {
}
@Override
protected void beforeEach() {
testType = getType(TestServiceImpl.class);
}
@Test
void testDeclaredMethods() {
TypeElement type = getType(Model.class);
List<ExecutableElement> 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<? extends ExecutableElement> doGetAllDeclaredMethods() {
return getAllDeclaredMethods(testType, Object.class);
}
@Test
void testGetAllDeclaredMethods() {
List<? extends ExecutableElement> methods = doGetAllDeclaredMethods();
assertEquals(14, methods.size());
}
@Test
void testGetPublicNonStaticMethods() {
List<? extends ExecutableElement> methods = getPublicNonStaticMethods(testType, Object.class);
assertEquals(14, methods.size());
methods = getPublicNonStaticMethods(testType.asType(), Object.class);
assertEquals(14, methods.size());
}
@Test
void testIsMethod() {
List<? extends ExecutableElement> methods = getPublicNonStaticMethods(testType, Object.class);
assertEquals(14, methods.stream().map(MethodUtils::isMethod).count());
}
@Test
void testIsPublicNonStaticMethod() {
List<? extends ExecutableElement> 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<? extends ExecutableElement> 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);
}
}

View File

@ -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<Class<?>> 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)));
}
}

View File

@ -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<Class<?>> 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<TypeMirror> 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<? extends TypeMirror> interfaces = getAllInterfaces(testType.asType());
assertEquals(4, interfaces.size());
Iterator<? extends TypeMirror> 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<TypeElement> allInterfaces = getAllInterfaces(testType);
assertEquals(4, interfaces.size());
Iterator<TypeElement> 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<DeclaredType> 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<DeclaredType> 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<TypeElement> 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));
}
}

View File

@ -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<String, Object> data, String param) {
return null;
}
@Override
public Map<String, Object> requestBodyUser(User user) {
return null;
}
public User user(User user) {
return user;
}
}

View File

@ -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<String, Object> data, String param);
Map<String, Object> requestBodyUser(User user);
}

View File

@ -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<String, Object> 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<String, Object> requestBodyUser(@RequestBody User user) {
Map<String, Object> map = new HashMap<>();
map.put("id", user.getId());
map.put("name", user.getName());
map.put("age", user.getAge());
return map;
}
}

View File

@ -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<String, Object> 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<String, Object> requestBodyUser(User user) {
Map<String, Object> map = new HashMap<>();
map.put("id", user.getId());
map.put("name", user.getName());
map.put("age", user.getAge());
return map;
}
}

View File

@ -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 + '}';
}
}

View File

@ -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;
}
}

View File

@ -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<Processor> 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<? extends JavaFileObject> 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;
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
return false;
}
public ProcessingEnvironment getProcessingEnvironment() {
return super.processingEnv;
}
public SourceVersion getSupportedSourceVersion(){
return latestSupported();
}
}

View File

@ -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
<T> 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);
}

View File

@ -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 {
}
}

Some files were not shown because too many files have changed in this diff Show More