Example usage for javax.annotation.processing RoundEnvironment getElementsAnnotatedWith

List of usage examples for javax.annotation.processing RoundEnvironment getElementsAnnotatedWith

Introduction

In this page you can find the example usage for javax.annotation.processing RoundEnvironment getElementsAnnotatedWith.

Prototype

Set<? extends Element> getElementsAnnotatedWith(Class<? extends Annotation> a);

Source Link

Document

Returns the elements annotated with the given annotation type.

Usage

From source file:uniol.apt.compiler.AbstractServiceProcessor.java

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (this.finished) // only run in the first round
        return false;

    for (Element ele : roundEnv.getElementsAnnotatedWith(this.annotationClass)) {
        if (!isValidClass(ele)) {
            return false;
        }// w ww .  j a v  a  2  s. co m
        TypeElement classEle = (TypeElement) ele;
        String className = classEle.getQualifiedName().toString();
        visitClass(classEle, className);
    }

    produceOutput();

    this.finished = true; // prevent running in subsequent rounds

    return true;
}

From source file:org.eclim.annotation.CommandListingProcessor.java

public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {
    Options options = new Options();
    Pattern pattern = null;//www .  ja va2  s.co m
    String filter = this.processingEnv.getOptions().get("filter");
    if (filter != null) {
        pattern = Pattern.compile(filter);
    }
    for (TypeElement element : annotations) {
        for (Element e : env.getElementsAnnotatedWith(element)) {
            Command command = e.getAnnotation(Command.class);
            if (pattern == null || pattern.matcher(command.name()).matches()) {
                Collection<Option> opts = options.parseOptions(command.options());
                System.out.print(command.name());
                for (Option opt : opts) {
                    String display = "-" + opt.getOpt();
                    if (opt.hasArg()) {
                        display += " " + opt.getLongOpt();
                    }
                    if (opt.isRequired()) {
                        System.out.print(" " + display);
                    } else {
                        System.out.print(" [" + display + "]");
                    }
                }
                System.out.println("\n\tclass: " + e);
            }
        }
    }
    return true;
}

From source file:com.spotify.docgenerator.JacksonJerseyAnnotationProcessor.java

/**
 * Go through found REST Annotations and produce {@link ResourceClass}es from what we find.
 *//*from  www . j ava  2  s.  co  m*/
private void processFoundRestAnnotations(final TypeElement foundAnnotations, final RoundEnvironment roundEnv) {
    final Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(foundAnnotations);
    for (final Element e : elements) {
        // should always be METHOD, but just being paranoid
        if (e.getKind() != ElementKind.METHOD) {
            continue;
        }
        final ExecutableElement ee = (ExecutableElement) e;
        final List<ResourceArgument> arguments = computeMethodArguments(ee);
        final ResourceMethod method = computeMethod(ee, arguments);
        final ResourceClass klass = getParentResourceClass(e);
        klass.getMembers().add(method);
    }
}

From source file:com.spotify.docgenerator.JacksonJerseyAnnotationProcessor.java

/**
 * If we see one of these, just create an entry that the class exists (with it's javadoc),
 * but don't try to do anything fancy./*w w w  .ja  v a  2 s.  c o  m*/
 */
private void processJsonSerializeAnnotations(final RoundEnvironment roundEnv) {
    final Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(JsonSerialize.class);
    for (final Element e : elements) {
        if (e.getKind() != ElementKind.CLASS) {
            debugMessages.add("kind for " + e + " is not CLASS, but " + e.getKind());
            continue;
        }

        final TypeElement te = (TypeElement) e;
        final String className = te.getQualifiedName().toString();
        if (jsonClasses.containsKey(className)) {
            // it has already been processed by other means
            continue;
        }

        getOrCreateTransferClass(className, processingEnv.getElementUtils().getDocComment(te));
    }
}

From source file:com.spotify.docgenerator.JacksonJerseyAnnotationProcessor.java

