Search in sources :

Example 11 with StandardJavaFileManager

use of javax.tools.StandardJavaFileManager in project jdk8u_jdk by JetBrains.

the class JavaToolUtils method compileFiles.

/**
     * Takes a list of files and compile these files into the working directory.
     *
     * @param files
     * @throws IOException
     */
public static void compileFiles(List<File> files) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)) {
        Iterable<? extends JavaFileObject> compilationUnit = fileManager.getJavaFileObjectsFromFiles(files);
        compiler.getTask(null, fileManager, null, null, null, compilationUnit).call();
    }
}
Also used : JavaCompiler(javax.tools.JavaCompiler) StandardJavaFileManager(javax.tools.StandardJavaFileManager)

Example 12 with StandardJavaFileManager

use of javax.tools.StandardJavaFileManager in project incubator-systemml by apache.

the class CodegenUtils method compileClassJavac.

////////////////////////////
//JAVAC-specific methods (used for hadoop environments)
private static Class<?> compileClassJavac(String name, String src) throws DMLRuntimeException {
    try {
        //create working dir on demand
        if (_workingDir == null)
            createWorkingDir();
        //write input file (for debugging / classpath handling)
        File ftmp = new File(_workingDir + "/" + name.replace(".", "/") + ".java");
        if (!ftmp.getParentFile().exists())
            ftmp.getParentFile().mkdirs();
        LocalFileUtils.writeTextFile(ftmp, src);
        //get system java compiler
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null)
            throw new RuntimeException("Unable to obtain system java compiler.");
        //prepare file manager
        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
        //prepare input source code
        Iterable<? extends JavaFileObject> sources = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(ftmp));
        //prepare class path 
        URL runDir = CodegenUtils.class.getProtectionDomain().getCodeSource().getLocation();
        String classpath = System.getProperty("java.class.path") + File.pathSeparator + runDir.getPath();
        List<String> options = Arrays.asList("-classpath", classpath);
        //compile source code
        CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, sources);
        Boolean success = task.call();
        //output diagnostics and error handling
        for (Diagnostic<? extends JavaFileObject> tmp : diagnostics.getDiagnostics()) if (tmp.getKind() == Kind.ERROR)
            System.err.println("ERROR: " + tmp.toString());
        if (success == null || !success)
            throw new RuntimeException("Failed to compile class " + name);
        //dynamically load compiled class
        URLClassLoader classLoader = null;
        try {
            classLoader = new URLClassLoader(new URL[] { new File(_workingDir).toURI().toURL(), runDir }, CodegenUtils.class.getClassLoader());
            return classLoader.loadClass(name);
        } finally {
            IOUtilFunctions.closeSilently(classLoader);
        }
    } catch (Exception ex) {
        throw new DMLRuntimeException(ex);
    }
}
Also used : JavaCompiler(javax.tools.JavaCompiler) URL(java.net.URL) CompilationTask(javax.tools.JavaCompiler.CompilationTask) DMLRuntimeException(org.apache.sysml.runtime.DMLRuntimeException) IOException(java.io.IOException) DMLRuntimeException(org.apache.sysml.runtime.DMLRuntimeException) JavaFileObject(javax.tools.JavaFileObject) DMLRuntimeException(org.apache.sysml.runtime.DMLRuntimeException) URLClassLoader(java.net.URLClassLoader) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector) File(java.io.File)

Example 13 with StandardJavaFileManager

use of javax.tools.StandardJavaFileManager in project logging-log4j2 by apache.

the class PluginManagerPackagesTest method compile.

static void compile(final File f) throws IOException {
    // set up compiler
    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    final DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    final List<String> errors = new ArrayList<>();
    try (final StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null)) {
        final Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(f));
        // compile generated source
        // (switch off annotation processing: no need to create Log4j2Plugins.dat)
        final List<String> options = Arrays.asList("-proc:none");
        compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits).call();
        // check we don't have any compilation errors
        for (final Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
            if (diagnostic.getKind() == Diagnostic.Kind.ERROR) {
                errors.add(String.format("Compile error: %s%n", diagnostic.getMessage(Locale.getDefault())));
            }
        }
    }
    assertTrue(errors.toString(), errors.isEmpty());
}
Also used : JavaFileObject(javax.tools.JavaFileObject) ArrayList(java.util.ArrayList) JavaCompiler(javax.tools.JavaCompiler) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector)

Example 14 with StandardJavaFileManager

use of javax.tools.StandardJavaFileManager in project gerrit by GerritCodeReview.

the class PrologCompiler method compileJava.

/** Compile java src into java .class files */
private void compileJava(File tempDir) throws IOException, CompileException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new CompileException("JDK required (running inside of JRE)");
    }
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null)) {
        Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(getAllFiles(tempDir, ".java"));
        ArrayList<String> options = new ArrayList<>();
        String classpath = getMyClasspath();
        if (classpath != null) {
            options.add("-classpath");
            options.add(classpath);
        }
        options.add("-d");
        options.add(tempDir.getPath());
        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits);
        if (!task.call()) {
            Locale myLocale = Locale.getDefault();
            StringBuilder msg = new StringBuilder();
            msg.append("Cannot compile to Java bytecode:");
            for (Diagnostic<? extends JavaFileObject> err : diagnostics.getDiagnostics()) {
                msg.append('\n');
                msg.append(err.getKind());
                msg.append(": ");
                if (err.getSource() != null) {
                    msg.append(err.getSource().getName());
                }
                msg.append(':');
                msg.append(err.getLineNumber());
                msg.append(": ");
                msg.append(err.getMessage(myLocale));
            }
            throw new CompileException(msg.toString());
        }
    }
}
Also used : Locale(java.util.Locale) ArrayList(java.util.ArrayList) JavaCompiler(javax.tools.JavaCompiler) JavaFileObject(javax.tools.JavaFileObject) CompileException(com.googlecode.prolog_cafe.exceptions.CompileException) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector)

