use of javax.tools.JavaCompiler.CompilationTask in project jadx by skylot.
the class DynamicCompiler method compile.
public boolean compile() throws Exception {
String fullName = clsNode.getFullName();
String code = clsNode.getCode().toString();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
fileManager = new ClassFileManager(compiler.getStandardFileManager(null, null, null));
List<JavaFileObject> jFiles = new ArrayList<JavaFileObject>(1);
jFiles.add(new CharSequenceJavaFileObject(fullName, code));
CompilationTask compilerTask = compiler.getTask(null, fileManager, null, null, null, jFiles);
return Boolean.TRUE.equals(compilerTask.call());
}
use of javax.tools.JavaCompiler.CompilationTask in project yyl_example by Relucent.
the class JavaCompilerTest method compile.
private static boolean compile(String className, String source) {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
//DiagnosticListener 编译的诊断信息
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
CompilationTask task = compiler.getTask(null, null, diagnostics, Arrays.asList("-d", tempdir), null, Arrays.asList(new JavaSourceFromString(className, source)));
boolean success = task.call();
System.out.println("Success: " + success);
print(diagnostics);
return success;
}
use of javax.tools.JavaCompiler.CompilationTask in project sling by apache.
the class ClassLoaderImpl method compile.
/**
* Compile multiple Java source strings and return a Map containing the
* resulting classes.
* <p>
* Thread safety: this method is thread safe if the <var>classes</var> and
* <var>diagnosticsList</var> are isolated to this thread.
*
* @param classes
* A Map whose keys are qualified class names and whose values are
* the Java source strings containing the definition of the class.
* A map value may be null, indicating that compiled class is
* expected, although no source exists for it (it may be a
* non-public class contained in one of the other strings.)
* @return A mapping of qualified class names to their corresponding classes.
* The map has the same keys as the input <var>classes</var>; the
* values are the corresponding Class objects.
* @throws CharSequenceJavaCompilerException
* if the source cannot be compiled
*/
public synchronized Map<String, Class<T>> compile(final Map<String, CharSequence> classes) throws CharSequenceJavaCompilerException {
List<JavaFileObject> sources = new ArrayList<>();
for (Entry<String, CharSequence> entry : classes.entrySet()) {
String qualifiedClassName = entry.getKey();
CharSequence javaSource = entry.getValue();
if (javaSource != null) {
final int dotPos = qualifiedClassName.lastIndexOf('.');
final String className = dotPos == -1 ? qualifiedClassName : qualifiedClassName.substring(dotPos + 1);
final String packageName = dotPos == -1 ? "" : qualifiedClassName.substring(0, dotPos);
final JavaFileObjectImpl source = new JavaFileObjectImpl(className, javaSource);
sources.add(source);
// Store the source file in the FileManager via package/class
// name.
// For source files, we add a .java extension
javaFileManager.putFileForInput(StandardLocation.SOURCE_PATH, packageName, className + JAVA_EXTENSION, source);
}
}
// Get a CompliationTask from the compiler and compile the sources
final CompilationTask task = compiler.getTask(null, javaFileManager, diagnostics, options, null, sources);
final Boolean result = task.call();
if (result == null || !result) {
throw new CharSequenceJavaCompilerException("Compilation failed.", classes.keySet(), diagnostics);
}
try {
// For each class name in the inpput map, get its compiled
// class and put it in the output map
Map<String, Class<T>> compiled = new HashMap<>();
for (String qualifiedClassName : classes.keySet()) {
final Class<T> newClass = loadClass(qualifiedClassName);
compiled.put(qualifiedClassName, newClass);
}
return compiled;
} catch (ClassNotFoundException e) {
throw new CharSequenceJavaCompilerException(classes.keySet(), e, diagnostics);
}
}
use of javax.tools.JavaCompiler.CompilationTask in project Gargoyle by callakrsos.
the class JavaSourceFromString method main.
public static void main(String[] args) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
StringWriter writer = new StringWriter();
PrintWriter out = new PrintWriter(writer);
// out.println("package pak;");
out.println("public class HelloWorld {");
out.println(" public static void main(String args[]) {");
out.println(" System.out.println(\"This is in another java file\");");
out.println(" }");
out.println("}");
out.close();
JavaFileObject file = new JavaSourceFromString("pak/HelloWorld", writer.toString());
Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);
boolean success = task.call();
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
System.out.println(diagnostic.getCode());
System.out.println(diagnostic.getKind());
System.out.println(diagnostic.getPosition());
System.out.println(diagnostic.getStartPosition());
System.out.println(diagnostic.getEndPosition());
System.out.println(diagnostic.getSource());
System.out.println(diagnostic.getMessage(null));
}
System.out.println("Success: " + success);
if (success) {
try {
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { new File("").toURI().toURL() });
Class.forName("HelloWorld", true, classLoader).getDeclaredMethod("main", new Class[] { String[].class }).invoke(null, new Object[] { null });
} catch (ClassNotFoundException e) {
System.err.println("Class not found: " + e);
} catch (NoSuchMethodException e) {
System.err.println("No such method: " + e);
} catch (IllegalAccessException e) {
System.err.println("Illegal access: " + e);
} catch (InvocationTargetException e) {
System.err.println("Invocation target: " + e);
}
}
}
use of javax.tools.JavaCompiler.CompilationTask 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());
}
}
Aggregations