Search in sources :

Example 66 with StandardJavaFileManager

use of javax.tools.StandardJavaFileManager in project checker-framework by typetools.

the class Main method main.

public static void main(String[] args) {
    final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    final StandardJavaFileManager fileManager = javac.getStandardFileManager(null, null, null);
    if (!doStuff(javac, fileManager)) {
        System.exit(1);
    }
    if (!doStuff(javac, fileManager)) {
        System.exit(1);
    }
    if (!doStuff(javac, fileManager)) {
        System.exit(1);
    }
}
Also used : JavaCompiler(javax.tools.JavaCompiler) StandardJavaFileManager(javax.tools.StandardJavaFileManager)

Example 67 with StandardJavaFileManager

use of javax.tools.StandardJavaFileManager in project suite by stupidsing.

the class JdkUtil method compile.

protected Path compile(String canonicalName, String java) throws IOException {
    Path srcFilePath = srcDir.resolve(canonicalName.replace('.', '/') + ".java");
    Path binFilePath = binDir.resolve(canonicalName.replace('.', '/') + ".class");
    LogUtil.info("Writing " + srcFilePath);
    try (OutputStream os = FileUtil.out(srcFilePath)) {
        os.write(java.getBytes(Constants.charset));
    }
    // compile the Java, load the class, return an instantiated object
    LogUtil.info("Compiling " + srcFilePath);
    FileUtil.mkdir(binDir);
    JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager sjfm = jc.getStandardFileManager(null, null, null)) {
        if (!// 
        jc.getTask(// 
        null, // 
        null, // 
        null, // 
        List.of("-d", binDir.toString()), // 
        null, sjfm.getJavaFileObjects(srcFilePath.toFile())).call())
            Fail.t("Java compilation error");
    }
    return binFilePath;
}
Also used : Path(java.nio.file.Path) OutputStream(java.io.OutputStream) JavaCompiler(javax.tools.JavaCompiler) StandardJavaFileManager(javax.tools.StandardJavaFileManager)

Example 68 with StandardJavaFileManager

use of javax.tools.StandardJavaFileManager in project knime-core by knime.

the class JavaCodeCompiler method compile.

