Search in sources :

Example 26 with JavaCompiler

use of javax.tools.JavaCompiler in project symmetric-ds by JumpMind.

the class SimpleClassCompiler method getCompiledClass.

public Object getCompiledClass(String javaCode) throws Exception {
    Integer id = javaCode.hashCode();
    Object javaObject = objectMap.get(id);
    if (javaObject == null) {
        String className = getNextClassName();
        String origClassName = null;
        Pattern pattern = Pattern.compile(REGEX_CLASS);
        Matcher matcher = pattern.matcher(javaCode);
        if (matcher.find()) {
            origClassName = matcher.group(1);
        }
        javaCode = javaCode.replaceAll(REGEX_CLASS, "public class " + className);
        log.info("Compiling class '" + origClassName + "'");
        if (log.isDebugEnabled()) {
            log.debug("Compiling code: \n" + javaCode);
        }
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null) {
            throw new SimpleClassCompilerException("Missing Java compiler: the JDK is required for compiling classes.");
        }
        JavaFileManager fileManager = new ClassFileManager(compiler.getStandardFileManager(null, null, null));
        DiagnosticCollector<JavaFileObject> diag = new DiagnosticCollector<JavaFileObject>();
        List<JavaFileObject> javaFiles = new ArrayList<JavaFileObject>();
        javaFiles.add(new JavaObjectFromString(className, javaCode));
        Boolean success = compiler.getTask(null, fileManager, diag, null, null, javaFiles).call();
        if (success) {
            log.debug("Compilation has succeeded");
            Class<?> clazz = fileManager.getClassLoader(null).loadClass(className);
            if (clazz != null) {
                javaObject = clazz.newInstance();
                objectMap.put(id, javaObject);
            } else {
                throw new SimpleClassCompilerException("The '" + className + "' class could not be located");
            }
        } else {
            log.error("Compilation of '" + origClassName + "' failed");
            for (Diagnostic diagnostic : diag.getDiagnostics()) {
                log.error(origClassName + " at line " + diagnostic.getLineNumber() + ", column " + diagnostic.getColumnNumber() + ": " + diagnostic.getMessage(null));
            }
            throw new SimpleClassCompilerException(diag.getDiagnostics());
        }
    }
    return javaObject;
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) JavaFileManager(javax.tools.JavaFileManager) ForwardingJavaFileManager(javax.tools.ForwardingJavaFileManager) StandardJavaFileManager(javax.tools.StandardJavaFileManager) ArrayList(java.util.ArrayList) JavaCompiler(javax.tools.JavaCompiler) Diagnostic(javax.tools.Diagnostic) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) FileObject(javax.tools.FileObject) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) DiagnosticCollector(javax.tools.DiagnosticCollector)

Example 27 with JavaCompiler

use of javax.tools.JavaCompiler 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 28 with JavaCompiler

use of javax.tools.JavaCompiler 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 29 with JavaCompiler

use of javax.tools.JavaCompiler in project phoenix by apache.

the class UserDefinedFunctionsIT method compileTestClass.

/**
     * Compiles the test class with bogus code into a .class file.
     */
private static void compileTestClass(String className, String program, int counter) throws Exception {
    String javaFileName = className + ".java";
    File javaFile = new File(javaFileName);
    String classFileName = className + ".class";
    File classFile = new File(classFileName);
    String jarName = "myjar" + counter + ".jar";
    String jarPath = "." + File.separator + jarName;
    File jarFile = new File(jarPath);
    try {
        String packageName = "org.apache.phoenix.end2end";
        FileOutputStream fos = new FileOutputStream(javaFileName);
        fos.write(program.getBytes());
        fos.close();
        JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
        int result = jc.run(null, null, null, javaFileName);
        assertEquals(0, result);
        Manifest manifest = new Manifest();
        manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
        FileOutputStream jarFos = new FileOutputStream(jarPath);
        JarOutputStream jarOutputStream = new JarOutputStream(jarFos, manifest);
        String pathToAdd = packageName.replace('.', '/') + '/';
        String jarPathStr = new String(pathToAdd);
        Set<String> pathsInJar = new HashSet<String>();
        while (pathsInJar.add(jarPathStr)) {
            int ix = jarPathStr.lastIndexOf('/', jarPathStr.length() - 2);
            if (ix < 0) {
                break;
            }
            jarPathStr = jarPathStr.substring(0, ix);
        }
        for (String pathInJar : pathsInJar) {
            jarOutputStream.putNextEntry(new JarEntry(pathInJar));
            jarOutputStream.closeEntry();
        }
        jarOutputStream.putNextEntry(new JarEntry(pathToAdd + classFile.getName()));
        byte[] allBytes = new byte[(int) classFile.length()];
        FileInputStream fis = new FileInputStream(classFile);
        fis.read(allBytes);
        fis.close();
        jarOutputStream.write(allBytes);
        jarOutputStream.closeEntry();
        jarOutputStream.close();
        jarFos.close();
        assertTrue(jarFile.exists());
        Connection conn = driver.connect(url, EMPTY_PROPS);
        Statement stmt = conn.createStatement();
        stmt.execute("add jars '" + jarFile.getAbsolutePath() + "'");
    } finally {
        if (javaFile != null)
            javaFile.delete();
        if (classFile != null)
            classFile.delete();
        if (jarFile != null)
            jarFile.delete();
    }
}
Also used : PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) Connection(java.sql.Connection) JavaCompiler(javax.tools.JavaCompiler) JarOutputStream(java.util.jar.JarOutputStream) Manifest(java.util.jar.Manifest) JarEntry(java.util.jar.JarEntry) FileInputStream(java.io.FileInputStream) FileOutputStream(java.io.FileOutputStream) File(java.io.File) HashSet(java.util.HashSet)

Example 30 with JavaCompiler

use of javax.tools.JavaCompiler 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)

Aggregations

JavaCompiler (javax.tools.JavaCompiler)101 StandardJavaFileManager (javax.tools.StandardJavaFileManager)43 JavaFileObject (javax.tools.JavaFileObject)39 File (java.io.File)31 DiagnosticCollector (javax.tools.DiagnosticCollector)24 ArrayList (java.util.ArrayList)22 JavacTask (com.sun.source.util.JavacTask)20 IOException (java.io.IOException)17 CompilationTask (javax.tools.JavaCompiler.CompilationTask)16 SimpleJavaFileObject (javax.tools.SimpleJavaFileObject)15 CompilationUnitTree (com.sun.source.tree.CompilationUnitTree)11 Diagnostic (javax.tools.Diagnostic)11 PrintWriter (java.io.PrintWriter)9 Test (org.junit.Test)9 JavacTaskImpl (com.sun.tools.javac.api.JavacTaskImpl)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 FileOutputStream (java.io.FileOutputStream)5 StringWriter (java.io.StringWriter)5 JavaFileManager (javax.tools.JavaFileManager)5 OutputStream (java.io.OutputStream)4