Search in sources :

Example 46 with FileObject

use of javax.tools.FileObject in project vertx-examples by vert-x3.

the class CodeTransProcessor method process.

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (roundEnv.processingOver()) {
        if (log != null) {
            log.close();
        }
        return false;
    }
    if (outputDir != null && (outputDir.exists() || outputDir.mkdirs())) {
        List<ExecutableElement> methodElts = new ArrayList<>();
        try {
            PrintWriter log = getLogger();
            // Process all verticles automatically
            TypeMirror verticleType = processingEnv.getElementUtils().getTypeElement(Verticle.class.getName()).asType();
            for (Element rootElt : roundEnv.getRootElements()) {
                Set<Modifier> modifiers = rootElt.getModifiers();
                if (rootElt.getKind() == ElementKind.CLASS && !modifiers.contains(Modifier.ABSTRACT) && modifiers.contains(Modifier.PUBLIC) && processingEnv.getTypeUtils().isSubtype(rootElt.asType(), verticleType)) {
                    TypeElement typeElt = (TypeElement) rootElt;
                    for (Element enclosedElt : typeElt.getEnclosedElements()) {
                        if (enclosedElt.getKind() == ElementKind.METHOD) {
                            ExecutableElement methodElt = (ExecutableElement) enclosedElt;
                            if (methodElt.getSimpleName().toString().equals("start") && methodElt.getParameters().isEmpty()) {
                                methodElts.add(methodElt);
                            }
                        }
                    }
                }
            }
            // Process CodeTranslate annotations
            roundEnv.getElementsAnnotatedWith(CodeTranslate.class).forEach(annotatedElt -> {
                methodElts.add((ExecutableElement) annotatedElt);
            });
            // Generate
            for (ExecutableElement methodElt : methodElts) {
                TypeElement typeElt = (TypeElement) methodElt.getEnclosingElement();
                FileObject obj = processingEnv.getFiler().getResource(StandardLocation.SOURCE_PATH, "", typeElt.getQualifiedName().toString().replace('.', '/') + ".java");
                File srcFolder = new File(obj.toUri()).getParentFile();
                String filename = Case.SNAKE.format(Case.CAMEL.parse(typeElt.getSimpleName().toString()));
                for (Lang lang : langs) {
                    if (isSkipped(typeElt, lang)) {
                        log.write("Skipping " + lang.getExtension() + " translation for " + typeElt.getQualifiedName() + "#" + methodElt.getSimpleName());
                        continue;
                    }
                    String folderPath = processingEnv.getElementUtils().getPackageOf(typeElt).getQualifiedName().toString().replace('.', '/');
                    File dstFolder = new File(new File(outputDir, lang.getExtension()), folderPath);
                    if (dstFolder.exists() || dstFolder.mkdirs()) {
                        try {
                            String translation = translator.translate(methodElt, lang);
                            File f = new File(dstFolder, filename + "." + lang.getExtension());
                            Files.write(f.toPath(), translation.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
                            log.println("Generated " + f.getAbsolutePath());
                            copyDirRec(srcFolder, dstFolder, log);
                        } catch (Exception e) {
                            log.println("Skipping generation of " + typeElt.getQualifiedName());
                            e.printStackTrace(log);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    } else {
        return false;
    }
}
Also used : JavaScriptLang(io.vertx.codetrans.lang.js.JavaScriptLang) GroovyLang(io.vertx.codetrans.lang.groovy.GroovyLang) Lang(io.vertx.codetrans.Lang) RubyLang(io.vertx.codetrans.lang.ruby.RubyLang) IOException(java.io.IOException) CodeTranslate(io.vertx.codetrans.annotations.CodeTranslate) TypeMirror(javax.lang.model.type.TypeMirror) FileObject(javax.tools.FileObject) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 47 with FileObject

use of javax.tools.FileObject in project fabric8 by jboss-fuse.

the class AbstractKubernetesAnnotationProcessor method getFileObject.

private FileObject getFileObject(String fileName) throws IOException {
    FileObject fileObject = processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", fileName);
    Path path = Paths.get(fileObject.toUri());
    File file = path.toFile();
    if (file.exists() && !file.delete()) {
        throw new IOException("Failed to delete old kubernetes json file: " + fileName);
    }
    fileObject = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", fileName);
    return fileObject;
}
Also used : Path(java.nio.file.Path) FileObject(javax.tools.FileObject) IOException(java.io.IOException) File(java.io.File)

Example 48 with FileObject

use of javax.tools.FileObject in project fabric8 by jboss-fuse.

the class AbstractAnnotationProcessor method writeFile.

/**
 * Helper method to produce class output text file using the given handler
 */
protected void writeFile(String packageName, String fileName, String text) {
    Writer writer = null;
    try {
        Writer out;
        Filer filer = processingEnv.getFiler();
        FileObject resource;
        try {
            resource = filer.getResource(StandardLocation.CLASS_OUTPUT, packageName, fileName);
        } catch (Throwable e) {
            resource = filer.createResource(StandardLocation.CLASS_OUTPUT, packageName, fileName);
        }
        URI uri = resource.toUri();
        File file = null;
        if (uri != null) {
            try {
                file = new File(uri.getPath());
            } catch (Exception e) {
                warning("Could not convert output directory resource URI to a file " + e);
            }
        }
        if (file == null) {
            warning("No class output directory could be found!");
        } else {
            file.getParentFile().mkdirs();
            log("Generating file " + file);
            writer = new FileWriter(file);
            writer.write(text);
        }
    } catch (IOException e) {
        log(e);
    } finally {
        IOHelper.close(writer);
    }
}
Also used : FileWriter(java.io.FileWriter) FileObject(javax.tools.FileObject) IOException(java.io.IOException) Filer(javax.annotation.processing.Filer) URI(java.net.URI) File(java.io.File) PrintWriter(java.io.PrintWriter) StringWriter(java.io.StringWriter) FileWriter(java.io.FileWriter) Writer(java.io.Writer) IOException(java.io.IOException)

Example 49 with FileObject

use of javax.tools.FileObject in project qpid-broker-j by apache.

the class PluggableProcessor method generateServiceFiles.

private void generateServiceFiles(Filer filer) {
    for (String serviceName : factoryImplementations.keySet()) {
        processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Generating service file for " + serviceName);
        String relativeName = "META-INF/services/" + serviceName;
        loadExistingServicesFile(filer, serviceName);
        try {
            FileObject serviceFile = filer.createResource(StandardLocation.CLASS_OUTPUT, "", relativeName);
            try (PrintWriter pw = new PrintWriter(new OutputStreamWriter(serviceFile.openOutputStream(), "UTF-8"))) {
                for (String headerLine : License.LICENSE) {
                    pw.println("#" + headerLine);
                }
                pw.println("#");
                pw.println("# Note: Parts of this file are auto-generated from annotations.");
                pw.println("#");
                for (String implementation : factoryImplementations.get(serviceName)) {
                    pw.println(implementation);
                }
            }
        } catch (IOException e) {
            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Failed to write services file: " + relativeName + " - " + e.getLocalizedMessage());
        }
    }
}
Also used : OutputStreamWriter(java.io.OutputStreamWriter) FileObject(javax.tools.FileObject) IOException(java.io.IOException) PrintWriter(java.io.PrintWriter)

Example 50 with FileObject

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

the class ModelWriter method writeModel.

public void writeModel(FileObject sourceFile, Writable model) {
    try (BufferedWriter writer = new BufferedWriter(new IndentationCorrectingWriter(sourceFile.openWriter()))) {
        Map<Class<?>, Object> values = new HashMap<>();
        values.put(Configuration.class, CONFIGURATION);
        model.write(new DefaultModelElementWriterContext(values), writer);
        writer.flush();
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : HashMap(java.util.HashMap) FileObject(javax.tools.FileObject) IOException(java.io.IOException) BufferedWriter(java.io.BufferedWriter)

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