Example usage for javax.annotation.processing RoundEnvironment getRootElements

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

Introduction

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

Prototype

Set<? extends Element> getRootElements();

Source Link

Document

Returns the Processor root elements for annotation processing generated by the prior round.

Usage

From source file:ch.rasc.constgen.ConstAnnotationProcessor.java

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

    this.processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE,
            "Running " + getClass().getSimpleName());

    if (roundEnv.processingOver() || annotations.size() == 0) {
        return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS;
    }//  w  w w .j  a v  a  2s  .c o m

    if (roundEnv.getRootElements() == null || roundEnv.getRootElements().isEmpty()) {
        this.processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "No sources to process");
        return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS;
    }

    for (TypeElement annotation : annotations) {
        Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(annotation);
        boolean bsoncodecProject = annotation.getQualifiedName()
                .contentEquals("ch.rasc.bsoncodec.annotation.BsonDocument");
        for (Element element : elements) {

            try {
                TypeElement typeElement = (TypeElement) element;

                CodeGenerator codeGen = new CodeGenerator(typeElement, this.processingEnv.getElementUtils(),
                        bsoncodecProject);

                JavaFileObject jfo = this.processingEnv.getFiler()
                        .createSourceFile(codeGen.getPackageName() + "." + codeGen.getClassName());
                try (Writer writer = jfo.openWriter()) {
                    codeGen.generate(writer);
                }

            } catch (Exception e) {
                this.processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage());
            }

        }
    }

    return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS;
}

From source file:ch.rasc.extclassgenerator.ModelAnnotationProcessor.java

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    this.processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE,
            "Running " + getClass().getSimpleName());

    if (roundEnv.processingOver() || annotations.size() == 0) {
        return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS;
    }/*from w  ww. jav  a2 s. c o  m*/

    if (roundEnv.getRootElements() == null || roundEnv.getRootElements().isEmpty()) {
        this.processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "No sources to process");
        return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS;
    }

    OutputConfig outputConfig = new OutputConfig();

    outputConfig.setDebug(!"false".equals(this.processingEnv.getOptions().get(OPTION_DEBUG)));
    boolean createBaseAndSubclass = "true"
            .equals(this.processingEnv.getOptions().get(OPTION_CREATEBASEANDSUBCLASS));

    String outputFormatString = this.processingEnv.getOptions().get(OPTION_OUTPUTFORMAT);
    outputConfig.setOutputFormat(OutputFormat.EXTJS4);
    if (StringUtils.hasText(outputFormatString)) {
        if (OutputFormat.TOUCH2.name().equalsIgnoreCase(outputFormatString)) {
            outputConfig.setOutputFormat(OutputFormat.TOUCH2);
        } else if (OutputFormat.EXTJS5.name().equalsIgnoreCase(outputFormatString)) {
            outputConfig.setOutputFormat(OutputFormat.EXTJS5);
        }
    }

    String includeValidationString = this.processingEnv.getOptions().get(OPTION_INCLUDEVALIDATION);
    outputConfig.setIncludeValidation(IncludeValidation.NONE);
    if (StringUtils.hasText(includeValidationString)) {
        if (IncludeValidation.ALL.name().equalsIgnoreCase(includeValidationString)) {
            outputConfig.setIncludeValidation(IncludeValidation.ALL);
        } else if (IncludeValidation.BUILTIN.name().equalsIgnoreCase(includeValidationString)) {
            outputConfig.setIncludeValidation(IncludeValidation.BUILTIN);
        }
    }

    outputConfig.setUseSingleQuotes("true".equals(this.processingEnv.getOptions().get(OPTION_USESINGLEQUOTES)));
    outputConfig.setSurroundApiWithQuotes(
            "true".equals(this.processingEnv.getOptions().get(OPTION_SURROUNDAPIWITHQUOTES)));

    for (TypeElement annotation : annotations) {
        Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(annotation);
        for (Element element : elements) {

            try {
                TypeElement typeElement = (TypeElement) element;

                String qualifiedName = typeElement.getQualifiedName().toString();
                Class<?> modelClass = Class.forName(qualifiedName);

                String code = ModelGenerator.generateJavascript(modelClass, outputConfig);

                Model modelAnnotation = element.getAnnotation(Model.class);
                String modelName = modelAnnotation.value();
                String fileName;
                String packageName = "";
                if (StringUtils.hasText(modelName)) {
                    int lastDot = modelName.lastIndexOf('.');
                    if (lastDot != -1) {
                        fileName = modelName.substring(lastDot + 1);
                        int firstDot = modelName.indexOf('.');
                        if (firstDot < lastDot) {
                            packageName = modelName.substring(firstDot + 1, lastDot);
                        }
                    } else {
                        fileName = modelName;
                    }
                } else {
                    fileName = typeElement.getSimpleName().toString();
                }

                if (createBaseAndSubclass) {
                    code = code.replaceFirst("(Ext.define\\([\"'].+?)([\"'],)", "$1Base$2");
                    FileObject fo = this.processingEnv.getFiler().createResource(StandardLocation.SOURCE_OUTPUT,
                            packageName, fileName + "Base.js");
                    OutputStream os = fo.openOutputStream();
                    os.write(code.getBytes(ModelGenerator.UTF8_CHARSET));
                    os.close();

                    try {
                        fo = this.processingEnv.getFiler().getResource(StandardLocation.SOURCE_OUTPUT,
                                packageName, fileName + ".js");
                        InputStream is = fo.openInputStream();
                        is.close();
                    } catch (FileNotFoundException e) {
                        String subClassCode = generateSubclassCode(modelClass, outputConfig);
                        fo = this.processingEnv.getFiler().createResource(StandardLocation.SOURCE_OUTPUT,
                                packageName, fileName + ".js");
                        os = fo.openOutputStream();
                        os.write(subClassCode.getBytes(ModelGenerator.UTF8_CHARSET));
                        os.close();
                    }

                } else {
                    FileObject fo = this.processingEnv.getFiler().createResource(StandardLocation.SOURCE_OUTPUT,
                            packageName, fileName + ".js");
                    OutputStream os = fo.openOutputStream();
                    os.write(code.getBytes(ModelGenerator.UTF8_CHARSET));
                    os.close();
                }

            } catch (ClassNotFoundException e) {
                this.processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage());
            } catch (IOException e) {
                this.processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage());
            }

        }
    }

    return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS;
}

