Search in sources :

Example 1 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project lombok by rzwitserloot.

the class TestClassFileMetaData method compile.

static byte[] compile(File file) {
    try {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        File tempDir = getTempDir();
        tempDir.mkdirs();
        List<String> options = Arrays.asList("-proc:none", "-d", tempDir.getAbsolutePath());
        StringWriter captureWarnings = new StringWriter();
        final StringBuilder compilerErrors = new StringBuilder();
        DiagnosticListener<JavaFileObject> diagnostics = new DiagnosticListener<JavaFileObject>() {

            @Override
            public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
                compilerErrors.append(diagnostic.toString()).append("\n");
            }
        };
        CompilationTask task = compiler.getTask(captureWarnings, null, diagnostics, options, null, Collections.singleton(new ContentBasedJavaFileObject(file.getPath(), readFileAsString(file))));
        Boolean taskResult = task.call();
        assertTrue("Compilation task didn't succeed: \n<Warnings and Errors>\n" + compilerErrors.toString() + "\n</Warnings and Errors>", taskResult);
        return PostCompilerApp.readFile(new File(tempDir, file.getName().replaceAll("\\.java$", ".class")));
    } catch (Exception e) {
        throw Lombok.sneakyThrow(e);
    }
}
Also used : JavaCompiler(javax.tools.JavaCompiler) Diagnostic(javax.tools.Diagnostic) DiagnosticListener(javax.tools.DiagnosticListener) CompilationTask(javax.tools.JavaCompiler.CompilationTask) IOException(java.io.IOException) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) StringWriter(java.io.StringWriter) File(java.io.File)

Example 2 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project jadx by skylot.

the class StaticCompiler method compile.

public static List<File> compile(List<File> files, File outDir, boolean includeDebugInfo) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(files);
    StaticFileManager staticFileManager = new StaticFileManager(fileManager, outDir);
    List<String> options = new ArrayList<String>();
    options.add(includeDebugInfo ? "-g" : "-g:none");
    options.addAll(COMMON_ARGS);
    CompilationTask task = compiler.getTask(null, staticFileManager, null, options, null, compilationUnits);
    Boolean result = task.call();
    fileManager.close();
    if (Boolean.TRUE.equals(result)) {
        return staticFileManager.outputFiles();
    }
    return Collections.emptyList();
}
Also used : ArrayList(java.util.ArrayList) JavaCompiler(javax.tools.JavaCompiler) StandardJavaFileManager(javax.tools.StandardJavaFileManager) CompilationTask(javax.tools.JavaCompiler.CompilationTask)

