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;
}
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);
}
}
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());
}
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();
}
}
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());
}
}
}
Aggregations