Search in sources :

Example 6 with RoundEnvironment

use of javax.annotation.processing.RoundEnvironment in project auto by google.

the class AutoValueishProcessor method process.

@Override
public final boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (annotationType == null) {
        // This should not happen. If the annotation type is not found, how did the processor get
        // triggered?
        processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Did not process @" + annotationClassName + " because the annotation class was not found");
        return false;
    }
    List<TypeElement> deferredTypes = deferredTypeNames.stream().map(name -> elementUtils().getTypeElement(name)).collect(toList());
    if (roundEnv.processingOver()) {
        // was in deferredTypes.
        for (TypeElement type : deferredTypes) {
            errorReporter.reportError(type, "[%sUndefined] Did not generate @%s class for %s because it references" + " undefined types", simpleAnnotationName, simpleAnnotationName, type.getQualifiedName());
        }
        return false;
    }
    Collection<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(annotationType);
    List<TypeElement> types = new ImmutableList.Builder<TypeElement>().addAll(deferredTypes).addAll(ElementFilter.typesIn(annotatedElements)).build();
    deferredTypeNames.clear();
    for (TypeElement type : types) {
        try {
            validateType(type);
            processType(type);
        } catch (AbortProcessingException e) {
        // We abandoned this type; continue with the next.
        } catch (MissingTypeException e) {
            // We abandoned this type, but only because we needed another type that it references and
            // that other type was missing. It is possible that the missing type will be generated by
            // further annotation processing, so we will try again on the next round (perhaps failing
            // again and adding it back to the list).
            addDeferredType(type);
        } catch (RuntimeException e) {
            String trace = Throwables.getStackTraceAsString(e);
            errorReporter.reportError(type, "[%sException] @%s processor threw an exception: %s", simpleAnnotationName, simpleAnnotationName, trace);
            throw e;
        }
    }
    // never claim annotation, because who knows what other processors want?
    return false;
}
Also used : Arrays(java.util.Arrays) AbstractProcessor(javax.annotation.processing.AbstractProcessor) Modifier(javax.lang.model.element.Modifier) Inherited(java.lang.annotation.Inherited) TypeElement(javax.lang.model.element.TypeElement) Elements(javax.lang.model.util.Elements) MoreStreams.toImmutableSet(com.google.auto.common.MoreStreams.toImmutableSet) Diagnostic(javax.tools.Diagnostic) Sets.union(com.google.common.collect.Sets.union) Map(java.util.Map) MoreElements.isAnnotationPresent(com.google.auto.common.MoreElements.isAnnotationPresent) Collectors.toSet(java.util.stream.Collectors.toSet) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) EnumMap(java.util.EnumMap) Predicate(java.util.function.Predicate) Collection(java.util.Collection) Set(java.util.Set) Element(javax.lang.model.element.Element) Types(javax.lang.model.util.Types) Collectors.joining(java.util.stream.Collectors.joining) Serializable(java.io.Serializable) TypeKind(javax.lang.model.type.TypeKind) AnnotationMirrors.getAnnotationValue(com.google.auto.common.AnnotationMirrors.getAnnotationValue) JavaFileObject(javax.tools.JavaFileObject) SourceVersion(javax.lang.model.SourceVersion) List(java.util.List) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap) Writer(java.io.Writer) Optional(java.util.Optional) AnnotationValue(javax.lang.model.element.AnnotationValue) GeneratedAnnotations.generatedAnnotation(com.google.auto.common.GeneratedAnnotations.generatedAnnotation) IntStream(java.util.stream.IntStream) MoreTypes(com.google.auto.common.MoreTypes) COPY_ANNOTATIONS_NAME(com.google.auto.value.processor.ClassNames.COPY_ANNOTATIONS_NAME) VariableElement(javax.lang.model.element.VariableElement) MissingTypeException(com.google.auto.value.processor.MissingTypes.MissingTypeException) OptionalInt(java.util.OptionalInt) ArrayList(java.util.ArrayList) AUTO_VALUE_PACKAGE_NAME(com.google.auto.value.processor.ClassNames.AUTO_VALUE_PACKAGE_NAME) ImmutableBiMap(com.google.common.collect.ImmutableBiMap) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) Collectors.toCollection(java.util.stream.Collectors.toCollection) MoreElements.getPackage(com.google.auto.common.MoreElements.getPackage) ImmutableList(com.google.common.collect.ImmutableList) DeclaredType(javax.lang.model.type.DeclaredType) QualifiedNameable(javax.lang.model.element.QualifiedNameable) ElementFilter(javax.lang.model.util.ElementFilter) ElementFilter.constructorsIn(javax.lang.model.util.ElementFilter.constructorsIn) Name(javax.lang.model.element.Name) SimpleAnnotationValueVisitor8(javax.lang.model.util.SimpleAnnotationValueVisitor8) MoreElements(com.google.auto.common.MoreElements) ElementKind(javax.lang.model.element.ElementKind) ExecutableElement(javax.lang.model.element.ExecutableElement) Throwables(com.google.common.base.Throwables) Iterables.getOnlyElement(com.google.common.collect.Iterables.getOnlyElement) IOException(java.io.IOException) Target(java.lang.annotation.Target) ElementType(java.lang.annotation.ElementType) Visibility(com.google.auto.common.Visibility) AnnotationMirror(javax.lang.model.element.AnnotationMirror) TypeParameterElement(javax.lang.model.element.TypeParameterElement) MoreStreams.toImmutableList(com.google.auto.common.MoreStreams.toImmutableList) Collectors.toList(java.util.stream.Collectors.toList) TypeMirror(javax.lang.model.type.TypeMirror) RoundEnvironment(javax.annotation.processing.RoundEnvironment) ProcessingEnvironment(javax.annotation.processing.ProcessingEnvironment) MissingTypeException(com.google.auto.value.processor.MissingTypes.MissingTypeException) TypeElement(javax.lang.model.element.TypeElement) ImmutableList(com.google.common.collect.ImmutableList) MoreStreams.toImmutableList(com.google.auto.common.MoreStreams.toImmutableList)

