Search in sources :

Example 86 with TypeElement

use of javax.lang.model.element.TypeElement in project camel by apache.

the class SpringAnnotationProcessor method processElement.

private void processElement(ProcessingEnvironment processingEnv, RoundEnvironment roundEnv, TypeElement classElement, XmlElement element, XmlElementRef elementRef, VariableElement fieldElement, Set<EipOption> eipOptions, String prefix) {
    Elements elementUtils = processingEnv.getElementUtils();
    String fieldName;
    fieldName = fieldElement.getSimpleName().toString();
    if (element != null || elementRef != null) {
        String kind = "element";
        String name = element != null ? element.name() : elementRef.name();
        if (isNullOrEmpty(name) || "##default".equals(name)) {
            name = fieldName;
        }
        name = prefix + name;
        TypeMirror fieldType = fieldElement.asType();
        String fieldTypeName = fieldType.toString();
        TypeElement fieldTypeElement = findTypeElement(processingEnv, roundEnv, fieldTypeName);
        String defaultValue = findDefaultValue(fieldElement, fieldTypeName);
        String docComment = findJavaDoc(elementUtils, fieldElement, fieldName, name, classElement, true);
        if (isNullOrEmpty(docComment)) {
            Metadata metadata = fieldElement.getAnnotation(Metadata.class);
            docComment = metadata != null ? metadata.description() : null;
        }
        boolean required = element != null ? element.required() : elementRef.required();
        // metadata may overrule element required
        required = findRequired(fieldElement, required);
        // gather enums
        Set<String> enums = new LinkedHashSet<String>();
        boolean isEnum = fieldTypeElement != null && fieldTypeElement.getKind() == ElementKind.ENUM;
        if (isEnum) {
            TypeElement enumClass = findTypeElement(processingEnv, roundEnv, fieldTypeElement.asType().toString());
            // find all the enum constants which has the possible enum value that can be used
            List<VariableElement> fields = ElementFilter.fieldsIn(enumClass.getEnclosedElements());
            for (VariableElement var : fields) {
                if (var.getKind() == ElementKind.ENUM_CONSTANT) {
                    String val = var.toString();
                    enums.add(val);
                }
            }
        }
        // is it a definition/factory-bean type then its a oneOf
        TreeSet oneOfTypes = new TreeSet<String>();
        if (fieldTypeName.endsWith("Definition") || fieldTypeName.endsWith("FactoryBean")) {
            TypeElement definitionClass = findTypeElement(processingEnv, roundEnv, fieldTypeElement.asType().toString());
            if (definitionClass != null) {
                XmlRootElement rootElement = definitionClass.getAnnotation(XmlRootElement.class);
                if (rootElement != null) {
                    String childName = rootElement.name();
                    if (childName != null) {
                        oneOfTypes.add(childName);
                    }
                }
            }
        } else if (fieldTypeName.endsWith("Definition>") || fieldTypeName.endsWith("FactoryBean>")) {
            // its a list so we need to load the generic type
            String typeName = Strings.between(fieldTypeName, "<", ">");
            TypeElement definitionClass = findTypeElement(processingEnv, roundEnv, typeName);
            if (definitionClass != null) {
                XmlRootElement rootElement = definitionClass.getAnnotation(XmlRootElement.class);
                if (rootElement != null) {
                    String childName = rootElement.name();
                    if (childName != null) {
                        oneOfTypes.add(childName);
                    }
                }
            }
        }
        boolean oneOf = !oneOfTypes.isEmpty();
        boolean deprecated = fieldElement.getAnnotation(Deprecated.class) != null;
        boolean asPredicate = false;
        String displayName = null;
        Metadata metadata = fieldElement.getAnnotation(Metadata.class);
        if (metadata != null) {
            displayName = metadata.displayName();
        }
        EipOption ep = new EipOption(name, displayName, kind, fieldTypeName, required, defaultValue, docComment, deprecated, isEnum, enums, oneOf, oneOfTypes, asPredicate);
        eipOptions.add(ep);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) XmlRootElement(javax.xml.bind.annotation.XmlRootElement) TypeElement(javax.lang.model.element.TypeElement) AnnotationProcessorHelper.findTypeElement(org.apache.camel.tools.apt.AnnotationProcessorHelper.findTypeElement) Metadata(org.apache.camel.spi.Metadata) VariableElement(javax.lang.model.element.VariableElement) Elements(javax.lang.model.util.Elements) XmlElements(javax.xml.bind.annotation.XmlElements) TypeMirror(javax.lang.model.type.TypeMirror) TreeSet(java.util.TreeSet)

Example 87 with TypeElement

use of javax.lang.model.element.TypeElement in project auto by google.

the class BasicAnnotationProcessor method validElements.

/**
   * Returns the valid annotated elements contained in all of the deferred elements. If none are
   * found for a deferred element, defers it again.
   */
private ImmutableSetMultimap<Class<? extends Annotation>, Element> validElements(ImmutableMap<String, Optional<? extends Element>> deferredElements, RoundEnvironment roundEnv) {
    ImmutableSetMultimap.Builder<Class<? extends Annotation>, Element> deferredElementsByAnnotationBuilder = ImmutableSetMultimap.builder();
    for (Entry<String, Optional<? extends Element>> deferredTypeElementEntry : deferredElements.entrySet()) {
        Optional<? extends Element> deferredElement = deferredTypeElementEntry.getValue();
        if (deferredElement.isPresent()) {
            findAnnotatedElements(deferredElement.get(), getSupportedAnnotationClasses(), deferredElementsByAnnotationBuilder);
        } else {
            deferredElementNames.add(ElementName.forTypeName(deferredTypeElementEntry.getKey()));
        }
    }
    ImmutableSetMultimap<Class<? extends Annotation>, Element> deferredElementsByAnnotation = deferredElementsByAnnotationBuilder.build();
    ImmutableSetMultimap.Builder<Class<? extends Annotation>, Element> validElements = ImmutableSetMultimap.builder();
    Set<ElementName> validElementNames = new LinkedHashSet<ElementName>();
    // Look at the elements we've found and the new elements from this round and validate them.
    for (Class<? extends Annotation> annotationClass : getSupportedAnnotationClasses()) {
        // This should just call roundEnv.getElementsAnnotatedWith(Class) directly, but there is a bug
        // in some versions of eclipse that cause that method to crash.
        TypeElement annotationType = elements.getTypeElement(annotationClass.getCanonicalName());
        Set<? extends Element> elementsAnnotatedWith = (annotationType == null) ? ImmutableSet.<Element>of() : roundEnv.getElementsAnnotatedWith(annotationType);
        for (Element annotatedElement : Sets.union(elementsAnnotatedWith, deferredElementsByAnnotation.get(annotationClass))) {
            if (annotatedElement.getKind().equals(PACKAGE)) {
                PackageElement annotatedPackageElement = (PackageElement) annotatedElement;
                ElementName annotatedPackageName = ElementName.forPackageName(annotatedPackageElement.getQualifiedName().toString());
                boolean validPackage = validElementNames.contains(annotatedPackageName) || (!deferredElementNames.contains(annotatedPackageName) && validateElement(annotatedPackageElement));
                if (validPackage) {
                    validElements.put(annotationClass, annotatedPackageElement);
                    validElementNames.add(annotatedPackageName);
                } else {
                    deferredElementNames.add(annotatedPackageName);
                }
            } else {
                TypeElement enclosingType = getEnclosingType(annotatedElement);
                ElementName enclosingTypeName = ElementName.forTypeName(enclosingType.getQualifiedName().toString());
                boolean validEnclosingType = validElementNames.contains(enclosingTypeName) || (!deferredElementNames.contains(enclosingTypeName) && validateElement(enclosingType));
                if (validEnclosingType) {
                    validElements.put(annotationClass, annotatedElement);
                    validElementNames.add(enclosingTypeName);
                } else {
                    deferredElementNames.add(enclosingTypeName);
                }
            }
        }
    }
    return validElements.build();
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Optional(com.google.common.base.Optional) ImmutableSetMultimap(com.google.common.collect.ImmutableSetMultimap) TypeElement(javax.lang.model.element.TypeElement) PackageElement(javax.lang.model.element.PackageElement) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Element(javax.lang.model.element.Element) SuperficialValidation.validateElement(com.google.auto.common.SuperficialValidation.validateElement) Annotation(java.lang.annotation.Annotation) PackageElement(javax.lang.model.element.PackageElement)

Example 88 with TypeElement

use of javax.lang.model.element.TypeElement in project auto by google.

the class TypeSimplifierTest method testImportsForComplicatedTypes.

@Test
public void testImportsForComplicatedTypes() {
    TypeElement list = typeElementOf(java.util.List.class);
    TypeElement map = typeElementOf(java.util.Map.class);
    Set<TypeMirror> types = typeMirrorSet(typeUtils.getPrimitiveType(TypeKind.INT), typeMirrorOf(java.util.regex.Pattern.class), // List<Timer>
    typeUtils.getDeclaredType(// List<Timer>
    list, typeMirrorOf(java.util.Timer.class)), // Map<? extends Timer, ? super BigInteger>
    typeUtils.getDeclaredType(// Map<? extends Timer, ? super BigInteger>
    map, typeUtils.getWildcardType(typeMirrorOf(java.util.Timer.class), null), typeUtils.getWildcardType(null, typeMirrorOf(java.math.BigInteger.class))));
    // Timer is referenced twice but should obviously only be imported once.
    TypeSimplifier typeSimplifier = new TypeSimplifier(typeUtils, "foo.bar", types, baseWithoutContainedTypes());
    assertThat(typeSimplifier.typesToImport()).containsExactly("java.math.BigInteger", "java.util.List", "java.util.Map", "java.util.Timer", "java.util.regex.Pattern").inOrder();
}
Also used : TypeMirror(javax.lang.model.type.TypeMirror) TypeElement(javax.lang.model.element.TypeElement) Test(org.junit.Test)

Example 89 with TypeElement

use of javax.lang.model.element.TypeElement in project auto by google.

the class TypeSimplifierTest method testSimplifyComplicatedTypes.

@Test
public void testSimplifyComplicatedTypes() {
    // This test constructs a set of types and feeds them to TypeSimplifier. Then it verifies that
    // the resultant rewrites of those types are what we would expect.
    TypeElement list = typeElementOf(java.util.List.class);
    TypeElement map = typeElementOf(java.util.Map.class);
    TypeMirror string = typeMirrorOf(java.lang.String.class);
    TypeMirror integer = typeMirrorOf(java.lang.Integer.class);
    TypeMirror pattern = typeMirrorOf(java.util.regex.Pattern.class);
    TypeMirror timer = typeMirrorOf(java.util.Timer.class);
    TypeMirror bigInteger = typeMirrorOf(java.math.BigInteger.class);
    Set<TypeMirror> types = typeMirrorSet(typeUtils.getPrimitiveType(TypeKind.INT), typeUtils.getArrayType(typeUtils.getPrimitiveType(TypeKind.BYTE)), pattern, typeUtils.getArrayType(pattern), typeUtils.getArrayType(typeUtils.getArrayType(pattern)), typeUtils.getDeclaredType(list, typeUtils.getWildcardType(null, null)), typeUtils.getDeclaredType(list, timer), typeUtils.getDeclaredType(map, string, integer), typeUtils.getDeclaredType(map, typeUtils.getWildcardType(timer, null), typeUtils.getWildcardType(null, bigInteger)));
    Set<String> expectedSimplifications = ImmutableSet.of("int", "byte[]", "Pattern", "Pattern[]", "Pattern[][]", "List<?>", "List<Timer>", "Map<String, Integer>", "Map<? extends Timer, ? super BigInteger>");
    TypeSimplifier typeSimplifier = new TypeSimplifier(typeUtils, "foo.bar", types, baseWithoutContainedTypes());
    Set<String> actualSimplifications = new HashSet<String>();
    for (TypeMirror type : types) {
        actualSimplifications.add(typeSimplifier.simplify(type));
    }
    assertThat(actualSimplifications).isEqualTo(expectedSimplifications);
}
Also used : TypeMirror(javax.lang.model.type.TypeMirror) TypeElement(javax.lang.model.element.TypeElement) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 90 with TypeElement

use of javax.lang.model.element.TypeElement in project auto by google.

the class AutoValueProcessor method getFieldOfClasses.

/**
   * Returns the contents of a {@code Class[]}-typed field in an annotation.
   *
   * <p>This method is needed because directly reading the value of such a field from an
   * AnnotationMirror throws: <pre>
   * javax.lang.model.type.MirroredTypeException: Attempt to access Class object for TypeMirror Foo.
   * </pre>
   *
   * @param element The element on which the annotation is present. e.g. the class being processed
   *     by AutoValue.
   * @param annotation The class of the annotation to read from., e.g. {@link
   *     AutoValue.CopyAnnotations}.
   * @param fieldName The name of the field to read, e.g. "exclude".
   * @return a set of fully-qualified names of classes appearing in 'fieldName' on 'annotation' on
   *     'element'.
   */
private ImmutableSet<String> getFieldOfClasses(Element element, Class<? extends Annotation> annotation, String fieldName, Elements elementUtils) {
    TypeElement annotationElement = elementUtils.getTypeElement(annotation.getCanonicalName());
    if (annotationElement == null) {
        // This can happen if the annotation is on the -processorpath but not on the -classpath.
        return ImmutableSet.of();
    }
    TypeMirror annotationMirror = annotationElement.asType();
    for (AnnotationMirror annot : element.getAnnotationMirrors()) {
        if (!typeUtils.isSameType(annot.getAnnotationType(), annotationMirror)) {
            continue;
        }
        for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annot.getElementValues().entrySet()) {
            if (fieldName.contentEquals(entry.getKey().getSimpleName())) {
                ImmutableSet.Builder<String> result = ImmutableSet.builder();
                @SuppressWarnings("unchecked") List<AnnotationValue> annotationsToCopy = (List<AnnotationValue>) entry.getValue().getValue();
                for (AnnotationValue annotationValue : annotationsToCopy) {
                    String qualifiedName = ((TypeElement) ((DeclaredType) annotationValue.getValue()).asElement()).getQualifiedName().toString();
                    result.add(qualifiedName);
                }
                return result.build();
            }
        }
    }
    return ImmutableSet.of();
}
Also used : TypeElement(javax.lang.model.element.TypeElement) AnnotationMirror(javax.lang.model.element.AnnotationMirror) ImmutableSet(com.google.common.collect.ImmutableSet) TypeMirror(javax.lang.model.type.TypeMirror) AnnotationValue(javax.lang.model.element.AnnotationValue) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) ImmutableBiMap(com.google.common.collect.ImmutableBiMap) DeclaredType(javax.lang.model.type.DeclaredType)

Aggregations

TypeElement (javax.lang.model.element.TypeElement)1562 ExecutableElement (javax.lang.model.element.ExecutableElement)517 Element (javax.lang.model.element.Element)502 TypeMirror (javax.lang.model.type.TypeMirror)420 VariableElement (javax.lang.model.element.VariableElement)333 DeclaredType (javax.lang.model.type.DeclaredType)201 ArrayList (java.util.ArrayList)177 PackageElement (javax.lang.model.element.PackageElement)159 AnnotationMirror (javax.lang.model.element.AnnotationMirror)151 Test (org.junit.Test)136 HashMap (java.util.HashMap)118 HashSet (java.util.HashSet)109 Elements (javax.lang.model.util.Elements)101 Map (java.util.Map)98 IOException (java.io.IOException)97 List (java.util.List)97 ClassName (com.squareup.javapoet.ClassName)88 Test (org.junit.jupiter.api.Test)80 MethodSpec (com.squareup.javapoet.MethodSpec)72 TypeSpec (com.squareup.javapoet.TypeSpec)63