public void compile() throws CompilationFailedException {
    if (m_sources == null || m_sources.length == 0) {
        throw new CompilationFailedException("No sources set");
    }
    ArrayList<String> compileArgs = new ArrayList<String>();
    if (m_classpaths != null && m_classpaths.length > 0) {
        compileArgs.add("-classpath");
        StringBuilder b = new StringBuilder();
        for (int i = 0; i < m_classpaths.length; i++) {
            if (i > 0) {
                b.append(File.pathSeparatorChar);
            }
            b.append(m_classpaths[i]);
            File file = m_classpaths[i];
            String filePath = file.getAbsolutePath();
            if (!file.exists()) {
                throw new CompilationFailedException("Can't read file \"" + filePath + "\"; invalid class path");
            }
        }
        compileArgs.add(b.toString());
    }
    final String javaVersion = getJavaVersion();
    compileArgs.add("-source");
    compileArgs.add(javaVersion);
    compileArgs.add("-target");
    compileArgs.add(javaVersion);
    compileArgs.add("-nowarn");
    if (m_additionalCompileArgs != null) {
        compileArgs.addAll(Arrays.asList(m_additionalCompileArgs));
    }
    final StringWriter logString = new StringWriter();
    // ServiceLoader<JavaCompiler> serviceLoader =
    // ServiceLoader.load(JavaCompiler.class);
    // the service loader sometimes didn't work in the RMI instance,
    // so we hard-code the compiler here.
    JavaCompiler compiler = new EclipseCompiler();
    // compiler = com.sun.tools.javac.api.JavacTool.create();
    if (m_sourceCodeDebugDir != null) {
        try {
            File tmpDir = m_sourceCodeDebugDir;
            tmpDir.mkdir();
            for (JavaFileObject source : m_sources) {
                CharSequence charContent = source.getCharContent(false);
                File out = new File(tmpDir, source.getName());
                out.getParentFile().mkdirs();
                StringReader reader = new StringReader(charContent.toString());
                FileWriter writer = new FileWriter(out);
                FileUtil.copy(reader, writer);
                writer.close();
                reader.close();
            }
        } catch (IOException e) {
            LOGGER.warn("Unable to write source code to \"" + m_sourceCodeDebugDir.getAbsolutePath() + "\": " + e.getMessage(), e);
        }
    }
    DiagnosticCollector<JavaFileObject> digsCollector = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager stdFileMgr = compiler.getStandardFileManager(digsCollector, null, null);
    m_fileMgr = new InMemoryJavaFileManager(stdFileMgr);
    CompilationTask compileTask = compiler.getTask(logString, m_fileMgr, digsCollector, compileArgs, null, Arrays.asList(m_sources));
    if (!compileTask.call()) {
        boolean hasDiagnostic = false;
        StringBuilder b = new StringBuilder("Unable to compile expression");
        for (Diagnostic<? extends JavaFileObject> d : digsCollector.getDiagnostics()) {
            switch(d.getKind()) {
                case ERROR:
                    String[] sourceLines = new String[0];
                    if (d.getSource() != null) {
                        JavaFileObject srcJavaFileObject = d.getSource();
                        String src;
                        if (srcJavaFileObject instanceof InMemorySourceJavaFileObject) {
                            src = ((InMemorySourceJavaFileObject) srcJavaFileObject).getSource();
                        } else {
                            try {
                                src = srcJavaFileObject.getCharContent(false).toString();
                            } catch (IOException ioe) {
                                src = null;
                            }
                        }
                        if (src != null) {
                            sourceLines = getSourceLines(src);
                        }
                        if (LOGGER.isDebugEnabled()) {
                            LOGGER.debug("<<<< Expression Start >>>>");
                            LOGGER.debug("<<<< " + srcJavaFileObject.getName() + " >>>>");
                            for (int i = 0; i < sourceLines.length; i++) {
                                LOGGER.debug((i + 1) + ": " + sourceLines[i]);
                            }
                            LOGGER.debug("<<<< Expression End >>>>");
                        }
                    }
                    if (hasDiagnostic) {
                        // follow up error, insert empty line
                        b.append("\n");
                    }
                    hasDiagnostic = true;
                    int lineIndex = (int) (d.getLineNumber() - 1);
                    b.append("\nERROR at line ").append(lineIndex + 1);
                    b.append("\n").append(d.getMessage(Locale.US));
                    int sourceLineCount = sourceLines.length;
                    if (lineIndex - 1 >= 0 && lineIndex - 1 < sourceLineCount) {
                        // previous line
                        b.append("\n  Line : ").append(lineIndex);
                        b.append("  ").append(sourceLines[lineIndex - 1]);
                    }
                    if (lineIndex >= 0 && lineIndex < sourceLineCount) {
                        // error line
                        b.append("\n  Line : ").append(lineIndex + 1);
                        b.append("  ").append(sourceLines[lineIndex]);
                    }
                    break;
                default:
                    break;
            }
        }
        String errorOut = logString.toString();
        if (!hasDiagnostic) {
            b.append("\n").append(errorOut);
        } else {
            if (!errorOut.isEmpty()) {
                LOGGER.debug("Error output of compilation:\n" + errorOut);
                LOGGER.debug("Command line arguments were: " + compileArgs);
            }
        }
        throw new CompilationFailedException(b.toString());
    }
}
Also used : FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) JavaCompiler(javax.tools.JavaCompiler) IOException(java.io.IOException) CompilationTask(javax.tools.JavaCompiler.CompilationTask) EclipseCompiler(org.eclipse.jdt.internal.compiler.tool.EclipseCompiler) JavaFileObject(javax.tools.JavaFileObject) StringWriter(java.io.StringWriter) StringReader(java.io.StringReader) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector) File(java.io.File)

Example 69 with StandardJavaFileManager

use of javax.tools.StandardJavaFileManager in project knime-core by knime.

the class JavaSnippetCompiler method getTask.

