Search in sources :

Example 11 with Filer

use of javax.annotation.processing.Filer in project maven-plugins by apache.

the class SimpleAnnotationProcessor method process.

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (annotations.isEmpty()) {
        return true;
    }
    // assert that commons-lang3 is on the classpath
    try {
        getClass().getClassLoader().loadClass("org.apache.commons.lang3.StringUtils");
    } catch (ClassNotFoundException expected) {
        throw new RuntimeException("Expected org.apache.commons.lang3.StringUtils to be on the processorpath," + "because it is a declared dependency of the annotation processor.");
    }
    // assert that commons-io is NOT on the classpath, as it is only a project dependency in "annotation-user"
    try {
        getClass().getClassLoader().loadClass("org.apache.commons.io.IOUtils");
        throw new RuntimeException("Expected a ClassNotFoundException because " + "org.apache.commons.io.IOUtils is not supposed to be on the processorpath.");
    } catch (ClassNotFoundException expected) {
    // expected.
    }
    Filer filer = processingEnv.getFiler();
    Elements elementUtils = processingEnv.getElementUtils();
    Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(annotations.iterator().next());
    for (Element element : elements) {
        Name name = element.getSimpleName();
        PackageElement packageElement = elementUtils.getPackageOf(element);
        try {
            Name packageName = packageElement.getQualifiedName();
            FileObject resource = filer.createResource(StandardLocation.SOURCE_OUTPUT, packageName, name + ".txt", element);
            Writer writer = resource.openWriter();
            writer.write(name.toString());
            writer.close();
            String className = name + "Companion";
            JavaFileObject javaFile = filer.createSourceFile(packageName + "." + className, element);
            Writer javaWriter = javaFile.openWriter();
            javaWriter.append("package ").append(packageName).append(";\n\n");
            javaWriter.append("public class ").append(className).append(" {\n");
            javaWriter.append("    public ").append(className).append("() {\n");
            javaWriter.append("        System.out.println(\"Hey there!\");\n");
            javaWriter.append("    }\n}\n");
            javaWriter.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return !elements.isEmpty();
}
Also used : PackageElement(javax.lang.model.element.PackageElement) Element(javax.lang.model.element.Element) TypeElement(javax.lang.model.element.TypeElement) IOException(java.io.IOException) Elements(javax.lang.model.util.Elements) Name(javax.lang.model.element.Name) JavaFileObject(javax.tools.JavaFileObject) PackageElement(javax.lang.model.element.PackageElement) FileObject(javax.tools.FileObject) JavaFileObject(javax.tools.JavaFileObject) Filer(javax.annotation.processing.Filer) Writer(java.io.Writer)

Example 12 with Filer

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

the class AutoServiceProcessor method generateConfigFiles.

private void generateConfigFiles() {
    Filer filer = processingEnv.getFiler();
    for (String providerInterface : providers.keySet()) {
        String resourceFile = "META-INF/services/" + providerInterface;
        log("Working on resource file: " + resourceFile);
        try {
            SortedSet<String> allServices = Sets.newTreeSet();
            try {
                // would like to be able to print the full path
                // before we attempt to get the resource in case the behavior
                // of filer.getResource does change to match the spec, but there's
                // no good way to resolve CLASS_OUTPUT without first getting a resource.
                FileObject existingFile = filer.getResource(StandardLocation.CLASS_OUTPUT, "", resourceFile);
                log("Looking for existing resource file at " + existingFile.toUri());
                Set<String> oldServices = ServicesFiles.readServiceFile(existingFile.openInputStream());
                log("Existing service entries: " + oldServices);
                allServices.addAll(oldServices);
            } catch (IOException e) {
                // According to the javadoc, Filer.getResource throws an exception
                // if the file doesn't already exist.  In practice this doesn't
                // appear to be the case.  Filer.getResource will happily return a
                // FileObject that refers to a non-existent file but will throw
                // IOException if you try to open an input stream for it.
                log("Resource file did not already exist.");
            }
            Set<String> newServices = new HashSet<>(providers.get(providerInterface));
            if (!allServices.addAll(newServices)) {
                log("No new service entries being added.");
                continue;
            }
            log("New service file contents: " + allServices);
            FileObject fileObject = filer.createResource(StandardLocation.CLASS_OUTPUT, "", resourceFile);
            try (OutputStream out = fileObject.openOutputStream()) {
                ServicesFiles.writeServiceFile(allServices, out);
            }
            log("Wrote to: " + fileObject.toUri());
        } catch (IOException e) {
            fatalError("Unable to create " + resourceFile + ", " + e);
            return;
        }
    }
}
Also used : OutputStream(java.io.OutputStream) Throwables.getStackTraceAsString(com.google.common.base.Throwables.getStackTraceAsString) FileObject(javax.tools.FileObject) IOException(java.io.IOException) Filer(javax.annotation.processing.Filer) HashSet(java.util.HashSet)

Example 13 with Filer

use of javax.annotation.processing.Filer in project androidannotations by androidannotations.

the class FileHelper method findRootProjectHolder.

/**
 * We use a dirty trick to find the AndroidManifest.xml file, since it's not
 * available in the classpath. The idea is quite simple : create a fake class
 * file, retrieve its URI, and start going up in parent folders to find the
 * AndroidManifest.xml file. Any better solution will be appreciated.
 */
public static FileHolder findRootProjectHolder(ProcessingEnvironment processingEnv) throws FileNotFoundException {
    FileHolder rootProjectHolder = findKaptRootProjectHolder(processingEnv);
    if (rootProjectHolder != null) {
        return rootProjectHolder;
    }
    Filer filer = processingEnv.getFiler();
    FileObject dummySourceFile;
    try {
        dummySourceFile = filer.createResource(StandardLocation.SOURCE_OUTPUT, "", "dummy" + System.currentTimeMillis());
    } catch (IOException ignored) {
        throw new FileNotFoundException();
    }
    return createFileHolder(dummySourceFile.toUri().toString());
}
Also used : FileNotFoundException(java.io.FileNotFoundException) FileObject(javax.tools.FileObject) IOException(java.io.IOException) Filer(javax.annotation.processing.Filer)

Example 14 with Filer

use of javax.annotation.processing.Filer in project Payara by payara.

the class RestModelExtensionProcessor method process.

@Override
public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) {
    Messager messager = processingEnv.getMessager();
    BufferedWriter bw = null;
    try {
        Map<String, List<String>> classes = new HashMap<String, List<String>>();
        for (TypeElement te : elements) {
            for (Element e : env.getElementsAnnotatedWith(te)) {
                final RestModelExtension annotation = e.getAnnotation(RestModelExtension.class);
                final String parent = annotation.parent();
                List<String> list = classes.get(parent);
                if (list == null) {
                    list = new ArrayList<String>();
                    classes.put(parent, list);
                }
                list.add(e.toString());
            }
        }
        if (!classes.isEmpty()) {
            final Filer filer = processingEnv.getFiler();
            FileObject fo = filer.createResource(StandardLocation.CLASS_OUTPUT, "", "META-INF/restmodelextensions");
            bw = new BufferedWriter(fo.openWriter());
            // parent model:model extension
            for (Map.Entry<String, List<String>> entry : classes.entrySet()) {
                final String key = entry.getKey();
                for (String ext : entry.getValue()) {
                    bw.write(key + ":" + ext + "\n");
                }
            }
            bw.close();
        }
    } catch (IOException ex) {
        messager.printMessage(Kind.ERROR, ex.getLocalizedMessage());
        if (bw != null) {
            try {
                bw.close();
            } catch (Exception e) {
            }
        }
    }
    return true;
}
Also used : Messager(javax.annotation.processing.Messager) HashMap(java.util.HashMap) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) TypeElement(javax.lang.model.element.TypeElement) RestModelExtension(org.glassfish.admin.rest.composite.RestModelExtension) IOException(java.io.IOException) IOException(java.io.IOException) BufferedWriter(java.io.BufferedWriter) ArrayList(java.util.ArrayList) List(java.util.List) FileObject(javax.tools.FileObject) Filer(javax.annotation.processing.Filer) HashMap(java.util.HashMap) Map(java.util.Map)

