Search in sources :

Example 81 with FileObject

use of javax.tools.FileObject in project mvp4g2 by mvp4g.

the class HandlerAnnotationScanner method restore.

private HandlerMetaModel restore() {
    Properties props = new Properties();
    try {
        FileObject resource = this.processingEnvironment.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", this.createRelativeFileName());
        props.load(resource.openInputStream());
        return new HandlerMetaModel(props);
    } catch (IOException e) {
    // every thing is ok -> no operation
    // this.processorUtils.createNoteMessage("no resource found for : >>" + this.createRelativeFileName() + "<<");
    }
    return new HandlerMetaModel();
}
Also used : HandlerMetaModel(com.github.mvp4g.mvp4g2.processor.model.HandlerMetaModel) FileObject(javax.tools.FileObject) IOException(java.io.IOException) Properties(java.util.Properties)

Example 82 with FileObject

use of javax.tools.FileObject in project neo4j by neo4j.

the class ServiceAnnotationProcessor method loadIfExists.

private SortedSet<String> loadIfExists(String path) {
    final SortedSet<String> result = new TreeSet<>();
    try {
        final FileObject file = processingEnv.getFiler().getResource(CLASS_OUTPUT, "", path);
        final List<String> lines = new ArrayList<>();
        try (BufferedReader in = new BufferedReader(new InputStreamReader(file.openInputStream(), StandardCharsets.UTF_8))) {
            String line;
            while ((line = in.readLine()) != null) {
                lines.add(line);
            }
        }
        lines.stream().map(s -> substringBefore(s, "#")).map(String::trim).filter(StringUtils::isNotEmpty).forEach(result::add);
        info("Loaded existing providers: " + result);
    } catch (IOException ignore) {
        info("No existing providers loaded");
    }
    return result;
}
Also used : SortedSet(java.util.SortedSet) AbstractProcessor(javax.annotation.processing.AbstractProcessor) TypeElement(javax.lang.model.element.TypeElement) StringUtils(org.apache.commons.lang3.StringUtils) Elements(javax.lang.model.util.Elements) ERROR(javax.tools.Diagnostic.Kind.ERROR) Multimaps(org.eclipse.collections.impl.factory.Multimaps) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) FileObject(javax.tools.FileObject) DEFAULT_NEW_LINE(org.neo4j.annotations.AnnotationConstants.DEFAULT_NEW_LINE) MutableMultimap(org.eclipse.collections.api.multimap.MutableMultimap) CLASS_OUTPUT(javax.tools.StandardLocation.CLASS_OUTPUT) Collectors.toSet(java.util.stream.Collectors.toSet) BufferedWriter(java.io.BufferedWriter) Set(java.util.Set) ExceptionUtils.getStackTrace(org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace) UnifiedSet.newSetWith(org.eclipse.collections.impl.set.mutable.UnifiedSet.newSetWith) IOException(java.io.IOException) Element(javax.lang.model.element.Element) Types(javax.lang.model.util.Types) InputStreamReader(java.io.InputStreamReader) StandardCharsets(java.nio.charset.StandardCharsets) String.format(java.lang.String.format) SourceVersion(javax.lang.model.SourceVersion) NOTE(javax.tools.Diagnostic.Kind.NOTE) List(java.util.List) TypeMirror(javax.lang.model.type.TypeMirror) Collectors.toList(java.util.stream.Collectors.toList) RoundEnvironment(javax.annotation.processing.RoundEnvironment) ProcessingEnvironment(javax.annotation.processing.ProcessingEnvironment) Optional(java.util.Optional) BufferedReader(java.io.BufferedReader) StringUtils.substringBefore(org.apache.commons.lang3.StringUtils.substringBefore) InputStreamReader(java.io.InputStreamReader) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) BufferedReader(java.io.BufferedReader) FileObject(javax.tools.FileObject) IOException(java.io.IOException)

Example 83 with FileObject