Example 3 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask 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) {
    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<>();
        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) {
        LOG.error("Failed to compile class " + name + ": \n" + src);
        throw new DMLRuntimeException("Failed to compile class " + name + ".", 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 4 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project knime-core by knime.

the class JSnippetParser method parse.

/**
 * {@inheritDoc}
 */
@Override
public ParseResult parse(final RSyntaxDocument doc, final String style) {
    assert m_snippet.getDocument() == doc;
    JavaSnippetCompiler compiler = new JavaSnippetCompiler(m_snippet);
    StringWriter log = new StringWriter();
    DiagnosticCollector<JavaFileObject> digsCollector = new DiagnosticCollector<>();
    CompilationTask compileTask = null;
    try {
        compileTask = compiler.getTask(log, digsCollector);
    } catch (IOException e) {
        LOGGER.error("Cannot create an compile task.", e);
        return new DefaultParseResult(this);
    }
    compileTask.call();
    DefaultParseResult parseResult = new DefaultParseResult(this);
    parseResult.setError(null);
    for (Diagnostic<? extends JavaFileObject> d : digsCollector.getDiagnostics()) {
        boolean isSnippet = m_snippet.isSnippetSource(d.getSource());
        if (isSnippet) {
            DefaultParserNotice notice = new DefaultParserNotice(this, d.getMessage(Locale.US), (int) d.getLineNumber(), (int) d.getStartPosition(), (int) (d.getEndPosition() - d.getStartPosition() + 1));
            if (d.getKind().equals(Kind.ERROR)) {
                notice.setLevel(ParserNotice.Level.ERROR);
            // LOGGER.error(d.getMessage(Locale.US));
            } else if (d.getKind().equals(Kind.WARNING)) {
                notice.setLevel(ParserNotice.Level.WARNING);
            // LOGGER.warn(d.getMessage(Locale.US));
            } else {
                notice.setLevel(ParserNotice.Level.INFO);
            // LOGGER.debug(d.getMessage(Locale.US));
            }
            parseResult.addNotice(notice);
        }
    }
    return parseResult;
}
Also used : JavaFileObject(javax.tools.JavaFileObject) DefaultParseResult(org.fife.ui.rsyntaxtextarea.parser.DefaultParseResult) StringWriter(java.io.StringWriter) DiagnosticCollector(javax.tools.DiagnosticCollector) DefaultParserNotice(org.fife.ui.rsyntaxtextarea.parser.DefaultParserNotice) IOException(java.io.IOException) JavaSnippetCompiler(org.knime.base.node.jsnippet.util.JavaSnippetCompiler) CompilationTask(javax.tools.JavaCompiler.CompilationTask)

Example 5 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project knime-core by knime.

the class JavaSnippet method createSnippetClass.

/**
 * Create the class file of the snippet.
 *
 * Creates a URLClassLoader which may open jar files referenced by the Java Snippet class. Make sure to match every
 * call to this method with a call to {@link #close()} in order for KNIME to be able to clean up .jar files that
 * were downloaded from URLs.
 *
 * @return the compiled snippet
 */
@SuppressWarnings("unchecked")
private Class<? extends AbstractJSnippet> createSnippetClass() {
    JavaSnippetCompiler compiler = new JavaSnippetCompiler(this);
    /* Recompile/Reload either if the code changed or the class loader has been closed since */
    if (m_classLoader != null && m_snippetCache.isValid(getDocument())) {
        if (!m_snippetCache.hasCustomFields()) {
            return m_snippetCache.getSnippetClass();
        }
    } else {
        // recompile
        m_snippetCache.invalidate();
        StringWriter log = new StringWriter();
        DiagnosticCollector<JavaFileObject> digsCollector = new DiagnosticCollector<>();
        CompilationTask compileTask = null;
        try {
            compileTask = compiler.getTask(log, digsCollector);
        } catch (IOException e) {
            throw new IllegalStateException("Compile with errors: " + e.getMessage(), e);
        }
        boolean success = compileTask.call();
        if (!success) {
            StringBuilder msg = new StringBuilder();
            msg.append("Compile with errors:\n");
            for (Diagnostic<? extends JavaFileObject> d : digsCollector.getDiagnostics()) {
                boolean isSnippet = this.isSnippetSource(d.getSource());
                if (isSnippet && d.getKind().equals(javax.tools.Diagnostic.Kind.ERROR)) {
                    long line = d.getLineNumber();
                    if (line != Diagnostic.NOPOS) {
                        msg.append("Error in line " + line + ": ");
                    } else {
                        msg.append("Error: ");
                    }
                    msg.append(d.getMessage(Locale.US));
                    msg.append('\n');
                }
            }
            throw new IllegalStateException(msg.toString());
        }
    }
    try {
        close();
        final LinkedHashSet<ClassLoader> customTypeClassLoaders = new LinkedHashSet<>();
        customTypeClassLoaders.add(JavaSnippet.class.getClassLoader());
        for (final InCol col : m_fields.getInColFields()) {
            customTypeClassLoaders.addAll(getClassLoadersFor(col.getConverterFactoryId()));
        }
        for (final OutCol col : m_fields.getOutColFields()) {
            customTypeClassLoaders.addAll(getClassLoadersFor(col.getConverterFactoryId()));
        }
        /* Add class loaders of additional bundles */
        customTypeClassLoaders.addAll(getAdditionalBundlesClassLoaders());
        // remove core class loader:
        // (a) it's referenced via JavaSnippet.class classloader and
        // (b) it would collect buddies when used directly (see support ticket #1943)
        customTypeClassLoaders.remove(DataCellToJavaConverterRegistry.class.getClassLoader());
        final MultiParentClassLoader customTypeLoader = new MultiParentClassLoader(customTypeClassLoaders.stream().toArray(ClassLoader[]::new));
        // TODO (Next version bump) change return value of createClassLoader instead of cast
        m_classLoader = (URLClassLoader) compiler.createClassLoader(customTypeLoader);
        Class<? extends AbstractJSnippet> snippetClass = (Class<? extends AbstractJSnippet>) m_classLoader.loadClass("JSnippet");
        m_snippetCache.update(getDocument(), snippetClass, m_settings);
        return snippetClass;
    } catch (ClassNotFoundException e) {
        throw new IllegalStateException("Could not load class file.", e);
    } catch (IOException e) {
        throw new IllegalStateException("Could not load jar files.", e);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) DataCellToJavaConverterRegistry(org.knime.core.data.convert.java.DataCellToJavaConverterRegistry) OutCol(org.knime.base.node.jsnippet.util.field.OutCol) MultiParentClassLoader(org.knime.core.data.convert.util.MultiParentClassLoader) IOException(java.io.IOException) InCol(org.knime.base.node.jsnippet.util.field.InCol) CompilationTask(javax.tools.JavaCompiler.CompilationTask) JavaFileObject(javax.tools.JavaFileObject) StringWriter(java.io.StringWriter) AbstractJSnippet(org.knime.base.node.jsnippet.expression.AbstractJSnippet) URLClassLoader(java.net.URLClassLoader) MultiParentClassLoader(org.knime.core.data.convert.util.MultiParentClassLoader) ModuleClassLoader(org.eclipse.osgi.internal.loader.ModuleClassLoader) DiagnosticCollector(javax.tools.DiagnosticCollector) JavaSnippetCompiler(org.knime.base.node.jsnippet.util.JavaSnippetCompiler)

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