/**
 * Go through a Jackson-annotated constructor, and produce {@link TransferClass}es representing
 * what we found.//w  ww . ja v a2 s  .co m
 */
private void processJsonPropertyAnnotations(final RoundEnvironment roundEnv) {
    final Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(JsonProperty.class);
    for (final Element e : elements) {
        if (e.getEnclosingElement() == null) {
            continue;
        }
        final Element parentElement = e.getEnclosingElement().getEnclosingElement();
        if (parentElement == null) {
            continue;
        }
        if (!(parentElement instanceof TypeElement)) {
            continue;
        }
        final TypeElement parent = (TypeElement) parentElement;
        final String parentJavaDoc = processingEnv.getElementUtils().getDocComment(parent);
        final String parentName = parent.getQualifiedName().toString();

        final TransferClass klass = getOrCreateTransferClass(parentName, parentJavaDoc);

        klass.add(e.toString(), makeTypeDescriptor(e.asType()));
    }
}

From source file:org.jraf.android.prefs.compiler.PrefsProcessor.java

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    for (TypeElement te : annotations) {
        for (Element element : roundEnv.getElementsAnnotatedWith(te)) {
            TypeElement classElement = (TypeElement) element;
            PackageElement packageElement = (PackageElement) classElement.getEnclosingElement();

            String classComment = processingEnv.getElementUtils().getDocComment(classElement);

            List<Pref> prefList = new ArrayList<Pref>();
            // Iterate over the fields of the class
            for (VariableElement variableElement : ElementFilter.fieldsIn(classElement.getEnclosedElements())) {
                if (variableElement.getModifiers().contains(Modifier.STATIC)) {
                    // Ignore constants
                    continue;
                }//from   w  w w .  j a v  a2 s  .  c o  m

                TypeMirror fieldType = variableElement.asType();
                boolean isAllowedType = PrefType.isAllowedType(fieldType);
                if (!isAllowedType) {
                    processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                            fieldType + " is not allowed here, only these types are allowed: "
                                    + PrefType.getAllowedTypes(),
                            variableElement);
                    // Problem detected: halt
                    return true;
                }

                String fieldName = variableElement.getSimpleName().toString();
                org.jraf.android.prefs.Name fieldNameAnnot = variableElement
                        .getAnnotation(org.jraf.android.prefs.Name.class);
                String prefName = getPrefName(fieldName, fieldNameAnnot);

                String prefDefaultValue = getDefaultValue(variableElement, fieldType);
                if (prefDefaultValue == null) {
                    // Problem detected: halt
                    return true;
                }

                String fieldComment = processingEnv.getElementUtils().getDocComment(variableElement);
                Pref pref = new Pref(fieldName, prefName, PrefType.from(fieldType), prefDefaultValue,
                        fieldComment);
                prefList.add(pref);
            }

            Map<String, Object> args = new HashMap<String, Object>();

            // File name (optional - also use 'value' for this)
            org.jraf.android.prefs.Prefs prefsAnnot = classElement
                    .getAnnotation(org.jraf.android.prefs.Prefs.class);
            String fileName = prefsAnnot.value();
            if (fileName.isEmpty()) {
                fileName = prefsAnnot.fileName();
            }
            if (!fileName.isEmpty())
                args.put("fileName", fileName);

            // File mode (must only appear if fileName is defined)
            int fileMode = prefsAnnot.fileMode();
            if (fileMode != -1) {
                if (fileName.isEmpty()) {
                    // File mode set, but not file name (which makes no sense)
                    processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                            "fileMode must only be set if fileName (or value) is also set", classElement);
                    // Problem detected: halt
                    return true;
                }
                args.put("fileMode", fileMode);
            }

            // Disable @Nullable generation
            args.put("disableNullable", prefsAnnot.disableNullable());

            JavaFileObject javaFileObject = null;
            try {
                // SharedPreferencesWrapper
                javaFileObject = processingEnv.getFiler()
                        .createSourceFile(classElement.getQualifiedName() + SUFFIX_PREF_WRAPPER);
                Template template = getFreemarkerConfiguration().getTemplate("prefwrapper.ftl");
                args.put("package", packageElement.getQualifiedName());
                args.put("comment", classComment);
                args.put("prefWrapperClassName", classElement.getSimpleName() + SUFFIX_PREF_WRAPPER);
                args.put("editorWrapperClassName", classElement.getSimpleName() + SUFFIX_EDITOR_WRAPPER);
                args.put("prefList", prefList);
                Writer writer = javaFileObject.openWriter();
                template.process(args, writer);
                IOUtils.closeQuietly(writer);

                // EditorWrapper
                javaFileObject = processingEnv.getFiler()
                        .createSourceFile(classElement.getQualifiedName() + "EditorWrapper");
                template = getFreemarkerConfiguration().getTemplate("editorwrapper.ftl");
                writer = javaFileObject.openWriter();
                template.process(args, writer);
                IOUtils.closeQuietly(writer);

            } catch (Exception e) {
                processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                        "En error occurred while generating Prefs code " + e.getClass() + e.getMessage(),
                        element);
                e.printStackTrace();
                // Problem detected: halt
                return true;
            }
        }
    }
    return true;
}