Example 15 with StandardJavaFileManager

use of javax.tools.StandardJavaFileManager in project compiler by boalang.

the class BaseTest method codegen.

protected StartContext codegen(final String input, final String error) throws IOException {
    final File outputRoot = new File(new File(System.getProperty("java.io.tmpdir")), UUID.randomUUID().toString());
    final File outputSrcDir = new File(outputRoot, "boa");
    if (!outputSrcDir.mkdirs())
        throw new IOException("unable to mkdir " + outputSrcDir);
    final File outputFile = new File(outputSrcDir, "Test.java");
    CodeGeneratingVisitor.combineAggregatorStrings.clear();
    CodeGeneratingVisitor.reduceAggregatorStrings.clear();
    final List<String> jobnames = new ArrayList<String>();
    final List<String> jobs = new ArrayList<String>();
    final List<Integer> seeds = new ArrayList<Integer>();
    final StartContext ctx = typecheck(input);
    // use the whole input string to seed the RNG
    seeds.add(input.hashCode());
    final Start p = ctx.ast;
    try {
        new InheritedAttributeTransformer().start(p);
        new LocalAggregationTransformer().start(p);
        new VisitorOptimizingTransformer().start(p);
        final CodeGeneratingVisitor cg = new CodeGeneratingVisitor("1");
        cg.start(p);
        jobs.add(cg.getCode());
        jobnames.add("1");
        final ST st = AbstractCodeGeneratingVisitor.stg.getInstanceOf("Program");
        st.add("name", "Test");
        st.add("numreducers", 1);
        st.add("jobs", jobs);
        st.add("jobnames", jobnames);
        st.add("combineTables", CodeGeneratingVisitor.combineAggregatorStrings);
        st.add("reduceTables", CodeGeneratingVisitor.reduceAggregatorStrings);
        st.add("splitsize", 64 * 1024 * 1024);
        st.add("seeds", seeds);
        final BufferedOutputStream o = new BufferedOutputStream(new FileOutputStream(outputFile));
        try {
            o.write(st.render().getBytes());
        } finally {
            o.close();
        }
        final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        final DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
        final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
        final Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(new File[] { outputFile }));
        if (!compiler.getTask(null, fileManager, diagnostics, Arrays.asList(new String[] { "-cp", System.getProperty("java.class.path") }), null, compilationUnits).call())
            for (final Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) throw new RuntimeException("Error on line " + diagnostic.getLineNumber() + ": " + diagnostic.getMessage(null));
        if (error != null)
            fail("expected to see exception: " + error);
    } catch (final Exception e) {
        if (error == null) {
            if (e.getMessage() == null) {
                e.printStackTrace();
                fail("unexpected exception");
            } else
                fail("found unexpected exception: " + e.getMessage());
        } else
            assertEquals(error, e.getMessage());
    }
    delete(outputSrcDir);
    return ctx;
}
Also used : Start(boa.compiler.ast.Start) ArrayList(java.util.ArrayList) Diagnostic(javax.tools.Diagnostic) JavaFileObject(javax.tools.JavaFileObject) VisitorOptimizingTransformer(boa.compiler.transforms.VisitorOptimizingTransformer) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector) BufferedOutputStream(java.io.BufferedOutputStream) ST(org.stringtemplate.v4.ST) InheritedAttributeTransformer(boa.compiler.transforms.InheritedAttributeTransformer) JavaCompiler(javax.tools.JavaCompiler) LocalAggregationTransformer(boa.compiler.transforms.LocalAggregationTransformer) IOException(java.io.IOException) ParseCancellationException(org.antlr.v4.runtime.misc.ParseCancellationException) IOException(java.io.IOException) RecognitionException(org.antlr.v4.runtime.RecognitionException) StartContext(boa.parser.BoaParser.StartContext) FileOutputStream(java.io.FileOutputStream) AbstractCodeGeneratingVisitor(boa.compiler.visitors.AbstractCodeGeneratingVisitor) CodeGeneratingVisitor(boa.compiler.visitors.CodeGeneratingVisitor) File(java.io.File)

Aggregations

StandardJavaFileManager (javax.tools.StandardJavaFileManager)57 JavaCompiler (javax.tools.JavaCompiler)42 JavaFileObject (javax.tools.JavaFileObject)24 File (java.io.File)23 IOException (java.io.IOException)18 ArrayList (java.util.ArrayList)17 DiagnosticCollector (javax.tools.DiagnosticCollector)15 CompilationTask (javax.tools.JavaCompiler.CompilationTask)9 JavacTask (com.sun.source.util.JavacTask)7 CompilationUnitTree (com.sun.source.tree.CompilationUnitTree)4 JavacTaskImpl (com.sun.tools.javac.api.JavacTaskImpl)4 JavacTool (com.sun.tools.javac.api.JavacTool)4 FileOutputStream (java.io.FileOutputStream)4 StringWriter (java.io.StringWriter)3 ZipFile (java.util.zip.ZipFile)3 Test (org.junit.Test)3 JCCompilationUnit (com.sun.tools.javac.tree.JCTree.JCCompilationUnit)2 PrintWriter (java.io.PrintWriter)2 Method (java.lang.reflect.Method)2 URI (java.net.URI)2