Example 7 with RoundEnvironment

use of javax.annotation.processing.RoundEnvironment in project vertx-docgen by vert-x3.

the class BaseProcessorTest method testGen.

@Test
public void testGen() throws Exception {
    AtomicInteger count = new AtomicInteger();
    AbstractProcessor proc = new AbstractProcessor() {

        @Override
        public Set<String> getSupportedAnnotationTypes() {
            return Collections.singleton("*");
        }

        @Override
        public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
            if (count.getAndIncrement() == 0) {
                try {
                    Filer filer = processingEnv.getFiler();
                    Element elt = processingEnv.getElementUtils().getTypeElement("gen.GeneratedClass");
                    JavaFileObject src = filer.createSourceFile("io.vertx.test.gen.GeneratedClass", elt);
                    try (Writer writer = src.openWriter()) {
                        writer.append("package io.vertx.test.gen;\npublic class GeneratedClass {\n}");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return true;
        }
    };
    Compiler<TestGenProcessor> compiler = buildCompiler(new TestGenProcessor(), "io.vertx.test.gen");
    compiler.addProcessor(proc);
    compiler.assertCompile();
    assertEquals(3, count.get());
}
Also used : TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) TypeElement(javax.lang.model.element.TypeElement) AbstractProcessor(javax.annotation.processing.AbstractProcessor) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) IOException(java.io.IOException) RoundEnvironment(javax.annotation.processing.RoundEnvironment) JavaFileObject(javax.tools.JavaFileObject) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Filer(javax.annotation.processing.Filer) Writer(java.io.Writer) Test(org.junit.Test)

Example 8 with RoundEnvironment

use of javax.annotation.processing.RoundEnvironment in project qpid-broker-j by apache.

the class ConfiguredObjectRegistrationGenerator method process.

