Search in sources :

Example 31 with FileObject

use of javax.tools.FileObject in project SpongeAPI by SpongePowered.

the class PluginProcessor method createWriter.

private BufferedWriter createWriter() throws IOException {
    if (this.outputPath != null) {
        getMessager().printMessage(NOTE, "Writing plugin metadata to " + this.outputPath);
        return Files.newBufferedWriter(this.outputPath);
    }
    FileObject obj = this.processingEnv.getFiler().createResource(CLASS_OUTPUT, "", McModInfo.STANDARD_FILENAME);
    getMessager().printMessage(NOTE, "Writing plugin metadata to " + obj.toUri());
    return new BufferedWriter(obj.openWriter());
}
Also used : FileObject(javax.tools.FileObject) BufferedWriter(java.io.BufferedWriter)

Example 32 with FileObject

use of javax.tools.FileObject in project Nucleus by NucleusPowered.

the class StoreProcessor method process.

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    Map<Element, String> classes = new HashMap<>();
    Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(Store.class);
    for (Element element : elements) {
        // Only storing classes.
        if (element.getKind().isClass()) {
            Store s = element.getAnnotation(Store.class);
            classes.put(element, s.isRoot() ? null : s.value());
        }
    }
    // Get the root elements
    ClassElementVisitor cev = new ClassElementVisitor();
    Map<String, String> conv = classes.entrySet().stream().filter(x -> x.getValue() == null).map(x -> cev.visit(x.getKey(), true)).filter(Objects::nonNull).collect(Collectors.toMap(x -> x.pa, x -> x.cl));
    final Map<String, Map<String, List<String>>> result = conv.values().stream().collect(Collectors.toMap(x -> x, x -> new HashMap<>()));
    classes.entrySet().stream().filter(x -> x.getValue() != null).map(x -> {
        StringTuple st = cev.visit(x.getKey(), false);
        if (st != null) {
            return new StringTuple(x.getValue(), st.cl);
        }
        return null;
    }).filter(Objects::nonNull).forEach(x -> {
        // Check the class vs package name
        conv.entrySet().stream().filter(y -> x.cl.startsWith(y.getKey())).distinct().findFirst().ifPresent(y -> result.get(y.getValue()).computeIfAbsent(x.pa, z -> new ArrayList<>()).add(x.cl));
    });
    if (!classes.isEmpty()) {
        // Write this file
        try {
            FileObject fo = this.processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "assets.nucleus", "classes.json");
            try (Writer os = fo.openWriter()) {
                os.write(new GsonBuilder().setPrettyPrinting().create().toJson(result));
                os.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return false;
}
Also used : PackageElement(javax.lang.model.element.PackageElement) AbstractProcessor(javax.annotation.processing.AbstractProcessor) Modifier(javax.lang.model.element.Modifier) VariableElement(javax.lang.model.element.VariableElement) HashMap(java.util.HashMap) TypeElement(javax.lang.model.element.TypeElement) SupportedAnnotationTypes(javax.annotation.processing.SupportedAnnotationTypes) GsonBuilder(com.google.gson.GsonBuilder) ArrayList(java.util.ArrayList) FileObject(javax.tools.FileObject) SupportedSourceVersion(javax.annotation.processing.SupportedSourceVersion) Map(java.util.Map) AbstractElementVisitor8(javax.lang.model.util.AbstractElementVisitor8) Nullable(javax.annotation.Nullable) StandardLocation(javax.tools.StandardLocation) ExecutableElement(javax.lang.model.element.ExecutableElement) Set(java.util.Set) IOException(java.io.IOException) Element(javax.lang.model.element.Element) Processor(javax.annotation.processing.Processor) Collectors(java.util.stream.Collectors) TypeParameterElement(javax.lang.model.element.TypeParameterElement) Objects(java.util.Objects) SourceVersion(javax.lang.model.SourceVersion) List(java.util.List) RoundEnvironment(javax.annotation.processing.RoundEnvironment) AutoService(com.google.auto.service.AutoService) Writer(java.io.Writer) HashMap(java.util.HashMap) GsonBuilder(com.google.gson.GsonBuilder) PackageElement(javax.lang.model.element.PackageElement) VariableElement(javax.lang.model.element.VariableElement) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Element(javax.lang.model.element.Element) TypeParameterElement(javax.lang.model.element.TypeParameterElement) IOException(java.io.IOException) FileObject(javax.tools.FileObject) HashMap(java.util.HashMap) Map(java.util.Map) Writer(java.io.Writer)

Example 33 with FileObject

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

the class PublicApiAnnotationProcessor method generateSignature.

private void generateSignature() throws IOException {
    // only verify on request
    if (!Boolean.getBoolean(VERIFY_TOGGLE)) {
        return;
    }
    if (!publicElements.isEmpty()) {
        StringBuilder sb = new StringBuilder();
        for (final String element : publicElements) {
            sb.append(element).append(newLine);
        }
        String newSignature = sb.toString();
        // Write new signature
        final FileObject file = processingEnv.getFiler().createResource(CLASS_OUTPUT, "", GENERATED_SIGNATURE_DESTINATION);
        try (BufferedWriter writer = new BufferedWriter(file.openWriter())) {
            writer.write(newSignature);
        }
        if (!testExecution) {
            // Verify files
            Path path = Path.of(file.toUri());
            Path metaPath = getAndAssertParent(path, "META-INF");
            Path classesPath = getAndAssertParent(metaPath, "classes");
            Path targetPath = getAndAssertParent(classesPath, "target");
            Path mavenModulePath = requireNonNull(targetPath.getParent());
            Path oldSignaturePath = mavenModulePath.resolve("PublicApi.txt");
            if (Boolean.getBoolean("overwrite")) {
                info("Overwriting " + oldSignaturePath);
                Files.writeString(oldSignaturePath, newSignature, UTF_8, WRITE, CREATE, TRUNCATE_EXISTING);
            }
            if (!Files.exists(oldSignaturePath)) {
                error(format("Missing file %s, use `-Doverwrite` to create it.", oldSignaturePath));
                return;
            }
            String oldSignature = Files.readString(oldSignaturePath, UTF_8);
            if (!oldSignature.equals(newSignature)) {
                oldSignature = oldSignature.replace(WINDOWS_NEW_LINE, DEFAULT_NEW_LINE);
                newSignature = newSignature.replace(WINDOWS_NEW_LINE, DEFAULT_NEW_LINE);
                if (!oldSignature.equals(newSignature)) {
                    StringBuilder diff = diff(oldSignaturePath);
                    error(format("Public API signature mismatch. The generated signature, %s, does not match the old signature in %s.%n" + "Specify `-Doverwrite` to maven to replace it. Changed public elements, compared to the committed PublicApi.txt:%n%s%n", path, oldSignaturePath, diff));
                }
            } else {
                info("Public API signature matches. " + oldSignaturePath);
            }
        }
    }
}
Also used : Path(java.nio.file.Path) FileObject(javax.tools.FileObject) BufferedWriter(java.io.BufferedWriter)

Example 34 with FileObject

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

use of javax.tools.FileObject in project maven-plugins by apache.

the class ServiceProviderProcessor method writeServices.

private void writeServices() {
    try {
        FileObject out = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", "META-INF/one", new Element[0]);
        OutputStream os = out.openOutputStream();
        OutputStream os2 = processingEnv.getFiler().createSourceFile("org.Milos", new Element[0]).openOutputStream();
        OutputStreamWriter osr = new OutputStreamWriter(os2);
        try {
            PrintWriter w = new PrintWriter(new OutputStreamWriter(os, "UTF-8"));
            w.write("test");
            w.flush();
            String clazz = "package org;\n class Milos {}";
            osr.write(clazz.toCharArray());
            osr.flush();
        } finally {
            osr.close();
            os.close();
        }
    } catch (IOException x) {
        processingEnv.getMessager().printMessage(Kind.ERROR, "Failed to write to one: " + x.toString());
    }
}
Also used : OutputStream(java.io.OutputStream) Element(javax.lang.model.element.Element) TypeElement(javax.lang.model.element.TypeElement) OutputStreamWriter(java.io.OutputStreamWriter) FileObject(javax.tools.FileObject) IOException(java.io.IOException) PrintWriter(java.io.PrintWriter)

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