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