From source file:com.predic8.membrane.annot.SpringConfigurationXSDGeneratingAnnotationProcessor.java

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    // An instance is create per compiler call and not kept for the next incremental compilation.
    ////from   w ww  . j ava  2  s  .c om
    // Use "roundEnv.getRootElements()" to get root elements (=classes) changed since last round.
    // Use "processingEnv.getElementUtils().getTypeElement(className)" to get the TypeElement of any class (changed or not).
    // "annotations.size()" equals the number of our annotations found in the "roundEnv.getRootElement()" classes.
    //
    // * rounds are repeated until nothing is filed (=created) any more
    // * resources (and java files?) may only be filed in one round
    // * in the last round, "roundEnv.processingOver()" is true
    try {

        String status = "process() a=" + annotations.size() + " r=" + roundEnv.getRootElements().size() + " h="
                + hashCode() + (roundEnv.processingOver() ? " processing-over" : " ");
        log(status);

        read();
        if (roundEnv.processingOver())
            write();

        if (annotations.size() > 0) { // a class with one of our annotation needs to be compiled

            status = "working with " + getCachedElementsAnnotatedWith(roundEnv, MCMain.class).size() + " and "
                    + getCachedElementsAnnotatedWith(roundEnv, MCElement.class).size();
            log(status);

            Model m = new Model();

            Set<? extends Element> mcmains = getCachedElementsAnnotatedWith(roundEnv, MCMain.class);
            if (mcmains.isEmpty()) {
                processingEnv.getMessager().printMessage(Kind.WARNING, "@MCMain was nowhere found.");
                return true;
            }
            for (Element element : mcmains) {
                MainInfo main = new MainInfo();
                main.setElement((TypeElement) element);
                main.setAnnotation(element.getAnnotation(MCMain.class));
                m.getMains().add(main);
            }

            for (Element e : getCachedElementsAnnotatedWith(roundEnv, MCElement.class)) {
                ElementInfo ii = new ElementInfo();
                ii.setElement((TypeElement) e);
                ii.setAnnotation(e.getAnnotation(MCElement.class));
                MainInfo main = ii.getMain(m);
                main.getIis().add(ii);

                main.getElements().put(ii.getElement(), ii);
                if (main.getGlobals().containsKey(ii.getAnnotation().name()))
                    throw new ProcessingException("Duplicate global @MCElement name.",
                            main.getGlobals().get(ii.getAnnotation().name()).getElement(), ii.getElement());
                if (main.getIds().containsKey(ii.getId()))
                    throw new ProcessingException(
                            "Duplicate element id \"" + ii.getId()
                                    + "\". Please assign one using @MCElement(id=\"...\").",
                            e, main.getIds().get(ii.getId()).getElement());
                main.getIds().put(ii.getId(), ii);

                scan(m, main, ii);

                if (ii.getTci() != null && !ii.getAnnotation().mixed())
                    throw new ProcessingException(
                            "@MCTextContent requires @MCElement(..., mixed=true) on the class.",
                            ii.getElement());
                if (ii.getTci() == null && ii.getAnnotation().mixed())
                    throw new ProcessingException(
                            "@MCElement(..., mixed=true) requires @MCTextContent on a property.",
                            ii.getElement());
            }

            for (MainInfo main : m.getMains()) {

                for (Map.Entry<TypeElement, ChildElementDeclarationInfo> f : main.getChildElementDeclarations()
                        .entrySet()) {
                    ChildElementDeclarationInfo cedi = f.getValue();
                    ElementInfo ei = main.getElements().get(f.getKey());

                    if (ei != null)
                        cedi.getElementInfo().add(ei);
                    else {
                        for (Map.Entry<TypeElement, ElementInfo> e : main.getElements().entrySet())
                            if (processingEnv.getTypeUtils().isAssignable(e.getKey().asType(),
                                    f.getKey().asType()))
                                cedi.getElementInfo().add(e.getValue());
                    }

                    for (ElementInfo ei2 : cedi.getElementInfo())
                        ei2.addUsedBy(f.getValue());

                    if (cedi.getElementInfo().isEmpty() && cedi.isRaiseErrorWhenNoSpecimen()) {
                        processingEnv.getMessager().printMessage(Kind.ERROR,
                                "@MCChildElement references " + f.getKey().getQualifiedName()
                                        + ", but there is no @MCElement among it and its subclasses.",
                                f.getKey());
                        return true;
                    }
                }
            }

            if (mcmains.isEmpty()) {
                processingEnv.getMessager().printMessage(Kind.ERROR, "@MCMain but no @MCElement found.",
                        mcmains.iterator().next());
                return true;
            }

            process(m);
        }

        return true;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (ProcessingException e1) {
        for (int i = 0; i < e1.getElements().length; i++)
            processingEnv.getMessager().printMessage(Kind.ERROR, i == 0 ? e1.getMessage() : "also here",
                    e1.getElements()[i]);
        return true;
    }
}

