use of javax.tools.JavaCompiler.CompilationTask 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;
}
use of javax.tools.JavaCompiler.CompilationTask in project drill by axbaretto.
the class JDKClassCompiler method doCompile.
private DrillJavaFileObject doCompile(final ClassNames className, final String sourceCode) throws CompileException, IOException, ClassNotFoundException {
try {
// Create one Java source file in memory, which will be compiled later.
DrillJavaFileObject compilationUnit = new DrillJavaFileObject(className.dot, sourceCode);
CompilationTask task = compiler.getTask(null, fileManager, listener, compilerOptions, null, Collections.singleton(compilationUnit));
// Run the compiler.
if (!task.call()) {
throw new CompileException("Compilation failed", null);
} else if (!compilationUnit.isCompiled()) {
throw new ClassNotFoundException(className + ": Class file not created by compilation.");
}
// all good
return compilationUnit;
} catch (RuntimeException rte) {
// Unwrap the compilation exception and throw it.
Throwable cause = rte.getCause();
if (cause != null) {
cause = cause.getCause();
if (cause instanceof CompileException) {
throw (CompileException) cause;
}
if (cause instanceof IOException) {
throw (IOException) cause;
}
}
throw rte;
}
}
use of javax.tools.JavaCompiler.CompilationTask in project GIPC by pdewan.
the class MyDynamicCompilation method compileSourceFile.
public static void compileSourceFile(File sourceFile) throws Exception {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File("/temp")));
// Compile the file
CompilationTask compilationTask = compiler.getTask(null, fileManager, null, null, null, fileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFile)));
compilationTask.call();
fileManager.close();
// delete the source file
// sourceFile.deleteOnExit();
}
use of javax.tools.JavaCompiler.CompilationTask in project spring-cloud-function by spring-cloud.
the class RuntimeJavaCompiler method compile.
/**
* Compile the named class consisting of the supplied source code. If successful load the class
* and return it. Multiple classes may get loaded if the source code included anonymous/inner/local
* classes.
* @param className the name of the class (dotted form, e.g. com.foo.bar.Goo)
* @param classSourceCode the full source code for the class
* @param dependencies optional coordinates for dependencies, maven 'maven://groupId:artifactId:version', or 'file:' URIs for local files
* @return a CompilationResult that encapsulates what happened during compilation (classes/messages produced)
*/
public CompilationResult compile(String className, String classSourceCode, String... dependencies) {
logger.info("Compiling source for class {} using compiler {}", className, compiler.getClass().getName());
DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
MemoryBasedJavaFileManager fileManager = new MemoryBasedJavaFileManager();
List<CompilationMessage> resolutionMessages = fileManager.addAndResolveDependencies(dependencies);
// JavaFileObject sourceFile = new StringBasedJavaSourceFileObject(className, classSourceCode);
JavaFileObject sourceFile = InMemoryJavaFileObject.getSourceJavaFileObject(className, classSourceCode);
// new InMemoryJavaFileObject(StandardLocation.SOURCE_PATH, className, javax.tools.JavaFileObject.Kind.SOURCE, null);
// try (Writer w = sourceFile.openWriter()) {
// w.write(classSourceCode);
// } catch (IOException ioe) {
// ioe.printStackTrace();
// }
Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(sourceFile);
CompilationTask task = compiler.getTask(null, fileManager, diagnosticCollector, null, null, compilationUnits);
boolean success = task.call();
CompilationResult compilationResult = new CompilationResult(success);
compilationResult.recordCompilationMessages(resolutionMessages);
compilationResult.setResolvedAdditionalDependencies(new ArrayList<>(fileManager.getResolvedAdditionalDependencies().values()));
// If successful there may be no errors but there might be info/warnings
for (Diagnostic<? extends JavaFileObject> diagnostic : diagnosticCollector.getDiagnostics()) {
CompilationMessage.Kind kind = (diagnostic.getKind() == Kind.ERROR ? CompilationMessage.Kind.ERROR : CompilationMessage.Kind.OTHER);
// String sourceCode = ((StringBasedJavaSourceFileObject)diagnostic.getSource()).getSourceCode();
String sourceCode = null;
try {
sourceCode = (String) diagnostic.getSource().getCharContent(true);
} catch (IOException ioe) {
// Unexpected, but leave sourceCode null to indicate it was not retrievable
} catch (NullPointerException npe) {
// TODO: should we skip warning diagnostics in the loop altogether?
}
int startPosition = (int) diagnostic.getPosition();
if (startPosition == Diagnostic.NOPOS) {
startPosition = (int) diagnostic.getStartPosition();
}
CompilationMessage compilationMessage = new CompilationMessage(kind, diagnostic.getMessage(null), sourceCode, startPosition, (int) diagnostic.getEndPosition());
compilationResult.recordCompilationMessage(compilationMessage);
}
if (success) {
List<CompiledClassDefinition> ccds = fileManager.getCompiledClasses();
List<Class<?>> classes = new ArrayList<>();
try (SimpleClassLoader ccl = new SimpleClassLoader(this.getClass().getClassLoader())) {
for (CompiledClassDefinition ccd : ccds) {
Class<?> clazz = ccl.defineClass(ccd.getClassName(), ccd.getBytes());
classes.add(clazz);
compilationResult.addClassBytes(ccd.getClassName(), ccd.getBytes());
}
} catch (IOException ioe) {
logger.debug("Unexpected exception defining classes", ioe);
}
compilationResult.setCompiledClasses(classes);
}
return compilationResult;
}
use of javax.tools.JavaCompiler.CompilationTask in project jetbrick-template-1x by subchen.
the class JdkCompiler method generateJavaClass.
@Override
protected void generateJavaClass(JavaSource source) {
// 编译代码
// 编译器编译中的诊断信息
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
// 要编译的所有Java文件
Iterable<? extends JavaFileObject> files = fileManager.getJavaFileObjects(source.getJavaFile());
CompilationTask task = jc.getTask(null, fileManager, diagnostics, options, null, files);
Boolean result;
if (isJdk6) {
// jdk6 的 compiler 是线程不安全的,需要手动同步
synchronized (this) {
result = task.call();
}
} else {
// jdk7+ 的 compiler 是线程安全的
result = task.call();
}
// 返回编译结果
if ((result == null) || !result.booleanValue()) {
String[] sourceCodeLines = source.getSourceCode().split("\r?\n", -1);
StringBuilder sb = new StringBuilder();
sb.append("Compilation failed.");
sb.append('\n');
for (Diagnostic<? extends JavaFileObject> d : diagnostics.getDiagnostics()) {
sb.append(d.getMessage(Locale.ENGLISH)).append('\n');
sb.append(StringUtils.getPrettyError(sourceCodeLines, (int) d.getLineNumber(), (int) d.getColumnNumber(), (int) d.getPosition(), (int) d.getPosition(), 3));
}
sb.append(diagnostics.getDiagnostics().size());
sb.append(" error(s)\n");
throw new CompileErrorException(sb.toString());
}
}
Aggregations