public static void parse(Path moduleInfoPath, ModuleClassVisitor moduleClassVisitor) throws IOException { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); try(StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)) { Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(moduleInfoPath); CompilationTask task = compiler.getTask(null, fileManager, null, null, null, compilationUnits); JavacTask javacTask = (JavacTask)task; Iterable<? extends CompilationUnitTree> units= javacTask.parse(); CompilationUnitTree unit = units.iterator().next(); ModuleHandler moduleHandler = new ModuleHandler(moduleClassVisitor); TreeVisitor<?,?> visitor = (TreeVisitor<?,?>)Proxy.newProxyInstance(TreeVisitor.class.getClassLoader(), new Class<?>[]{ TreeVisitor.class}, (proxy, method, args) -> { ModuleHandler.METHOD_MAP .getOrDefault(method.getName(), (handler, node, v) -> { throw new AssertionError("invalid node " + node.getClass()); }) .visit(moduleHandler, (Tree)args[0], (TreeVisitor<?,?>)proxy); return null; }); unit.accept(visitor, null); } }
int run(JavaCompiler comp, StandardJavaFileManager fm) throws IOException { System.err.println("test: ck:" + ck + " gk:" + gk + " sk:" + sk); File testDir = new File(ck + "-" + gk + "-" + sk); testDir.mkdirs(); fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(testDir)); JavaSource js = new JavaSource(); System.err.println(js.getCharContent(false)); CompilationTask t = comp.getTask(null, fm, null, null, null, Arrays.asList(js)); if (!t.call()) throw new Error("compilation failed"); File testClass = new File(testDir, "Test.class"); String out = javap(testClass); // Extract class sig from first line of Java source String expect = js.source.replaceAll("(?s)^(.* Test[^{]+?) *\\{.*", "$1"); // Extract class sig from line from javap output String found = out.replaceAll("(?s).*\n(.* Test[^{]+?) *\\{.*", "$1"); checkEqual("class signature", expect, found); return errors; }
public static void main(String[] args) throws Exception { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if (compiler == null) { throw new RuntimeException("can't get javax.tools.JavaCompiler!"); } try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) { List<File> files = new ArrayList<File>(); files.add(new File(T6956462.class.getResource("TestClass.java").toURI())); final CompilationTask task = compiler.getTask(null, fm, null, null, null, fm.getJavaFileObjectsFromFiles(files)); JavacTask javacTask = (JavacTask) task; for (CompilationUnitTree cu : javacTask.parse()) { cu.accept(new MyVisitor(javacTask), null); } } }
public static void main(String[] args) throws IOException { // Get a compiler tool JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); String srcdir = System.getProperty("test.src"); File source = new File(srcdir, "T6378728.java"); try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) { CompilationTask task = compiler.getTask(null, new ExceptionalFileManager(fm), null, Arrays.asList("-proc:only"), null, fm.getJavaFileObjectsFromFiles(Arrays.asList(source))); if (!task.call()) throw new RuntimeException("Unexpected compilation failure"); } }
private void testSingleSourceDir(JavaCompiler javac) throws Exception { System.err.println("testSingleSourceDir"); File tmpdir = new File("testSingleSourceDir"); File srcdir = new File(tmpdir, "src"); File destdir = new File(tmpdir, "dest"); write(srcdir, "pkg/X.java", "package pkg; class X {}"); write(srcdir, "resources/file.txt", "hello"); destdir.mkdirs(); CompilationTask task = javac.getTask(null, null, null, Arrays.asList("-sourcepath", srcdir.toString(), "-d", destdir.toString()), Collections.singleton("pkg.X"), null); task.setProcessors(Collections.singleton(new AnnoProc())); boolean result = task.call(); System.err.println("javac result with single source dir: " + result); expect(result, true); }
private void testCompositeSourcePath(JavaCompiler javac) throws Exception { System.err.println("testCompositeSearchPath"); File tmpdir = new File("testCompositeSourcePath"); File srcdir = new File(tmpdir, "src"); File rsrcdir = new File(tmpdir, "rsrc"); File destdir = new File(tmpdir, "dest"); write(srcdir, "pkg/X.java", "package pkg; class X {}"); write(rsrcdir, "resources/file.txt", "hello"); destdir.mkdirs(); CompilationTask task = javac.getTask(null, null, null, Arrays.asList("-sourcepath", srcdir + File.pathSeparator + rsrcdir, "-d", destdir.toString()), Collections.singleton("pkg.X"), null); task.setProcessors(Collections.singleton(new AnnoProc())); boolean result = task.call(); System.err.println("javac result with composite source path: " + result); expect(result, true); }
private void testMissingResource(JavaCompiler javac) throws Exception { System.err.println("testMissingResource"); File tmpdir = new File("testMissingResource"); File srcdir = new File(tmpdir, "src"); File destdir = new File(tmpdir, "dest"); write(srcdir, "pkg/X.java", "package pkg; class X {}"); destdir.mkdirs(); CompilationTask task = javac.getTask(null, null, null, Arrays.asList("-sourcepath", srcdir.toString(), "-d", destdir.toString()), Collections.singleton("pkg.X"), null); task.setProcessors(Collections.singleton(new AnnoProc())); boolean result = task.call(); System.err.println("javac result when missing resource: " + result); expect(result, false); if (errors > 0) throw new Exception(errors + " errors occurred"); }
public static void main(String... args) throws Exception { String testSrc = System.getProperty("test.src"); String testClasses = System.getProperty("test.classes"); JavaCompiler c = ToolProvider.getSystemJavaCompiler(); try (StandardJavaFileManager fm = c.getStandardFileManager(null, null, null)) { String thisName = TreePosRoundsTest.class.getName(); File thisFile = new File(testSrc, thisName + ".java"); Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(thisFile); List<String> options = Arrays.asList( "-proc:only", "-processor", thisName, "-processorpath", testClasses); CompilationTask t = c.getTask(null, fm, null, options, null, files); boolean ok = t.call(); if (!ok) throw new Exception("processing failed"); } }
File createFile(Dir dir) throws IOException { File src = new File(dir.file, classId + ".java"); try (FileWriter w = new FileWriter(src)) { w.append("public class " + classId + " {}"); } // If we're after the ".java" representation, we're done... if(dir == Dir.SOURCE_PATH) return src; // ...otherwise compile into a ".class". CompilationTask task = comp.getTask(null, fm, null, null, null, fm.getJavaFileObjects(src)); File dest = new File(dir.file, classId + ".class"); if(!task.call() || !dest.exists()) throw new RuntimeException("Compilation failure."); src.delete(); return dest; }
void callTask(List<String> options, List<JavaFileObject> files) { out.print("compile: "); if (options != null) { for (String o: options) { if (o.length() > 64) { o = o.substring(0, 32) + "..." + o.substring(o.length() - 32); } out.print(" " + o); } } for (JavaFileObject f: files) out.print(" " + f.getName()); out.println(); CompilationTask t = compiler.getTask(out, fileManager, null, options, null, files); boolean ok = t.call(); if (!ok) error("compilation failed"); }
void test(List<String> options, String expect) throws Exception { System.err.println("test: " + options); JavaCompiler javac = ToolProvider.getSystemJavaCompiler(); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); JavaFileObject f = new MyFileObject("myfo://test", "class Bad { Missing x; }"); List<? extends JavaFileObject> files = Arrays.asList(f); CompilationTask task = javac.getTask(pw, null, null, options, null, files); boolean ok = task.call(); pw.close(); String out = sw.toString(); if (!out.isEmpty()) System.err.println(out); if (ok) throw new Exception("Compilation succeeded unexpectedly"); if (!out.contains(expect)) throw new Exception("expected text not found: " + expect); }
void run() throws Exception { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); System.err.println("using " + compiler.getClass() + " from " + compiler.getClass().getProtectionDomain().getCodeSource()); CompilationTask task = compiler.getTask(null, null, null, Collections.singleton("-proc:only"), Collections.singleton("java.lang.Object"), null); task.setProcessors(Collections.singleton(new Proc())); check("compilation", task.call()); task = compiler.getTask(null, null, null, Arrays.asList("-proc:only", "-AexpectFile"), Collections.singleton("java.lang.Object"), null); task.setProcessors(Collections.singleton(new Proc())); check("compilation", task.call()); }
public static void compileFiles(File projectRoot, List<String> javaFiles) { DiagnosticCollector diagnosticCollector = new DiagnosticCollector(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticCollector, Locale.ENGLISH, Charset.forName("utf-8")); Iterable<? extends JavaFileObject> javaFileObjects = fileManager.getJavaFileObjects(javaFiles.toArray(new String[0])); File outputFolder = new File(projectRoot, "bin"); if (!outputFolder.exists()) { outputFolder.mkdir(); } String[] options = new String[] { "-d", outputFolder.getAbsolutePath() , "-g", "-proc:none"}; final StringWriter output = new StringWriter(); CompilationTask task = compiler.getTask(output, fileManager, diagnosticCollector, Arrays.asList(options), null, javaFileObjects); boolean result = task.call(); if (!result) { throw new IllegalArgumentException( "Compilation failed:\n" + output); } List list = diagnosticCollector.getDiagnostics(); for (Object object : list) { Diagnostic d = (Diagnostic) object; System.out.println(d.getMessage(Locale.ENGLISH)); } }
@BeforeClass public static void compileDependencyClass() throws IOException, ClassNotFoundException { JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler(); Assume.assumeNotNull(javaCompiler); classes = temporaryFolder.newFolder("classes");; StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, Locale.ROOT, UTF_8); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, ImmutableList.of(classes)); SimpleJavaFileObject compilationUnit = new SimpleJavaFileObject(URI.create("FooTest.java"), Kind.SOURCE) { String fooTestSource = Resources.toString(Resources.getResource("com/dremio/exec/compile/FooTest.java"), UTF_8); @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return fooTestSource; } }; CompilationTask task = javaCompiler.getTask(null, fileManager, null, Collections.<String>emptyList(), null, ImmutableList.of(compilationUnit)); assertTrue(task.call()); }
public static Class<?> compile(String mainClass, Code... codes) throws Exception { JavaCompiler javac = ToolProvider.getSystemJavaCompiler(); DynamicClassLoader cl = new DynamicClassLoader(ClassLoader.getSystemClassLoader()); ExtendedStandardJavaFileManager fileManager = new ExtendedStandardJavaFileManager(javac.getStandardFileManager(null, null, null), null, cl); JavaFileObject[] sCodes = new JavaFileObject[codes.length]; // List<CompiledCode> cCodes = new ArrayList<>(); for (int i = 0; i < codes.length; i++) { SourceCode sourceCode = new SourceCode(codes[i].getClassName(), codes[i].getSourceCode()); CompiledCode compiledCode = new CompiledCode(codes[i].getClassName()); sCodes[i] = sourceCode; fileManager.addCode(compiledCode); } Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(sCodes); CompilationTask task = javac.getTask(null, fileManager, null, null, null, compilationUnits); task.call(); return cl.loadClass(mainClass); }
public static Class<?> compile(List<SourceCode> codeList, String className) throws Exception { JavaCompiler javac = ToolProvider.getSystemJavaCompiler(); DynamicClassLoader cl = new DynamicClassLoader(ClassLoader.getSystemClassLoader()); ExtendedStandardJavaFileManager fileManager = new ExtendedStandardJavaFileManager(javac.getStandardFileManager(null, null, null), cl); for (SourceCode sourceCode : codeList) { // SourceCode sourceCode = new SourceCode(className, // sourceCodeInText); CompiledCode compiledCode = new CompiledCode(sourceCode.getClassName()); fileManager.addCode(compiledCode); } Iterable<? extends JavaFileObject> compilationUnits = codeList;// Arrays.asList(sourceCode); JavaCompiler.CompilationTask task = javac.getTask(null, fileManager, null, getDefaultOption(), null, compilationUnits); boolean result = task.call(); return cl.loadClass(className); }
public synchronized Class compile(String packageName, String className, final CharSequence javaSource) throws JdkCompileException, ClassCastException { DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); JavaFileManagerImpl javaFileManager = buildFileManager(classLoader, classLoader.getParent(), diagnostics); JavaFileObjectImpl source = new JavaFileObjectImpl(className, javaSource); javaFileManager.putFileForInput(StandardLocation.SOURCE_PATH, packageName, className + EXTENSION, source); CompilationTask task = compiler.getTask(null, javaFileManager, diagnostics, options, null, Arrays.asList(source)); final Boolean result = task.call(); if (result == null || !result.booleanValue()) { throw new JdkCompileException("Compilation failed.", diagnostics); } try { return (Class<T>) classLoader.loadClass(packageName + "." + className); } catch (Throwable e) { throw new JdkCompileException(e, diagnostics); } }
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); } }
/** Convenient JavaCompiler facade returning a ClassLoader with all compiled units. */ static ClassLoader compile( ClassLoader parent, List<String> options, List<Processor> processors, List<JavaFileObject> units) { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); Objects.requireNonNull(compiler, "no system java compiler available - JDK is required!"); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>(); StandardJavaFileManager sjfm = compiler.getStandardFileManager(diagnostics, Locale.getDefault(), StandardCharsets.UTF_8); Manager manager = new Manager(sjfm, parent); CompilationTask task = compiler.getTask(null, manager, diagnostics, options, null, units); if (!processors.isEmpty()) { task.setProcessors(processors); } boolean success = task.call(); if (!success) { throw new RuntimeException("compilation failed! " + diagnostics.getDiagnostics()); } return manager.getClassLoader(StandardLocation.CLASS_PATH); }
public static void main(String[] args) { // Get a compiler tool JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); String srcdir = System.getProperty("test.src"); File source = new File(srcdir, "T6378728.java"); StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null); CompilationTask task = compiler.getTask(null, new ExceptionalFileManager(fm), null, Arrays.asList("-proc:only"), null, fm.getJavaFileObjectsFromFiles(Arrays.asList(source))); if (!task.call()) throw new RuntimeException("Unexpected compilation failure"); }
public static void main(String... args) throws Exception { String testSrc = System.getProperty("test.src"); String testClasses = System.getProperty("test.classes"); JavaCompiler c = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fm = c.getStandardFileManager(null, null, null); String thisName = TreePosRoundsTest.class.getName(); File thisFile = new File(testSrc, thisName + ".java"); Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(thisFile); List<String> options = Arrays.asList( "-proc:only", "-processor", thisName, "-processorpath", testClasses); CompilationTask t = c.getTask(null, fm, null, options, null, files); boolean ok = t.call(); if (!ok) throw new Exception("processing failed"); }
/** Attempts to compile all found source files into the cache directory, as class files */ private void compileFiles() { StandardJavaFileManager fileManager = javac.getStandardFileManager( diagnostics, null, Charset.forName("UTF-8") ); // See https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javac.html // and https://docs.oracle.com/javase/8/docs/technotes/tools/windows/classpath.html List<String> options = Arrays.asList ( "-d", Config.Dirs.cache.toString(), // Built class output directory "-classpath", generateClasspath(), // Use Bukkit + plugins as classpath "-Xlint" // Report all code warnings ); SOFTLOG.info("Compiling " + sourceFiles.size() + " source files. . ."); CompilationTask task = javac.getTask( null, fileManager, diagnostics, options, null, fileManager.getJavaFileObjectsFromFiles(sourceFiles) ); if ( !task.call() ) throw new CompilerException(); }
public String compile(File file) { // http://www.tutego.de/blog/javainsel/2010/04/java-compiler-api-teil-1-grundlagen/ JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager manager = compiler.getStandardFileManager(null, null, null); Iterable<? extends JavaFileObject> units; units = manager.getJavaFileObjectsFromFiles(Arrays.asList(file)); Iterable<String> options = Arrays.asList(new String[] { "-d", "./plugins/bin", "-verbose" }); // Iterable<String> options = Arrays.asList( new String[]{"-d", // "./plugins/bin"}); StringWriter sw = new StringWriter(); CompilationTask task = compiler.getTask(sw, manager, null, options, null, units); task.call(); try { manager.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sw.getBuffer().toString(); }