use of javax.tools.FileObject in project neo4j by neo4j.

the class ServiceAnnotationProcessor method generateConfigs.

private void generateConfigs() throws IOException {
    for (final TypeElement service : serviceProviders.keySet()) {
        final String path = "META-INF/services/" + elementUtils.getBinaryName(service);
        info("Generating service config file: " + path);
        final SortedSet<String> oldProviders = loadIfExists(path);
        final SortedSet<String> newProviders = new TreeSet<>();
        serviceProviders.get(service).forEach(providerType -> {
            final String providerName = elementUtils.getBinaryName(providerType).toString();
            newProviders.add(providerName);
        });
        if (oldProviders.containsAll(newProviders)) {
            info("No new service providers found");
            return;
        }
        newProviders.addAll(oldProviders);
        final FileObject file = processingEnv.getFiler().createResource(CLASS_OUTPUT, "", path);
        try (BufferedWriter writer = new BufferedWriter(file.openWriter())) {
            info("Writing service providers: " + newProviders);
            for (final String provider : newProviders) {
                writer.write(provider);
                writer.write(newLine);
            }
        }
    }
}
Also used : TypeElement(javax.lang.model.element.TypeElement) TreeSet(java.util.TreeSet) FileObject(javax.tools.FileObject) BufferedWriter(java.io.BufferedWriter)

Example 84 with FileObject

use of javax.tools.FileObject in project commons by twitter.

the class CmdLineProcessor method process.

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    try {
        // Collect all live classnames from this round, so that if they lose all annotated fields, we
        // can delete their previous resources.
        liveClassNamesBuilder.addAll(extractClassNames(roundEnv));
        // Then collect all relevant annotated classes.
        Set<? extends Element> parsers = getAnnotatedElements(roundEnv, ArgParser.class);
        @Nullable Set<String> parsedTypes = getParsedTypes(parsers);
        Set<? extends Element> cmdlineArgs = getAnnotatedElements(roundEnv, CmdLine.class);
        Set<? extends Element> positionalArgs = getAnnotatedElements(roundEnv, Positional.class);
        ImmutableSet<? extends Element> invalidArgs = Sets.intersection(cmdlineArgs, positionalArgs).immutableCopy();
        if (!invalidArgs.isEmpty()) {
            error("An Arg cannot be annotated with both @CmdLine and @Positional, found bad Arg " + "fields: %s", invalidArgs);
        }
        for (ArgInfo cmdLineInfo : processAnnotatedArgs(parsedTypes, cmdlineArgs, CmdLine.class)) {
            getBuilder(cmdLineInfo.className).addCmdLineArg(cmdLineInfo);
        }
        for (ArgInfo positionalInfo : processAnnotatedArgs(parsedTypes, positionalArgs, Positional.class)) {
            getBuilder(positionalInfo.className).addPositionalInfo(positionalInfo);
        }
        checkPositionalArgsAreLists(roundEnv);
        processParsers(parsers);
        Set<? extends Element> verifiers = getAnnotatedElements(roundEnv, VerifierFor.class);
        processVerifiers(verifiers);
        if (roundEnv.processingOver()) {
            for (String className : this.liveClassNamesBuilder.build()) {
                FileObject cmdLinePropertiesResource = createCommandLineDb(className);
                Configuration.Builder configBuilder = getBuilder(className);
                // no fields.
                if (configBuilder.isEmpty()) {
                    cmdLinePropertiesResource.delete();
                    continue;
                }
                // Otherwise, write a new copy of the resource.
                Writer writer = null;
                try {
                    writer = cmdLinePropertiesResource.openWriter();
                    configBuilder.build().store(writer, "Generated via apt by " + getClass().getName());
                } catch (IOException e) {
                    throw new RuntimeException("Failed to write Arg resource file for " + className + ":", e);
                } finally {
                    closeQuietly(writer);
                }
            }
        }
    } catch (RuntimeException e) {
        // SUPPRESS CHECKSTYLE IllegalCatch
        // Catch internal errors - when these bubble more useful queued error messages are lost in
        // some javac implementations.
        error("Unexpected error completing annotation processing:\n%s", Throwables.getStackTraceAsString(e));
    }
    return true;
}
Also used : FileObject(javax.tools.FileObject) IOException(java.io.IOException) Nullable(javax.annotation.Nullable) Writer(java.io.Writer) ArgInfo(com.twitter.common.args.apt.Configuration.ArgInfo)

