index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/RestServiceTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.tools; import org.apache.dubbo.metadata.rest.RestService; import org.apache.dubbo.metadata.rest.SpringRestService; import org.apache.dubbo.metadata.rest.StandardRestService; import org.apache.dubbo.metadata.rest.User; import java.io.IOException; import org.junit.jupiter.api.Test; /** * {@link RestService} Test * * @since 2.7.6 */ class RestServiceTest { @Test void test() throws IOException { Compiler compiler = new Compiler(); compiler.compile(User.class, RestService.class, StandardRestService.class, SpringRestService.class); } }
7,100
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/Compiler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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; } }
7,101
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/DefaultTestService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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; } }
7,102
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/CompilerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.IOException; import org.junit.jupiter.api.Test; /** * The Compiler test case */ class CompilerTest { @Test void testCompile() throws IOException { Compiler compiler = new Compiler(); compiler.compile(TestServiceImpl.class, DefaultTestService.class, GenericTestService.class); } }
7,103
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/Ancestor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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; } }
7,104
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/Parent.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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; } }
7,105
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/TestService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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); }
7,106
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/GenericTestService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.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; } }
7,107
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/AnnotationProcessingTestProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 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 org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.InvocationInterceptor; import org.junit.jupiter.api.extension.ReflectiveInvocationContext; 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(); } }
7,108
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/AbstractAnnotationProcessingTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 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; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.extension.ExtendWith; /** * 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); } }
7,109
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/CompilerInvocationInterceptor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 java.lang.reflect.Method; import java.util.LinkedHashSet; import java.util.Set; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.InvocationInterceptor; import org.junit.jupiter.api.extension.ReflectiveInvocationContext; 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])); } }
7,110
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 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 org.junit.jupiter.api.Test; import org.springframework.web.bind.annotation.GetMapping; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.findAnnotation; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.findMetaAnnotation; 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(1, annotations.size()); // assertEquals("com.alibaba.dubbo.config.annotation.Service", // iterator.next().getAnnotationType().toString()); assertEquals( "org.apache.dubbo.config.annotation.Service", iterator.next().getAnnotationType().toString()); annotations = getAnnotations(testType, Service.class); 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(4, annotations.size()); annotations = getAllAnnotations(testType.asType(), annotation -> true); assertEquals(4, annotations.size()); annotations = getAllAnnotations(processingEnv, TestServiceImpl.class); assertEquals(4, annotations.size()); annotations = getAllAnnotations(testType.asType(), Service.class); assertEquals(3, annotations.size()); annotations = getAllAnnotations(testType, Override.class); assertEquals(0, annotations.size()); // annotations = getAllAnnotations(testType.asType(), com.alibaba.dubbo.config.annotation.Service.class); // assertEquals(2, annotations.size()); 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")); } }
7,111
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MemberUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 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 org.junit.jupiter.api.Test; 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")); } }
7,112
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MethodUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 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 org.junit.jupiter.api.Test; 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); } }
7,113
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/LoggerUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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"); } }
7,114
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/FieldUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 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 org.junit.jupiter.api.Test; 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()); } }
7,115
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/TypeUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 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 org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; 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)); } }
7,116
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 javax.lang.model.element.TypeElement; import java.util.LinkedHashSet; import java.util.Set; import org.junit.jupiter.api.Test; 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))); } }
7,117
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/SimpleTypeModel.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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; } }
7,118
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/ArrayTypeModel.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 }
7,119
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/MapTypeModel.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 }
7,120
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/PrimitiveTypeModel.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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; } }
7,121
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/CollectionTypeModel.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 }
7,122
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/Model.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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; } }
7,123
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/Color.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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; } }
7,124
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ArrayTypeDefinitionBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 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 org.junit.jupiter.api.Test; 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)); } }
7,125
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/EnumTypeDefinitionBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 javax.lang.model.element.TypeElement; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.junit.jupiter.api.Test; 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()); } }
7,126
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/SimpleTypeDefinitionBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import java.util.Set; import org.junit.jupiter.api.Test; 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); } }
7,127
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/CollectionTypeDefinitionBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import java.util.Set; import org.junit.jupiter.api.Test; 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); } }
7,128
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ServiceDefinitionBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 java.util.Arrays; import java.util.List; import java.util.Set; import org.junit.jupiter.api.Test; 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; } }
7,129
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/MapTypeDefinitionBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 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 org.junit.jupiter.api.Test; 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)); } }
7,130
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/GeneralTypeDefinitionBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 java.util.Set; import org.junit.jupiter.api.Test; 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() {} }
7,131
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/PrimitiveTypeDefinitionBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 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 org.junit.jupiter.api.Test; 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()); } }
7,132
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/rest/AnnotatedMethodParameterProcessorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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()); } }
7,133
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/DefaultRestService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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; } }
7,134
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/User.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 + '}'; } }
7,135
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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; } }
7,136
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.rest; import org.apache.dubbo.config.annotation.DubboService; import java.util.HashMap; import java.util.Map; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * Spring MVC {@link RestService} * * @since 2.7.6 */ @DubboService(version = "2.0.0", group = "spring") @RestController public class SpringRestService implements RestService { @Override @GetMapping(value = "/param") public String param(@RequestParam(defaultValue = "value-param") String param) { return null; } @Override @PostMapping("/params") public String params( @RequestParam(defaultValue = "value-a") int a, @RequestParam(defaultValue = "value-b") String b) { return null; } @Override @GetMapping("/headers") public String headers( @RequestHeader(name = "h", defaultValue = "value-h") String header, @RequestHeader(name = "h2", defaultValue = "value-h2") String header2, @RequestParam(value = "v", defaultValue = "1") Integer param) { return null; } @Override @GetMapping("/path-variables/{p1}/{p2}") public String pathVariables( @PathVariable("p1") String path1, @PathVariable("p2") String path2, @RequestParam("v") String param) { return null; } @Override @PostMapping("/form") public String form(@RequestParam("f") String form) { return String.valueOf(form); } @Override @PostMapping(value = "/request/body/map", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public User requestBodyMap(@RequestBody Map<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; } }
7,137
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/RestService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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); }
7,138
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/ServiceDefinitionMetadataAnnotationProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.common.utils.JsonUtils; import org.apache.dubbo.metadata.definition.model.ServiceDefinition; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.element.TypeElement; import java.util.LinkedList; import java.util.List; import java.util.Set; import static javax.lang.model.util.ElementFilter.typesIn; import static org.apache.dubbo.metadata.annotation.processing.builder.ServiceDefinitionBuilder.build; /** * The {@link Processor} class to generate the metadata of {@link ServiceDefinition} whose classes are annotated by Dubbo's @Service * * @see Processor * @since 2.7.6 */ public class ServiceDefinitionMetadataAnnotationProcessor extends AbstractServiceAnnotationProcessor { private List<ServiceDefinition> serviceDefinitions = new LinkedList<>(); @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { typesIn(roundEnv.getRootElements()).forEach(serviceType -> process(processingEnv, serviceType, annotations)); if (roundEnv.processingOver()) { ClassPathMetadataStorage writer = new ClassPathMetadataStorage(processingEnv); writer.write(() -> JsonUtils.toJson(serviceDefinitions), "META-INF/dubbo/service-definitions.json"); } return false; } private void process( ProcessingEnvironment processingEnv, TypeElement serviceType, Set<? extends TypeElement> annotations) { serviceDefinitions.add(build(processingEnv, serviceType)); } }
7,139
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/ClassPathMetadataStorage.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 javax.annotation.processing.Filer; import javax.annotation.processing.ProcessingEnvironment; import javax.tools.FileObject; import java.io.File; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; import static java.util.Optional.empty; import static java.util.Optional.ofNullable; import static javax.tools.StandardLocation.CLASS_OUTPUT; import static org.apache.dubbo.metadata.annotation.processing.util.LoggerUtils.info; import static org.apache.dubbo.metadata.annotation.processing.util.LoggerUtils.warn; /** * A storage class for metadata under class path */ public class ClassPathMetadataStorage { private final Filer filer; public ClassPathMetadataStorage(ProcessingEnvironment processingEnv) { this.filer = processingEnv.getFiler(); } public void write(Supplier<String> contentSupplier, String resourceName) { try (Writer writer = getWriter(resourceName)) { writer.write(contentSupplier.get()); } catch (IOException e) { throw new RuntimeException(e); } } public <T> Optional<T> read(String resourceName, Function<Reader, T> consumer) { if (exists(resourceName)) { try (Reader reader = getReader(resourceName)) { return ofNullable(consumer.apply(reader)); } catch (IOException e) { throw new RuntimeException(e); } } return empty(); } private boolean exists(String resourceName) { return getResource(resourceName) .map(FileObject::toUri) .map(File::new) .map(File::exists) .orElse(false); } private Reader getReader(String resourceName) { return getResource(resourceName) .map(fileObject -> { try { return fileObject.openReader(false); } catch (IOException e) { } return null; }) .orElse(null); } private FileObject createResource(String resourceName) throws IOException { return filer.createResource(CLASS_OUTPUT, "", resourceName); } private Optional<FileObject> getResource(String resourceName) { try { FileObject fileObject = filer.getResource(CLASS_OUTPUT, "", resourceName); return ofNullable(fileObject); } catch (IOException e) { warn(e.getMessage()); } return empty(); } private Writer getWriter(String resourceName) throws IOException { FileObject fileObject = createResource(resourceName); info( "The resource[path : %s , deleted : %s] will be written", fileObject.toUri().getPath(), fileObject.delete()); return fileObject.openWriter(); } }
7,140
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/AbstractServiceAnnotationProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.util.Elements; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import static javax.lang.model.util.ElementFilter.methodsIn; import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.SUPPORTED_ANNOTATION_TYPES; /** * Abstract {@link Processor} for the classes that were annotated by Dubbo's @Service * * @since 2.7.6 */ public abstract class AbstractServiceAnnotationProcessor extends AbstractProcessor { protected Elements elements; private List<? extends Element> objectMembers; public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); this.elements = processingEnv.getElementUtils(); this.objectMembers = elements.getAllMembers(elements.getTypeElement(Object.class.getName())); } protected List<? extends Element> getActualMembers(TypeElement type) { List<? extends Element> members = new LinkedList<>(elements.getAllMembers(type)); members.removeAll(objectMembers); return members; } protected List<? extends ExecutableElement> getActualMethods(TypeElement type) { return methodsIn(getActualMembers(type)); } protected Map<String, ExecutableElement> getActualMethodsMap(TypeElement type) { Map<String, ExecutableElement> methodsMap = new HashMap<>(); getActualMethods(type).forEach(method -> { methodsMap.put(method.toString(), method); }); return methodsMap; } public static String getMethodSignature(ExecutableElement method) { if (!ElementKind.METHOD.equals(method.getKind())) { throw new IllegalArgumentException("The argument must be Method Kind"); } StringBuilder methodSignatureBuilder = new StringBuilder(); method.getModifiers().forEach(member -> { methodSignatureBuilder.append(member).append(' '); }); methodSignatureBuilder.append(method.getReturnType()).append(' ').append(method.toString()); return methodSignatureBuilder.toString(); } protected TypeElement getTypeElement(CharSequence className) { return elements.getTypeElement(className); } protected PackageElement getPackageElement(Element type) { return this.elements.getPackageOf(type); } @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latest(); } @Override public final Set<String> getSupportedAnnotationTypes() { return SUPPORTED_ANNOTATION_TYPES; } }
7,141
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/ExecutableElementComparator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.common.utils.CharSequenceComparator; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.VariableElement; import java.util.Comparator; import java.util.List; /** * The Comparator class for {@link ExecutableElement}, the comparison rule : * <ol> * <li>Comparing to two {@link ExecutableElement#getSimpleName() element names} {@link String#compareTo(String) lexicographically}. * If equals, go to step 2</li> * <li>Comparing to the count of two parameters. If equals, go to step 3</li> * <li>Comparing to the type names of parameters {@link String#compareTo(String) lexicographically}</li> * </ol> * * @since 2.7.6 */ public class ExecutableElementComparator implements Comparator<ExecutableElement> { public static final ExecutableElementComparator INSTANCE = new ExecutableElementComparator(); private ExecutableElementComparator() {} @Override public int compare(ExecutableElement e1, ExecutableElement e2) { if (e1.equals(e2)) { return 0; } // Step 1 int value = CharSequenceComparator.INSTANCE.compare(e1.getSimpleName(), e2.getSimpleName()); if (value == 0) { // Step 2 List<? extends VariableElement> ps1 = e1.getParameters(); List<? extends VariableElement> ps2 = e1.getParameters(); value = ps1.size() - ps2.size(); if (value == 0) { // Step 3 for (int i = 0; i < ps1.size(); i++) { value = CharSequenceComparator.INSTANCE.compare( ps1.get(i).getSimpleName(), ps2.get(i).getSimpleName()); if (value != 0) { break; } } } } return Integer.compare(value, 0); } }
7,142
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/TypeUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.common.utils.ClassUtils; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.tools.FileObject; import javax.tools.StandardLocation; import java.io.IOException; import java.lang.reflect.Type; import java.net.URL; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.function.Predicate; import static java.lang.String.valueOf; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.emptySet; import static java.util.stream.Collectors.toSet; import static java.util.stream.Stream.of; import static java.util.stream.StreamSupport.stream; import static javax.lang.model.element.ElementKind.ANNOTATION_TYPE; import static javax.lang.model.element.ElementKind.CLASS; import static javax.lang.model.element.ElementKind.ENUM; import static javax.lang.model.element.ElementKind.INTERFACE; import static org.apache.dubbo.common.function.Predicates.EMPTY_ARRAY; import static org.apache.dubbo.common.function.Streams.filterAll; import static org.apache.dubbo.common.function.Streams.filterFirst; import static org.apache.dubbo.common.utils.MethodUtils.invokeMethod; /** * The utilities class for type in the package "javax.lang.model.*" * * @since 2.7.6 */ public interface TypeUtils { List<String> SIMPLE_TYPES = asList(ClassUtils.SIMPLE_TYPES.stream().map(Class::getName).toArray(String[]::new)); static boolean isSimpleType(Element element) { return element != null && isSimpleType(element.asType()); } static boolean isSimpleType(TypeMirror type) { return type != null && SIMPLE_TYPES.contains(type.toString()); } static boolean isSameType(TypeMirror type, CharSequence typeName) { if (type == null || typeName == null) { return false; } return Objects.equals(valueOf(type), valueOf(typeName)); } static boolean isSameType(TypeMirror typeMirror, Type type) { return type != null && isSameType(typeMirror, type.getTypeName()); } static boolean isArrayType(TypeMirror type) { return type != null && TypeKind.ARRAY.equals(type.getKind()); } static boolean isArrayType(Element element) { return element != null && isArrayType(element.asType()); } static boolean isEnumType(TypeMirror type) { DeclaredType declaredType = ofDeclaredType(type); return declaredType != null && ENUM.equals(declaredType.asElement().getKind()); } static boolean isEnumType(Element element) { return element != null && isEnumType(element.asType()); } static boolean isClassType(TypeMirror type) { DeclaredType declaredType = ofDeclaredType(type); return declaredType != null && isClassType(declaredType.asElement()); } static boolean isClassType(Element element) { return element != null && CLASS.equals(element.getKind()); } static boolean isPrimitiveType(TypeMirror type) { return type != null && type.getKind().isPrimitive(); } static boolean isPrimitiveType(Element element) { return element != null && isPrimitiveType(element.asType()); } static boolean isInterfaceType(TypeMirror type) { DeclaredType declaredType = ofDeclaredType(type); return declaredType != null && isInterfaceType(declaredType.asElement()); } static boolean isInterfaceType(Element element) { return element != null && INTERFACE.equals(element.getKind()); } static boolean isAnnotationType(TypeMirror type) { DeclaredType declaredType = ofDeclaredType(type); return declaredType != null && isAnnotationType(declaredType.asElement()); } static boolean isAnnotationType(Element element) { return element != null && ANNOTATION_TYPE.equals(element.getKind()); } static Set<TypeElement> getHierarchicalTypes(TypeElement type) { return getHierarchicalTypes(type, true, true, true); } static Set<DeclaredType> getHierarchicalTypes(TypeMirror type) { return getHierarchicalTypes(type, EMPTY_ARRAY); } static Set<DeclaredType> getHierarchicalTypes(TypeMirror type, Predicate<DeclaredType>... typeFilters) { return filterAll(ofDeclaredTypes(getHierarchicalTypes(ofTypeElement(type))), typeFilters); } static Set<DeclaredType> getHierarchicalTypes(TypeMirror type, Type... excludedTypes) { return getHierarchicalTypes( type, of(excludedTypes).map(Type::getTypeName).toArray(String[]::new)); } static Set<DeclaredType> getHierarchicalTypes(TypeMirror type, CharSequence... excludedTypeNames) { Set<String> typeNames = of(excludedTypeNames).map(CharSequence::toString).collect(toSet()); return getHierarchicalTypes(type, t -> !typeNames.contains(t.toString())); } static Set<TypeElement> getHierarchicalTypes( TypeElement type, boolean includeSelf, boolean includeSuperTypes, boolean includeSuperInterfaces, Predicate<TypeElement>... typeFilters) { if (type == null) { return emptySet(); } Set<TypeElement> hierarchicalTypes = new LinkedHashSet<>(); if (includeSelf) { hierarchicalTypes.add(type); } if (includeSuperTypes) { hierarchicalTypes.addAll(getAllSuperTypes(type)); } if (includeSuperInterfaces) { hierarchicalTypes.addAll(getAllInterfaces(type)); } return filterAll(hierarchicalTypes, typeFilters); } static Set<DeclaredType> getHierarchicalTypes( TypeMirror type, boolean includeSelf, boolean includeSuperTypes, boolean includeSuperInterfaces) { return ofDeclaredTypes( getHierarchicalTypes(ofTypeElement(type), includeSelf, includeSuperTypes, includeSuperInterfaces)); } static List<TypeMirror> getInterfaces(TypeElement type, Predicate<TypeMirror>... interfaceFilters) { return type == null ? emptyList() : filterAll((List<TypeMirror>) ofTypeElement(type).getInterfaces(), interfaceFilters); } static List<TypeMirror> getInterfaces(TypeMirror type, Predicate<TypeMirror>... interfaceFilters) { return getInterfaces(ofTypeElement(type), interfaceFilters); } static Set<TypeElement> getAllInterfaces(TypeElement type, Predicate<TypeElement>... interfaceFilters) { return type == null ? emptySet() : filterAll(ofTypeElements(getAllInterfaces(type.asType())), interfaceFilters); } static Set<? extends TypeMirror> getAllInterfaces(TypeMirror type, Predicate<TypeMirror>... interfaceFilters) { if (type == null) { return emptySet(); } Set<TypeMirror> allInterfaces = new LinkedHashSet<>(); getInterfaces(type).forEach(i -> { // Add current type's interfaces allInterfaces.add(i); // Add allInterfaces.addAll(getAllInterfaces(i)); }); // Add all super types' interfaces getAllSuperTypes(type).forEach(superType -> allInterfaces.addAll(getAllInterfaces(superType))); return filterAll(allInterfaces, interfaceFilters); } static TypeMirror findInterface(TypeMirror type, CharSequence interfaceClassName) { return filterFirst(getAllInterfaces(type), t -> isSameType(t, interfaceClassName)); } static TypeElement getType(ProcessingEnvironment processingEnv, Type type) { return type == null ? null : getType(processingEnv, type.getTypeName()); } static TypeElement getType(ProcessingEnvironment processingEnv, TypeMirror type) { return type == null ? null : getType(processingEnv, type.toString()); } static TypeElement getType(ProcessingEnvironment processingEnv, CharSequence typeName) { if (processingEnv == null || typeName == null) { return null; } Elements elements = processingEnv.getElementUtils(); return elements.getTypeElement(typeName); } static TypeElement getSuperType(TypeElement type) { return type == null ? null : ofTypeElement(type.getSuperclass()); } static DeclaredType getSuperType(TypeMirror type) { TypeElement superType = getSuperType(ofTypeElement(type)); return superType == null ? null : ofDeclaredType(superType.asType()); } static Set<TypeElement> getAllSuperTypes(TypeElement type) { return getAllSuperTypes(type, EMPTY_ARRAY); } static Set<TypeElement> getAllSuperTypes(TypeElement type, Predicate<TypeElement>... typeFilters) { if (type == null) { return emptySet(); } Set<TypeElement> allSuperTypes = new LinkedHashSet<>(); TypeElement superType = getSuperType(type); if (superType != null) { // add super type allSuperTypes.add(superType); // add ancestors' types allSuperTypes.addAll(getAllSuperTypes(superType)); } return filterAll(allSuperTypes, typeFilters); } static Set<DeclaredType> getAllSuperTypes(TypeMirror type) { return getAllSuperTypes(type, EMPTY_ARRAY); } static Set<DeclaredType> getAllSuperTypes(TypeMirror type, Predicate<DeclaredType>... typeFilters) { return filterAll(ofDeclaredTypes(getAllSuperTypes(ofTypeElement(type))), typeFilters); } static boolean isDeclaredType(Element element) { return element != null && isDeclaredType(element.asType()); } static boolean isDeclaredType(TypeMirror type) { return type instanceof DeclaredType; } static DeclaredType ofDeclaredType(Element element) { return element == null ? null : ofDeclaredType(element.asType()); } static DeclaredType ofDeclaredType(TypeMirror type) { return isDeclaredType(type) ? (DeclaredType) type : null; } static boolean isTypeElement(Element element) { return element instanceof TypeElement; } static boolean isTypeElement(TypeMirror type) { DeclaredType declaredType = ofDeclaredType(type); return declaredType != null && isTypeElement(declaredType.asElement()); } static TypeElement ofTypeElement(Element element) { return isTypeElement(element) ? (TypeElement) element : null; } static TypeElement ofTypeElement(TypeMirror type) { DeclaredType declaredType = ofDeclaredType(type); if (declaredType != null) { return ofTypeElement(declaredType.asElement()); } return null; } static Set<DeclaredType> ofDeclaredTypes(Iterable<? extends Element> elements) { return elements == null ? emptySet() : stream(elements.spliterator(), false) .map(TypeUtils::ofTypeElement) .filter(Objects::nonNull) .map(Element::asType) .map(TypeUtils::ofDeclaredType) .filter(Objects::nonNull) .collect(LinkedHashSet::new, Set::add, Set::addAll); } static Set<TypeElement> ofTypeElements(Iterable<? extends TypeMirror> types) { return types == null ? emptySet() : stream(types.spliterator(), false) .map(TypeUtils::ofTypeElement) .filter(Objects::nonNull) .collect(LinkedHashSet::new, Set::add, Set::addAll); } static List<DeclaredType> listDeclaredTypes(Iterable<? extends Element> elements) { return new ArrayList<>(ofDeclaredTypes(elements)); } static List<TypeElement> listTypeElements(Iterable<? extends TypeMirror> types) { return new ArrayList<>(ofTypeElements(types)); } static URL getResource(ProcessingEnvironment processingEnv, Element type) { return getResource(processingEnv, ofDeclaredType(type)); } static URL getResource(ProcessingEnvironment processingEnv, TypeMirror type) { return type == null ? null : getResource(processingEnv, type.toString()); } static URL getResource(ProcessingEnvironment processingEnv, CharSequence type) { String relativeName = getResourceName(type); URL resource = null; try { if (relativeName != null) { FileObject fileObject = processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", relativeName); resource = fileObject.toUri().toURL(); // try to open it resource.getContent(); } } catch (IOException e) { throw new RuntimeException(e); } return resource; } static String getResourceName(CharSequence type) { return type == null ? null : type.toString().replace('.', '/').concat(".class"); } static String toString(TypeMirror type) { TypeElement element = ofTypeElement(type); if (element != null) { List<? extends TypeParameterElement> typeParameterElements = element.getTypeParameters(); if (!typeParameterElements.isEmpty()) { List<? extends TypeMirror> typeMirrors; if (type instanceof DeclaredType) { typeMirrors = ((DeclaredType) type).getTypeArguments(); } else { typeMirrors = invokeMethod(type, "getTypeArguments"); } StringBuilder typeBuilder = new StringBuilder(element.toString()); typeBuilder.append('<'); for (int i = 0; i < typeMirrors.size(); i++) { if (i > 0) { typeBuilder.append(", "); } typeBuilder.append(typeMirrors.get(i).toString()); } typeBuilder.append('>'); return typeBuilder.toString(); } } return type.toString(); } }
7,143
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/MethodUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import java.lang.reflect.Type; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static javax.lang.model.element.ElementKind.METHOD; import static javax.lang.model.util.ElementFilter.methodsIn; import static org.apache.dubbo.common.function.Predicates.EMPTY_ARRAY; import static org.apache.dubbo.common.function.Streams.filter; import static org.apache.dubbo.common.function.Streams.filterAll; import static org.apache.dubbo.common.function.Streams.filterFirst; import static org.apache.dubbo.metadata.annotation.processing.util.MemberUtils.getDeclaredMembers; 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.TypeUtils.getHierarchicalTypes; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.ofDeclaredType; /** * The utilities class for method in the package "javax.lang.model." * * @since 2.7.6 */ public interface MethodUtils { static List<ExecutableElement> getDeclaredMethods(TypeElement type, Predicate<ExecutableElement>... methodFilters) { return type == null ? emptyList() : getDeclaredMethods(type.asType(), methodFilters); } static List<ExecutableElement> getDeclaredMethods(TypeMirror type, Predicate<ExecutableElement>... methodFilters) { return filterAll(methodsIn(getDeclaredMembers(type)), methodFilters); } static List<ExecutableElement> getAllDeclaredMethods( TypeElement type, Predicate<ExecutableElement>... methodFilters) { return type == null ? emptyList() : getAllDeclaredMethods(type.asType(), methodFilters); } static List<ExecutableElement> getAllDeclaredMethods(TypeElement type) { return getAllDeclaredMethods(type, EMPTY_ARRAY); } static List<ExecutableElement> getAllDeclaredMethods( TypeMirror type, Predicate<ExecutableElement>... methodFilters) { return getHierarchicalTypes(type).stream() .map(t -> getDeclaredMethods(t, methodFilters)) .flatMap(Collection::stream) .collect(Collectors.toList()); } static List<ExecutableElement> getAllDeclaredMethods(TypeMirror type) { return getAllDeclaredMethods(type, EMPTY_ARRAY); } static List<ExecutableElement> getAllDeclaredMethods(TypeElement type, Type... excludedTypes) { return type == null ? emptyList() : getAllDeclaredMethods(type.asType(), excludedTypes); } static List<ExecutableElement> getAllDeclaredMethods(TypeMirror type, Type... excludedTypes) { return getHierarchicalTypes(type, excludedTypes).stream() .map(t -> getDeclaredMethods(t)) .flatMap(Collection::stream) .collect(Collectors.toList()); } static List<ExecutableElement> getPublicNonStaticMethods(TypeElement type, Type... excludedTypes) { return getPublicNonStaticMethods(ofDeclaredType(type), excludedTypes); } static List<ExecutableElement> getPublicNonStaticMethods(TypeMirror type, Type... excludedTypes) { return filter(getAllDeclaredMethods(type, excludedTypes), MethodUtils::isPublicNonStaticMethod); } static boolean isMethod(ExecutableElement method) { return method != null && METHOD.equals(method.getKind()); } static boolean isPublicNonStaticMethod(ExecutableElement method) { return isMethod(method) && isPublicNonStatic(method); } static ExecutableElement findMethod( TypeElement type, String methodName, Type oneParameterType, Type... otherParameterTypes) { return type == null ? null : findMethod(type.asType(), methodName, oneParameterType, otherParameterTypes); } static ExecutableElement findMethod( TypeMirror type, String methodName, Type oneParameterType, Type... otherParameterTypes) { List<Type> parameterTypes = new LinkedList<>(); parameterTypes.add(oneParameterType); parameterTypes.addAll(asList(otherParameterTypes)); return findMethod( type, methodName, parameterTypes.stream().map(Type::getTypeName).toArray(String[]::new)); } static ExecutableElement findMethod(TypeElement type, String methodName, CharSequence... parameterTypes) { return type == null ? null : findMethod(type.asType(), methodName, parameterTypes); } static ExecutableElement findMethod(TypeMirror type, String methodName, CharSequence... parameterTypes) { return filterFirst( getAllDeclaredMethods(type), method -> methodName.equals(method.getSimpleName().toString()), method -> matchParameterTypes(method.getParameters(), parameterTypes)); } static ExecutableElement getOverrideMethod( ProcessingEnvironment processingEnv, TypeElement type, ExecutableElement declaringMethod) { Elements elements = processingEnv.getElementUtils(); return filterFirst(getAllDeclaredMethods(type), method -> elements.overrides(method, declaringMethod, type)); } static String getMethodName(ExecutableElement method) { return method == null ? null : method.getSimpleName().toString(); } static String getReturnType(ExecutableElement method) { return method == null ? null : TypeUtils.toString(method.getReturnType()); } static String[] getMethodParameterTypes(ExecutableElement method) { return method == null ? new String[0] : method.getParameters().stream() .map(VariableElement::asType) .map(TypeUtils::toString) .toArray(String[]::new); } }
7,144
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/LoggerUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import static java.lang.String.format; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_METADATA_PROCESSOR; /** * Logger Utils * * @since 2.7.6 */ public interface LoggerUtils { ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger("dubbo-metadata-processor"); static void info(String format, Object... args) { if (LOGGER.isInfoEnabled()) { LOGGER.info(format(format, args)); } } static void warn(String format, Object... args) { if (LOGGER.isWarnEnabled()) { LOGGER.warn(COMMON_METADATA_PROCESSOR, "", "", format(format, args)); } } }
7,145
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/MemberUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import static java.util.Collections.emptyList; 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.TypeUtils.getHierarchicalTypes; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.ofTypeElement; /** * The utilities class for the members in the package "javax.lang.model.", such as "field", "method", "constructor" * * @since 2.7.6 */ public interface MemberUtils { static boolean matches(Element member, ElementKind kind) { return member == null || kind == null ? false : kind.equals(member.getKind()); } static boolean isPublicNonStatic(Element member) { return hasModifiers(member, PUBLIC) && !hasModifiers(member, STATIC); } static boolean hasModifiers(Element member, Modifier... modifiers) { if (member == null || modifiers == null) { return false; } Set<Modifier> actualModifiers = member.getModifiers(); for (Modifier modifier : modifiers) { if (!actualModifiers.contains(modifier)) { return false; } } return true; } static List<? extends Element> getDeclaredMembers(TypeMirror type) { TypeElement element = ofTypeElement(type); return element == null ? emptyList() : element.getEnclosedElements(); } static List<? extends Element> getAllDeclaredMembers(TypeMirror type) { return getHierarchicalTypes(type).stream() .map(MemberUtils::getDeclaredMembers) .flatMap(Collection::stream) .collect(Collectors.toList()); } static boolean matchParameterTypes(List<? extends VariableElement> parameters, CharSequence... parameterTypes) { int size = parameters.size(); if (size != parameterTypes.length) { return false; } for (int i = 0; i < size; i++) { VariableElement parameter = parameters.get(i); if (!Objects.equals(parameter.asType().toString(), parameterTypes[i])) { return false; } } return true; } }
7,146
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.AnnotatedConstruct; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.type.ArrayType; import javax.lang.model.type.TypeMirror; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.Type; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Predicate; import java.util.stream.Collectors; import static java.lang.Enum.valueOf; import static java.util.Collections.emptyList; import static org.apache.dubbo.common.function.Predicates.EMPTY_ARRAY; import static org.apache.dubbo.common.function.Streams.filterAll; import static org.apache.dubbo.common.function.Streams.filterFirst; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getHierarchicalTypes; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getType; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isSameType; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isTypeElement; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.ofTypeElement; /** * The utilities class for annotation in the package "javax.lang.model.*" * * @since 2.7.6 */ public interface AnnotationUtils { static AnnotationMirror getAnnotation( AnnotatedConstruct annotatedConstruct, Class<? extends Annotation> annotationClass) { return annotationClass == null ? null : getAnnotation(annotatedConstruct, annotationClass.getTypeName()); } static AnnotationMirror getAnnotation(AnnotatedConstruct annotatedConstruct, CharSequence annotationClassName) { List<AnnotationMirror> annotations = getAnnotations(annotatedConstruct, annotationClassName); return annotations.isEmpty() ? null : annotations.get(0); } static List<AnnotationMirror> getAnnotations( AnnotatedConstruct annotatedConstruct, Class<? extends Annotation> annotationClass) { return annotationClass == null ? emptyList() : getAnnotations(annotatedConstruct, annotationClass.getTypeName()); } static List<AnnotationMirror> getAnnotations( AnnotatedConstruct annotatedConstruct, CharSequence annotationClassName) { return getAnnotations( annotatedConstruct, annotation -> isSameType(annotation.getAnnotationType(), annotationClassName)); } static List<AnnotationMirror> getAnnotations(AnnotatedConstruct annotatedConstruct) { return getAnnotations(annotatedConstruct, EMPTY_ARRAY); } static List<AnnotationMirror> getAnnotations( AnnotatedConstruct annotatedConstruct, Predicate<AnnotationMirror>... annotationFilters) { AnnotatedConstruct actualAnnotatedConstruct = annotatedConstruct; if (annotatedConstruct instanceof TypeMirror) { actualAnnotatedConstruct = ofTypeElement((TypeMirror) actualAnnotatedConstruct); } return actualAnnotatedConstruct == null ? emptyList() : filterAll( (List<AnnotationMirror>) actualAnnotatedConstruct.getAnnotationMirrors(), annotationFilters); } static List<AnnotationMirror> getAllAnnotations(TypeMirror type) { return getAllAnnotations(ofTypeElement(type)); } static List<AnnotationMirror> getAllAnnotations(Element element) { return getAllAnnotations(element, EMPTY_ARRAY); } static List<AnnotationMirror> getAllAnnotations(TypeMirror type, Class<? extends Annotation> annotationClass) { return getAllAnnotations(ofTypeElement(type), annotationClass); } static List<AnnotationMirror> getAllAnnotations(Element element, Class<? extends Annotation> annotationClass) { return element == null || annotationClass == null ? emptyList() : getAllAnnotations(element, annotationClass.getTypeName()); } static List<AnnotationMirror> getAllAnnotations(TypeMirror type, CharSequence annotationClassName) { return getAllAnnotations(ofTypeElement(type), annotationClassName); } static List<AnnotationMirror> getAllAnnotations(Element element, CharSequence annotationClassName) { return getAllAnnotations( element, annotation -> isSameType(annotation.getAnnotationType(), annotationClassName)); } static List<AnnotationMirror> getAllAnnotations(TypeMirror type, Predicate<AnnotationMirror>... annotationFilters) { return getAllAnnotations(ofTypeElement(type), annotationFilters); } static List<AnnotationMirror> getAllAnnotations(Element element, Predicate<AnnotationMirror>... annotationFilters) { List<AnnotationMirror> allAnnotations = isTypeElement(element) ? getHierarchicalTypes(ofTypeElement(element)).stream() .map(AnnotationUtils::getAnnotations) .flatMap(Collection::stream) .collect(Collectors.toList()) : element == null ? emptyList() : (List<AnnotationMirror>) element.getAnnotationMirrors(); return filterAll(allAnnotations, annotationFilters); } static List<AnnotationMirror> getAllAnnotations(ProcessingEnvironment processingEnv, Type annotatedType) { return getAllAnnotations(processingEnv, annotatedType, EMPTY_ARRAY); } static List<AnnotationMirror> getAllAnnotations( ProcessingEnvironment processingEnv, Type annotatedType, Predicate<AnnotationMirror>... annotationFilters) { return annotatedType == null ? emptyList() : getAllAnnotations(processingEnv, annotatedType.getTypeName(), annotationFilters); } static List<AnnotationMirror> getAllAnnotations( ProcessingEnvironment processingEnv, CharSequence annotatedTypeName, Predicate<AnnotationMirror>... annotationFilters) { return getAllAnnotations(getType(processingEnv, annotatedTypeName), annotationFilters); } static AnnotationMirror findAnnotation(TypeMirror type, Class<? extends Annotation> annotationClass) { return annotationClass == null ? null : findAnnotation(type, annotationClass.getTypeName()); } static AnnotationMirror findAnnotation(TypeMirror type, CharSequence annotationClassName) { return findAnnotation(ofTypeElement(type), annotationClassName); } static AnnotationMirror findAnnotation(Element element, Class<? extends Annotation> annotationClass) { return annotationClass == null ? null : findAnnotation(element, annotationClass.getTypeName()); } static AnnotationMirror findAnnotation(Element element, CharSequence annotationClassName) { return filterFirst(getAllAnnotations( element, annotation -> isSameType(annotation.getAnnotationType(), annotationClassName))); } static AnnotationMirror findMetaAnnotation(Element annotatedConstruct, CharSequence metaAnnotationClassName) { return annotatedConstruct == null ? null : getAnnotations(annotatedConstruct).stream() .map(annotation -> findAnnotation(annotation.getAnnotationType(), metaAnnotationClassName)) .filter(Objects::nonNull) .findFirst() .orElse(null); } static boolean isAnnotationPresent(Element element, CharSequence annotationClassName) { return findAnnotation(element, annotationClassName) != null || findMetaAnnotation(element, annotationClassName) != null; } static <T> T getAttribute(AnnotationMirror annotation, String attributeName) { return annotation == null ? null : getAttribute(annotation.getElementValues(), attributeName); } static <T> T getAttribute( Map<? extends ExecutableElement, ? extends AnnotationValue> attributesMap, String attributeName) { T annotationValue = null; for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : attributesMap.entrySet()) { ExecutableElement attributeMethod = entry.getKey(); if (Objects.equals(attributeName, attributeMethod.getSimpleName().toString())) { TypeMirror attributeType = attributeMethod.getReturnType(); AnnotationValue value = entry.getValue(); if (attributeType instanceof ArrayType) { // array-typed attribute values ArrayType arrayType = (ArrayType) attributeType; String componentType = arrayType.getComponentType().toString(); ClassLoader classLoader = AnnotationUtils.class.getClassLoader(); List<AnnotationValue> values = (List<AnnotationValue>) value.getValue(); int size = values.size(); try { Class componentClass = classLoader.loadClass(componentType); boolean isEnum = componentClass.isEnum(); Object array = Array.newInstance(componentClass, values.size()); for (int i = 0; i < size; i++) { Object element = values.get(i).getValue(); if (isEnum) { element = valueOf(componentClass, element.toString()); } Array.set(array, i, element); } annotationValue = (T) array; } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } else { annotationValue = (T) value.getValue(); } break; } } return annotationValue; } static <T> T getValue(AnnotationMirror annotation) { return (T) getAttribute(annotation, "value"); } }
7,147
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.TypeElement; import java.util.LinkedHashSet; import java.util.Objects; import java.util.Set; import static java.lang.String.valueOf; import static java.util.Arrays.asList; import static java.util.Collections.unmodifiableSet; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getAttribute; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.isAnnotationPresent; /** * The utilities class for @Service annotation * * @since 2.7.6 */ public interface ServiceAnnotationUtils { /** * The class name of @Service * * @deprecated Recommend {@link #DUBBO_SERVICE_ANNOTATION_TYPE} */ @Deprecated String SERVICE_ANNOTATION_TYPE = "org.apache.dubbo.config.annotation.Service"; /** * The class name of the legacy @Service * * @deprecated Recommend {@link #DUBBO_SERVICE_ANNOTATION_TYPE} */ @Deprecated String LEGACY_SERVICE_ANNOTATION_TYPE = "com.alibaba.dubbo.config.annotation.Service"; /** * The class name of @DubboService * * @since 2.7.9 */ String DUBBO_SERVICE_ANNOTATION_TYPE = "org.apache.dubbo.config.annotation.DubboService"; /** * the attribute name of @Service.interfaceClass() */ String INTERFACE_CLASS_ATTRIBUTE_NAME = "interfaceClass"; /** * the attribute name of @Service.interfaceName() */ String INTERFACE_NAME_ATTRIBUTE_NAME = "interfaceName"; /** * the attribute name of @Service.group() */ String GROUP_ATTRIBUTE_NAME = "group"; /** * the attribute name of @Service.version() */ String VERSION_ATTRIBUTE_NAME = "version"; Set<String> SUPPORTED_ANNOTATION_TYPES = unmodifiableSet(new LinkedHashSet<>( asList(DUBBO_SERVICE_ANNOTATION_TYPE, SERVICE_ANNOTATION_TYPE, LEGACY_SERVICE_ANNOTATION_TYPE))); static boolean isServiceAnnotationPresent(TypeElement annotatedType) { return SUPPORTED_ANNOTATION_TYPES.stream() .filter(type -> isAnnotationPresent(annotatedType, type)) .findFirst() .isPresent(); } static AnnotationMirror getAnnotation(TypeElement annotatedClass) { return getAnnotation(annotatedClass.getAnnotationMirrors()); } static AnnotationMirror getAnnotation(Iterable<? extends AnnotationMirror> annotationMirrors) { AnnotationMirror matchedAnnotationMirror = null; MAIN: for (String supportedAnnotationType : SUPPORTED_ANNOTATION_TYPES) { // Prioritized for (AnnotationMirror annotationMirror : annotationMirrors) { String annotationType = annotationMirror.getAnnotationType().toString(); if (Objects.equals(supportedAnnotationType, annotationType)) { matchedAnnotationMirror = annotationMirror; break MAIN; } } } if (matchedAnnotationMirror == null) { throw new IllegalArgumentException( "The annotated element must be annotated any of " + SUPPORTED_ANNOTATION_TYPES); } return matchedAnnotationMirror; } static String resolveServiceInterfaceName(TypeElement annotatedClass, AnnotationMirror serviceAnnotation) { Object interfaceClass = getAttribute(serviceAnnotation, INTERFACE_CLASS_ATTRIBUTE_NAME); if (interfaceClass == null) { // try to find the "interfaceName" attribute interfaceClass = getAttribute(serviceAnnotation, INTERFACE_NAME_ATTRIBUTE_NAME); } if (interfaceClass == null) { // last, get the interface class from first one interfaceClass = ((TypeElement) annotatedClass).getInterfaces().get(0); } return valueOf(interfaceClass); } static String getGroup(AnnotationMirror serviceAnnotation) { return getAttribute(serviceAnnotation, GROUP_ATTRIBUTE_NAME); } static String getVersion(AnnotationMirror serviceAnnotation) { return getAttribute(serviceAnnotation, VERSION_ATTRIBUTE_NAME); } }
7,148
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/FieldUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 javax.lang.model.element.Element; import javax.lang.model.element.Modifier; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import java.util.Collection; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; import static java.util.Collections.emptyList; import static javax.lang.model.element.ElementKind.ENUM_CONSTANT; import static javax.lang.model.element.ElementKind.FIELD; import static javax.lang.model.element.Modifier.STATIC; import static javax.lang.model.util.ElementFilter.fieldsIn; import static org.apache.dubbo.common.function.Predicates.EMPTY_ARRAY; import static org.apache.dubbo.common.function.Streams.filterAll; import static org.apache.dubbo.common.function.Streams.filterFirst; 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.matches; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getHierarchicalTypes; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isEnumType; /** * The utilities class for the field in the package "javax.lang.model." * * @since 2.7.6 */ public interface FieldUtils { static List<VariableElement> getDeclaredFields(Element element, Predicate<VariableElement>... fieldFilters) { return element == null ? emptyList() : getDeclaredFields(element.asType(), fieldFilters); } static List<VariableElement> getDeclaredFields(Element element) { return getDeclaredFields(element, EMPTY_ARRAY); } static List<VariableElement> getDeclaredFields(TypeMirror type, Predicate<VariableElement>... fieldFilters) { return filterAll(fieldsIn(getDeclaredMembers(type)), fieldFilters); } static List<VariableElement> getDeclaredFields(TypeMirror type) { return getDeclaredFields(type, EMPTY_ARRAY); } static List<VariableElement> getAllDeclaredFields(Element element, Predicate<VariableElement>... fieldFilters) { return element == null ? emptyList() : getAllDeclaredFields(element.asType(), fieldFilters); } static List<VariableElement> getAllDeclaredFields(Element element) { return getAllDeclaredFields(element, EMPTY_ARRAY); } static List<VariableElement> getAllDeclaredFields(TypeMirror type, Predicate<VariableElement>... fieldFilters) { return getHierarchicalTypes(type).stream() .map(t -> getDeclaredFields(t, fieldFilters)) .flatMap(Collection::stream) .collect(Collectors.toList()); } static List<VariableElement> getAllDeclaredFields(TypeMirror type) { return getAllDeclaredFields(type, EMPTY_ARRAY); } static VariableElement getDeclaredField(Element element, String fieldName) { return element == null ? null : getDeclaredField(element.asType(), fieldName); } static VariableElement getDeclaredField(TypeMirror type, String fieldName) { return filterFirst(getDeclaredFields( type, field -> fieldName.equals(field.getSimpleName().toString()))); } static VariableElement findField(Element element, String fieldName) { return element == null ? null : findField(element.asType(), fieldName); } static VariableElement findField(TypeMirror type, String fieldName) { return filterFirst(getAllDeclaredFields(type, field -> equals(field, fieldName))); } /** * is Enum's member field or not * * @param field {@link VariableElement} must be public static final fields * @return if field is public static final, return <code>true</code>, or <code>false</code> */ static boolean isEnumMemberField(VariableElement field) { if (field == null || !isEnumType(field.getEnclosingElement())) { return false; } return ENUM_CONSTANT.equals(field.getKind()); } static boolean isNonStaticField(VariableElement field) { return isField(field) && !hasModifiers(field, STATIC); } static boolean isField(VariableElement field) { return matches(field, FIELD) || isEnumMemberField(field); } static boolean isField(VariableElement field, Modifier... modifiers) { return isField(field) && hasModifiers(field, modifiers); } static List<VariableElement> getNonStaticFields(TypeMirror type) { return getDeclaredFields(type, FieldUtils::isNonStaticField); } static List<VariableElement> getNonStaticFields(Element element) { return element == null ? emptyList() : getNonStaticFields(element.asType()); } static List<VariableElement> getAllNonStaticFields(TypeMirror type) { return getAllDeclaredFields(type, FieldUtils::isNonStaticField); } static List<VariableElement> getAllNonStaticFields(Element element) { return element == null ? emptyList() : getAllNonStaticFields(element.asType()); } static boolean equals(VariableElement field, CharSequence fieldName) { return field != null && fieldName != null && field.getSimpleName().toString().equals(fieldName.toString()); } }
7,149
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/DeclaredTypeDefinitionBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.ofDeclaredType; /** * An interface of {@link TypeBuilder} for {@link DeclaredType} * * @since 2.7.6 */ public interface DeclaredTypeDefinitionBuilder extends TypeBuilder<DeclaredType> { @Override default boolean accept(ProcessingEnvironment processingEnv, TypeMirror type) { DeclaredType declaredType = ofDeclaredType(type); if (declaredType == null) { return false; } return accept(processingEnv, declaredType); } /** * Test the specified {@link DeclaredType type} is accepted or not * * @param processingEnv {@link ProcessingEnvironment} * @param type {@link DeclaredType type} * @return <code>true</code> if accepted */ boolean accept(ProcessingEnvironment processingEnv, DeclaredType type); }
7,150
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/MethodDefinitionBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.definition.model.MethodDefinition; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.ExecutableElement; import java.util.List; import java.util.Map; import java.util.stream.Collectors; 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.getReturnType; /** * A Builder class for {@link MethodDefinition} * * @see MethodDefinition * @since 2.7.6 */ public interface MethodDefinitionBuilder { static MethodDefinition build( ProcessingEnvironment processingEnv, ExecutableElement method, Map<String, TypeDefinition> typeCache) { MethodDefinition methodDefinition = new MethodDefinition(); methodDefinition.setName(getMethodName(method)); methodDefinition.setReturnType(getReturnType(method)); methodDefinition.setParameterTypes(getMethodParameterTypes(method)); methodDefinition.setParameters(getMethodParameters(processingEnv, method, typeCache)); return methodDefinition; } static List<TypeDefinition> getMethodParameters( ProcessingEnvironment processingEnv, ExecutableElement method, Map<String, TypeDefinition> typeCache) { return method.getParameters().stream() .map(element -> TypeDefinitionBuilder.build(processingEnv, element, typeCache)) .collect(Collectors.toList()); } }
7,151
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/PrimitiveTypeDefinitionBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.definition.model.TypeDefinition; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.type.PrimitiveType; import javax.lang.model.type.TypeMirror; import java.util.Map; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isPrimitiveType; /** * {@link TypeBuilder} for Java {@link PrimitiveType primitve type} * * @since 2.7.6 */ public class PrimitiveTypeDefinitionBuilder implements TypeBuilder<PrimitiveType> { @Override public boolean accept(ProcessingEnvironment processingEnv, TypeMirror type) { return isPrimitiveType(type); } @Override public TypeDefinition build( ProcessingEnvironment processingEnv, PrimitiveType type, Map<String, TypeDefinition> typeCache) { TypeDefinition typeDefinition = new TypeDefinition(type.toString()); return typeDefinition; } @Override public int getPriority() { return MIN_PRIORITY - 3; } }
7,152
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/TypeBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.common.extension.SPI; import org.apache.dubbo.common.lang.Prioritized; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.type.TypeMirror; import java.util.Map; @SPI public interface TypeBuilder<T extends TypeMirror> extends Prioritized { /** * Test the specified {@link TypeMirror type} is accepted or not * * @param processingEnv {@link ProcessingEnvironment} * @param type {@link TypeMirror type} * @return <code>true</code> if accepted */ boolean accept(ProcessingEnvironment processingEnv, TypeMirror type); /** * Build the instance of {@link TypeDefinition} * * @param processingEnv {@link ProcessingEnvironment} * @param type {@link T type} * @return an instance of {@link TypeDefinition} */ TypeDefinition build(ProcessingEnvironment processingEnv, T type, Map<String, TypeDefinition> typeCache); }
7,153
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/ArrayTypeDefinitionBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.definition.model.TypeDefinition; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.type.ArrayType; import javax.lang.model.type.TypeMirror; import java.lang.reflect.Array; import java.util.Map; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isArrayType; /** * {@link TypeBuilder} for Java {@link Array} * * @since 2.7.6 */ public class ArrayTypeDefinitionBuilder implements TypeBuilder<ArrayType> { @Override public boolean accept(ProcessingEnvironment processingEnv, TypeMirror type) { return isArrayType(type); } @Override public TypeDefinition build( ProcessingEnvironment processingEnv, ArrayType type, Map<String, TypeDefinition> typeCache) { TypeDefinition typeDefinition = new TypeDefinition(type.toString()); TypeMirror componentType = type.getComponentType(); TypeDefinition subTypeDefinition = TypeDefinitionBuilder.build(processingEnv, componentType, typeCache); typeDefinition.getItems().add(subTypeDefinition.getType()); return typeDefinition; } @Override public int getPriority() { return MIN_PRIORITY - 4; } }
7,154
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/SimpleTypeDefinitionBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.util.TypeUtils; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.type.DeclaredType; import java.util.Map; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isSimpleType; /** * {@link TypeBuilder} for {@link TypeUtils#SIMPLE_TYPES Java Simple Type} * * @since 2.7.6 */ public class SimpleTypeDefinitionBuilder implements DeclaredTypeDefinitionBuilder { @Override public boolean accept(ProcessingEnvironment processingEnv, DeclaredType type) { return isSimpleType(type); } @Override public TypeDefinition build( ProcessingEnvironment processingEnv, DeclaredType type, Map<String, TypeDefinition> typeCache) { TypeDefinition td = new TypeDefinition(type.toString()); return td; } @Override public int getPriority() { return MIN_PRIORITY - 1; } }
7,155
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/ServiceDefinitionBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.definition.model.ServiceDefinition; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.TypeElement; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getPublicNonStaticMethods; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getHierarchicalTypes; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getResourceName; /** * A Builder for {@link ServiceDefinition} * * @see ServiceDefinition * @since 2.7.6 */ public interface ServiceDefinitionBuilder { static ServiceDefinition build(ProcessingEnvironment processingEnv, TypeElement type) { ServiceDefinition serviceDefinition = new ServiceDefinition(); serviceDefinition.setCanonicalName(type.toString()); serviceDefinition.setCodeSource(getResourceName(type.toString())); Map<String, TypeDefinition> types = new HashMap<>(); // Get all super types and interface excluding the specified type // and then the result will be added into ServiceDefinition#getTypes() getHierarchicalTypes(type.asType(), Object.class) .forEach(t -> TypeDefinitionBuilder.build(processingEnv, t, types)); // Get all declared methods that will be added into ServiceDefinition#getMethods() getPublicNonStaticMethods(type, Object.class).stream() .map(method -> MethodDefinitionBuilder.build(processingEnv, method, types)) .forEach(serviceDefinition.getMethods()::add); serviceDefinition.setTypes(new ArrayList<>(types.values())); return serviceDefinition; } }
7,156
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/TypeDefinitionBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.common.lang.Prioritized; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import org.apache.dubbo.rpc.model.ApplicationModel; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Element; import javax.lang.model.type.TypeMirror; import java.util.Map; /** * A class builds the instance of {@link TypeDefinition} * * @since 2.7.6 */ public interface TypeDefinitionBuilder<T extends TypeMirror> extends Prioritized { /** * Build the instance of {@link TypeDefinition} from the specified {@link Element element} * * @param processingEnv {@link ProcessingEnvironment} * @param element {@link Element source element} * @return non-null */ static TypeDefinition build( ProcessingEnvironment processingEnv, Element element, Map<String, TypeDefinition> typeCache) { TypeDefinition typeDefinition = build(processingEnv, element.asType(), typeCache); // Comment this code for the compatibility // typeDefinition.set$ref(element.toString()); return typeDefinition; } /** * Build the instance of {@link TypeDefinition} from the specified {@link TypeMirror type} * * @param processingEnv {@link ProcessingEnvironment} * @param type {@link TypeMirror type} * @return non-null */ static TypeDefinition build( ProcessingEnvironment processingEnv, TypeMirror type, Map<String, TypeDefinition> typeCache) { // Build by all instances of TypeDefinitionBuilder that were loaded By Java SPI TypeDefinition typeDefinition = ApplicationModel.defaultModel() .getExtensionLoader(TypeBuilder.class) .getSupportedExtensionInstances() .stream() // load(TypeDefinitionBuilder.class, TypeDefinitionBuilder.class.getClassLoader()) .filter(builder -> builder.accept(processingEnv, type)) .findFirst() .map(builder -> { return builder.build(processingEnv, type, typeCache); // typeDefinition.setTypeBuilderName(builder.getClass().getName()); }) .orElse(null); if (typeDefinition != null) { typeCache.put(typeDefinition.getType(), typeDefinition); } return typeDefinition; } }
7,157
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/CollectionTypeDefinitionBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.definition.model.TypeDefinition; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import java.util.Collection; import java.util.Map; import java.util.Objects; /** * {@link TypeBuilder} for Java {@link Collection} * * @since 2.7.6 */ public class CollectionTypeDefinitionBuilder implements DeclaredTypeDefinitionBuilder { @Override public boolean accept(ProcessingEnvironment processingEnv, DeclaredType type) { Elements elements = processingEnv.getElementUtils(); TypeElement collectionTypeElement = elements.getTypeElement(Collection.class.getTypeName()); TypeMirror collectionType = collectionTypeElement.asType(); Types types = processingEnv.getTypeUtils(); TypeMirror erasedType = types.erasure(type); return types.isAssignable(erasedType, collectionType); } @Override public TypeDefinition build( ProcessingEnvironment processingEnv, DeclaredType type, Map<String, TypeDefinition> typeCache) { String typeName = type.toString(); TypeDefinition typeDefinition = new TypeDefinition(typeName); // Generic Type arguments type.getTypeArguments().stream() .map(typeArgument -> TypeDefinitionBuilder.build( processingEnv, typeArgument, typeCache)) // build the TypeDefinition from typeArgument .filter(Objects::nonNull) .map(TypeDefinition::getType) .forEach(typeDefinition.getItems()::add); // Add into the declared TypeDefinition return typeDefinition; } @Override public int getPriority() { return MIN_PRIORITY - 5; } }
7,158
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/GeneralTypeDefinitionBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.definition.model.TypeDefinition; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import java.util.Map; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.getNonStaticFields; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getType; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isClassType; /** * {@link TypeBuilder} for General Object * * @since 2.7.6 */ public class GeneralTypeDefinitionBuilder implements DeclaredTypeDefinitionBuilder { @Override public boolean accept(ProcessingEnvironment processingEnv, DeclaredType type) { return isClassType(type); } @Override public TypeDefinition build( ProcessingEnvironment processingEnv, DeclaredType type, Map<String, TypeDefinition> typeCache) { String typeName = type.toString(); TypeElement typeElement = getType(processingEnv, typeName); return buildProperties(processingEnv, typeElement, typeCache); } protected TypeDefinition buildProperties( ProcessingEnvironment processingEnv, TypeElement type, Map<String, TypeDefinition> typeCache) { TypeDefinition definition = new TypeDefinition(type.toString()); getNonStaticFields(type).forEach(field -> { String fieldName = field.getSimpleName().toString(); TypeDefinition propertyType = TypeDefinitionBuilder.build(processingEnv, field, typeCache); if (propertyType != null) { typeCache.put(propertyType.getType(), propertyType); definition.getProperties().put(fieldName, propertyType.getType()); } }); return definition; } @Override public int getPriority() { return MIN_PRIORITY; } }
7,159
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/MapTypeDefinitionBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.definition.model.TypeDefinition; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import java.util.Map; import java.util.Objects; /** * {@link TypeBuilder} for Java {@link Map} * * @since 2.7.6 */ public class MapTypeDefinitionBuilder implements DeclaredTypeDefinitionBuilder { @Override public boolean accept(ProcessingEnvironment processingEnv, DeclaredType type) { Elements elements = processingEnv.getElementUtils(); TypeElement mapTypeElement = elements.getTypeElement(Map.class.getTypeName()); TypeMirror mapType = mapTypeElement.asType(); Types types = processingEnv.getTypeUtils(); TypeMirror erasedType = types.erasure(type); return types.isAssignable(erasedType, mapType); } @Override public TypeDefinition build( ProcessingEnvironment processingEnv, DeclaredType type, Map<String, TypeDefinition> typeCache) { TypeDefinition typeDefinition = new TypeDefinition(type.toString()); // Generic Type arguments type.getTypeArguments().stream() .map(typeArgument -> TypeDefinitionBuilder.build( processingEnv, typeArgument, typeCache)) // build the TypeDefinition from typeArgument .filter(Objects::nonNull) .map(TypeDefinition::getType) .forEach(typeDefinition.getItems()::add); // Add into the declared TypeDefinition return typeDefinition; } @Override public int getPriority() { return MIN_PRIORITY - 6; } }
7,160
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/EnumTypeDefinitionBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.util.FieldUtils; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Element; import javax.lang.model.element.Name; import javax.lang.model.type.DeclaredType; import java.util.Map; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.getDeclaredFields; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isEnumType; /** * {@link TypeBuilder} for Java {@link Enum} * * @since 2.7.6 */ public class EnumTypeDefinitionBuilder implements DeclaredTypeDefinitionBuilder { @Override public boolean accept(ProcessingEnvironment processingEnv, DeclaredType type) { return isEnumType(type); } @Override public TypeDefinition build( ProcessingEnvironment processingEnv, DeclaredType type, Map<String, TypeDefinition> typeCache) { TypeDefinition typeDefinition = new TypeDefinition(type.toString()); getDeclaredFields(type, FieldUtils::isEnumMemberField).stream() .map(Element::getSimpleName) .map(Name::toString) .forEach(typeDefinition.getEnums()::add); return typeDefinition; } @Override public int getPriority() { return MIN_PRIORITY - 2; } }
7,161
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/AbstractServiceRestMetadataResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.annotation.processing.rest; import org.apache.dubbo.metadata.annotation.processing.util.ExecutableElementComparator; import org.apache.dubbo.metadata.definition.model.MethodDefinition; import org.apache.dubbo.metadata.rest.RequestMetadata; import org.apache.dubbo.metadata.rest.RestMethodMetadata; import org.apache.dubbo.metadata.rest.ServiceRestMetadata; import org.apache.dubbo.rpc.model.ApplicationModel; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.util.Elements; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import static java.lang.ThreadLocal.withInitial; import static java.util.Collections.emptyList; import static java.util.Collections.sort; import static java.util.Optional.empty; import static java.util.Optional.of; import static org.apache.dubbo.metadata.annotation.processing.builder.MethodDefinitionBuilder.build; import static org.apache.dubbo.metadata.annotation.processing.util.LoggerUtils.info; import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getOverrideMethod; import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getPublicNonStaticMethods; import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.getAnnotation; import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.getGroup; import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.getVersion; import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.resolveServiceInterfaceName; /** * Abstract {@link ServiceRestMetadataResolver} implementation * * @since 2.7.6 */ public abstract class AbstractServiceRestMetadataResolver implements ServiceRestMetadataResolver { private static final ThreadLocal<Map<String, Object>> threadLocalCache = withInitial(HashMap::new); private static final Map<String, List<AnnotatedMethodParameterProcessor>> parameterProcessorsMap = loadAnnotatedMethodParameterProcessors(); private final String processorName = getClass().getSimpleName(); @Override public final ServiceRestMetadata resolve( ProcessingEnvironment processingEnv, TypeElement serviceType, Set<? extends TypeElement> annotations) { info( "%s is processing the service type[%s] with annotations[%s]", processorName, serviceType, annotations.stream().map(t -> "@" + t.toString()).collect(Collectors.joining(","))); ServiceRestMetadata serviceRestMetadata = new ServiceRestMetadata(); Elements elements = processingEnv.getElementUtils(); try { AnnotationMirror serviceAnnotation = getAnnotation(serviceType); String serviceInterfaceName = resolveServiceInterfaceName(serviceType, serviceAnnotation); serviceRestMetadata.setServiceInterface(serviceInterfaceName); serviceRestMetadata.setGroup(getGroup(serviceAnnotation)); serviceRestMetadata.setVersion(getVersion(serviceAnnotation)); TypeElement serviceInterfaceType = elements.getTypeElement(serviceInterfaceName); List<? extends ExecutableElement> serviceMethods = new LinkedList<>(getPublicNonStaticMethods(serviceInterfaceType, Object.class)); // Sorts sort(serviceMethods, ExecutableElementComparator.INSTANCE); serviceMethods.forEach(serviceMethod -> { resolveRestMethodMetadata( processingEnv, serviceType, serviceInterfaceType, serviceMethod, serviceRestMetadata) .ifPresent(serviceRestMetadata.getMeta()::add); }); } finally { clearCache(); } info("The %s's process result : %s", processorName, serviceRestMetadata); return serviceRestMetadata; } protected Optional<RestMethodMetadata> resolveRestMethodMetadata( ProcessingEnvironment processingEnv, TypeElement serviceType, TypeElement serviceInterfaceType, ExecutableElement serviceMethod, ServiceRestMetadata serviceRestMetadata) { ExecutableElement restCapableMethod = findRestCapableMethod(processingEnv, serviceType, serviceInterfaceType, serviceMethod); if (restCapableMethod == null) { // if can't be found return empty(); } String requestPath = resolveRequestPath(processingEnv, serviceType, restCapableMethod); // requestPath is required if (requestPath == null) { return empty(); } String requestMethod = resolveRequestMethod(processingEnv, serviceType, restCapableMethod); // requestMethod is required if (requestMethod == null) { return empty(); } RestMethodMetadata metadata = new RestMethodMetadata(); MethodDefinition methodDefinition = resolveMethodDefinition(processingEnv, serviceType, restCapableMethod); // Set MethodDefinition metadata.setMethod(methodDefinition); // process the annotated method parameters processAnnotatedMethodParameters(restCapableMethod, serviceType, metadata); // process produces Set<String> produces = new LinkedHashSet<>(); processProduces(processingEnv, serviceType, restCapableMethod, produces); // process consumes Set<String> consumes = new LinkedHashSet<>(); processConsumes(processingEnv, serviceType, restCapableMethod, consumes); // Initialize RequestMetadata RequestMetadata request = metadata.getRequest(); request.setPath(requestPath); request.appendContextPathFromUrl(serviceRestMetadata.getContextPathFromUrl()); request.setMethod(requestMethod); request.setProduces(produces); request.setConsumes(consumes); // Post-Process postProcessRestMethodMetadata(processingEnv, serviceType, serviceMethod, metadata); return of(metadata); } /** * Find the method with the capable for REST from the specified service method and its override method * * @param processingEnv {@link ProcessingEnvironment} * @param serviceType * @param serviceInterfaceType * @param serviceMethod * @return <code>null</code> if can't be found */ private ExecutableElement findRestCapableMethod( ProcessingEnvironment processingEnv, TypeElement serviceType, TypeElement serviceInterfaceType, ExecutableElement serviceMethod) { // try to judge the override first ExecutableElement overrideMethod = getOverrideMethod(processingEnv, serviceType, serviceMethod); if (supports(processingEnv, serviceType, serviceInterfaceType, overrideMethod)) { return overrideMethod; } // or, try to judge the declared method return supports(processingEnv, serviceType, serviceInterfaceType, serviceMethod) ? serviceMethod : null; } /** * Does the specified method support REST or not ? * * @param processingEnv {@link ProcessingEnvironment} * @param method the method may be declared on the interface or class * @return if supports, return <code>true</code>, or <code>false</code> */ protected abstract boolean supports( ProcessingEnvironment processingEnv, TypeElement serviceType, TypeElement serviceInterfaceType, ExecutableElement method); /** * Post-Process for {@link RestMethodMetadata}, sub-type could override this method for further works * * @param processingEnv {@link ProcessingEnvironment} * @param serviceType The type that @Service annotated * @param method The public method of <code>serviceType</code> * @param metadata {@link RestMethodMetadata} maybe updated */ protected void postProcessRestMethodMetadata( ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method, RestMethodMetadata metadata) {} protected abstract String resolveRequestPath( ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method); protected abstract String resolveRequestMethod( ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method); protected MethodDefinition resolveMethodDefinition( ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method) { return build(processingEnv, method, new HashMap<>()); } protected void processAnnotatedMethodParameters( ExecutableElement method, TypeElement type, RestMethodMetadata metadata) { List<? extends VariableElement> methodParameters = method.getParameters(); int size = methodParameters.size(); for (int i = 0; i < size; i++) { VariableElement parameter = methodParameters.get(i); // Add indexed parameter name metadata.addIndexToName(i, parameter.getSimpleName().toString()); processAnnotatedMethodParameter(parameter, i, method, type, metadata); } } protected void processAnnotatedMethodParameter( VariableElement parameter, int parameterIndex, ExecutableElement method, TypeElement serviceType, RestMethodMetadata metadata) { parameter.getAnnotationMirrors().forEach(annotation -> { String annotationType = annotation.getAnnotationType().toString(); parameterProcessorsMap.getOrDefault(annotationType, emptyList()).forEach(parameterProcessor -> { parameterProcessor.process(annotation, parameter, parameterIndex, method, metadata); }); }); } protected abstract void processProduces( ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method, Set<String> produces); protected abstract void processConsumes( ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method, Set<String> consumes); protected static final void put(String name, Object value) { Map<String, Object> cache = getCache(); cache.put(name, value); } protected static final <T> T get(String name) throws ClassCastException { Map<String, Object> cache = getCache(); return (T) cache.get(name); } protected static final <V> V computeIfAbsent(String name, Function<? super String, ? extends V> mappingFunction) { return (V) getCache().computeIfAbsent(name, mappingFunction); } private static Map<String, List<AnnotatedMethodParameterProcessor>> loadAnnotatedMethodParameterProcessors() { Map<String, List<AnnotatedMethodParameterProcessor>> parameterProcessorsMap = new LinkedHashMap<>(); // load(AnnotatedMethodParameterProcessor.class, // AnnotatedMethodParameterProcessor.class.getClassLoader()) ApplicationModel.defaultModel() .getExtensionLoader(AnnotatedMethodParameterProcessor.class) .getSupportedExtensionInstances() .forEach(processor -> { List<AnnotatedMethodParameterProcessor> processors = parameterProcessorsMap.computeIfAbsent( processor.getAnnotationType(), k -> new LinkedList<>()); processors.add(processor); }); return parameterProcessorsMap; } private static Map<String, Object> getCache() { return threadLocalCache.get(); } private static void clearCache() { Map<String, Object> cache = getCache(); cache.clear(); threadLocalCache.remove(); } }
7,162
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/ServiceRestMetadataStorage.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.annotation.processing.rest; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.metadata.annotation.processing.ClassPathMetadataStorage; import org.apache.dubbo.metadata.rest.ServiceRestMetadata; import javax.annotation.processing.ProcessingEnvironment; import java.io.IOException; import java.util.Set; import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SERVICE_REST_METADATA_RESOURCE_PATH; /** * The storage for {@link ServiceRestMetadata} */ public class ServiceRestMetadataStorage { private final ClassPathMetadataStorage storage; public ServiceRestMetadataStorage(ProcessingEnvironment processingEnv) { this.storage = new ClassPathMetadataStorage(processingEnv); } public void append(Set<ServiceRestMetadata> serviceRestMetadata) throws IOException { // Add all existed ServiceRestMetadata storage.read(SERVICE_REST_METADATA_RESOURCE_PATH, reader -> { try { StringBuilder stringBuilder = new StringBuilder(); char[] buf = new char[1024]; int len; while ((len = reader.read(buf)) != -1) { stringBuilder.append(buf, 0, len); } return JsonUtils.toJavaList(stringBuilder.toString(), ServiceRestMetadata.class); } catch (IOException e) { return null; } }) .ifPresent(serviceRestMetadata::addAll); write(serviceRestMetadata); } public void write(Set<ServiceRestMetadata> serviceRestMetadata) throws IOException { if (serviceRestMetadata.isEmpty()) { return; } storage.write(() -> JsonUtils.toJson(serviceRestMetadata), SERVICE_REST_METADATA_RESOURCE_PATH); } }
7,163
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/AnnotatedMethodParameterProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.annotation.processing.rest; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.common.lang.Prioritized; import org.apache.dubbo.metadata.rest.RestMethodMetadata; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.VariableElement; /** * The interface to process the parameter of method that was annotated * * @since 2.7.6 */ @SPI public interface AnnotatedMethodParameterProcessor extends Prioritized { /** * The string presenting the annotation type * * @return non-null */ String getAnnotationType(); /** * Process the specified method {@link VariableElement parameter} * * @param annotation {@link AnnotationMirror the target annotation} whose type is {@link #getAnnotationType()} * @param parameter {@link VariableElement method parameter} * @param parameterIndex the index of parameter in the method * @param method {@link ExecutableElement method that parameter belongs to} * @param restMethodMetadata {@link RestMethodMetadata the metadata is used to update} */ void process( AnnotationMirror annotation, VariableElement parameter, int parameterIndex, ExecutableElement method, RestMethodMetadata restMethodMetadata); /** * Build the default value * * @param parameterIndex the index of parameter * @return the placeholder */ static String buildDefaultValue(int parameterIndex) { return "{" + parameterIndex + "}"; } }
7,164
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/ServiceRestMetadataResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.annotation.processing.rest; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.common.lang.Prioritized; import org.apache.dubbo.metadata.rest.ServiceRestMetadata; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.TypeElement; import java.util.Set; /** * The class to resolve {@link ServiceRestMetadata} based on Annotation Processor Tool * * @since 2.7.6 */ @SPI("default") public interface ServiceRestMetadataResolver extends Prioritized { /** * Supports or not to the specified service type * * @param processingEnvironment {@link ProcessingEnvironment} * @param serviceType Dubbo service type or interface * @return if supports, return <code>true</code>, or <code>false</code> */ boolean supports(ProcessingEnvironment processingEnvironment, TypeElement serviceType); /** * Resolve the {@link ServiceRestMetadata} from given service type * * @param processingEnvironment {@link ProcessingEnvironment} * @param serviceType Dubbo service type or interface * @param annotations * @return non-null */ ServiceRestMetadata resolve( ProcessingEnvironment processingEnvironment, TypeElement serviceType, Set<? extends TypeElement> annotations); }
7,165
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/ServiceRestMetadataAnnotationProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.annotation.processing.rest; import org.apache.dubbo.metadata.annotation.processing.AbstractServiceAnnotationProcessor; import org.apache.dubbo.metadata.rest.ServiceRestMetadata; import org.apache.dubbo.rpc.model.ApplicationModel; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.element.TypeElement; import java.io.IOException; import java.util.LinkedHashSet; import java.util.Set; import static javax.lang.model.util.ElementFilter.typesIn; import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.isServiceAnnotationPresent; /** * The {@link Processor} class to generate the metadata of REST from the classes that are annotated by Dubbo's * * @Service * @see Processor * @since 2.7.6 */ public class ServiceRestMetadataAnnotationProcessor extends AbstractServiceAnnotationProcessor { private Set<ServiceRestMetadataResolver> metadataProcessors; private ServiceRestMetadataStorage serviceRestMetadataWriter; private Set<ServiceRestMetadata> serviceRestMetadata = new LinkedHashSet<>(); @Override public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); this.metadataProcessors = ApplicationModel.defaultModel() .getExtensionLoader(ServiceRestMetadataResolver.class) .getSupportedExtensionInstances(); this.serviceRestMetadataWriter = new ServiceRestMetadataStorage(processingEnv); } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { typesIn(roundEnv.getRootElements()).forEach(serviceType -> process(processingEnv, serviceType, annotations)); if (roundEnv.processingOver()) { try { serviceRestMetadataWriter.append(serviceRestMetadata); } catch (IOException e) { throw new IllegalStateException(e); } } return false; } private void process( ProcessingEnvironment processingEnv, TypeElement serviceType, Set<? extends TypeElement> annotations) { metadataProcessors.stream() .filter(processor -> supports(processor, processingEnv, serviceType)) .map(processor -> processor.resolve(processingEnv, serviceType, annotations)) .forEach(serviceRestMetadata::add); } private boolean supports( ServiceRestMetadataResolver processor, ProcessingEnvironment processingEnv, TypeElement serviceType) { // @Service must be present in service type return isServiceAnnotationPresent(serviceType) && processor.supports(processingEnv, serviceType); } }
7,166
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/DefaultServiceRestMetadataResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.annotation.processing.rest; import org.apache.dubbo.common.convert.Converter; import org.apache.dubbo.common.convert.ConverterUtil; import org.apache.dubbo.metadata.annotation.processing.rest.jaxrs.JAXRSServiceRestMetadataResolver; import org.apache.dubbo.metadata.annotation.processing.rest.springmvc.SpringMvcServiceRestMetadataResolver; import org.apache.dubbo.rpc.model.FrameworkModel; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import java.util.HashSet; import java.util.List; import java.util.Set; import static java.lang.String.valueOf; import static java.util.Arrays.asList; import static org.apache.dubbo.common.utils.ClassUtils.forName; import static org.apache.dubbo.common.utils.StringUtils.SLASH_CHAR; import static org.apache.dubbo.metadata.annotation.processing.util.LoggerUtils.warn; import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.getAnnotation; import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.resolveServiceInterfaceName; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.findInterface; /** * The default implementation of {@link ServiceRestMetadataResolver} * * @since 2.7.6 */ public class DefaultServiceRestMetadataResolver extends AbstractServiceRestMetadataResolver { private static final char PACKAGE_SEPARATOR = '.'; private static final char PATH_SEPARATOR = SLASH_CHAR; private static final String HTTP_REQUEST_METHOD = "POST"; private static final List<String> MEDIA_TYPES = asList( "application/json;", "application/*+json", "application/xml;charset=UTF-8", "text/xml;charset=UTF-8", "application/*+xml;charset=UTF-8"); private final Set<ExecutableElement> hasComplexParameterTypeMethods = new HashSet<>(); @Override public boolean supports(ProcessingEnvironment processingEnvironment, TypeElement serviceType) { return !JAXRSServiceRestMetadataResolver.supports(serviceType) && !SpringMvcServiceRestMetadataResolver.supports(serviceType); } @Override protected boolean supports( ProcessingEnvironment processingEnv, TypeElement serviceType, TypeElement serviceInterfaceType, ExecutableElement method) { // TODO add some criterion return true; } @Override protected String resolveRequestPath( ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method) { AnnotationMirror serviceAnnotation = getAnnotation(serviceType); String serviceInterfaceName = resolveServiceInterfaceName(serviceType, serviceAnnotation); TypeMirror serviceInterface = findInterface(serviceType.asType(), serviceInterfaceName); StringBuilder requestPathBuilder = new StringBuilder(); // the name of service type as the root path String rootPath = buildRootPath(serviceInterface); // the method name as the sub path String subPath = buildSubPath(method); requestPathBuilder.append(rootPath).append(subPath); // the methods' parameters as the the path variables List<? extends VariableElement> parameters = method.getParameters(); for (int i = 0; i < parameters.size(); i++) { VariableElement parameter = parameters.get(i); TypeMirror parameterType = parameter.asType(); if (isComplexType(parameterType)) { if (addComplexParameterType(method)) { continue; } else { // The count of complex types must be only one, or return immediately warn( "The method[%s] contains more than one complex parameter type, " + "thus it will not be chosen as the REST service", method.toString()); } } String parameterName = parameter.getSimpleName().toString(); // If "-parameters" option is enabled, take the parameter name as the path variable name, // or use the index of parameter String pathVariableName = isEnabledParametersCompilerOption(parameterName) ? parameterName : valueOf(i); requestPathBuilder .append(PATH_SEPARATOR) .append('{') .append(pathVariableName) .append('}'); } return requestPathBuilder.toString(); } private String buildRootPath(TypeMirror serviceInterface) { return PATH_SEPARATOR + serviceInterface.toString().replace(PACKAGE_SEPARATOR, PATH_SEPARATOR); } private String buildSubPath(ExecutableElement method) { return PATH_SEPARATOR + method.getSimpleName().toString(); } private boolean isEnabledParametersCompilerOption(String parameterName) { return !parameterName.startsWith("arg"); } private boolean isComplexType(TypeMirror parameterType) { return !supportsPathVariableType(parameterType); } /** * Supports the type of parameter or not, based by {@link Converter}'s conversion feature * * @param parameterType the type of parameter * @return if supports, this method will return <code>true</code>, or <code>false</code> */ private boolean supportsPathVariableType(TypeMirror parameterType) { String className = parameterType.toString(); ClassLoader classLoader = getClass().getClassLoader(); boolean supported; try { Class<?> targetType = forName(className, classLoader); supported = FrameworkModel.defaultModel() .getBeanFactory() .getBean(ConverterUtil.class) .getConverter(String.class, targetType) != null; } catch (ClassNotFoundException e) { supported = false; } return supported; } @Override protected String resolveRequestMethod( ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method) { return HTTP_REQUEST_METHOD; } @Override protected void processProduces( ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method, Set<String> produces) { TypeMirror returnType = method.getReturnType(); if (isComplexType(returnType)) { produces.addAll(MEDIA_TYPES); } } @Override protected void processConsumes( ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method, Set<String> consumes) { if (hasComplexParameterType(method)) { consumes.addAll(MEDIA_TYPES); } } private boolean addComplexParameterType(ExecutableElement method) { return hasComplexParameterTypeMethods.add(method); } private boolean hasComplexParameterType(ExecutableElement method) { return hasComplexParameterTypeMethods.remove(method); } }
7,167
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/AbstractAnnotatedMethodParameterProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.annotation.processing.rest; import org.apache.dubbo.metadata.rest.RestMethodMetadata; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.VariableElement; import static org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor.buildDefaultValue; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getValue; /** * The abstract {@link AnnotatedMethodParameterProcessor} implementation * * @since 2.7.6 */ public abstract class AbstractAnnotatedMethodParameterProcessor implements AnnotatedMethodParameterProcessor { @Override public final void process( AnnotationMirror annotation, VariableElement parameter, int parameterIndex, ExecutableElement method, RestMethodMetadata restMethodMetadata) { String annotationValue = getAnnotationValue(annotation, parameter, parameterIndex); String defaultValue = getDefaultValue(annotation, parameter, parameterIndex); process(annotationValue, defaultValue, annotation, parameter, parameterIndex, method, restMethodMetadata); } protected abstract void process( String annotationValue, String defaultValue, AnnotationMirror annotation, VariableElement parameter, int parameterIndex, ExecutableElement method, RestMethodMetadata restMethodMetadata); protected String getAnnotationValue(AnnotationMirror annotation, VariableElement parameter, int parameterIndex) { return getValue(annotation); } protected String getDefaultValue(AnnotationMirror annotation, VariableElement parameter, int parameterIndex) { return buildDefaultValue(parameterIndex); } }
7,168
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/FormParamParameterProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.annotation.processing.rest.jaxrs; import org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor; import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.FORM_PARAM_ANNOTATION_CLASS_NAME; /** * The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @FormParam * * @since 2.7.6 */ public class FormParamParameterProcessor extends ParamAnnotationParameterProcessor { @Override public String getAnnotationType() { return FORM_PARAM_ANNOTATION_CLASS_NAME; } }
7,169
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/JAXRSServiceRestMetadataResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.annotation.processing.rest.jaxrs; import org.apache.dubbo.metadata.annotation.processing.rest.AbstractServiceRestMetadataResolver; import org.apache.dubbo.metadata.annotation.processing.rest.ServiceRestMetadataResolver; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.AnnotatedConstruct; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import java.util.Set; import java.util.stream.Stream; import static org.apache.dubbo.common.utils.PathUtils.buildPath; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.findAnnotation; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.findMetaAnnotation; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getAnnotation; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getValue; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.isAnnotationPresent; import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.CONSUMES_ANNOTATION_CLASS_NAME; import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.HTTP_METHOD_ANNOTATION_CLASS_NAME; import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.PATH_ANNOTATION_CLASS_NAME; import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.PRODUCES_ANNOTATION_CLASS_NAME; /** * {@link ServiceRestMetadataResolver} implementation for JAX-RS 2 and 1 * * @since 2.7.6 */ public class JAXRSServiceRestMetadataResolver extends AbstractServiceRestMetadataResolver { @Override public boolean supports(ProcessingEnvironment processingEnvironment, TypeElement serviceType) { return supports(serviceType); } public static boolean supports(TypeElement serviceType) { return isAnnotationPresent(serviceType, PATH_ANNOTATION_CLASS_NAME); } @Override protected boolean supports( ProcessingEnvironment processingEnv, TypeElement serviceType, TypeElement serviceInterfaceType, ExecutableElement method) { return isAnnotationPresent(method, PATH_ANNOTATION_CLASS_NAME) || isAnnotationPresent(method, HTTP_METHOD_ANNOTATION_CLASS_NAME); } @Override protected String resolveRequestPath( ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method) { String pathFromType = getPathValue(processingEnv, serviceType); String pathFromMethod = getPathValue(method); return buildPath(pathFromType, pathFromMethod); } @Override protected String resolveRequestMethod( ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method) { AnnotationMirror annotation = findMetaAnnotation(method, HTTP_METHOD_ANNOTATION_CLASS_NAME); return getValue(annotation); } @Override protected void processProduces( ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method, Set<String> produces) { addAnnotationValues(method, PRODUCES_ANNOTATION_CLASS_NAME, produces); } @Override protected void processConsumes( ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method, Set<String> consumes) { addAnnotationValues(method, CONSUMES_ANNOTATION_CLASS_NAME, consumes); } private void addAnnotationValues(Element element, String annotationAttributeName, Set<String> result) { AnnotationMirror annotation = findAnnotation(element, annotationAttributeName); String[] value = getValue(annotation); if (value != null) { Stream.of(value).forEach(result::add); } } private String getPathValue(ProcessingEnvironment processingEnv, TypeElement serviceType) { AnnotationMirror annotation = findAnnotation(serviceType, PATH_ANNOTATION_CLASS_NAME); return getValue(annotation); } private String getPathValue(AnnotatedConstruct annotatedConstruct) { AnnotationMirror annotation = getAnnotation(annotatedConstruct, PATH_ANNOTATION_CLASS_NAME); return getValue(annotation); } }
7,170
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/DefaultValueParameterProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.annotation.processing.rest.jaxrs; import org.apache.dubbo.metadata.annotation.processing.rest.AbstractAnnotatedMethodParameterProcessor; import org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor; import org.apache.dubbo.metadata.rest.RequestMetadata; import org.apache.dubbo.metadata.rest.RestMethodMetadata; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.VariableElement; import java.util.List; import java.util.Map; import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.DEFAULT_VALUE_ANNOTATION_CLASS_NAME; /** * The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @DefaultValue * * * * @since 2.7.6 */ public class DefaultValueParameterProcessor extends AbstractAnnotatedMethodParameterProcessor { @Override public String getAnnotationType() { return DEFAULT_VALUE_ANNOTATION_CLASS_NAME; } @Override protected void process( String annotationValue, String defaultValue, AnnotationMirror annotation, VariableElement parameter, int parameterIndex, ExecutableElement method, RestMethodMetadata restMethodMetadata) { RequestMetadata requestMetadata = restMethodMetadata.getRequest(); // process the request parameters setDefaultValue(requestMetadata.getParams(), defaultValue, annotationValue); // process the request headers setDefaultValue(requestMetadata.getHeaders(), defaultValue, annotationValue); } private void setDefaultValue(Map<String, List<String>> source, String placeholderValue, String defaultValue) { OUTTER: for (Map.Entry<String, List<String>> entry : source.entrySet()) { List<String> values = entry.getValue(); int size = values.size(); for (int i = 0; i < size; i++) { String value = values.get(i); if (placeholderValue.equals(value)) { values.set(i, defaultValue); break OUTTER; } } } } @Override public int getPriority() { return MIN_PRIORITY; } }
7,171
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/QueryParamParameterProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.annotation.processing.rest.jaxrs; import org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor; import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.QUERY_PARAM_ANNOTATION_CLASS_NAME; /** * The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @QueryParam * * @since 2.7.6 */ public class QueryParamParameterProcessor extends ParamAnnotationParameterProcessor { @Override public String getAnnotationType() { return QUERY_PARAM_ANNOTATION_CLASS_NAME; } }
7,172
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/MatrixParamParameterProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.annotation.processing.rest.jaxrs; import org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor; import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.MATRIX_PARAM_ANNOTATION_CLASS_NAME; /** * The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @MatrixParam * * @since 2.7.6 */ public class MatrixParamParameterProcessor extends ParamAnnotationParameterProcessor { @Override public String getAnnotationType() { return MATRIX_PARAM_ANNOTATION_CLASS_NAME; } }
7,173
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/HeaderParamParameterProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.annotation.processing.rest.jaxrs; import org.apache.dubbo.metadata.annotation.processing.rest.AbstractAnnotatedMethodParameterProcessor; import org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor; import org.apache.dubbo.metadata.rest.RequestMetadata; import org.apache.dubbo.metadata.rest.RestMethodMetadata; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.VariableElement; import static org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor.buildDefaultValue; import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.HEADER_PARAM_ANNOTATION_CLASS_NAME; /** * The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @HeaderParam * * @since 2.7.6 */ public class HeaderParamParameterProcessor extends AbstractAnnotatedMethodParameterProcessor { @Override public String getAnnotationType() { return HEADER_PARAM_ANNOTATION_CLASS_NAME; } @Override protected void process( String headerName, String defaultValue, AnnotationMirror annotation, VariableElement parameter, int parameterIndex, ExecutableElement method, RestMethodMetadata restMethodMetadata) { RequestMetadata requestMetadata = restMethodMetadata.getRequest(); // Add the placeholder as header value requestMetadata.addHeader(headerName, buildDefaultValue(parameterIndex)); } }
7,174
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/ParamAnnotationParameterProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.annotation.processing.rest.jaxrs; import org.apache.dubbo.metadata.annotation.processing.rest.AbstractAnnotatedMethodParameterProcessor; import org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor; import org.apache.dubbo.metadata.rest.RequestMetadata; import org.apache.dubbo.metadata.rest.RestMethodMetadata; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.VariableElement; /** * The abstract {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @*Param */ public abstract class ParamAnnotationParameterProcessor extends AbstractAnnotatedMethodParameterProcessor { protected void process( String name, String defaultValue, AnnotationMirror annotation, VariableElement parameter, int parameterIndex, ExecutableElement method, RestMethodMetadata restMethodMetadata) { RequestMetadata requestMetadata = restMethodMetadata.getRequest(); requestMetadata.addParam(name, defaultValue); } }
7,175
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/AbstractRequestAnnotationParameterProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.annotation.processing.rest.springmvc; import org.apache.dubbo.metadata.annotation.processing.rest.AbstractAnnotatedMethodParameterProcessor; import org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor; import org.apache.dubbo.metadata.rest.RestMethodMetadata; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.VariableElement; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getAttribute; /** * The abstract {@link AnnotatedMethodParameterProcessor} implementation for Spring Web MVC's @Request* */ public abstract class AbstractRequestAnnotationParameterProcessor extends AbstractAnnotatedMethodParameterProcessor { protected abstract void process( String name, String defaultValue, AnnotationMirror annotation, VariableElement parameter, int parameterIndex, ExecutableElement method, RestMethodMetadata restMethodMetadata); @Override protected String getAnnotationValue(AnnotationMirror annotation, VariableElement parameter, int parameterIndex) { // try to get "value" attribute first String name = super.getAnnotationValue(annotation, parameter, parameterIndex); // try to get "name" attribute if required if (isEmpty(name)) { name = getAttribute(annotation, "name"); } // finally , try to the name of parameter if (isEmpty(name)) { name = parameter.getSimpleName().toString(); } return name; } protected String getDefaultValue(AnnotationMirror annotation, VariableElement parameter, int parameterIndex) { String defaultValue = getAttribute(annotation, "defaultValue"); if (isEmpty(defaultValue)) { defaultValue = super.getDefaultValue(annotation, parameter, parameterIndex); } return defaultValue; } protected boolean isEmpty(String str) { return str == null || str.isEmpty(); } }
7,176
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/RequestParamParameterProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.annotation.processing.rest.springmvc; import org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor; import org.apache.dubbo.metadata.rest.RestMethodMetadata; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.VariableElement; import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SPRING_MVC.REQUEST_PARAM_ANNOTATION_CLASS_NAME; /** * The {@link AnnotatedMethodParameterProcessor} implementation for Spring Web MVC's @RequestParam */ public class RequestParamParameterProcessor extends AbstractRequestAnnotationParameterProcessor { @Override public String getAnnotationType() { return REQUEST_PARAM_ANNOTATION_CLASS_NAME; } @Override protected void process( String name, String defaultValue, AnnotationMirror annotation, VariableElement parameter, int parameterIndex, ExecutableElement method, RestMethodMetadata restMethodMetadata) { restMethodMetadata.getRequest().addParam(name, defaultValue); } }
7,177
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/RequestHeaderParameterProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.annotation.processing.rest.springmvc; import org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor; import org.apache.dubbo.metadata.rest.RestMethodMetadata; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.VariableElement; import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SPRING_MVC.REQUEST_HEADER_ANNOTATION_CLASS_NAME; /** * The {@link AnnotatedMethodParameterProcessor} implementation for Spring Web MVC's @RequestHeader */ public class RequestHeaderParameterProcessor extends AbstractRequestAnnotationParameterProcessor { @Override public String getAnnotationType() { return REQUEST_HEADER_ANNOTATION_CLASS_NAME; } @Override protected void process( String name, String defaultValue, AnnotationMirror annotation, VariableElement parameter, int parameterIndex, ExecutableElement method, RestMethodMetadata restMethodMetadata) { restMethodMetadata.getRequest().addHeader(name, defaultValue); } }
7,178
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/SpringMvcServiceRestMetadataResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.annotation.processing.rest.springmvc; import org.apache.dubbo.metadata.annotation.processing.rest.AbstractServiceRestMetadataResolver; import org.apache.dubbo.metadata.annotation.processing.rest.ServiceRestMetadataResolver; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import java.lang.reflect.Array; import java.util.Set; import static java.lang.String.valueOf; import static java.lang.reflect.Array.getLength; import static java.util.stream.Stream.of; import static org.apache.dubbo.common.function.Streams.filterFirst; import static org.apache.dubbo.common.utils.ArrayUtils.isEmpty; import static org.apache.dubbo.common.utils.ArrayUtils.isNotEmpty; import static org.apache.dubbo.common.utils.PathUtils.buildPath; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.findAnnotation; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.findMetaAnnotation; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getAllAnnotations; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getAttribute; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.isAnnotationPresent; import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SPRING_MVC.CONTROLLER_ANNOTATION_CLASS_NAME; import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SPRING_MVC.REQUEST_MAPPING_ANNOTATION_CLASS_NAME; /** * {@link ServiceRestMetadataResolver} * * @since 2.7.6 */ public class SpringMvcServiceRestMetadataResolver extends AbstractServiceRestMetadataResolver { private static final int FIRST_ELEMENT_INDEX = 0; @Override public boolean supports(ProcessingEnvironment processingEnvironment, TypeElement serviceType) { return supports(serviceType); } @Override protected boolean supports( ProcessingEnvironment processingEnv, TypeElement serviceType, TypeElement serviceInterfaceType, ExecutableElement method) { return isAnnotationPresent(method, REQUEST_MAPPING_ANNOTATION_CLASS_NAME); } public static boolean supports(TypeElement serviceType) { // class @Controller or @RequestMapping return isAnnotationPresent(serviceType, CONTROLLER_ANNOTATION_CLASS_NAME) || isAnnotationPresent(serviceType, REQUEST_MAPPING_ANNOTATION_CLASS_NAME); } @Override protected String resolveRequestPath( ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method) { String requestPathFromType = getRequestPath(serviceType); String requestPathFromMethod = getRequestPath(method); return buildPath(requestPathFromType, requestPathFromMethod); } @Override protected String resolveRequestMethod( ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method) { AnnotationMirror requestMapping = getRequestMapping(method); // httpMethod is an array of RequestMethod Object httpMethod = getAttribute(requestMapping, "method"); if (httpMethod == null || getLength(httpMethod) < 1) { return null; } // TODO Is is required to support more request methods? return valueOf(Array.get(httpMethod, FIRST_ELEMENT_INDEX)); } private AnnotationMirror getRequestMapping(Element element) { // try "@RequestMapping" first AnnotationMirror requestMapping = findAnnotation(element, REQUEST_MAPPING_ANNOTATION_CLASS_NAME); // try the annotation meta-annotated later if (requestMapping == null) { requestMapping = findMetaAnnotation(element, REQUEST_MAPPING_ANNOTATION_CLASS_NAME); } return requestMapping; } @Override protected void processProduces( ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method, Set<String> produces) { addMediaTypes(method, "produces", produces); } @Override protected void processConsumes( ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method, Set<String> consumes) { addMediaTypes(method, "consumes", consumes); } private void addMediaTypes(ExecutableElement method, String annotationAttributeName, Set<String> mediaTypesSet) { AnnotationMirror mappingAnnotation = getMappingAnnotation(method); String[] mediaTypes = getAttribute(mappingAnnotation, annotationAttributeName); if (isNotEmpty(mediaTypes)) { of(mediaTypes).forEach(mediaTypesSet::add); } } private AnnotationMirror getMappingAnnotation(Element element) { return computeIfAbsent( valueOf(element), key -> filterFirst(getAllAnnotations(element), annotation -> { DeclaredType annotationType = annotation.getAnnotationType(); // try "@RequestMapping" first if (REQUEST_MAPPING_ANNOTATION_CLASS_NAME.equals(annotationType.toString())) { return true; } // try meta annotation return isAnnotationPresent(annotationType.asElement(), REQUEST_MAPPING_ANNOTATION_CLASS_NAME); })); } private String getRequestPath(Element element) { AnnotationMirror mappingAnnotation = getMappingAnnotation(element); return getRequestPath(mappingAnnotation); } private String getRequestPath(AnnotationMirror mappingAnnotation) { // try "value" first String[] value = getAttribute(mappingAnnotation, "value"); if (isEmpty(value)) { // try "path" later value = getAttribute(mappingAnnotation, "path"); } if (isEmpty(value)) { return ""; } // TODO Is is required to support more request paths? return value[FIRST_ELEMENT_INDEX]; } }
7,179
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport4TstService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.store.zookeeper; /** * 2018/10/26 */ public interface ZookeeperMetadataReport4TstService { int getCounter(); void printResult(String var); }
7,180
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.store.zookeeper; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.ConfigItem; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.metadata.MappingChangedEvent; import org.apache.dubbo.metadata.MappingListener; import org.apache.dubbo.metadata.MetadataInfo; import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder; import org.apache.dubbo.metadata.definition.model.FullServiceDefinition; import org.apache.dubbo.metadata.report.MetadataReport; import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum; import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier; import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.metadata.ServiceNameMapping.DEFAULT_MAPPING_GROUP; /** * 2018/10/9 */ class ZookeeperMetadataReportTest { private ZookeeperMetadataReport zookeeperMetadataReport; private URL registryUrl; private ZookeeperMetadataReportFactory zookeeperMetadataReportFactory; private static String zookeeperConnectionAddress1; @BeforeAll public static void beforeAll() { zookeeperConnectionAddress1 = System.getProperty("zookeeper.connection.address.1"); } @BeforeEach public void setUp() throws Exception { this.registryUrl = URL.valueOf(zookeeperConnectionAddress1); zookeeperMetadataReportFactory = new ZookeeperMetadataReportFactory(ApplicationModel.defaultModel()); this.zookeeperMetadataReport = (ZookeeperMetadataReport) zookeeperMetadataReportFactory.getMetadataReport(registryUrl); } private void deletePath(MetadataIdentifier metadataIdentifier, ZookeeperMetadataReport zookeeperMetadataReport) { String category = zookeeperMetadataReport.toRootDir() + metadataIdentifier.getUniqueKey(KeyTypeEnum.PATH); zookeeperMetadataReport.zkClient.delete(category); } @Test void testStoreProvider() throws ClassNotFoundException, InterruptedException { String interfaceName = "org.apache.dubbo.metadata.store.zookeeper.ZookeeperMetadataReport4TstService"; String version = "1.0.0.zk.md"; String group = null; String application = "vic.zk.md"; MetadataIdentifier providerMetadataIdentifier = storePrivider(zookeeperMetadataReport, interfaceName, version, group, application); String fileContent = zookeeperMetadataReport.zkClient.getContent( zookeeperMetadataReport.getNodePath(providerMetadataIdentifier)); fileContent = waitSeconds(fileContent, 3500, zookeeperMetadataReport.getNodePath(providerMetadataIdentifier)); Assertions.assertNotNull(fileContent); deletePath(providerMetadataIdentifier, zookeeperMetadataReport); fileContent = zookeeperMetadataReport.zkClient.getContent( zookeeperMetadataReport.getNodePath(providerMetadataIdentifier)); fileContent = waitSeconds(fileContent, 1000, zookeeperMetadataReport.getNodePath(providerMetadataIdentifier)); Assertions.assertNull(fileContent); providerMetadataIdentifier = storePrivider(zookeeperMetadataReport, interfaceName, version, group, application); fileContent = zookeeperMetadataReport.zkClient.getContent( zookeeperMetadataReport.getNodePath(providerMetadataIdentifier)); fileContent = waitSeconds(fileContent, 3500, zookeeperMetadataReport.getNodePath(providerMetadataIdentifier)); Assertions.assertNotNull(fileContent); FullServiceDefinition fullServiceDefinition = JsonUtils.toJavaObject(fileContent, FullServiceDefinition.class); Assertions.assertEquals(fullServiceDefinition.getParameters().get("paramTest"), "zkTest"); } @Test void testConsumer() throws ClassNotFoundException, InterruptedException { String interfaceName = "org.apache.dubbo.metadata.store.zookeeper.ZookeeperMetadataReport4TstService"; String version = "1.0.0.zk.md"; String group = null; String application = "vic.zk.md"; MetadataIdentifier consumerMetadataIdentifier = storeConsumer(zookeeperMetadataReport, interfaceName, version, group, application); String fileContent = zookeeperMetadataReport.zkClient.getContent( zookeeperMetadataReport.getNodePath(consumerMetadataIdentifier)); fileContent = waitSeconds(fileContent, 3500, zookeeperMetadataReport.getNodePath(consumerMetadataIdentifier)); Assertions.assertNotNull(fileContent); deletePath(consumerMetadataIdentifier, zookeeperMetadataReport); fileContent = zookeeperMetadataReport.zkClient.getContent( zookeeperMetadataReport.getNodePath(consumerMetadataIdentifier)); fileContent = waitSeconds(fileContent, 1000, zookeeperMetadataReport.getNodePath(consumerMetadataIdentifier)); Assertions.assertNull(fileContent); consumerMetadataIdentifier = storeConsumer(zookeeperMetadataReport, interfaceName, version, group, application); fileContent = zookeeperMetadataReport.zkClient.getContent( zookeeperMetadataReport.getNodePath(consumerMetadataIdentifier)); fileContent = waitSeconds(fileContent, 3000, zookeeperMetadataReport.getNodePath(consumerMetadataIdentifier)); Assertions.assertNotNull(fileContent); Assertions.assertEquals(fileContent, "{\"paramConsumerTest\":\"zkCm\"}"); } @Test void testDoSaveMetadata() throws ExecutionException, InterruptedException { String interfaceName = "org.apache.dubbo.metadata.store.zookeeper.ZookeeperMetadataReport4TstService"; String version = "1.0.0"; String group = null; String application = "etc-metadata-report-consumer-test"; String revision = "90980"; String protocol = "xxx"; URL url = generateURL(interfaceName, version, group, application); ServiceMetadataIdentifier serviceMetadataIdentifier = new ServiceMetadataIdentifier(interfaceName, version, group, "provider", revision, protocol); zookeeperMetadataReport.doSaveMetadata(serviceMetadataIdentifier, url); String fileContent = zookeeperMetadataReport.zkClient.getContent( zookeeperMetadataReport.getNodePath(serviceMetadataIdentifier)); Assertions.assertNotNull(fileContent); Assertions.assertEquals(fileContent, URL.encode(url.toFullString())); } @Test void testDoRemoveMetadata() throws ExecutionException, InterruptedException { String interfaceName = "org.apache.dubbo.metadata.store.zookeeper.ZookeeperMetadataReport4TstService"; String version = "1.0.0"; String group = null; String application = "etc-metadata-report-consumer-test"; String revision = "90980"; String protocol = "xxx"; URL url = generateURL(interfaceName, version, group, application); ServiceMetadataIdentifier serviceMetadataIdentifier = new ServiceMetadataIdentifier(interfaceName, version, group, "provider", revision, protocol); zookeeperMetadataReport.doSaveMetadata(serviceMetadataIdentifier, url); String fileContent = zookeeperMetadataReport.zkClient.getContent( zookeeperMetadataReport.getNodePath(serviceMetadataIdentifier)); Assertions.assertNotNull(fileContent); zookeeperMetadataReport.doRemoveMetadata(serviceMetadataIdentifier); fileContent = zookeeperMetadataReport.zkClient.getContent( zookeeperMetadataReport.getNodePath(serviceMetadataIdentifier)); Assertions.assertNull(fileContent); } @Test void testDoGetExportedURLs() throws ExecutionException, InterruptedException { String interfaceName = "org.apache.dubbo.metadata.store.zookeeper.ZookeeperMetadataReport4TstService"; String version = "1.0.0"; String group = null; String application = "etc-metadata-report-consumer-test"; String revision = "90980"; String protocol = "xxx"; URL url = generateURL(interfaceName, version, group, application); ServiceMetadataIdentifier serviceMetadataIdentifier = new ServiceMetadataIdentifier(interfaceName, version, group, "provider", revision, protocol); zookeeperMetadataReport.doSaveMetadata(serviceMetadataIdentifier, url); List<String> r = zookeeperMetadataReport.doGetExportedURLs(serviceMetadataIdentifier); Assertions.assertTrue(r.size() == 1); String fileContent = r.get(0); Assertions.assertNotNull(fileContent); Assertions.assertEquals(fileContent, url.toFullString()); } @Test void testDoSaveSubscriberData() throws ExecutionException, InterruptedException { String interfaceName = "org.apache.dubbo.metadata.store.zookeeper.ZookeeperMetadataReport4TstService"; String version = "1.0.0"; String group = null; String application = "etc-metadata-report-consumer-test"; String revision = "90980"; String protocol = "xxx"; URL url = generateURL(interfaceName, version, group, application); SubscriberMetadataIdentifier subscriberMetadataIdentifier = new SubscriberMetadataIdentifier(application, revision); String r = JsonUtils.toJson(Arrays.asList(url.toString())); zookeeperMetadataReport.doSaveSubscriberData(subscriberMetadataIdentifier, r); String fileContent = zookeeperMetadataReport.zkClient.getContent( zookeeperMetadataReport.getNodePath(subscriberMetadataIdentifier)); Assertions.assertNotNull(fileContent); Assertions.assertEquals(fileContent, r); } @Test void testDoGetSubscribedURLs() throws ExecutionException, InterruptedException { String interfaceName = "org.apache.dubbo.metadata.store.zookeeper.ZookeeperMetadataReport4TstService"; String version = "1.0.0"; String group = null; String application = "etc-metadata-report-consumer-test"; String revision = "90980"; String protocol = "xxx"; URL url = generateURL(interfaceName, version, group, application); SubscriberMetadataIdentifier subscriberMetadataIdentifier = new SubscriberMetadataIdentifier(application, revision); String r = JsonUtils.toJson(Arrays.asList(url.toString())); zookeeperMetadataReport.doSaveSubscriberData(subscriberMetadataIdentifier, r); String fileContent = zookeeperMetadataReport.zkClient.getContent( zookeeperMetadataReport.getNodePath(subscriberMetadataIdentifier)); Assertions.assertNotNull(fileContent); Assertions.assertEquals(fileContent, r); } private MetadataIdentifier storePrivider( MetadataReport zookeeperMetadataReport, String interfaceName, String version, String group, String application) throws ClassNotFoundException, InterruptedException { URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + "?paramTest=zkTest&version=" + version + "&application=" + application + (group == null ? "" : "&group=" + group)); MetadataIdentifier providerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE, application); Class interfaceClass = Class.forName(interfaceName); FullServiceDefinition fullServiceDefinition = ServiceDefinitionBuilder.buildFullDefinition(interfaceClass, url.getParameters()); zookeeperMetadataReport.storeProviderMetadata(providerMetadataIdentifier, fullServiceDefinition); Thread.sleep(2000); return providerMetadataIdentifier; } private MetadataIdentifier storeConsumer( MetadataReport zookeeperMetadataReport, String interfaceName, String version, String group, String application) throws ClassNotFoundException, InterruptedException { URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + "?version=" + version + "&application=" + application + (group == null ? "" : "&group=" + group)); MetadataIdentifier consumerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, CONSUMER_SIDE, application); Class interfaceClass = Class.forName(interfaceName); Map<String, String> tmp = new HashMap<>(); tmp.put("paramConsumerTest", "zkCm"); zookeeperMetadataReport.storeConsumerMetadata(consumerMetadataIdentifier, tmp); Thread.sleep(2000); return consumerMetadataIdentifier; } private String waitSeconds(String value, long moreTime, String path) throws InterruptedException { if (value == null) { Thread.sleep(moreTime); return zookeeperMetadataReport.zkClient.getContent(path); } return value; } private URL generateURL(String interfaceName, String version, String group, String application) { URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":8989/" + interfaceName + "?paramTest=etcdTest&version=" + version + "&application=" + application + (group == null ? "" : "&group=" + group)); return url; } @Test void testMapping() throws InterruptedException { String serviceKey = ZookeeperMetadataReportTest.class.getName(); URL url = URL.valueOf("test://127.0.0.1:8888/" + serviceKey); String appNames = "demo1,demo2"; CountDownLatch latch = new CountDownLatch(1); Set<String> serviceAppMapping = zookeeperMetadataReport.getServiceAppMapping( serviceKey, new MappingListener() { @Override public void onEvent(MappingChangedEvent event) { Set<String> apps = event.getApps(); Assertions.assertEquals(apps.size(), 2); Assertions.assertTrue(apps.contains("demo1")); Assertions.assertTrue(apps.contains("demo2")); latch.countDown(); } @Override public void stop() {} }, url); Assertions.assertTrue(serviceAppMapping.isEmpty()); ConfigItem configItem = zookeeperMetadataReport.getConfigItem(serviceKey, DEFAULT_MAPPING_GROUP); zookeeperMetadataReport.registerServiceAppMapping( serviceKey, DEFAULT_MAPPING_GROUP, appNames, configItem.getTicket()); latch.await(); } @Test void testAppMetadata() { String serviceKey = ZookeeperMetadataReportTest.class.getName(); String appName = "demo"; URL url = URL.valueOf("test://127.0.0.1:8888/" + serviceKey); MetadataInfo metadataInfo = new MetadataInfo(appName); metadataInfo.addService(url); SubscriberMetadataIdentifier identifier = new SubscriberMetadataIdentifier(appName, metadataInfo.calAndGetRevision()); MetadataInfo appMetadata = zookeeperMetadataReport.getAppMetadata(identifier, Collections.emptyMap()); Assertions.assertNull(appMetadata); zookeeperMetadataReport.publishAppMetadata(identifier, metadataInfo); appMetadata = zookeeperMetadataReport.getAppMetadata(identifier, Collections.emptyMap()); Assertions.assertNotNull(appMetadata); Assertions.assertEquals(appMetadata.calAndGetRevision(), metadataInfo.calAndGetRevision()); } }
7,181
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.store.zookeeper; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.DisableInject; import org.apache.dubbo.metadata.report.MetadataReport; import org.apache.dubbo.metadata.report.support.AbstractMetadataReportFactory; import org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter; import org.apache.dubbo.rpc.model.ApplicationModel; /** * ZookeeperRegistryFactory. */ public class ZookeeperMetadataReportFactory extends AbstractMetadataReportFactory { private ZookeeperTransporter zookeeperTransporter; private ApplicationModel applicationModel; public ZookeeperMetadataReportFactory(ApplicationModel applicationModel) { this.applicationModel = applicationModel; this.zookeeperTransporter = ZookeeperTransporter.getExtension(applicationModel); } @DisableInject public void setZookeeperTransporter(ZookeeperTransporter zookeeperTransporter) { this.zookeeperTransporter = zookeeperTransporter; } @Override public MetadataReport createMetadataReport(URL url) { return new ZookeeperMetadataReport(url, zookeeperTransporter); } }
7,182
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.store.zookeeper; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.ConfigItem; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.metadata.MappingChangedEvent; import org.apache.dubbo.metadata.MappingListener; import org.apache.dubbo.metadata.MetadataInfo; import org.apache.dubbo.metadata.report.identifier.BaseMetadataIdentifier; import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum; import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier; import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier; import org.apache.dubbo.metadata.report.support.AbstractMetadataReport; import org.apache.dubbo.remoting.zookeeper.DataListener; import org.apache.dubbo.remoting.zookeeper.EventType; import org.apache.dubbo.remoting.zookeeper.ZookeeperClient; import org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.zookeeper.data.Stat; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ZOOKEEPER_EXCEPTION; import static org.apache.dubbo.metadata.ServiceNameMapping.DEFAULT_MAPPING_GROUP; import static org.apache.dubbo.metadata.ServiceNameMapping.getAppNames; /** * ZookeeperMetadataReport */ public class ZookeeperMetadataReport extends AbstractMetadataReport { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ZookeeperMetadataReport.class); private final String root; ZookeeperClient zkClient; private ConcurrentMap<String, MappingDataListener> casListenerMap = new ConcurrentHashMap<>(); public ZookeeperMetadataReport(URL url, ZookeeperTransporter zookeeperTransporter) { super(url); if (url.isAnyHost()) { throw new IllegalStateException("registry address == null"); } String group = url.getGroup(DEFAULT_ROOT); if (!group.startsWith(PATH_SEPARATOR)) { group = PATH_SEPARATOR + group; } this.root = group; zkClient = zookeeperTransporter.connect(url); } protected String toRootDir() { if (root.equals(PATH_SEPARATOR)) { return root; } return root + PATH_SEPARATOR; } @Override protected void doStoreProviderMetadata(MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions) { storeMetadata(providerMetadataIdentifier, serviceDefinitions); } @Override protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, String value) { storeMetadata(consumerMetadataIdentifier, value); } @Override protected void doSaveMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url) { zkClient.createOrUpdate(getNodePath(metadataIdentifier), URL.encode(url.toFullString()), false); } @Override protected void doRemoveMetadata(ServiceMetadataIdentifier metadataIdentifier) { zkClient.delete(getNodePath(metadataIdentifier)); } @Override protected List<String> doGetExportedURLs(ServiceMetadataIdentifier metadataIdentifier) { String content = zkClient.getContent(getNodePath(metadataIdentifier)); if (StringUtils.isEmpty(content)) { return Collections.emptyList(); } return new ArrayList<>(Collections.singletonList(URL.decode(content))); } @Override protected void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urls) { zkClient.createOrUpdate(getNodePath(subscriberMetadataIdentifier), urls, false); } @Override protected String doGetSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) { return zkClient.getContent(getNodePath(subscriberMetadataIdentifier)); } @Override public String getServiceDefinition(MetadataIdentifier metadataIdentifier) { return zkClient.getContent(getNodePath(metadataIdentifier)); } private void storeMetadata(MetadataIdentifier metadataIdentifier, String v) { zkClient.createOrUpdate(getNodePath(metadataIdentifier), v, false); } String getNodePath(BaseMetadataIdentifier metadataIdentifier) { return toRootDir() + metadataIdentifier.getUniqueKey(KeyTypeEnum.PATH); } @Override public void publishAppMetadata(SubscriberMetadataIdentifier identifier, MetadataInfo metadataInfo) { String path = getNodePath(identifier); if (StringUtils.isBlank(zkClient.getContent(path)) && StringUtils.isNotEmpty(metadataInfo.getContent())) { zkClient.createOrUpdate(path, metadataInfo.getContent(), false); } } @Override public void unPublishAppMetadata(SubscriberMetadataIdentifier identifier, MetadataInfo metadataInfo) { String path = getNodePath(identifier); if (StringUtils.isNotEmpty(zkClient.getContent(path))) { zkClient.delete(path); } } @Override public MetadataInfo getAppMetadata(SubscriberMetadataIdentifier identifier, Map<String, String> instanceMetadata) { String content = zkClient.getContent(getNodePath(identifier)); return JsonUtils.toJavaObject(content, MetadataInfo.class); } @Override public Set<String> getServiceAppMapping(String serviceKey, MappingListener listener, URL url) { String path = buildPathKey(DEFAULT_MAPPING_GROUP, serviceKey); MappingDataListener mappingDataListener = ConcurrentHashMapUtils.computeIfAbsent(casListenerMap, path, _k -> { MappingDataListener newMappingListener = new MappingDataListener(serviceKey, path); zkClient.addDataListener(path, newMappingListener); return newMappingListener; }); mappingDataListener.addListener(listener); return getAppNames(zkClient.getContent(path)); } @Override public void removeServiceAppMappingListener(String serviceKey, MappingListener listener) { String path = buildPathKey(DEFAULT_MAPPING_GROUP, serviceKey); if (null != casListenerMap.get(path)) { removeCasServiceMappingListener(path, listener); } } @Override public Set<String> getServiceAppMapping(String serviceKey, URL url) { String path = buildPathKey(DEFAULT_MAPPING_GROUP, serviceKey); return getAppNames(zkClient.getContent(path)); } @Override public ConfigItem getConfigItem(String serviceKey, String group) { String path = buildPathKey(group, serviceKey); return zkClient.getConfigItem(path); } @Override public boolean registerServiceAppMapping(String key, String group, String content, Object ticket) { try { if (ticket != null && !(ticket instanceof Stat)) { throw new IllegalArgumentException("zookeeper publishConfigCas requires stat type ticket"); } String pathKey = buildPathKey(group, key); zkClient.createOrUpdate(pathKey, content, false, ticket == null ? null : ((Stat) ticket).getVersion()); return true; } catch (Exception e) { logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "zookeeper publishConfigCas failed.", e); return false; } } @Override public void destroy() { super.destroy(); // release zk client reference, but should not close it zkClient = null; } private String buildPathKey(String group, String serviceKey) { return toRootDir() + group + PATH_SEPARATOR + serviceKey; } private void removeCasServiceMappingListener(String path, MappingListener listener) { MappingDataListener mappingDataListener = casListenerMap.get(path); mappingDataListener.removeListener(listener); if (mappingDataListener.isEmpty()) { zkClient.removeDataListener(path, mappingDataListener); casListenerMap.remove(path, mappingDataListener); } } private static class MappingDataListener implements DataListener { private String serviceKey; private String path; private Set<MappingListener> listeners; public MappingDataListener(String serviceKey, String path) { this.serviceKey = serviceKey; this.path = path; this.listeners = new HashSet<>(); } public void addListener(MappingListener listener) { this.listeners.add(listener); } public void removeListener(MappingListener listener) { this.listeners.remove(listener); } public boolean isEmpty() { return listeners.isEmpty(); } @Override public void dataChanged(String path, Object value, EventType eventType) { if (!this.path.equals(path)) { return; } if (EventType.NodeCreated != eventType && EventType.NodeDataChanged != eventType) { return; } Set<String> apps = getAppNames((String) value); MappingChangedEvent event = new MappingChangedEvent(serviceKey, apps); listeners.forEach(mappingListener -> mappingListener.onEvent(event)); } } }
7,183
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/TestMediaType.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata; import org.apache.dubbo.metadata.rest.media.MediaType; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class TestMediaType { @Test void testGetAll() { Assertions.assertDoesNotThrow(() -> { MediaType.getAllContentType(); MediaType.getSupportMediaTypes(); }); } }
7,184
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/MetadataInfoTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.JsonUtils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Field; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PAYLOAD; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.metadata.RevisionResolver.EMPTY_REVISION; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Some construction and filter cases are covered in InMemoryMetadataServiceTest */ class MetadataInfoTest { private static URL url = URL.valueOf("dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService2?" + "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2" + "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService2" + "&metadata-type=remote&methods=sayHello&sayHello.timeout=7000&pid=36621&release=&revision=1.0.0&service-name-mapping=true" + "&side=provider&timeout=5000&timestamp=1629970068002&version=1.0.0&params-filter=customized,-excluded"); private static URL url2 = URL.valueOf("dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService?" + "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2" + "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService" + "&metadata-type=remote&methods=sayHello&pid=36621&release=&revision=1.0.0&service-name-mapping=true" + "&side=provider&timeout=5000&timestamp=1629970068002&version=1.0.0&params-filter=customized,-excluded"); private static URL url3 = URL.valueOf("dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService?" + "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2" + "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService" + "&metadata-type=remote&methods=sayHello&sayHello.timeout=7000&pid=36621&release=&revision=1.0.0&service-name-mapping=true" + "&side=provider&timeout=5000&timestamp=1629970068002&version=1.0.0&params-filter=-customized,excluded"); private static URL url4 = URL.valueOf( "dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService?" + "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2" + "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService" + "&metadata-type=remote&methods=sayHello&sayHello.timeout=7000&pid=36621&release=&revision=1.0.0&service-name-mapping=true" + "&side=provider&timeout=5000&timestamp=1629970068002&version=1.0.0&params-filter=-customized,excluded&payload=1024"); @Test void testEmptyRevision() { MetadataInfo metadataInfo = new MetadataInfo("demo"); metadataInfo.setApp("demo"); Assertions.assertEquals(EMPTY_REVISION, metadataInfo.calAndGetRevision()); } @Test void testParamsFilterIncluded() { MetadataInfo metadataInfo = new MetadataInfo("demo"); // export normal url again metadataInfo.addService(url); MetadataInfo.ServiceInfo serviceInfo2 = metadataInfo.getServiceInfo(url.getProtocolServiceKey()); assertNotNull(serviceInfo2); assertEquals(5, serviceInfo2.getParams().size()); assertNull(serviceInfo2.getParams().get(INTERFACE_KEY)); assertNull(serviceInfo2.getParams().get("delay")); assertNotNull(serviceInfo2.getParams().get(APPLICATION_KEY)); assertNotNull(serviceInfo2.getParams().get(VERSION_KEY)); assertNotNull(serviceInfo2.getParams().get(GROUP_KEY)); assertNotNull(serviceInfo2.getParams().get(TIMEOUT_KEY)); assertEquals("7000", serviceInfo2.getMethodParameter("sayHello", TIMEOUT_KEY, "1000")); } @Test void testParamsFilterExcluded() { MetadataInfo metadataInfo = new MetadataInfo("demo"); // export normal url again metadataInfo.addService(url3); MetadataInfo.ServiceInfo serviceInfo3 = metadataInfo.getServiceInfo(url3.getProtocolServiceKey()); assertNotNull(serviceInfo3); assertEquals(14, serviceInfo3.getParams().size()); assertNotNull(serviceInfo3.getParams().get(INTERFACE_KEY)); assertNotNull(serviceInfo3.getParams().get(APPLICATION_KEY)); assertNotNull(serviceInfo3.getParams().get(VERSION_KEY)); assertNull(serviceInfo3.getParams().get(GROUP_KEY)); assertNull(serviceInfo3.getParams().get(TIMEOUT_KEY)); assertNull(serviceInfo3.getParams().get("anyhost")); assertEquals("1000", serviceInfo3.getMethodParameter("sayHello", TIMEOUT_KEY, "1000")); } @Test void testEqualsAndRevision() { // same metadata MetadataInfo metadataInfo = new MetadataInfo("demo"); metadataInfo.addService(url); MetadataInfo sameMetadataInfo = new MetadataInfo("demo"); sameMetadataInfo.addService(url); assertEquals(metadataInfo, sameMetadataInfo); assertEquals(metadataInfo.calAndGetRevision(), sameMetadataInfo.calAndGetRevision()); // url with different params that are not counted in ServiceInfo MetadataInfo metadataInfoWithDifferentParam1 = new MetadataInfo("demo"); metadataInfoWithDifferentParam1.addService(url.addParameter("delay", 6000)); assertEquals(metadataInfo, metadataInfoWithDifferentParam1); assertEquals(metadataInfo.calAndGetRevision(), metadataInfoWithDifferentParam1.calAndGetRevision()); // url with different params that are counted in ServiceInfo MetadataInfo metadataInfoWithDifferentParam2 = new MetadataInfo("demo"); metadataInfoWithDifferentParam2.addService(url.addParameter(TIMEOUT_KEY, 6000)); assertNotEquals(metadataInfo, metadataInfoWithDifferentParam2); assertNotEquals(metadataInfo.calAndGetRevision(), metadataInfoWithDifferentParam2.calAndGetRevision()); MetadataInfo metadataInfoWithDifferentGroup = new MetadataInfo("demo"); metadataInfoWithDifferentGroup.addService(url.addParameter(GROUP_KEY, "newGroup")); assertNotEquals(metadataInfo, metadataInfoWithDifferentGroup); assertNotEquals(metadataInfo.calAndGetRevision(), metadataInfoWithDifferentGroup.calAndGetRevision()); MetadataInfo metadataInfoWithDifferentServices = new MetadataInfo("demo"); metadataInfoWithDifferentServices.addService(url); metadataInfoWithDifferentServices.addService(url2); assertNotEquals(metadataInfo, metadataInfoWithDifferentServices); assertNotEquals(metadataInfo.calAndGetRevision(), metadataInfoWithDifferentServices.calAndGetRevision()); } @Test void testChanged() { MetadataInfo metadataInfo = new MetadataInfo("demo"); metadataInfo.addService(url); metadataInfo.addService(url2); assertTrue(metadataInfo.updated); metadataInfo.calAndGetRevision(); assertFalse(metadataInfo.updated); metadataInfo.removeService(url2); assertTrue(metadataInfo.updated); } @Test void testJsonFormat() { MetadataInfo metadataInfo = new MetadataInfo("demo"); // export normal url again metadataInfo.addService(url); System.out.println(JsonUtils.toJson(metadataInfo)); MetadataInfo metadataInfo2 = new MetadataInfo("demo"); // export normal url again metadataInfo2.addService(url); metadataInfo2.addService(url2); System.out.println(JsonUtils.toJson(metadataInfo2)); } @Test void testJdkSerialize() throws IOException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); MetadataInfo metadataInfo = new MetadataInfo("demo"); metadataInfo.addService(url); objectOutputStream.writeObject(metadataInfo); objectOutputStream.close(); byteArrayOutputStream.close(); byte[] bytes = byteArrayOutputStream.toByteArray(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); MetadataInfo metadataInfo2 = (MetadataInfo) objectInputStream.readObject(); objectInputStream.close(); Assertions.assertEquals(metadataInfo, metadataInfo2); Field initiatedField = MetadataInfo.class.getDeclaredField("initiated"); initiatedField.setAccessible(true); Assertions.assertInstanceOf(AtomicBoolean.class, initiatedField.get(metadataInfo2)); Assertions.assertFalse(((AtomicBoolean) initiatedField.get(metadataInfo2)).get()); } @Test void testCal() { MetadataInfo metadataInfo = new MetadataInfo("demo"); // export normal url again metadataInfo.addService(url); metadataInfo.calAndGetRevision(); metadataInfo.addService(url2); metadataInfo.calAndGetRevision(); metadataInfo.addService(url3); metadataInfo.calAndGetRevision(); Map<String, Object> ret = JsonUtils.toJavaObject(metadataInfo.getContent(), Map.class); assertNull(ret.get("content")); assertNull(ret.get("rawMetadataInfo")); } @Test void testPayload() { MetadataInfo metadataInfo = new MetadataInfo("demo"); metadataInfo.addService(url4); MetadataInfo.ServiceInfo serviceInfo4 = metadataInfo.getServiceInfo(url4.getProtocolServiceKey()); assertNotNull(serviceInfo4); assertEquals("1024", serviceInfo4.getParameter(PAYLOAD)); } }
7,185
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/DemoService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata; import org.apache.dubbo.metadata.rest.User; import java.util.List; /** * DemoService */ public interface DemoService { String sayName(String name); void throwRuntimeException() throws RuntimeException; List<User> getUsers(List<User> users); int echo(int i); }
7,186
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/AbstractServiceNameMappingTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; 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 static org.apache.dubbo.common.constants.RegistryConstants.PROVIDED_BY; import static org.apache.dubbo.common.constants.RegistryConstants.SUBSCRIBED_SERVICE_NAMES_KEY; /** * @see AbstractServiceNameMapping */ class AbstractServiceNameMappingTest { private MockServiceNameMapping mapping = new MockServiceNameMapping(ApplicationModel.defaultModel()); private MockServiceNameMapping2 mapping2 = new MockServiceNameMapping2(ApplicationModel.defaultModel()); URL url = URL.valueOf("dubbo://127.0.0.1:21880/" + AbstractServiceNameMappingTest.class.getName()); @BeforeEach public void setUp() throws Exception {} @AfterEach public void clearup() { mapping.removeCachedMapping(ServiceNameMapping.buildMappingKey(url)); } @Test void testGetServices() { url = url.addParameter(PROVIDED_BY, "app1,app2"); Set<String> services = mapping.getMapping(url); Assertions.assertTrue(services.contains("app1")); Assertions.assertTrue(services.contains("app2")); // // remove mapping cache, check get() works. // mapping.removeCachedMapping(ServiceNameMapping.buildMappingKey(url)); // services = mapping.initInterfaceAppMapping(url); // Assertions.assertTrue(services.contains("remote-app1")); // Assertions.assertTrue(services.contains("remote-app2")); // Assertions.assertNotNull(mapping.getCachedMapping(url)); // Assertions.assertIterableEquals(mapping.getCachedMapping(url), services); } @Test void testGetAndListener() { URL registryURL = URL.valueOf("registry://127.0.0.1:7777/test"); registryURL = registryURL.addParameter(SUBSCRIBED_SERVICE_NAMES_KEY, "registry-app1"); Set<String> services = mapping2.getAndListen(registryURL, url, null); Assertions.assertTrue(services.contains("registry-app1")); // remove mapping cache, check get() works. mapping2.removeCachedMapping(ServiceNameMapping.buildMappingKey(url)); mapping2.enabled = true; services = mapping2.getAndListen(registryURL, url, new MappingListener() { @Override public void onEvent(MappingChangedEvent event) {} @Override public void stop() {} }); Assertions.assertTrue(services.contains("remote-app3")); } private class MockServiceNameMapping extends AbstractServiceNameMapping { public boolean enabled = false; public MockServiceNameMapping(ApplicationModel applicationModel) { super(applicationModel); } @Override public Set<String> get(URL url) { return new HashSet<>(Arrays.asList("remote-app1", "remote-app2")); } @Override public Set<String> getAndListen(URL url, MappingListener mappingListener) { if (!enabled) { return Collections.emptySet(); } return new HashSet<>(Arrays.asList("remote-app3")); } @Override protected void removeListener(URL url, MappingListener mappingListener) {} @Override public boolean map(URL url) { return false; } @Override public boolean hasValidMetadataCenter() { return false; } } private class MockServiceNameMapping2 extends AbstractServiceNameMapping { public boolean enabled = false; public MockServiceNameMapping2(ApplicationModel applicationModel) { super(applicationModel); } @Override public Set<String> get(URL url) { return Collections.emptySet(); } @Override public Set<String> getAndListen(URL url, MappingListener mappingListener) { if (!enabled) { return Collections.emptySet(); } return new HashSet<>(Arrays.asList("remote-app3")); } @Override protected void removeListener(URL url, MappingListener mappingListener) {} @Override public boolean map(URL url) { return false; } @Override public boolean hasValidMetadataCenter() { return false; } } }
7,187
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/PathMatcherTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata; import org.apache.dubbo.metadata.rest.PathMatcher; import java.lang.reflect.Method; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class PathMatcherTest { @Test void testPathMatcher() { PathMatcher pathMatherMeta = new PathMatcher("/a/b/c/{path1}/d/{path2}/e"); PathMatcher requestPathMather = new PathMatcher("/a/b/c/1/d/2/e"); Assertions.assertEquals(requestPathMather, pathMatherMeta); PathMatcher requestPathMather1 = new PathMatcher("/{c}/b/c/1/d/2/e"); Assertions.assertEquals(requestPathMather, requestPathMather1); PathMatcher pathMatcher = new PathMatcher("/{d}/b/c/1/d/2/e"); pathMatcher.setGroup(null); pathMatcher.setPort(null); pathMatcher.setVersion(null); pathMatcher.setContextPath(""); Assertions.assertEquals(pathMatherMeta, pathMatcher); } @Test void testEqual() { PathMatcher pathMatherMeta = new PathMatcher("/a/b/c"); pathMatherMeta.setContextPath("/context"); PathMatcher pathMatherMeta1 = new PathMatcher("/a/b/d"); pathMatherMeta1.setContextPath("/context"); Assertions.assertNotEquals(pathMatherMeta, pathMatherMeta1); pathMatherMeta1 = new PathMatcher("/a/b/c"); pathMatherMeta1.setContextPath("/context"); Assertions.assertEquals(pathMatherMeta, pathMatherMeta1); pathMatherMeta.setContextPath("context"); pathMatherMeta1.setContextPath("context"); Assertions.assertEquals(pathMatherMeta, pathMatherMeta1); Assertions.assertEquals(pathMatherMeta.toString(), pathMatherMeta1.toString()); } @Test void testMethodCompare() { Method hashCode = null; Method equals = null; try { hashCode = Object.class.getDeclaredMethod("hashCode"); equals = Object.class.getDeclaredMethod("equals", Object.class); } catch (NoSuchMethodException e) { } // no need to compare service method PathMatcher pathMatcher = new PathMatcher(hashCode); PathMatcher pathMatchers = new PathMatcher(hashCode); Assertions.assertNotEquals(pathMatcher, pathMatchers); // equal PathMatcher pathMatherMetaHashCode = PathMatcher.getInvokeCreatePathMatcher(hashCode); PathMatcher pathMatherMetaHashCodes = new PathMatcher(hashCode); Assertions.assertEquals(pathMatherMetaHashCode, pathMatherMetaHashCodes); PathMatcher pathMatherMetaEquals = PathMatcher.getInvokeCreatePathMatcher(equals); PathMatcher pathMatherMetaEqual = PathMatcher.getInvokeCreatePathMatcher(equals); Assertions.assertEquals(pathMatherMetaEqual, pathMatherMetaEquals); Assertions.assertNotEquals(pathMatherMetaHashCode, pathMatherMetaEquals); } }
7,188
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/test/JTestMetadataReport4Test.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.test; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.metadata.MappingListener; import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum; import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier; import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier; import org.apache.dubbo.metadata.report.support.AbstractMetadataReport; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * ZookeeperRegistry */ class JTestMetadataReport4Test extends AbstractMetadataReport { private static final Logger logger = LoggerFactory.getLogger(JTestMetadataReport4Test.class); public JTestMetadataReport4Test(URL url) { super(url); } public volatile Map<String, String> store = new ConcurrentHashMap<>(); private static String getProtocol(URL url) { String protocol = url.getSide(); protocol = protocol == null ? url.getProtocol() : protocol; return protocol; } @Override protected void doStoreProviderMetadata(MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions) { store.put(providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), serviceDefinitions); } @Override protected void doStoreConsumerMetadata( MetadataIdentifier consumerMetadataIdentifier, String serviceParameterString) { store.put(consumerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), serviceParameterString); } @Override protected void doSaveMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url) { store.put(metadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), url.toFullString()); } @Override protected void doRemoveMetadata(ServiceMetadataIdentifier metadataIdentifier) { store.remove(metadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY)); } @Override protected List<String> doGetExportedURLs(ServiceMetadataIdentifier metadataIdentifier) { return Arrays.asList(store.getOrDefault(metadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), "")); } @Override protected void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urls) { store.put(subscriberMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), urls); } @Override protected String doGetSubscribedURLs(SubscriberMetadataIdentifier metadataIdentifier) { throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); } public static String getProviderKey(URL url) { return new MetadataIdentifier(url).getUniqueKey(KeyTypeEnum.UNIQUE_KEY); } public static String getConsumerKey(URL url) { return new MetadataIdentifier(url).getUniqueKey(KeyTypeEnum.UNIQUE_KEY); } @Override public String getServiceDefinition(MetadataIdentifier consumerMetadataIdentifier) { return store.get(consumerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY)); } @Override public void removeServiceAppMappingListener(String serviceKey, MappingListener listener) {} }
7,189
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/test/JTestMetadataReportFactory4Test.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.test; import org.apache.dubbo.common.URL; import org.apache.dubbo.metadata.report.MetadataReport; import org.apache.dubbo.metadata.report.support.AbstractMetadataReportFactory; /** * ZookeeperRegistryFactory. */ public class JTestMetadataReportFactory4Test extends AbstractMetadataReportFactory { @Override public MetadataReport createMetadataReport(URL url) { return new JTestMetadataReport4Test(url); } }
7,190
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/MetadataReportInstanceTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.report; import org.apache.dubbo.common.URL; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.MetadataReportConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Collections; import java.util.Map; import org.hamcrest.Matchers; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; class MetadataReportInstanceTest { private MetadataReportInstance metadataReportInstance; private MetadataReportConfig metadataReportConfig; private ConfigManager configManager; private final String registryId = "9103"; @BeforeEach public void setUp() { configManager = mock(ConfigManager.class); ApplicationModel applicationModel = spy(ApplicationModel.defaultModel()); metadataReportInstance = new MetadataReportInstance(applicationModel); URL url = URL.valueOf("metadata://127.0.0.1:20880/TestService?version=1.0.0&metadata=JTest"); metadataReportConfig = mock(MetadataReportConfig.class); when(metadataReportConfig.getUsername()).thenReturn("username"); when(metadataReportConfig.getPassword()).thenReturn("password"); when(metadataReportConfig.getApplicationModel()).thenReturn(applicationModel); when(metadataReportConfig.toUrl()).thenReturn(url); when(metadataReportConfig.getScopeModel()).thenReturn(applicationModel); when(metadataReportConfig.getRegistry()).thenReturn(registryId); when(configManager.getMetadataConfigs()).thenReturn(Collections.emptyList()); when(applicationModel.getApplicationConfigManager()).thenReturn(configManager); when(applicationModel.getApplicationConfigManager().getApplicationOrElseThrow()) .thenReturn(new ApplicationConfig("test")); when(applicationModel.getCurrentConfig()).thenReturn(new ApplicationConfig("test")); } @Test void test() { Assertions.assertNull( metadataReportInstance.getMetadataReport(registryId), "the metadata report was not initialized."); assertThat(metadataReportInstance.getMetadataReports(true), Matchers.anEmptyMap()); metadataReportInstance.init(Collections.singletonList(metadataReportConfig)); MetadataReport metadataReport = metadataReportInstance.getMetadataReport(registryId); Assertions.assertNotNull(metadataReport); MetadataReport metadataReport2 = metadataReportInstance.getMetadataReport(registryId + "NOT_EXIST"); Assertions.assertEquals(metadataReport, metadataReport2); Map<String, MetadataReport> metadataReports = metadataReportInstance.getMetadataReports(true); Assertions.assertEquals(metadataReports.size(), 1); Assertions.assertEquals(metadataReports.get(registryId), metadataReport); Assertions.assertEquals(metadataReportConfig.getUsername(), "username"); Assertions.assertEquals(metadataReportConfig.getPassword(), "password"); } }
7,191
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/BaseApplicationMetadataIdentifierTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.report.identifier; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class BaseApplicationMetadataIdentifierTest { private BaseApplicationMetadataIdentifier baseApplicationMetadataIdentifier; { baseApplicationMetadataIdentifier = new BaseApplicationMetadataIdentifier(); baseApplicationMetadataIdentifier.application = "app"; } @Test void getUniqueKey() { String uniqueKey = baseApplicationMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY, "reversion"); Assertions.assertEquals(uniqueKey, "app:reversion"); String uniqueKey2 = baseApplicationMetadataIdentifier.getUniqueKey(KeyTypeEnum.PATH, "reversion"); Assertions.assertEquals(uniqueKey2, "metadata/app/reversion"); } @Test void getIdentifierKey() { String identifierKey = baseApplicationMetadataIdentifier.getIdentifierKey("reversion"); Assertions.assertEquals(identifierKey, "app:reversion"); } }
7,192
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/KeyTypeEnumTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.report.identifier; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * {@link KeyTypeEnum} Test-Cases * * @since 2.7.8 */ class KeyTypeEnumTest { /** * {@link KeyTypeEnum#build(String, String...)} */ @Test void testBuild() { assertEquals("/A/B/C", KeyTypeEnum.PATH.build("/A", "/B", "C")); assertEquals("A:B:C", KeyTypeEnum.UNIQUE_KEY.build("A", "B", "C")); } }
7,193
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/BaseServiceMetadataIdentifierTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.report.identifier; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class BaseServiceMetadataIdentifierTest { private BaseServiceMetadataIdentifier baseServiceMetadataIdentifier; { baseServiceMetadataIdentifier = new BaseServiceMetadataIdentifier(); baseServiceMetadataIdentifier.version = "1.0.0"; baseServiceMetadataIdentifier.group = "test"; baseServiceMetadataIdentifier.side = "provider"; baseServiceMetadataIdentifier.serviceInterface = "BaseServiceMetadataIdentifierTest"; } @Test void getUniqueKey() { String uniqueKey = baseServiceMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY, "appName"); Assertions.assertEquals(uniqueKey, "BaseServiceMetadataIdentifierTest:1.0.0:test:provider:appName"); String uniqueKey2 = baseServiceMetadataIdentifier.getUniqueKey(KeyTypeEnum.PATH, "appName"); Assertions.assertEquals(uniqueKey2, "metadata/BaseServiceMetadataIdentifierTest/1.0.0/test/provider/appName"); } @Test void getIdentifierKey() { String identifierKey = baseServiceMetadataIdentifier.getIdentifierKey("appName"); Assertions.assertEquals(identifierKey, "BaseServiceMetadataIdentifierTest:1.0.0:test:provider:appName"); } }
7,194
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/MetadataIdentifierTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.report.identifier; import org.apache.dubbo.metadata.MetadataConstants; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; /** * 2019/1/7 */ class MetadataIdentifierTest { @Test void testGetUniqueKey() { String interfaceName = "org.apache.dubbo.metadata.integration.InterfaceNameTestService"; String version = "1.0.0.zk.md"; String group = null; String application = "vic.zk.md"; MetadataIdentifier providerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE, application); Assertions.assertEquals( providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.PATH), "metadata" + PATH_SEPARATOR + interfaceName + PATH_SEPARATOR + (version == null ? "" : (version + PATH_SEPARATOR)) + (group == null ? "" : (group + PATH_SEPARATOR)) + PROVIDER_SIDE + PATH_SEPARATOR + application); Assertions.assertEquals( providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), interfaceName + MetadataConstants.KEY_SEPARATOR + (version == null ? "" : version) + MetadataConstants.KEY_SEPARATOR + (group == null ? "" : group) + MetadataConstants.KEY_SEPARATOR + PROVIDER_SIDE + MetadataConstants.KEY_SEPARATOR + application); } }
7,195
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactoryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.report.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.metadata.MappingListener; import org.apache.dubbo.metadata.definition.model.ServiceDefinition; import org.apache.dubbo.metadata.report.MetadataReport; import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier; import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * 2018/9/14 */ class AbstractMetadataReportFactoryTest { private AbstractMetadataReportFactory metadataReportFactory = new AbstractMetadataReportFactory() { @Override protected MetadataReport createMetadataReport(URL url) { return new MetadataReport() { @Override public void storeProviderMetadata( MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) { store.put(providerMetadataIdentifier.getIdentifierKey(), JsonUtils.toJson(serviceDefinition)); } @Override public void saveServiceMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url) {} @Override public void removeServiceMetadata(ServiceMetadataIdentifier metadataIdentifier) {} @Override public void saveSubscribedData( SubscriberMetadataIdentifier subscriberMetadataIdentifier, Set<String> urls) {} @Override public List<String> getExportedURLs(ServiceMetadataIdentifier metadataIdentifier) { return null; } @Override public void destroy() {} @Override public List<String> getSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) { return null; } @Override public void removeServiceAppMappingListener(String serviceKey, MappingListener listener) {} @Override public boolean shouldReportDefinition() { return true; } @Override public boolean shouldReportMetadata() { return false; } @Override public String getServiceDefinition(MetadataIdentifier consumerMetadataIdentifier) { return null; } @Override public void storeConsumerMetadata( MetadataIdentifier consumerMetadataIdentifier, Map serviceParameterMap) { store.put(consumerMetadataIdentifier.getIdentifierKey(), JsonUtils.toJson(serviceParameterMap)); } Map<String, String> store = new ConcurrentHashMap<>(); }; } }; @Test void testGetOneMetadataReport() { URL url = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic"); MetadataReport metadataReport1 = metadataReportFactory.getMetadataReport(url); MetadataReport metadataReport2 = metadataReportFactory.getMetadataReport(url); Assertions.assertEquals(metadataReport1, metadataReport2); } @Test void testGetOneMetadataReportForIpFormat() { String hostName = NetUtils.getLocalAddress().getHostName(); String ip = NetUtils.getIpByHost(hostName); URL url1 = URL.valueOf( "zookeeper://" + hostName + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic"); URL url2 = URL.valueOf("zookeeper://" + ip + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic"); MetadataReport metadataReport1 = metadataReportFactory.getMetadataReport(url1); MetadataReport metadataReport2 = metadataReportFactory.getMetadataReport(url2); Assertions.assertEquals(metadataReport1, metadataReport2); } @Test void testGetForDiffService() { URL url1 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService1?version=1.0.0&application=vic"); URL url2 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService2?version=1.0.0&application=vic"); MetadataReport metadataReport1 = metadataReportFactory.getMetadataReport(url1); MetadataReport metadataReport2 = metadataReportFactory.getMetadataReport(url2); Assertions.assertEquals(metadataReport1, metadataReport2); } @Test void testGetForDiffGroup() { URL url1 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic&group=aaa"); URL url2 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic&group=bbb"); MetadataReport metadataReport1 = metadataReportFactory.getMetadataReport(url1); MetadataReport metadataReport2 = metadataReportFactory.getMetadataReport(url2); Assertions.assertNotEquals(metadataReport1, metadataReport2); } }
7,196
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.report.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.metadata.MappingListener; import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder; import org.apache.dubbo.metadata.definition.model.FullServiceDefinition; import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum; import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier; import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadPoolExecutor; 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 static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; class AbstractMetadataReportTest { private NewMetadataReport abstractMetadataReport; private ApplicationModel applicationModel; @BeforeEach public void before() { // set the simple name of current class as the application name FrameworkModel frameworkModel = FrameworkModel.defaultModel(); applicationModel = frameworkModel.newApplication(); applicationModel .getApplicationConfigManager() .setApplication(new ApplicationConfig(getClass().getSimpleName())); URL url = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic"); abstractMetadataReport = new NewMetadataReport(url, applicationModel); } @AfterEach public void reset() { // reset ApplicationModel.reset(); } @Test void testGetProtocol() { URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic&side=provider"); String protocol = abstractMetadataReport.getProtocol(url); assertEquals("provider", protocol); URL url2 = URL.valueOf("consumer://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic"); String protocol2 = abstractMetadataReport.getProtocol(url2); assertEquals("consumer", protocol2); } @Test void testStoreProviderUsual() throws ClassNotFoundException { String interfaceName = "org.apache.dubbo.metadata.store.InterfaceNameTestService"; String version = "1.0.0"; String group = null; String application = "vic"; ThreadPoolExecutor reportCacheExecutor = (ThreadPoolExecutor) abstractMetadataReport.getReportCacheExecutor(); long completedTaskCount1 = reportCacheExecutor.getCompletedTaskCount(); MetadataIdentifier providerMetadataIdentifier = storeProvider(abstractMetadataReport, interfaceName, version, group, application); await().until(() -> reportCacheExecutor.getCompletedTaskCount() > completedTaskCount1); Assertions.assertNotNull( abstractMetadataReport.store.get(providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY))); } @Test void testStoreProviderSync() throws ClassNotFoundException { String interfaceName = "org.apache.dubbo.metadata.store.InterfaceNameTestService"; String version = "1.0.0"; String group = null; String application = "vic"; abstractMetadataReport.syncReport = true; MetadataIdentifier providerMetadataIdentifier = storeProvider(abstractMetadataReport, interfaceName, version, group, application); Assertions.assertNotNull( abstractMetadataReport.store.get(providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY))); } @Test void testFileExistAfterPut() throws ClassNotFoundException { // just for one method URL singleUrl = URL.valueOf( "redis://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.metadata.store.InterfaceNameTestService?version=1.0.0&application=singleTest"); NewMetadataReport singleMetadataReport = new NewMetadataReport(singleUrl, applicationModel); assertFalse(singleMetadataReport.file.exists()); String interfaceName = "org.apache.dubbo.metadata.store.InterfaceNameTestService"; String version = "1.0.0"; String group = null; String application = "vic"; ThreadPoolExecutor reportCacheExecutor = (ThreadPoolExecutor) singleMetadataReport.getReportCacheExecutor(); long completedTaskCount1 = reportCacheExecutor.getCompletedTaskCount(); MetadataIdentifier providerMetadataIdentifier = storeProvider(singleMetadataReport, interfaceName, version, group, application); await().until(() -> reportCacheExecutor.getCompletedTaskCount() > completedTaskCount1); assertTrue(singleMetadataReport.file.exists()); assertTrue(singleMetadataReport.properties.containsKey( providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY))); } @Test void testRetry() throws ClassNotFoundException { String interfaceName = "org.apache.dubbo.metadata.store.RetryTestService"; String version = "1.0.0.retry"; String group = null; String application = "vic.retry"; URL storeUrl = URL.valueOf("retryReport://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestServiceForRetry?version=1.0.0.retry&application=vic.retry"); RetryMetadataReport retryReport = new RetryMetadataReport(storeUrl, 2, applicationModel); retryReport.metadataReportRetry.retryPeriod = 400L; URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic"); Assertions.assertNull(retryReport.metadataReportRetry.retryScheduledFuture); assertEquals(0, retryReport.metadataReportRetry.retryCounter.get()); assertTrue(retryReport.store.isEmpty()); assertTrue(retryReport.failedReports.isEmpty()); ThreadPoolExecutor reportCacheExecutor = (ThreadPoolExecutor) retryReport.getReportCacheExecutor(); ScheduledThreadPoolExecutor retryExecutor = (ScheduledThreadPoolExecutor) retryReport.getMetadataReportRetry().getRetryExecutor(); long completedTaskCount1 = reportCacheExecutor.getCompletedTaskCount(); long completedTaskCount2 = retryExecutor.getCompletedTaskCount(); storeProvider(retryReport, interfaceName, version, group, application); await().until(() -> reportCacheExecutor.getCompletedTaskCount() > completedTaskCount1); assertTrue(retryReport.store.isEmpty()); assertFalse(retryReport.failedReports.isEmpty()); assertNotNull(retryReport.metadataReportRetry.retryScheduledFuture); await().until(() -> retryExecutor.getCompletedTaskCount() > completedTaskCount2 + 2); assertNotEquals(0, retryReport.metadataReportRetry.retryCounter.get()); assertTrue(retryReport.metadataReportRetry.retryCounter.get() >= 3); assertFalse(retryReport.store.isEmpty()); assertTrue(retryReport.failedReports.isEmpty()); } @Test void testRetryCancel() throws ClassNotFoundException { String interfaceName = "org.apache.dubbo.metadata.store.RetryTestService"; String version = "1.0.0.retrycancel"; String group = null; String application = "vic.retry"; URL storeUrl = URL.valueOf("retryReport://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestServiceForRetryCancel?version=1.0.0.retrycancel&application=vic.retry"); RetryMetadataReport retryReport = new RetryMetadataReport(storeUrl, 2, applicationModel); retryReport.metadataReportRetry.retryPeriod = 150L; retryReport.metadataReportRetry.retryTimesIfNonFail = 2; retryReport.semaphore = new Semaphore(1); ScheduledThreadPoolExecutor retryExecutor = (ScheduledThreadPoolExecutor) retryReport.getMetadataReportRetry().getRetryExecutor(); long completedTaskCount = retryExecutor.getCompletedTaskCount(); storeProvider(retryReport, interfaceName, version, group, application); // Wait for the assignment of retryScheduledFuture to complete await().until(() -> retryReport.metadataReportRetry.retryScheduledFuture != null); assertFalse(retryReport.metadataReportRetry.retryScheduledFuture.isCancelled()); assertFalse(retryReport.metadataReportRetry.retryExecutor.isShutdown()); retryReport.semaphore.release(2); await().until(() -> retryExecutor.getCompletedTaskCount() > completedTaskCount + 2); await().untilAsserted(() -> assertTrue(retryReport.metadataReportRetry.retryScheduledFuture.isCancelled())); await().untilAsserted(() -> assertTrue(retryReport.metadataReportRetry.retryExecutor.isShutdown())); } private MetadataIdentifier storeProvider( AbstractMetadataReport abstractMetadataReport, String interfaceName, String version, String group, String application) throws ClassNotFoundException { URL url = URL.valueOf( "xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + "?version=" + version + "&application=" + application + (group == null ? "" : "&group=" + group) + "&testPKey=8989"); MetadataIdentifier providerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE, application); Class interfaceClass = Class.forName(interfaceName); FullServiceDefinition fullServiceDefinition = ServiceDefinitionBuilder.buildFullDefinition(interfaceClass, url.getParameters()); abstractMetadataReport.storeProviderMetadata(providerMetadataIdentifier, fullServiceDefinition); return providerMetadataIdentifier; } private MetadataIdentifier storeConsumer( AbstractMetadataReport abstractMetadataReport, String interfaceName, String version, String group, String application, Map<String, String> tmp) { URL url = URL.valueOf( "xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + "?version=" + version + "&application=" + application + (group == null ? "" : "&group=" + group) + "&testPKey=9090"); tmp.putAll(url.getParameters()); MetadataIdentifier consumerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, CONSUMER_SIDE, application); abstractMetadataReport.storeConsumerMetadata(consumerMetadataIdentifier, tmp); return consumerMetadataIdentifier; } @Test void testPublishAll() throws ClassNotFoundException { ThreadPoolExecutor reportCacheExecutor = (ThreadPoolExecutor) abstractMetadataReport.getReportCacheExecutor(); assertTrue(abstractMetadataReport.store.isEmpty()); assertTrue(abstractMetadataReport.allMetadataReports.isEmpty()); String interfaceName = "org.apache.dubbo.metadata.store.InterfaceNameTestService"; String version = "1.0.0"; String group = null; String application = "vic"; long completedTaskCount1 = reportCacheExecutor.getCompletedTaskCount(); MetadataIdentifier providerMetadataIdentifier1 = storeProvider(abstractMetadataReport, interfaceName, version, group, application); await().until(() -> reportCacheExecutor.getCompletedTaskCount() > completedTaskCount1); assertEquals(1, abstractMetadataReport.allMetadataReports.size()); assertTrue(((FullServiceDefinition) abstractMetadataReport.allMetadataReports.get(providerMetadataIdentifier1)) .getParameters() .containsKey("testPKey")); long completedTaskCount2 = reportCacheExecutor.getCompletedTaskCount(); MetadataIdentifier providerMetadataIdentifier2 = storeProvider(abstractMetadataReport, interfaceName, version + "_2", group + "_2", application); await().until(() -> reportCacheExecutor.getCompletedTaskCount() > completedTaskCount2); assertEquals(2, abstractMetadataReport.allMetadataReports.size()); assertTrue(((FullServiceDefinition) abstractMetadataReport.allMetadataReports.get(providerMetadataIdentifier2)) .getParameters() .containsKey("testPKey")); assertEquals( ((FullServiceDefinition) abstractMetadataReport.allMetadataReports.get(providerMetadataIdentifier2)) .getParameters() .get("version"), version + "_2"); Map<String, String> tmpMap = new HashMap<>(); tmpMap.put("testKey", "value"); long completedTaskCount3 = reportCacheExecutor.getCompletedTaskCount(); MetadataIdentifier consumerMetadataIdentifier = storeConsumer(abstractMetadataReport, interfaceName, version + "_3", group + "_3", application, tmpMap); await().until(() -> reportCacheExecutor.getCompletedTaskCount() > completedTaskCount3); assertEquals(3, abstractMetadataReport.allMetadataReports.size()); Map tmpMapResult = (Map) abstractMetadataReport.allMetadataReports.get(consumerMetadataIdentifier); assertEquals("9090", tmpMapResult.get("testPKey")); assertEquals("value", tmpMapResult.get("testKey")); assertEquals(3, abstractMetadataReport.store.size()); abstractMetadataReport.store.clear(); assertEquals(0, abstractMetadataReport.store.size()); long completedTaskCount4 = reportCacheExecutor.getCompletedTaskCount(); abstractMetadataReport.publishAll(); await().until(() -> reportCacheExecutor.getCompletedTaskCount() > completedTaskCount4); assertEquals(3, abstractMetadataReport.store.size()); String v = abstractMetadataReport.store.get(providerMetadataIdentifier1.getUniqueKey(KeyTypeEnum.UNIQUE_KEY)); FullServiceDefinition data = JsonUtils.toJavaObject(v, FullServiceDefinition.class); checkParam(data.getParameters(), application, version); String v2 = abstractMetadataReport.store.get(providerMetadataIdentifier2.getUniqueKey(KeyTypeEnum.UNIQUE_KEY)); data = JsonUtils.toJavaObject(v2, FullServiceDefinition.class); checkParam(data.getParameters(), application, version + "_2"); String v3 = abstractMetadataReport.store.get(consumerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY)); Map v3Map = JsonUtils.toJavaObject(v3, Map.class); checkParam(v3Map, application, version + "_3"); } @Test void testCalculateStartTime() { for (int i = 0; i < 300; i++) { long t = abstractMetadataReport.calculateStartTime() + System.currentTimeMillis(); Calendar c = Calendar.getInstance(); c.setTimeInMillis(t); assertTrue(c.get(Calendar.HOUR_OF_DAY) >= 2); assertTrue(c.get(Calendar.HOUR_OF_DAY) <= 6); } } private void checkParam(Map<String, String> map, String application, String version) { assertEquals(map.get("application"), application); assertEquals(map.get("version"), version); } private static class NewMetadataReport extends AbstractMetadataReport { Map<String, String> store = new ConcurrentHashMap<>(); public NewMetadataReport(URL metadataReportURL, ApplicationModel applicationModel) { super(metadataReportURL); this.applicationModel = applicationModel; } @Override protected void doStoreProviderMetadata( MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions) { store.put(providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), serviceDefinitions); } @Override protected void doStoreConsumerMetadata( MetadataIdentifier consumerMetadataIdentifier, String serviceParameterString) { store.put(consumerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), serviceParameterString); } @Override protected void doSaveMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url) { throw new UnsupportedOperationException( "This extension does not support working as a remote metadata center."); } @Override protected void doRemoveMetadata(ServiceMetadataIdentifier metadataIdentifier) { throw new UnsupportedOperationException( "This extension does not support working as a remote metadata center."); } @Override protected List<String> doGetExportedURLs(ServiceMetadataIdentifier metadataIdentifier) { throw new UnsupportedOperationException( "This extension does not support working as a remote metadata center."); } @Override protected void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urls) {} @Override protected String doGetSubscribedURLs(SubscriberMetadataIdentifier metadataIdentifier) { throw new UnsupportedOperationException( "This extension does not support working as a remote metadata center."); } @Override public String getServiceDefinition(MetadataIdentifier consumerMetadataIdentifier) { throw new UnsupportedOperationException( "This extension does not support working as a remote metadata center."); } @Override public void removeServiceAppMappingListener(String serviceKey, MappingListener listener) { throw new UnsupportedOperationException( "This extension does not support working as a remote metadata center."); } } private static class RetryMetadataReport extends AbstractMetadataReport { Map<String, String> store = new ConcurrentHashMap<>(); int needRetryTimes; int executeTimes = 0; Semaphore semaphore = new Semaphore(Integer.MAX_VALUE); public RetryMetadataReport(URL metadataReportURL, int needRetryTimes, ApplicationModel applicationModel) { super(metadataReportURL); this.needRetryTimes = needRetryTimes; this.applicationModel = applicationModel; } @Override protected void doStoreProviderMetadata( MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions) { ++executeTimes; System.out.println("***" + executeTimes + ";" + System.currentTimeMillis()); semaphore.acquireUninterruptibly(); if (executeTimes <= needRetryTimes) { throw new RuntimeException("must retry:" + executeTimes); } store.put(providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), serviceDefinitions); } @Override protected void doStoreConsumerMetadata( MetadataIdentifier consumerMetadataIdentifier, String serviceParameterString) { ++executeTimes; if (executeTimes <= needRetryTimes) { throw new RuntimeException("must retry:" + executeTimes); } store.put(consumerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), serviceParameterString); } @Override protected void doSaveMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url) { throw new UnsupportedOperationException( "This extension does not support working as a remote metadata center."); } @Override protected void doRemoveMetadata(ServiceMetadataIdentifier metadataIdentifier) { throw new UnsupportedOperationException( "This extension does not support working as a remote metadata center."); } @Override protected List<String> doGetExportedURLs(ServiceMetadataIdentifier metadataIdentifier) { throw new UnsupportedOperationException( "This extension does not support working as a remote metadata center."); } @Override protected void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urls) {} @Override protected String doGetSubscribedURLs(SubscriberMetadataIdentifier metadataIdentifier) { throw new UnsupportedOperationException( "This extension does not support working as a remote metadata center."); } @Override public String getServiceDefinition(MetadataIdentifier consumerMetadataIdentifier) { throw new UnsupportedOperationException( "This extension does not support working as a remote metadata center."); } @Override public void removeServiceAppMappingListener(String serviceKey, MappingListener listener) { throw new UnsupportedOperationException( "This extension does not support working as a remote metadata center."); } } }
7,197
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/filter/ExcludedParamsFilter2.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.filter; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.metadata.MetadataParamsFilter; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY; @Activate(order = 2) // Will take effect before ExcludedParamsFilter public class ExcludedParamsFilter2 implements MetadataParamsFilter { @Override public String[] serviceParamsIncluded() { return new String[0]; } @Override public String[] serviceParamsExcluded() { return new String[] {DEPRECATED_KEY, SIDE_KEY}; } /** * Not included in this test */ @Override public String[] instanceParamsIncluded() { return new String[0]; } @Override public String[] instanceParamsExcluded() { return new String[0]; } }
7,198
0
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/filter/CustomizedParamsFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata.filter; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.metadata.MetadataParamsFilter; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; @Activate(order = 3) // Will take effect after ExcludedParamsFilter public class CustomizedParamsFilter implements MetadataParamsFilter { @Override public String[] serviceParamsIncluded() { return new String[] {APPLICATION_KEY, TIMEOUT_KEY, GROUP_KEY, VERSION_KEY}; } @Override public String[] serviceParamsExcluded() { return new String[0]; } /** * Not included in this test */ @Override public String[] instanceParamsIncluded() { return new String[0]; } @Override public String[] instanceParamsExcluded() { return new String[0]; } }
7,199