From source file:org.jannocessor.processor.JannocessorProcessorBase.java

private void processProblems(RoundEnvironment env) {
    for (Problem error : problems.getErrors()) {
        if (error.getElement() instanceof SourceHolder) {
            SourceHolder sourceHolder = (SourceHolder) error.getElement();
            error(error.getMessage(), sourceHolder.retrieveSourceElement());
        } else {/*from  ww  w  .j a v a2  s  .  c  om*/
            throw new IllegalStateException("Expected source holder");
        }
    }

    for (Problem warning : problems.getWarnings()) {
        if (warning.getElement() instanceof SourceHolder) {
            SourceHolder sourceHolder = (SourceHolder) warning.getElement();
            warning(warning.getMessage(), sourceHolder.retrieveSourceElement());
        } else {
            throw new IllegalStateException("Expected source holder");
        }
    }

    Set<? extends Element> roots = env.getRootElements();
    for (Element rootElement : roots) {
        for (String globalError : globalErrors) {
            error(globalError, rootElement);
        }
        for (String globalWarning : globalWarnings) {
            warning(globalWarning, rootElement);
        }
    }
}

From source file:org.mule.module.extension.internal.capability.xml.schema.AnnotationProcessorUtils.java

/**
 * Scans all classes in the {@code roundEnvironment} looking
 * for methods annotated with {@link Operation}.
 *
 * @param roundEnvironment the current {@link RoundEnvironment}
 * @return a {@link Map} which keys are the method names and the values are the
 * method represented as a {@link ExecutableElement}
 *///from   ww w. ja  va2  s .  co m
static Map<String, ExecutableElement> getOperationMethods(RoundEnvironment roundEnvironment) {
    ImmutableMap.Builder<String, ExecutableElement> methods = ImmutableMap.builder();
    for (Element rootElement : roundEnvironment.getRootElements()) {
        if (!(rootElement instanceof TypeElement)) {
            continue;
        }

        methods.putAll(getMethodsAnnotatedWith((TypeElement) rootElement, Operation.class));
    }

    return methods.build();
}