@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) {
    if (!_elementProcessingDone) {
        final Elements elementUtils = processingEnv.getElementUtils();
        final TypeElement managedObjectElement = elementUtils.getTypeElement(MANAGED_OBJECT_CANONICAL_NAME);
        try {
            roundEnv.getElementsAnnotatedWith(managedObjectElement).stream().map(element -> elementUtils.getPackageOf(element)).flatMap(packageElement -> packageElement.getEnclosedElements().stream()).filter(element -> hasAnnotation(element, managedObjectElement)).forEach(annotatedElement -> processAnnotatedElement(elementUtils, managedObjectElement, annotatedElement));
            for (Map.Entry<String, Set<String>> entry : _managedObjectClasses.entrySet()) {
                processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, String.format("Generating CO registration for package '%s'", entry.getKey()));
                generateRegistrationFile(entry.getKey(), entry.getValue());
            }
            _managedObjectClasses.clear();
            _typeMap.clear();
            _categoryMap.clear();
            _elementProcessingDone = true;
        } catch (Exception e) {
            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Error: " + e.getLocalizedMessage());
        }
    }
    return false;
}
Also used : PackageElement(javax.lang.model.element.PackageElement) AbstractProcessor(javax.annotation.processing.AbstractProcessor) HashMap(java.util.HashMap) TypeElement(javax.lang.model.element.TypeElement) SupportedAnnotationTypes(javax.annotation.processing.SupportedAnnotationTypes) Elements(javax.lang.model.util.Elements) HashSet(java.util.HashSet) Diagnostic(javax.tools.Diagnostic) Map(java.util.Map) OutputStreamWriter(java.io.OutputStreamWriter) PrintWriter(java.io.PrintWriter) ElementKind(javax.lang.model.element.ElementKind) ExecutableElement(javax.lang.model.element.ExecutableElement) Set(java.util.Set) IOException(java.io.IOException) Element(javax.lang.model.element.Element) AnnotationMirror(javax.lang.model.element.AnnotationMirror) JavaFileObject(javax.tools.JavaFileObject) SourceVersion(javax.lang.model.SourceVersion) License(org.apache.qpid.server.License) List(java.util.List) TypeMirror(javax.lang.model.type.TypeMirror) RoundEnvironment(javax.annotation.processing.RoundEnvironment) AnnotationValue(javax.lang.model.element.AnnotationValue) Collections(java.util.Collections) HashSet(java.util.HashSet) Set(java.util.Set) TypeElement(javax.lang.model.element.TypeElement) Elements(javax.lang.model.util.Elements) HashMap(java.util.HashMap) Map(java.util.Map) IOException(java.io.IOException)

Example 9 with RoundEnvironment

use of javax.annotation.processing.RoundEnvironment in project mule by mulesoft.

the class DescriptionDeclarationEnricher method enrich.

@Override
public void enrich(ExtensionLoadingContext loadingContext) {
    ProcessingEnvironment processingEnv = getParameterOrFail(loadingContext, PROCESSING_ENVIRONMENT);
    TypeElement extensionElement = getParameterOrFail(loadingContext, EXTENSION_ELEMENT);
    RoundEnvironment roundEnvironment = getParameterOrFail(loadingContext, ROUND_ENVIRONMENT);
    ExtensionDescriptionDocumenter declarer = new ExtensionDescriptionDocumenter(processingEnv, roundEnvironment);
    declarer.document(loadingContext.getExtensionDeclarer().getDeclaration(), extensionElement);
}
Also used : RoundEnvironment(javax.annotation.processing.RoundEnvironment) TypeElement(javax.lang.model.element.TypeElement) ProcessingEnvironment(javax.annotation.processing.ProcessingEnvironment)

Example 10 with RoundEnvironment

use of javax.annotation.processing.RoundEnvironment in project jvarkit by lindenb.

the class JVarkitAnnotationProcessor method process.