From source file:me.oriley.shiv.ShivProcessor.java

private void collectBindings(@NonNull RoundEnvironment env, @NonNull Map<TypeElement, BindingManager> bindings,
        @NonNull Class<? extends Annotation> annotation) throws ShivException {
    for (Element e : env.getElementsAnnotatedWith(annotation)) {
        if (e.getKind() != ElementKind.FIELD) {
            throw new ShivException(
                    e.getSimpleName() + " is annotated with @" + annotation.getName() + " but is not a field");
        }//from   ww w  . ja  v a2  s.com

        TypeMirror fieldType = e.asType();
        if (isPrivate(e)) {
            throw new ShivException("Field must not be private: " + e.getSimpleName());
        } else if (isStatic(e)) {
            throw new ShivException("Field must not be static: " + e.getSimpleName());
        }

        final TypeElement type = findEnclosingElement(e);
        // class should exist
        if (type == null) {
            throw new ShivException("Could not find a class for " + e.getSimpleName());
        }
        // and it should be public
        if (isPrivate(type)) {
            throw new ShivException("Class is private: " + type);
        }
        // as well as all parent classes
        TypeElement parentType = findEnclosingElement(type);
        while (parentType != null) {
            if (isPrivate(parentType)) {
                throw new ShivException("Parent class is private: " + parentType);
            }
            parentType = findEnclosingElement(parentType);
        }

        if (annotation == BindView.class) {
            if (!isSubtypeOfType(type, Activity.class) && !isSubtypeOfType(type, Fragment.class)
                    && !isSubtypeOfType(type, android.support.v4.app.Fragment.class)
                    && !isSubtypeOfType(type, ViewGroup.class)) {
                throw new ShivException("Invalid view binding class: " + type.getSimpleName());
            } else if (!isSubtypeOfType(fieldType, View.class)) {
                throw new ShivException("Field must inherit from View type: " + e.getSimpleName());
            }
        } else if (annotation == BindExtra.class) {
            if (!isSubtypeOfType(type, Activity.class) && !isSubtypeOfType(type, Fragment.class)
                    && !isSubtypeOfType(type, android.support.v4.app.Fragment.class)) {
                throw new ShivException("Invalid extra binding class: " + type.getSimpleName());
            } else if (!isValidBundleEntry(fieldType)) {
                throw new ShivException("Extra field not suitable for bundle: " + e.getSimpleName());
            }
        } else if (annotation == BindPreference.class) {
            if (isSubtypeOfType(type, PreferenceFragment.class)
                    || isSubtypeOfType(type, PreferenceActivity.class)) {
                if (!isSubtypeOfType(fieldType, Preference.class)) {
                    throw new ShivException("Preferences in " + type.getQualifiedName() + " must inherit from "
                            + Preference.class + ": " + e.getSimpleName());
                }
            } else if (isSubtypeOfType(type, PreferenceFragmentCompat.class)) {
                if (!isSubtypeOfType(fieldType, android.support.v7.preference.Preference.class)) {
                    throw new ShivException("Preferences in " + PreferenceFragmentCompat.class
                            + " must inherit from " + android.support.v7.preference.Preference.class + ": "
                            + e.getSimpleName());
                }
            } else {
                throw new ShivException("Invalid preference binding class: " + type.getSimpleName());
            }
        } else if (annotation == BindInstance.class) {
            if (!isSubtypeOfType(type, Activity.class) && !isSubtypeOfType(type, Fragment.class)
                    && !isSubtypeOfType(type, android.support.v4.app.Fragment.class)) {
                throw new ShivException("Invalid instance binding class: " + type.getSimpleName());
            } else if (!isValidBundleEntry(fieldType)) {
                throw new ShivException("Instance field not suitable for bundle: " + e.getSimpleName());
            }
        } else if (annotation == BindNonConfigurationInstance.class) {
            if (!isSubtypeOfType(type, Activity.class)) {
                throw new ShivException(
                        "Invalid non-configuration instance binding class: " + type.getSimpleName());
            }
        } else if (annotation == BindService.class) {
            if (!isSubtypeOfType(type, Activity.class) && !isSubtypeOfType(type, Fragment.class)
                    && !isSubtypeOfType(type, android.support.v4.app.Fragment.class)
                    && !isSubtypeOfType(type, View.class)) {
                throw new ShivException("Invalid service binding class: " + type.getSimpleName());
            }
        } else {
            throw new ShivException("Unrecognised annotation: " + annotation);
        }

        BindingManager manager = bindings.get(type);
        if (manager == null) {
            manager = new BindingManager(this, type);
            bindings.put(type, manager);
        }

        manager.addBinding(annotation, e);
    }
}

