Search in sources :

Example 66 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project ceylon by eclipse.

the class T6378728 method main.

public static void main(String[] args) {
    // Get a compiler tool
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    String srcdir = System.getProperty("test.src");
    File source = new File(srcdir, "T6378728.java");
    StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
    CompilationTask task = compiler.getTask(null, new ExceptionalFileManager(fm), null, Arrays.asList("-proc:only"), null, fm.getJavaFileObjectsFromFiles(Arrays.asList(source)));
    if (!task.call())
        throw new RuntimeException("Unexpected compilation failure");
}
Also used : File(java.io.File) CompilationTask(javax.tools.JavaCompiler.CompilationTask)

Example 67 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project ceylon by eclipse.

the class ToolsTest 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)

Example 68 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project zeppelin by apache.

the class JavaSourceFromString method execute.

public static String execute(String generatedClassName, String code) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    // Java parasing
    JavaProjectBuilder builder = new JavaProjectBuilder();
    JavaSource src = builder.addSource(new StringReader(code));
    // get all classes in code (paragraph)
    List<JavaClass> classes = src.getClasses();
    String mainClassName = null;
    // Searching for class containing Main method
    for (int i = 0; i < classes.size(); i++) {
        boolean hasMain = false;
        for (int j = 0; j < classes.get(i).getMethods().size(); j++) {
            if (classes.get(i).getMethods().get(j).getName().equals("main") && classes.get(i).getMethods().get(j).isStatic()) {
                mainClassName = classes.get(i).getName();
                hasMain = true;
                break;
            }
        }
        if (hasMain == true) {
            break;
        }
    }
    // if there isn't Main method, will retuen error
    if (mainClassName == null) {
        logger.error("Exception for Main method", "There isn't any class " + "containing static main method.");
        throw new Exception("There isn't any class containing static main method.");
    }
    // replace name of class containing Main method with generated name
    code = code.replace(mainClassName, generatedClassName);
    JavaFileObject file = new JavaSourceFromString(generatedClassName, code.toString());
    Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
    ByteArrayOutputStream baosOut = new ByteArrayOutputStream();
    ByteArrayOutputStream baosErr = new ByteArrayOutputStream();
    // Creating new stream to get the output data
    PrintStream newOut = new PrintStream(baosOut);
    PrintStream newErr = new PrintStream(baosErr);
    // Save the old System.out!
    PrintStream oldOut = System.out;
    PrintStream oldErr = System.err;
    // Tell Java to use your special stream
    System.setOut(newOut);
    System.setErr(newErr);
    CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);
    // executing the compilation process
    boolean success = task.call();
    // if success is false will get error
    if (!success) {
        for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
            if (diagnostic.getLineNumber() == -1) {
                continue;
            }
            System.err.println("line " + diagnostic.getLineNumber() + " : " + diagnostic.getMessage(null));
        }
        System.out.flush();
        System.err.flush();
        System.setOut(oldOut);
        System.setErr(oldErr);
        logger.error("Exception in Interpreter while compilation", baosErr.toString());
        throw new Exception(baosErr.toString());
    } else {
        try {
            // creating new class loader
            URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { new File("").toURI().toURL() });
            // execute the Main method
            Class.forName(generatedClassName, true, classLoader).getDeclaredMethod("main", new Class[] { String[].class }).invoke(null, new Object[] { null });
            System.out.flush();
            System.err.flush();
            // set the stream to old stream
            System.setOut(oldOut);
            System.setErr(oldErr);
            return baosOut.toString();
        } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            logger.error("Exception in Interpreter while execution", e);
            System.err.println(e);
            e.printStackTrace(newErr);
            throw new Exception(baosErr.toString(), e);
        } finally {
            System.out.flush();
            System.err.flush();
            System.setOut(oldOut);
            System.setErr(oldErr);
        }
    }
}
Also used : Diagnostic(javax.tools.Diagnostic) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) JavaSource(com.thoughtworks.qdox.model.JavaSource) StringReader(java.io.StringReader) DiagnosticCollector(javax.tools.DiagnosticCollector) JavaProjectBuilder(com.thoughtworks.qdox.JavaProjectBuilder) PrintStream(java.io.PrintStream) JavaCompiler(javax.tools.JavaCompiler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) InvocationTargetException(java.lang.reflect.InvocationTargetException) CompilationTask(javax.tools.JavaCompiler.CompilationTask) InvocationTargetException(java.lang.reflect.InvocationTargetException) JavaClass(com.thoughtworks.qdox.model.JavaClass) URLClassLoader(java.net.URLClassLoader) JavaClass(com.thoughtworks.qdox.model.JavaClass) File(java.io.File)

