use of javax.tools.StandardJavaFileManager in project checker-framework by typetools.
the class Main method main.
public static void main(String[] args) {
final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
final StandardJavaFileManager fileManager = javac.getStandardFileManager(null, null, null);
if (!doStuff(javac, fileManager)) {
System.exit(1);
}
if (!doStuff(javac, fileManager)) {
System.exit(1);
}
if (!doStuff(javac, fileManager)) {
System.exit(1);
}
}
use of javax.tools.StandardJavaFileManager in project suite by stupidsing.
the class JdkUtil method compile.
protected Path compile(String canonicalName, String java) throws IOException {
Path srcFilePath = srcDir.resolve(canonicalName.replace('.', '/') + ".java");
Path binFilePath = binDir.resolve(canonicalName.replace('.', '/') + ".class");
LogUtil.info("Writing " + srcFilePath);
try (OutputStream os = FileUtil.out(srcFilePath)) {
os.write(java.getBytes(Constants.charset));
}
// compile the Java, load the class, return an instantiated object
LogUtil.info("Compiling " + srcFilePath);
FileUtil.mkdir(binDir);
JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager sjfm = jc.getStandardFileManager(null, null, null)) {
if (!//
jc.getTask(//
null, //
null, //
null, //
List.of("-d", binDir.toString()), //
null, sjfm.getJavaFileObjects(srcFilePath.toFile())).call())
Fail.t("Java compilation error");
}
return binFilePath;
}
use of javax.tools.StandardJavaFileManager 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());
}
}
use of javax.tools.StandardJavaFileManager 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.StandardJavaFileManager in project tez by apache.
the class TestMRRJobsDAGApi method createTestJar.
private static void createTestJar(OutputStream outStream, String dummyClassName) throws URISyntaxException, IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
JavaFileObject srcFileObject = new SimpleJavaFileObjectImpl(URI.create("string:///" + dummyClassName + Kind.SOURCE.extension), Kind.SOURCE);
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
compiler.getTask(null, fileManager, null, null, null, Collections.singletonList(srcFileObject)).call();
JavaFileObject javaFileObject = fileManager.getJavaFileForOutput(StandardLocation.CLASS_OUTPUT, dummyClassName, Kind.CLASS, null);
File classFile = new File(dummyClassName + Kind.CLASS.extension);
JarOutputStream jarOutputStream = new JarOutputStream(outStream);
JarEntry jarEntry = new JarEntry(classFile.getName());
jarEntry.setTime(classFile.lastModified());
jarOutputStream.putNextEntry(jarEntry);
InputStream in = javaFileObject.openInputStream();
byte[] buffer = new byte[4096];
while (true) {
int nRead = in.read(buffer, 0, buffer.length);
if (nRead <= 0)
break;
jarOutputStream.write(buffer, 0, nRead);
}
in.close();
jarOutputStream.close();
javaFileObject.delete();
}
Aggregations