Example 85 with FileObject

use of javax.tools.FileObject in project jvarkit by lindenb.

the class JVarkitAnnotationProcessor method copySource.

private void copySource(final javax.lang.model.element.Element element) {
    if (element == null || element.getKind() != ElementKind.CLASS)
        return;
    final String thisDir = System.getProperty("jvarkit.this.dir");
    if (thisDir == null || thisDir.isEmpty()) {
        System.err.println("jvarkit.this.dir is not defined");
        return;
    }
    Writer writer = null;
    Reader reader = null;
    try {
        do {
            String className = element.toString();
            if (className == null || className.isEmpty() || className.equals("java.lang.Object"))
                return;
            int dollar = className.indexOf('$');
            if (dollar != -1)
                className = className.substring(0, dollar);
            File javaFile = new File(thisDir + "/src/main/java/" + className.replace('.', '/') + ".java");
            if (!javaFile.exists())
                break;
            final Filer filer = super.processingEnv.getFiler();
            final String packageName;
            final String fileName;
            int dot = className.lastIndexOf('.');
            if (dot == -1) {
                packageName = "";
                fileName = className;
            } else {
                packageName = className.substring(0, dot);
                fileName = className.substring(dot + 1);
            }
            final FileObject fo = filer.createResource(StandardLocation.CLASS_OUTPUT, packageName, fileName + ".java");
            if (new File(fo.getName()).exists())
                break;
            System.err.println("## Copying " + javaFile + " -> " + fo.getName());
            reader = new FileReader(javaFile);
            writer = fo.openWriter();
            final char[] buffer = new char[1024];
            int nRead;
            while ((nRead = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, nRead);
            }
            writer.close();
            writer = null;
            reader.close();
            reader = null;
        } while (false);
    } catch (final Exception err) {
        System.err.println(err.getMessage());
    } finally {
        if (writer != null)
            try {
                writer.close();
            } catch (Exception err) {
            }
        if (reader != null)
            try {
                reader.close();
            } catch (Exception err) {
            }
    }
    final TypeMirror superclass = ((TypeElement) element).getSuperclass();
    if (superclass == null || superclass.getKind() == TypeKind.NONE) {
        return;
    }
    final DeclaredType kind = (DeclaredType) superclass;
    copySource(kind.asElement());
}
Also used : TypeElement(javax.lang.model.element.TypeElement) Reader(java.io.Reader) FileReader(java.io.FileReader) TypeMirror(javax.lang.model.type.TypeMirror) FileReader(java.io.FileReader) FileObject(javax.tools.FileObject) File(java.io.File) Filer(javax.annotation.processing.Filer) Writer(java.io.Writer) DeclaredType(javax.lang.model.type.DeclaredType)

Aggregations

FileObject (javax.tools.FileObject)98 IOException (java.io.IOException)61 File (java.io.File)21 TypeElement (javax.lang.model.element.TypeElement)19 PrintWriter (java.io.PrintWriter)17 Writer (java.io.Writer)16 Filer (javax.annotation.processing.Filer)14 Element (javax.lang.model.element.Element)14 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 URI (java.net.URI)10 Properties (java.util.Properties)10 InputStream (java.io.InputStream)8 FileWriter (java.io.FileWriter)7 FilerException (javax.annotation.processing.FilerException)7 MainInfo (com.predic8.membrane.annot.model.MainInfo)6 BufferedReader (java.io.BufferedReader)6