@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) {
    final String mainClass = System.getProperty("jvarkit.main.class");
    final String thisDir = System.getProperty("jvarkit.this.dir");
    roundEnv.getElementsAnnotatedWith(IncludeSourceInJar.class).stream().filter(E -> E.getKind() == ElementKind.CLASS).filter(E -> E.getAnnotation(IncludeSourceInJar.class) != null).forEach(E -> {
        if (thisDir == null || thisDir.isEmpty())
            return;
        copySource(E);
    });
    /* find if roundEnv contains main class annotated with 'Program' annotation
		 * if true: generate a file that will tell Make to compile the markdown
		 * documentation
		 */
    roundEnv.getElementsAnnotatedWith(Program.class).stream().filter(E -> E.getKind() == ElementKind.CLASS).filter(E -> {
        final Program prog = E.getAnnotation(Program.class);
        return prog != null && prog.generate_doc();
    }).forEach(E -> {
        copySource(E);
        final String className = E.toString();
        if (mainClass == null)
            return;
        if (!mainClass.equals(className))
            return;
        final Program prog = E.getAnnotation(Program.class);
        if (prog == null || !prog.generate_doc())
            return;
        try {
            final Filer filer = super.processingEnv.getFiler();
            FileObject fo = filer.createResource(StandardLocation.CLASS_OUTPUT, "", "markdown.flag");
            fo.openWriter().append(String.valueOf(mainClass)).close();
        } catch (final Exception err) {
            LOG.warn(err);
        }
        if (thisDir != null) {
            final File index_html = new File(thisDir, "docs/index.html");
            if (index_html.exists()) {
                try {
                    final Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(index_html);
                    Element tr = dom.createElement("tr");
                    tr.setAttribute("id", prog.name());
                    // name
                    Element td = dom.createElement("th");
                    tr.appendChild(td);
                    Element a = dom.createElement("a");
                    a.setAttribute("href", E.getSimpleName() + ".html");
                    a.setAttribute("title", E.getSimpleName().toString());
                    td.appendChild(a);
                    a.appendChild(dom.createTextNode(prog.name()));
                    // desc
                    td = dom.createElement("td");
                    tr.appendChild(td);
                    td.appendChild(dom.createTextNode(prog.description()));
                    // keywords
                    td = dom.createElement("td");
                    tr.appendChild(td);
                    td.appendChild(dom.createTextNode(Arrays.asList(prog.keywords()).stream().collect(Collectors.joining(" "))));
                    // terms
                    td = dom.createElement("td");
                    tr.appendChild(td);
                    td.appendChild(dom.createTextNode(Arrays.asList(prog.terms()).stream().map(T -> "[" + T.getAccession() + "]" + T.getLabel()).collect(Collectors.joining(" "))));
                    // misc
                    td = dom.createElement("td");
                    tr.appendChild(td);
                    final DocumentFragment misc = dom.createDocumentFragment();
                    if (prog.deprecatedMsg() != null && !prog.deprecatedMsg().isEmpty()) {
                        Element span = dom.createElement("span");
                        span.setAttribute("style", "color:orange;");
                        span.setAttribute("title", "deprecated");
                        span.appendChild(dom.createTextNode(prog.deprecatedMsg()));
                        misc.appendChild(span);
                        misc.appendChild(dom.createTextNode(". "));
                    }
                    td.appendChild(misc);
                    final XPath xpath = XPathFactory.newInstance().newXPath();
                    final NodeList nodeList = (NodeList) xpath.evaluate("//table[1]/tbody/tr[@id='" + prog.name() + "']", dom, XPathConstants.NODESET);
                    for (int i = 0; i < nodeList.getLength(); ++i) {
                        Node oldTr = nodeList.item(i);
                        if (tr != null) {
                            oldTr.getParentNode().replaceChild(tr, oldTr);
                            tr = null;
                        } else {
                            oldTr.getParentNode().removeChild(oldTr);
                        }
                    }
                    if (tr != null) {
                        Node tbody = (Node) xpath.evaluate("//table[1]/tbody", dom, XPathConstants.NODE);
                        if (tbody != null) {
                            tbody.appendChild(tr);
                            tbody.appendChild(dom.createTextNode("\n"));
                            tr = null;
                        }
                    }
                    if (tr != null) {
                        LOG.warn("Cannot insert new doc in " + index_html);
                    } else {
                        final Transformer transformer = TransformerFactory.newInstance().newTransformer();
                        transformer.setOutputProperty(OutputKeys.INDENT, "no");
                        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
                        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                        transformer.transform(new DOMSource(dom), new StreamResult(index_html));
                    }
                } catch (final Exception err) {
                    LOG.warn(err);
                }
            } else {
                LOG.warn("Cannot get " + index_html);
            }
        }
    });
    return true;
}
Also used : Transformer(javax.xml.transform.Transformer) DOMSource(javax.xml.transform.dom.DOMSource) Arrays(java.util.Arrays) XPath(javax.xml.xpath.XPath) Program(com.github.lindenb.jvarkit.util.jcommander.Program) AbstractProcessor(javax.annotation.processing.AbstractProcessor) XPathConstants(javax.xml.xpath.XPathConstants) StreamResult(javax.xml.transform.stream.StreamResult) TypeElement(javax.lang.model.element.TypeElement) FileObject(javax.tools.FileObject) SupportedSourceVersion(javax.annotation.processing.SupportedSourceVersion) Document(org.w3c.dom.Document) DeclaredType(javax.lang.model.type.DeclaredType) Node(org.w3c.dom.Node) StandardLocation(javax.tools.StandardLocation) NodeList(org.w3c.dom.NodeList) ElementKind(javax.lang.model.element.ElementKind) Logger(com.github.lindenb.jvarkit.util.log.Logger) Set(java.util.Set) Reader(java.io.Reader) OutputKeys(javax.xml.transform.OutputKeys) Collectors(java.util.stream.Collectors) File(java.io.File) TypeKind(javax.lang.model.type.TypeKind) DocumentFragment(org.w3c.dom.DocumentFragment) SourceVersion(javax.lang.model.SourceVersion) XPathFactory(javax.xml.xpath.XPathFactory) TypeMirror(javax.lang.model.type.TypeMirror) Element(org.w3c.dom.Element) RoundEnvironment(javax.annotation.processing.RoundEnvironment) Filer(javax.annotation.processing.Filer) Writer(java.io.Writer) ProcessingEnvironment(javax.annotation.processing.ProcessingEnvironment) FileReader(java.io.FileReader) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) TransformerFactory(javax.xml.transform.TransformerFactory) XPath(javax.xml.xpath.XPath) DOMSource(javax.xml.transform.dom.DOMSource) Program(com.github.lindenb.jvarkit.util.jcommander.Program) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) TypeElement(javax.lang.model.element.TypeElement) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Document(org.w3c.dom.Document) FileObject(javax.tools.FileObject) Filer(javax.annotation.processing.Filer) File(java.io.File) DocumentFragment(org.w3c.dom.DocumentFragment)

Aggregations

RoundEnvironment (javax.annotation.processing.RoundEnvironment)10 AbstractProcessor (javax.annotation.processing.AbstractProcessor)9 TypeElement (javax.lang.model.element.TypeElement)9 Set (java.util.Set)7 SourceVersion (javax.lang.model.SourceVersion)6 JavaFileObject (javax.tools.JavaFileObject)6 IOException (java.io.IOException)5 ProcessingEnvironment (javax.annotation.processing.ProcessingEnvironment)5 Element (javax.lang.model.element.Element)5 Writer (java.io.Writer)4 List (java.util.List)4 Map (java.util.Map)4 SupportedAnnotationTypes (javax.annotation.processing.SupportedAnnotationTypes)4 Diagnostic (javax.tools.Diagnostic)4 ElementKind (javax.lang.model.element.ElementKind)3 TypeMirror (javax.lang.model.type.TypeMirror)3 ImmutableSet (com.google.common.collect.ImmutableSet)2 Arrays (java.util.Arrays)2 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2