Example 15 with Filer

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

the class SystemConfigFactoryGenerator method process.

@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) {
    if (roundEnv.processingOver()) {
        return true;
    }
    Filer filer = processingEnv.getFiler();
    try {
        for (Element e : roundEnv.getElementsAnnotatedWith(SystemConfigFactoryConstructor.class)) {
            if (e.getKind() == ElementKind.CONSTRUCTOR) {
                ExecutableElement constructorElement = (ExecutableElement) e;
                String factoryName = generateObjectFactory(filer, constructorElement);
            }
        }
    } catch (Exception e) {
        processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Error: " + e.getLocalizedMessage());
    }
    return true;
}
Also used : PackageElement(javax.lang.model.element.PackageElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Element(javax.lang.model.element.Element) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Filer(javax.annotation.processing.Filer) IOException(java.io.IOException)

Aggregations

Filer (javax.annotation.processing.Filer)27 IOException (java.io.IOException)18 TypeElement (javax.lang.model.element.TypeElement)13 FileObject (javax.tools.FileObject)13 Writer (java.io.Writer)11 Element (javax.lang.model.element.Element)9 File (java.io.File)6 PackageElement (javax.lang.model.element.PackageElement)6 PrintWriter (java.io.PrintWriter)5 URI (java.net.URI)4 ExecutableElement (javax.lang.model.element.ExecutableElement)4 JavaFileObject (javax.tools.JavaFileObject)4 StringWriter (java.io.StringWriter)3 ArrayList (java.util.ArrayList)3 ProcessingEnvironment (javax.annotation.processing.ProcessingEnvironment)3 Name (javax.lang.model.element.Name)3 VariableElement (javax.lang.model.element.VariableElement)3 DeclaredType (javax.lang.model.type.DeclaredType)3 FileReader (java.io.FileReader)2 FileWriter (java.io.FileWriter)2