Example 69 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project neo4j by neo4j.

the class DbStructureInvocationTracingAcceptanceTest method compile.

private static <T> T compile(String className, String source, CompilationListener<T> listener) {
    JavaCompiler systemCompiler = ToolProvider.getSystemJavaCompiler();
    JavaFileManager manager = new InMemFileManager();
    DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<>();
    Iterable<? extends JavaFileObject> sources = Collections.singletonList(new InMemSource(className, source));
    CompilationTask task = systemCompiler.getTask(null, manager, diagnosticsCollector, null, null, sources);
    Boolean success = task.call();
    return listener.compiled(success, manager, diagnosticsCollector.getDiagnostics());
}
Also used : SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) JavaFileManager(javax.tools.JavaFileManager) ForwardingJavaFileManager(javax.tools.ForwardingJavaFileManager) JavaCompiler(javax.tools.JavaCompiler) DiagnosticCollector(javax.tools.DiagnosticCollector) CompilationTask(javax.tools.JavaCompiler.CompilationTask)

Example 70 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project androidannotations by androidannotations.

the class ProcessorTestHelper method compileFiles.

public CompileResult compileFiles(Collection<File> compilationUnits) {
    DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticCollector, null, null)) {
        CompilationTask task = compiler.getTask(null, fileManager, diagnosticCollector, compilerOptions, null, fileManager.getJavaFileObjectsFromFiles(compilationUnits));
        List<Processor> processors = new ArrayList<>();
        for (Class<? extends Processor> processorClass : processorsClasses) {
            try {
                processors.add(processorClass.newInstance());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        task.setProcessors(processors);
        task.call();
    } catch (IOException e) {
    // we should always be able to close the manager
    }
    return new CompileResult(diagnosticCollector.getDiagnostics());
}
Also used : Processor(javax.annotation.processing.Processor) ArrayList(java.util.ArrayList) JavaCompiler(javax.tools.JavaCompiler) IOException(java.io.IOException) CompilationTask(javax.tools.JavaCompiler.CompilationTask) IOException(java.io.IOException) JavaFileObject(javax.tools.JavaFileObject) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector)

Aggregations

CompilationTask (javax.tools.JavaCompiler.CompilationTask)84 JavaCompiler (javax.tools.JavaCompiler)38 File (java.io.File)33 JavaFileObject (javax.tools.JavaFileObject)32 StandardJavaFileManager (javax.tools.StandardJavaFileManager)28 DiagnosticCollector (javax.tools.DiagnosticCollector)27 IOException (java.io.IOException)20 ArrayList (java.util.ArrayList)18 SimpleJavaFileObject (javax.tools.SimpleJavaFileObject)14 URLClassLoader (java.net.URLClassLoader)10 StringWriter (java.io.StringWriter)9 URL (java.net.URL)6 JavaFileManager (javax.tools.JavaFileManager)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 Test (org.junit.Test)5 OutputStream (java.io.OutputStream)4 PrintWriter (java.io.PrintWriter)4 InvocationTargetException (java.lang.reflect.InvocationTargetException)4 FileInputStream (java.io.FileInputStream)3 FileOutputStream (java.io.FileOutputStream)3