From source file:net.minecrell.quartz.mappings.processor.MappingsGeneratorProcessor.java

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (roundEnv.processingOver()) {
        return false;
    }/*from   www  . ja v  a2  s .com*/

    List<TypeElement> mappingClasses = new ArrayList<>();

    for (Element element : roundEnv.getElementsAnnotatedWith(Mapping.class)) {
        if (element instanceof TypeElement) {
            mappingClasses.add((TypeElement) element);
        }
    }

    if (mappingClasses.isEmpty()) {
        return true;
    }

    try {
        FileObject file = this.processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "",
                "mappings.json");

        Map<String, MappedClass> mappings;
        try (Reader reader = file.openReader(false)) {
            mappings = Mappings.read(reader);
        } catch (IOException ignored) {
            mappings = new HashMap<>();
        }

        ClassMapper classMappings = createMapper(mappingClasses);

        // We need to remap the descriptors of the fields and methods, use ASM for convenience
        Remapper unmapper = classMappings.createUnmapper();

        for (TypeElement mappingClass : mappingClasses) {
            String internalName = getInternalName(mappingClass);

            Mapping annotation = mappingClass.getAnnotation(Mapping.class);
            String mappedName = annotation.value();
            if (mappedName.isEmpty()) {
                mappedName = internalName;
            }

            MappedClass mapping = new MappedClass(mappedName);

            Accessible accessible = mappingClass.getAnnotation(Accessible.class);
            if (accessible != null) {
                mapping.getAccess().put("", parseAccessible(accessible));
            }

            for (Element element : mappingClass.getEnclosedElements()) {
                accessible = element.getAnnotation(Accessible.class);

                Constructor constructor = element.getAnnotation(Constructor.class);
                if (constructor != null) {
                    if (accessible != null) {
                        String constructorDesc = getDescriptor((ExecutableElement) element);

                        mapping.getAccess().put("<init>" + constructorDesc, parseAccessible(accessible));
                    }
                    continue;
                }

                annotation = element.getAnnotation(Mapping.class);
                if (annotation == null) {
                    continue;
                }

                mappedName = annotation.value();
                checkArgument(!mappedName.isEmpty(), "Mapping detection is not supported yet");

                switch (element.getKind()) {
                case METHOD:
                    ExecutableElement method = (ExecutableElement) element;
                    String methodName = method.getSimpleName().toString();
                    String methodDesc = getDescriptor(method);
                    mapping.getMethods().put(mappedName + unmapper.mapMethodDesc(methodDesc), methodName);

                    if (accessible != null) {
                        mapping.getAccess().put(methodName + methodDesc, parseAccessible(accessible));
                    }

                    break;
                case FIELD:
                case ENUM_CONSTANT:
                    VariableElement field = (VariableElement) element;
                    String fieldName = field.getSimpleName().toString();
                    mapping.getFields().put(mappedName + ':' + unmapper.mapDesc(getDescriptor(field)),
                            fieldName);

                    if (accessible != null) {
                        mapping.getAccess().put(fieldName, parseAccessible(accessible));
                    }

                    break;
                default:
                }
            }

            mappings.put(internalName, mapping);
        }

        // Generate JSON output
        file = this.processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", "mappings.json");
        try (Writer writer = file.openWriter()) {
            Mappings.write(writer, mappings);
        }

        return true;
    } catch (IOException e) {
        this.processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, ExceptionUtils.getStackTrace(e));
        throw new RuntimeException("Failed to create mappings.json", e);
    }
}

