Search in sources :

Example 36 with FileObject

use of javax.tools.FileObject in project goci by EBISPOT.

the class SpiProcessor method process.

/**
 * Process @ServiceProvider annotations.  This will generate appropriate
 * entries in the META-INF/services file, making classes discoverable at
 * runtime for anything handling these annotations.
 */
public boolean process(Set<? extends TypeElement> typeElements, RoundEnvironment roundEnv) {
    processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "There are " + roundEnv.getElementsAnnotatedWith(Spi.class).size() + " Spi interfaces and " + roundEnv.getElementsAnnotatedWith(ServiceProvider.class).size() + " ServiceProvider implementations");
    // setup output options
    Map<String, PrintWriter> outputs = new HashMap<>();
    // check all elements annotated with @ServiceProvider
    for (Element element : roundEnv.getElementsAnnotatedWith(ServiceProvider.class)) {
        ElementVisitor<Void, Void> visitor = new SimpleElementVisitor6<Void, Void>() {

            public Void visitType(TypeElement e, Void aVoid) {
                typeElement = e;
                return super.visitType(e, aVoid);
            }
        };
        element.accept(visitor, null);
        // visiting this type - work out the superclass (i.e. the @Spi)
        Name result = findSpiAnnotation(typeElement);
        if (result != null) {
            Name spiName = findSpiAnnotation(typeElement);
            if (spiName == null) {
                processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Type annotated with @ServiceProvider but this type does not " + "implement an SPI");
            } else {
                // found the SPI, insert the service file
                processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Generating service entry for " + typeElement.getQualifiedName() + " for service " + spiName);
                String spiNameStr = spiName.toString();
                PrintWriter pw = outputs.get(spiNameStr);
                // lazily instantiate pw if it is null
                if (pw == null) {
                    try {
                        processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Generating service file for " + spiName);
                        FileObject fo = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", "META-INF/services/" + spiName);
                        pw = new PrintWriter(fo.openWriter());
                        outputs.put(spiNameStr, pw);
                    } catch (IOException e) {
                        e.printStackTrace();
                        processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Problem creating services file for " + spiName);
                    }
                }
                // pw should now have defo be non-null, unless something went wrong
                if (pw != null) {
                    pw.println(typeElement.getQualifiedName());
                }
            }
        } else {
            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, typeElement.getQualifiedName() + ": Classes annotated with " + ServiceProvider.class.getName() + " " + "MUST implement an interface marked with an " + Spi.class.getName() + " annotation");
            return false;
        }
    }
    // done all elements, so make sure all writers are closed
    for (PrintWriter pw : outputs.values()) {
        pw.close();
    }
    return true;
}
Also used : SimpleElementVisitor6(javax.lang.model.util.SimpleElementVisitor6) HashMap(java.util.HashMap) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) TypeElement(javax.lang.model.element.TypeElement) IOException(java.io.IOException) Name(javax.lang.model.element.Name) FileObject(javax.tools.FileObject) PrintWriter(java.io.PrintWriter)

Example 37 with FileObject

use of javax.tools.FileObject in project zuul by Netflix.

the class FilterProcessor method addNewClasses.

static void addNewClasses(Filer filer, Collection<String> elements) throws IOException {
    String resourceName = "META-INF/zuul/allfilters";
    List<String> existing = Collections.emptyList();
    try {
        FileObject existingFilters = filer.getResource(StandardLocation.CLASS_OUTPUT, "", resourceName);
        try (InputStream is = existingFilters.openInputStream();
            InputStreamReader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) {
            existing = readResourceFile(reader);
        }
    } catch (FileNotFoundException | NoSuchFileException e) {
    // Perhaps log this.
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    int sizeBefore = existing.size();
    Set<String> existingSet = new LinkedHashSet<>(existing);
    List<String> newElements = new ArrayList<>(existingSet);
    for (String element : elements) {
        if (existingSet.add(element)) {
            newElements.add(element);
        }
    }
    if (newElements.size() == sizeBefore) {
        // nothing to do.
        return;
    }
    newElements.sort(String::compareTo);
    FileObject dest = filer.createResource(StandardLocation.CLASS_OUTPUT, "", resourceName);
    try (OutputStream os = dest.openOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8)) {
        writeResourceFile(osw, newElements);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileNotFoundException(java.io.FileNotFoundException) NoSuchFileException(java.nio.file.NoSuchFileException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) OutputStreamWriter(java.io.OutputStreamWriter) FileObject(javax.tools.FileObject)

Example 38 with FileObject

use of javax.tools.FileObject in project druid by druid-io.

the class LocalDataSegmentPuller method buildFileObject.

public static FileObject buildFileObject(final URI uri) {
    final Path path = Paths.get(uri);
    final File file = path.toFile();
    return new FileObject() {

        @Override
        public URI toUri() {
            return uri;
        }

        @Override
        public String getName() {
            return path.getFileName().toString();
        }

        @Override
        public InputStream openInputStream() throws IOException {
            return new FileInputStream(file);
        }

        @Override
        public OutputStream openOutputStream() throws IOException {
            return new FileOutputStream(file);
        }

        @Override
        public Reader openReader(boolean ignoreEncodingErrors) throws IOException {
            return Files.newReader(file, Charset.defaultCharset());
        }

        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            throw new UOE("CharSequence not supported");
        }

        @Override
        public Writer openWriter() throws IOException {
            return Files.newWriter(file, Charset.defaultCharset());
        }

        @Override
        public long getLastModified() {
            return file.lastModified();
        }

        @Override
        public boolean delete() {
            return file.delete();
        }
    };
}
Also used : Path(java.nio.file.Path) FileOutputStream(java.io.FileOutputStream) UOE(org.apache.druid.java.util.common.UOE) FileObject(javax.tools.FileObject) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 39 with FileObject

use of javax.tools.FileObject in project neo4j-mobile-android by neo4j-contrib.

the class AnnotationProcessor method append.

Writer append(String... path) throws IOException {
    FileObject file = processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", path(path));
    URI uri = file.toUri();
    return new FileWriter(new File(uri.toString()), true);
}
Also used : FileWriter(java.io.FileWriter) FileObject(javax.tools.FileObject) URI(java.net.URI) File(java.io.File)

Example 40 with FileObject

use of javax.tools.FileObject 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)

Aggregations

FileObject (javax.tools.FileObject)91 IOException (java.io.IOException)57 TypeElement (javax.lang.model.element.TypeElement)19 File (java.io.File)18 PrintWriter (java.io.PrintWriter)16 Element (javax.lang.model.element.Element)14 Writer (java.io.Writer)13 Filer (javax.annotation.processing.Filer)13 BufferedWriter (java.io.BufferedWriter)12 ArrayList (java.util.ArrayList)12 OutputStream (java.io.OutputStream)11 JavaFileObject (javax.tools.JavaFileObject)11 OutputStreamWriter (java.io.OutputStreamWriter)10 Properties (java.util.Properties)10 InputStream (java.io.InputStream)8 URI (java.net.URI)8 FilerException (javax.annotation.processing.FilerException)7 MainInfo (com.predic8.membrane.annot.model.MainInfo)6 BufferedReader (java.io.BufferedReader)6 FileWriter (java.io.FileWriter)6