use of javax.tools.JavaCompiler.CompilationTask in project cxf by apache.
the class Compiler method internalJava6Compile.
protected boolean internalJava6Compile(JavaCompiler compiler, JavaFileManager fileManager, DiagnosticListener<JavaFileObject> listener, Iterable<? extends JavaFileObject> fileList) {
List<String> args = new ArrayList<>();
addArgs(args);
CompilationTask task = compiler.getTask(null, fileManager, listener, args, null, fileList);
Boolean ret = task.call();
try {
fileManager.close();
} catch (IOException e) {
System.err.print("[ERROR] IOException during compiling.");
e.printStackTrace();
}
return ret;
}
use of javax.tools.JavaCompiler.CompilationTask in project bazel by bazelbuild.
the class VanillaJavaBuilder method run.
public VanillaJavaBuilderResult run(List<String> args) throws IOException {
OptionsParser optionsParser;
try {
optionsParser = new OptionsParser(args);
} catch (InvalidCommandLineException e) {
return new VanillaJavaBuilderResult(false, e.getMessage());
}
DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
StringWriter output = new StringWriter();
JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(diagnosticCollector, ENGLISH, UTF_8);
setLocations(optionsParser, fileManager);
ImmutableList<JavaFileObject> sources = getSources(optionsParser, fileManager);
boolean ok;
if (sources.isEmpty()) {
ok = true;
} else {
CompilationTask task = javaCompiler.getTask(new PrintWriter(output, true), fileManager, diagnosticCollector, JavacOptions.removeBazelSpecificFlags(optionsParser.getJavacOpts()), ImmutableList.<String>of(), /*classes*/
sources);
setProcessors(optionsParser, fileManager, task);
ok = task.call();
}
if (ok) {
writeOutput(optionsParser);
}
writeGeneratedSourceOutput(optionsParser);
// the file to be created
if (optionsParser.getOutputDepsProtoFile() != null) {
try (OutputStream os = Files.newOutputStream(Paths.get(optionsParser.getOutputDepsProtoFile()))) {
Deps.Dependencies.newBuilder().setRuleLabel(optionsParser.getTargetLabel()).setSuccess(ok).build().writeTo(os);
}
}
// TODO(cushon): support manifest protos & genjar
if (optionsParser.getManifestProtoPath() != null) {
try (OutputStream os = Files.newOutputStream(Paths.get(optionsParser.getManifestProtoPath()))) {
Manifest.getDefaultInstance().writeTo(os);
}
}
for (Diagnostic<? extends JavaFileObject> diagnostic : diagnosticCollector.getDiagnostics()) {
StringBuilder message = new StringBuilder();
if (diagnostic.getSource() != null) {
message.append(diagnostic.getSource().getName());
if (diagnostic.getLineNumber() != -1) {
message.append(':').append(diagnostic.getLineNumber());
}
message.append(": ");
}
message.append(diagnostic.getKind().toString().toLowerCase(ENGLISH));
message.append(": ").append(diagnostic.getMessage(ENGLISH)).append(System.lineSeparator());
output.write(message.toString());
}
return new VanillaJavaBuilderResult(ok, output.toString());
}
use of javax.tools.JavaCompiler.CompilationTask in project enumerable by hraberg.
the class InMemoryCompiler method compile.
public Class<?> compile(String className, String source) throws IOException {
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
JavaFileManager manager = new ForwardingJavaFileManager<StandardJavaFileManager>(compiler.getStandardFileManager(null, null, null)) {
public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException {
return new ByteArrayFileObject(className.replace('/', '.'));
}
};
JavaFileObject file = new JavaSourceFromString(className, source);
List<String> options = new ArrayList<String>(asList("-source", "1.5", "-target", "1.5"));
if (debugInfo) {
options.add("-g");
}
if (useECJ) {
options.add("-warn:-raw");
options.add("-warn:-deadCode");
options.add("-warn:-serial");
}
CompilationTask task = compiler.getTask(null, manager, diagnostics, options, null, Arrays.asList(file));
boolean success = task.call();
if (success) {
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
throw uncheck(e);
}
} else {
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));
}
return null;
}
}
use of javax.tools.JavaCompiler.CompilationTask in project zeppelin by apache.
the class JavaSourceFromString method execute.
public static String execute(String generatedClassName, String code) throws Exception {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
// Java parasing
JavaProjectBuilder builder = new JavaProjectBuilder();
JavaSource src = builder.addSource(new StringReader(code));
// get all classes in code (paragraph)
List<JavaClass> classes = src.getClasses();
String mainClassName = null;
// Searching for class containing Main method
for (int i = 0; i < classes.size(); i++) {
boolean hasMain = false;
for (int j = 0; j < classes.get(i).getMethods().size(); j++) {
if (classes.get(i).getMethods().get(j).getName().equals("main") && classes.get(i).getMethods().get(j).isStatic()) {
mainClassName = classes.get(i).getName();
hasMain = true;
break;
}
}
if (hasMain == true) {
break;
}
}
// if there isn't Main method, will retuen error
if (mainClassName == null) {
logger.error("Exception for Main method", "There isn't any class " + "containing static main method.");
throw new Exception("There isn't any class containing static main method.");
}
// replace name of class containing Main method with generated name
code = code.replace(mainClassName, generatedClassName);
JavaFileObject file = new JavaSourceFromString(generatedClassName, code.toString());
Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
ByteArrayOutputStream baosOut = new ByteArrayOutputStream();
ByteArrayOutputStream baosErr = new ByteArrayOutputStream();
// Creating new stream to get the output data
PrintStream newOut = new PrintStream(baosOut);
PrintStream newErr = new PrintStream(baosErr);
// Save the old System.out!
PrintStream oldOut = System.out;
PrintStream oldErr = System.err;
// Tell Java to use your special stream
System.setOut(newOut);
System.setErr(newErr);
CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);
// executing the compilation process
boolean success = task.call();
// if success is false will get error
if (!success) {
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
if (diagnostic.getLineNumber() == -1) {
continue;
}
System.err.println("line " + diagnostic.getLineNumber() + " : " + diagnostic.getMessage(null));
}
System.out.flush();
System.err.flush();
System.setOut(oldOut);
System.setErr(oldErr);
logger.error("Exception in Interpreter while compilation", baosErr.toString());
throw new Exception(baosErr.toString());
} else {
try {
// creating new class loader
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { new File("").toURI().toURL() });
// execute the Main method
Class.forName(generatedClassName, true, classLoader).getDeclaredMethod("main", new Class[] { String[].class }).invoke(null, new Object[] { null });
System.out.flush();
System.err.flush();
// set the stream to old stream
System.setOut(oldOut);
System.setErr(oldErr);
return baosOut.toString();
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
logger.error("Exception in Interpreter while execution", e);
System.err.println(e);
e.printStackTrace(newErr);
throw new Exception(baosErr.toString(), e);
} finally {
System.out.flush();
System.err.flush();
System.setOut(oldOut);
System.setErr(oldErr);
}
}
}
use of javax.tools.JavaCompiler.CompilationTask in project error-prone by google.
the class CompilationTestHelper method checkWellFormed.
private void checkWellFormed(Iterable<JavaFileObject> sources, String[] args) {
JavaCompiler compiler = JavacTool.create();
OutputStream outputStream = new ByteArrayOutputStream();
String[] remainingArgs = null;
try {
remainingArgs = ErrorProneOptions.processArgs(args).getRemainingArgs();
} catch (InvalidCommandLineOptionException e) {
fail("Exception during argument processing: " + e);
}
CompilationTask task = compiler.getTask(new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream, UTF_8)), /*autoFlush=*/
true), fileManager, null, buildArguments(Arrays.asList(remainingArgs)), null, sources);
boolean result = task.call();
assertWithMessage(String.format("Test program failed to compile with non Error Prone error: %s", outputStream.toString())).that(result).isTrue();
}
Aggregations