Search in sources :

Example 81 with StandardJavaFileManager

use of javax.tools.StandardJavaFileManager in project groovy-cps by cloudbees.

the class Driver method run.

public void run(File dir) throws Exception {
    JavaCompiler javac = JavacTool.create();
    DiagnosticListener<JavaFileObject> errorListener = createErrorListener();
    try (StandardJavaFileManager fileManager = javac.getStandardFileManager(errorListener, Locale.getDefault(), Charset.defaultCharset())) {
        fileManager.setLocation(StandardLocation.CLASS_PATH, Collections.singleton(Which.jarFile(GroovyShell.class)));
        File groovySrcJar = Which.jarFile(Driver.class.getClassLoader().getResource("groovy/lang/GroovyShell.java"));
        // classes to translate
        // TODO include other classes mentioned in DefaultGroovyMethods.DGM_LIKE_CLASSES if they have any applicable methods
        List<String> fileNames = asList("DefaultGroovyMethods", "DefaultGroovyStaticMethods", "StringGroovyMethods");
        List<JavaFileObject> src = new ArrayList<>();
        ZipArchive a = new ZipArchive((JavacFileManager) fileManager, new ZipFile(groovySrcJar));
        for (String name : fileNames) {
            src.add(a.getFileObject(new RelativeDirectory("org/codehaus/groovy/runtime"), name + ".java"));
        }
        // annotation processing appears to cause the source files to be reparsed
        // (even though I couldn't find exactly where it's done), which causes
        // Tree symbols created by the original JavacTask.parse() call to be thrown away,
        // which breaks later processing.
        // So for now, don't perform annotation processing
        List<String> options = asList("-proc:none");
        Translator t = new Translator(javac.getTask(null, fileManager, errorListener, options, null, src));
        for (String name : fileNames) {
            t.translate("org.codehaus.groovy.runtime." + name, "com.cloudbees.groovy.cps.Cps" + name, groovySrcJar.getName());
        }
        dir.mkdirs();
        t.generateTo(new FileCodeWriter(dir));
    }
}
Also used : RelativeDirectory(com.sun.tools.javac.file.RelativePath.RelativeDirectory) ArrayList(java.util.ArrayList) JavaCompiler(javax.tools.JavaCompiler) ZipArchive(com.sun.tools.javac.file.ZipArchive) FileCodeWriter(com.sun.codemodel.writer.FileCodeWriter) JavaFileObject(javax.tools.JavaFileObject) ZipFile(java.util.zip.ZipFile) StandardJavaFileManager(javax.tools.StandardJavaFileManager) File(java.io.File) ZipFile(java.util.zip.ZipFile)

Example 82 with StandardJavaFileManager

use of javax.tools.StandardJavaFileManager in project querydsl by querydsl.

the class CompileMojo method execute.

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager sjfm = jc.getStandardFileManager(null, null, null);
    try {
        Set<File> generatedFiles = getJavaFiles(sourceFolder);
        Iterable<? extends JavaFileObject> fileObjects = sjfm.getJavaFileObjectsFromFiles(generatedFiles);
        List<String> opts = getCompilerOptions();
        jc.getTask(null, null, null, opts, null, fileObjects).call();
    } finally {
        try {
            sjfm.close();
        } catch (IOException e) {
            throw new MojoFailureException(e.getMessage(), e);
        }
    }
}
Also used : MojoFailureException(org.apache.maven.plugin.MojoFailureException) JavaCompiler(javax.tools.JavaCompiler) StandardJavaFileManager(javax.tools.StandardJavaFileManager) IOException(java.io.IOException) File(java.io.File)

Example 83 with StandardJavaFileManager

use of javax.tools.StandardJavaFileManager in project kafka by apache.

the class TestPlugins method compileJavaSources.

/**
 * Compile a directory of .java source files into .class files
 * .class files are placed into the same directory as their sources.
 *
 * <p>Dependencies between source files in this directory are resolved against one another
 * and the classes present in the test environment.
 * See https://stackoverflow.com/questions/1563909/ for more information.
 * Additional dependencies in your plugins should be added as test scope to :connect:runtime.
 * @param sourceDir Directory containing java source files
 * @throws IOException if the files cannot be compiled
 */
private static void compileJavaSources(Path sourceDir, Path binDir) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    List<File> sourceFiles = Files.walk(sourceDir).filter(Files::isRegularFile).filter(path -> path.toFile().getName().endsWith(".java")).map(Path::toFile).collect(Collectors.toList());
    StringWriter writer = new StringWriter();
    List<String> options = Arrays.asList(// Write class output to a different directory.
    "-d", // Write class output to a different directory.
    binDir.toString());
    try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)) {
        boolean success = compiler.getTask(writer, fileManager, null, options, null, fileManager.getJavaFileObjectsFromFiles(sourceFiles)).call();
        if (!success) {
            throw new RuntimeException("Failed to compile test plugin:\n" + writer);
        }
    }
}
Also used : StringWriter(java.io.StringWriter) JavaCompiler(javax.tools.JavaCompiler) StandardJavaFileManager(javax.tools.StandardJavaFileManager) File(java.io.File)