/**
 * Creates a compilation task.
 *
 * @param out a Writer for additional output from the compiler;
 * use System.err if null
 * @param digsCollector a diagnostic listener; if null use the compiler's
 * default method for reporting diagnostics
 * @return an object representing the compilation process
 * @throws IOException if temporary jar files cannot be created
 */
public CompilationTask getTask(final Writer out, final DiagnosticCollector<JavaFileObject> digsCollector) throws IOException {
    if (m_compiler == null) {
        m_compileArgs = new ArrayList<>();
        final File[] classpaths = m_snippet.getCompiletimeClassPath();
        m_compileArgs.add("-classpath");
        m_compileArgs.add(Arrays.stream(classpaths).map(f -> f.getAbsolutePath()).map(FilenameUtils::normalize).collect(Collectors.joining(File.pathSeparator)));
        m_compileArgs.add("-source");
        m_compileArgs.add("1.8");
        m_compileArgs.add("-target");
        m_compileArgs.add("1.8");
        m_compileArgs.add("-encoding");
        m_compileArgs.add("UTF-8");
        m_compiler = new EclipseCompiler();
    }
    final StandardJavaFileManager stdFileMgr = m_compiler.getStandardFileManager(digsCollector, null, Charset.forName("UTF-8"));
    final CompilationTask compileTask = m_compiler.getTask(out, stdFileMgr, digsCollector, m_compileArgs, null, m_snippet.getCompilationUnits());
    // Release all .jar files that may have been opened
    stdFileMgr.close();
    return compileTask;
}
Also used : Arrays(java.util.Arrays) MalformedURLException(java.net.MalformedURLException) URL(java.net.URL) EclipseCompiler(org.eclipse.jdt.internal.compiler.tool.EclipseCompiler) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) File(java.io.File) ArrayList(java.util.ArrayList) JavaFileObject(javax.tools.JavaFileObject) StandardJavaFileManager(javax.tools.StandardJavaFileManager) URLClassLoader(java.net.URLClassLoader) Charset(java.nio.charset.Charset) CompilationTask(javax.tools.JavaCompiler.CompilationTask) Writer(java.io.Writer) DiagnosticCollector(javax.tools.DiagnosticCollector) FilenameUtils(org.apache.commons.io.FilenameUtils) EclipseCompiler(org.eclipse.jdt.internal.compiler.tool.EclipseCompiler) StandardJavaFileManager(javax.tools.StandardJavaFileManager) File(java.io.File) FilenameUtils(org.apache.commons.io.FilenameUtils) CompilationTask(javax.tools.JavaCompiler.CompilationTask)

Example 70 with StandardJavaFileManager

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

the class TestMRRJobsDAGApi method createTestJar.

private static void createTestJar(OutputStream outStream, String dummyClassName) throws URISyntaxException, IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    JavaFileObject srcFileObject = new SimpleJavaFileObjectImpl(URI.create("string:///" + dummyClassName + Kind.SOURCE.extension), Kind.SOURCE);
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    compiler.getTask(null, fileManager, null, null, null, Collections.singletonList(srcFileObject)).call();
    JavaFileObject javaFileObject = fileManager.getJavaFileForOutput(StandardLocation.CLASS_OUTPUT, dummyClassName, Kind.CLASS, null);
    File classFile = new File(dummyClassName + Kind.CLASS.extension);
    JarOutputStream jarOutputStream = new JarOutputStream(outStream);
    JarEntry jarEntry = new JarEntry(classFile.getName());
    jarEntry.setTime(classFile.lastModified());
    jarOutputStream.putNextEntry(jarEntry);
    InputStream in = javaFileObject.openInputStream();
    byte[] buffer = new byte[4096];
    while (true) {
        int nRead = in.read(buffer, 0, buffer.length);
        if (nRead <= 0)
            break;
        jarOutputStream.write(buffer, 0, nRead);
    }
    in.close();
    jarOutputStream.close();
    javaFileObject.delete();
}
Also used : SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) InputStream(java.io.InputStream) JavaCompiler(javax.tools.JavaCompiler) StandardJavaFileManager(javax.tools.StandardJavaFileManager) JarOutputStream(java.util.jar.JarOutputStream) JarEntry(java.util.jar.JarEntry) File(java.io.File)

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