From source file:org.jdto.tools.AnnotationConfigVerifier.java

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {

    Messager messager = processingEnv.getMessager();

    if (annotations.isEmpty()) {
        return false;
    }//  w w w.  j av a  2s. c  om

    TypeElement annotationElement = annotations.iterator().next();

    Set<? extends Element> elms = roundEnv.getElementsAnnotatedWith(annotationElement);

    //at this point we have all the DTO's annotated with @DTOVerify
    for (Element element : elms) {
        messager.printMessage(Diagnostic.Kind.NOTE, "Validating: " + element.toString());

        TypeElement targetType = extractTargetType(element, annotationElement, messager);

        validateDTO((TypeElement) element, targetType, messager);
    }

    return true;
}

From source file:org.boundbox.processor.BoundBoxProcessor.java

@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnvironment) {
    // Get all classes that has the annotation
    Set<? extends Element> classElements = roundEnvironment.getElementsAnnotatedWith(BoundBox.class);
    // For each class that has the annotation
    for (final Element classElement : classElements) {

        // Get the annotation information
        TypeElement boundClass = null;
        String maxSuperClass = null;
        String[] prefixes = null;
        String boundBoxPackageName = null;

        List<? extends AnnotationValue> extraBoundFields = null;
        List<? extends AnnotationMirror> listAnnotationMirrors = classElement.getAnnotationMirrors();
        if (listAnnotationMirrors == null) {
            messager.printMessage(Kind.WARNING, "listAnnotationMirrors is null", classElement);
            return true;
        }//from www. jav  a  2  s .c  o m

        StringBuilder message = new StringBuilder();
        for (AnnotationMirror annotationMirror : listAnnotationMirrors) {
            log.info("mirror " + annotationMirror.getAnnotationType());
            Map<? extends ExecutableElement, ? extends AnnotationValue> map = annotationMirror
                    .getElementValues();
            for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : map.entrySet()) {
                message.append(entry.getKey().getSimpleName().toString());
                message.append("\n");
                message.append(entry.getValue().toString());
                if (BOUNDBOX_ANNOTATION_PARAMETER_BOUND_CLASS
                        .equals(entry.getKey().getSimpleName().toString())) {
                    boundClass = getAnnotationValueAsTypeElement(entry.getValue());
                }
                if (BOUNDBOX_ANNOTATION_PARAMETER_MAX_SUPER_CLASS
                        .equals(entry.getKey().getSimpleName().toString())) {
                    maxSuperClass = getAnnotationValueAsTypeElement(entry.getValue()).asType().toString();
                }
                if (BOUNDBOX_ANNOTATION_PARAMETER_EXTRA_BOUND_FIELDS
                        .equals(entry.getKey().getSimpleName().toString())) {
                    extraBoundFields = getAnnotationValueAsAnnotationValueList(entry.getValue());
                }
                if (BOUNDBOX_ANNOTATION_PARAMETER_PREFIXES.equals(entry.getKey().getSimpleName().toString())) {
                    List<? extends AnnotationValue> listPrefixes = getAnnotationValueAsAnnotationValueList(
                            entry.getValue());
                    prefixes = new String[listPrefixes.size()];
                    for (int indexAnnotation = 0; indexAnnotation < listPrefixes.size(); indexAnnotation++) {
                        prefixes[indexAnnotation] = getAnnotationValueAsString(
                                listPrefixes.get(indexAnnotation));
                    }
                }
                if (BOUNDBOX_ANNOTATION_PARAMETER_PACKAGE.equals(entry.getKey().getSimpleName().toString())) {
                    boundBoxPackageName = getAnnotationValueAsString(entry.getValue());
                }
            }
        }

        if (boundClass == null) {
            messager.printMessage(Kind.WARNING, "BoundClass is null : " + message, classElement);
            return true;
        }

        if (maxSuperClass != null) {
            boundClassVisitor.setMaxSuperClassName(maxSuperClass);
        }

        if (prefixes != null && prefixes.length != 2 && prefixes.length != 1) {
            error(classElement,
                    "You must provide 1 or 2 prefixes. The first one for class names, the second one for methods.");
            return true;
        }
        if (prefixes != null && prefixes.length == 1) {
            String[] newPrefixes = new String[] { prefixes[0], prefixes[0].toLowerCase(Locale.US) };
            prefixes = newPrefixes;
        }
        boundboxWriter.setPrefixes(prefixes);

        if (boundBoxPackageName == null) {
            String boundClassFQN = boundClass.getQualifiedName().toString();
            if (boundClassFQN.contains(PACKAGE_SEPARATOR)) {
                boundBoxPackageName = StringUtils.substringBeforeLast(boundClassFQN, PACKAGE_SEPARATOR);
            } else {
                boundBoxPackageName = StringUtils.EMPTY;
            }
        }
        boundClassVisitor.setBoundBoxPackageName(boundBoxPackageName);
        boundboxWriter.setBoundBoxPackageName(boundBoxPackageName);

        ClassInfo classInfo = boundClassVisitor.scan(boundClass);

        injectExtraBoundFields(extraBoundFields, classInfo);

        listClassInfo.add(classInfo);

        // perform some computations on meta model
        inheritanceComputer.computeInheritanceAndHidingFields(classInfo.getListFieldInfos());
        inheritanceComputer.computeInheritanceAndOverridingMethods(classInfo.getListMethodInfos(), boundClass,
                elements);
        inheritanceComputer.computeInheritanceAndHidingInnerClasses(classInfo.getListInnerClassInfo());
        inheritanceComputer.computeInheritanceInInnerClasses(classInfo, elements);

        // write meta model to java class file
        Writer sourceWriter = null;
        try {
            String boundBoxClassName = boundboxWriter.getNamingGenerator().createBoundBoxName(classInfo);
            String boundBoxClassFQN = boundBoxPackageName.isEmpty() ? boundBoxClassName
                    : boundBoxPackageName + PACKAGE_SEPARATOR + boundBoxClassName;
            JavaFileObject sourceFile = filer.createSourceFile(boundBoxClassFQN, (Element[]) null);
            sourceWriter = sourceFile.openWriter();

            boundboxWriter.writeBoundBox(classInfo, sourceWriter);
        } catch (IOException e) {
            e.printStackTrace();
            error(classElement, e.getMessage());
        } finally {
            if (sourceWriter != null) {
                IOUtils.closeQuietly(sourceWriter);
            }
        }
    }

    return true;
}