Example 84 with StandardJavaFileManager

use of javax.tools.StandardJavaFileManager in project Java-Runtime-Compiler by OpenHFT.

the class CachedCompiler method loadFromJava.

public Class loadFromJava(@NotNull ClassLoader classLoader, @NotNull String className, @NotNull String javaCode, @Nullable PrintWriter writer) throws ClassNotFoundException {
    Class clazz = null;
    Map<String, Class> loadedClasses;
    synchronized (loadedClassesMap) {
        loadedClasses = loadedClassesMap.get(classLoader);
        if (loadedClasses == null)
            loadedClassesMap.put(classLoader, loadedClasses = new LinkedHashMap<String, Class>());
        else
            clazz = loadedClasses.get(className);
    }
    PrintWriter printWriter = (writer == null ? DEFAULT_WRITER : writer);
    if (clazz != null)
        return clazz;
    MyJavaFileManager fileManager = fileManagerMap.get(classLoader);
    if (fileManager == null) {
        StandardJavaFileManager standardJavaFileManager = s_compiler.getStandardFileManager(null, null, null);
        fileManagerMap.put(classLoader, fileManager = new MyJavaFileManager(standardJavaFileManager));
    }
    for (Map.Entry<String, byte[]> entry : compileFromJava(className, javaCode, printWriter, fileManager).entrySet()) {
        String className2 = entry.getKey();
        synchronized (loadedClassesMap) {
            if (loadedClasses.containsKey(className2))
                continue;
        }
        byte[] bytes = entry.getValue();
        if (classDir != null) {
            String filename = className2.replaceAll("\\.", '\\' + File.separator) + ".class";
            boolean changed = writeBytes(new File(classDir, filename), bytes);
            if (changed) {
                LOG.info("Updated {} in {}", className2, classDir);
            }
        }
        Class clazz2 = CompilerUtils.defineClass(classLoader, className2, bytes);
        synchronized (loadedClassesMap) {
            loadedClasses.put(className2, clazz2);
        }
    }
    synchronized (loadedClassesMap) {
        loadedClasses.put(className, clazz = classLoader.loadClass(className));
    }
    return clazz;
}
Also used : StandardJavaFileManager(javax.tools.StandardJavaFileManager) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 85 with StandardJavaFileManager

use of javax.tools.StandardJavaFileManager in project ceylon by eclipse.

the class MainTest method compileAndJar.

public static File compileAndJar(String javaModule, String javaClassName, File addToClassPath) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    String javaModulePath = javaModule.replace('.', '/');
    File moduleFile = new File("test/" + javaModulePath, javaClassName + ".java");
    Iterable<? extends JavaFileObject> units = fileManager.getJavaFileObjects(moduleFile);
    File destDir = new File("build/javaModules");
    FileUtil.delete(destDir);
    destDir.mkdirs();
    List<String> options = new LinkedList<String>();
    options.add("-d");
    options.add(destDir.getPath());
    if (addToClassPath != null) {
        options.add("-cp");
        options.add(addToClassPath.getPath());
    }
    CompilationTask task = compiler.getTask(null, null, null, options, null, units);
    Boolean result = task.call();
    assertTrue(result != null && result.booleanValue());
    File compiledModuleFile = new File(destDir, javaModulePath + "/" + javaClassName + ".class");
    assertTrue(compiledModuleFile.isFile());
    return jar(compiledModuleFile, javaModulePath);
}
Also used : JavaCompiler(javax.tools.JavaCompiler) StandardJavaFileManager(javax.tools.StandardJavaFileManager) File(java.io.File) LinkedList(java.util.LinkedList) CompilationTask(javax.tools.JavaCompiler.CompilationTask)

Aggregations

StandardJavaFileManager (javax.tools.StandardJavaFileManager)124 JavaCompiler (javax.tools.JavaCompiler)99 File (java.io.File)60 JavaFileObject (javax.tools.JavaFileObject)50 IOException (java.io.IOException)37 DiagnosticCollector (javax.tools.DiagnosticCollector)36 ArrayList (java.util.ArrayList)33 CompilationTask (javax.tools.JavaCompiler.CompilationTask)25 JavacTask (com.sun.source.util.JavacTask)17 StringWriter (java.io.StringWriter)10 SimpleJavaFileObject (javax.tools.SimpleJavaFileObject)9 JavacTool (com.sun.tools.javac.api.JavacTool)8 CompilationUnitTree (com.sun.source.tree.CompilationUnitTree)6 JavacTaskImpl (com.sun.tools.javac.api.JavacTaskImpl)5 URL (java.net.URL)5 FileOutputStream (java.io.FileOutputStream)4 PrintWriter (java.io.PrintWriter)4 Diagnostic (javax.tools.Diagnostic)4 Charset (java.nio.charset.Charset)3 HashSet (java.util.HashSet)3