com.sun.source.util.JavacTask Java Examples
The following examples show how to use
com.sun.source.util.JavacTask.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AnnotatedArrayOrder.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws Exception { PrintWriter out = new PrintWriter(System.out, true); JavacTool tool = JavacTool.create(); StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null); File testSrc = new File(System.getProperty("test.src")); Iterable<? extends JavaFileObject> f = fm.getJavaFileObjectsFromFiles(Arrays.asList(new File(testSrc, "AnnotatedArrayOrder.java"))); JavacTask task = tool.getTask(out, fm, null, null, null, f); Iterable<? extends CompilationUnitTree> trees = task.parse(); out.flush(); Scanner s = new Scanner(); for (CompilationUnitTree t: trees) s.scan(t, null); }
Example #2
Source File: T6410706.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
public static void main(String... args) throws IOException { String testSrc = System.getProperty("test.src", "."); String testClasses = System.getProperty("test.classes", "."); JavacTool tool = JavacTool.create(); MyDiagListener dl = new MyDiagListener(); StandardJavaFileManager fm = tool.getStandardFileManager(dl, null, null); fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File(testClasses))); Iterable<? extends JavaFileObject> files = fm.getJavaFileObjectsFromFiles(Arrays.asList(new File(testSrc, T6410706.class.getName()+".java"))); JavacTask task = tool.getTask(null, fm, dl, null, null, files); task.parse(); task.analyze(); task.generate(); // expect 2 notes: // Note: T6410706.java uses or overrides a deprecated API. // Note: Recompile with -Xlint:deprecation for details. if (dl.notes != 2) throw new AssertionError(dl.notes + " notes given"); }
Example #3
Source File: JavacTemplateTestBase.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
private File compile(List<File> classpaths, List<JavaFileObject> files, boolean generate) throws IOException { JavaCompiler systemJavaCompiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fm = systemJavaCompiler.getStandardFileManager(null, null, null); if (classpaths.size() > 0) fm.setLocation(StandardLocation.CLASS_PATH, classpaths); JavacTask ct = (JavacTask) systemJavaCompiler.getTask(null, fm, diags, compileOptions, null, files); if (generate) { File destDir = new File(root, Integer.toString(counter.incrementAndGet())); // @@@ Assert that this directory didn't exist, or start counter at max+1 destDir.mkdirs(); fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(destDir)); ct.generate(); return destDir; } else { ct.analyze(); return nullDir; } }
Example #4
Source File: ArrayCreationTree.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws Exception { PrintWriter out = new PrintWriter(System.out, true); JavacTool tool = JavacTool.create(); StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null); File testSrc = new File(System.getProperty("test.src")); Iterable<? extends JavaFileObject> f = fm.getJavaFileObjectsFromFiles(Arrays.asList(new File(testSrc, "ArrayCreationTree.java"))); JavacTask task = tool.getTask(out, fm, null, null, null, f); Iterable<? extends CompilationUnitTree> trees = task.parse(); out.flush(); Scanner s = new Scanner(); for (CompilationUnitTree t: trees) s.scan(t, null); }
Example #5
Source File: T6733837.java From jdk8u60 with GNU General Public License v2.0 | 6 votes |
public void exec() { JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) { public CharSequence getCharContent(boolean ignoreEncodingErrors) { return "\tclass ErroneousWithTab"; } }; StringWriter sw = new StringWriter(); PrintWriter out = new PrintWriter(sw); List<? extends JavaFileObject> files = Arrays.asList(sfo); task = tool.getTask(sw, fm, null, null, null, files); try { ((JavacTask)task).analyze(); } catch (Throwable t) { throw new Error("Compiler threw an exception"); } System.err.println(sw.toString()); if (!sw.toString().contains("/Test.java")) throw new Error("Bad source name in diagnostic"); }
Example #6
Source File: TestGetScope.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
public void run() throws IOException { File srcDir = new File(System.getProperty("test.src")); File thisFile = new File(srcDir, getClass().getName() + ".java"); JavaCompiler c = ToolProvider.getSystemJavaCompiler(); try (StandardJavaFileManager fm = c.getStandardFileManager(null, null, null)) { List<String> opts = Arrays.asList("-proc:only", "-doe"); Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(thisFile); JavacTask t = (JavacTask) c.getTask(null, fm, null, opts, null, files); t.setProcessors(Collections.singleton(this)); boolean ok = t.call(); if (!ok) throw new Error("compilation failed"); } }
Example #7
Source File: T6963934.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws Exception { File testSrc = new File(System.getProperty("test.src")); File thisSrc = new File(testSrc, T6963934.class.getSimpleName() + ".java"); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); JavacTask task = (JavacTask) compiler.getTask(null, fileManager, null, null, null, fileManager.getJavaFileObjects(thisSrc)); CompilationUnitTree tree = task.parse().iterator().next(); int count = 0; for (ImportTree importTree : tree.getImports()) { System.out.println(importTree); count++; } int expected = 7; if (count != expected) throw new Exception("unexpected number of imports found: " + count + ", expected: " + expected); }
Example #8
Source File: EdgeCases.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
@Test public void testAddExportUndefinedModule(Path base) throws Exception { Path src = base.resolve("src"); tb.writeJavaFiles(src, "package test; import undefPackage.Any; public class Test {}"); Path classes = base.resolve("classes"); tb.createDirectories(classes); List<String> log = new JavacTask(tb) .options("--add-exports", "undefModule/undefPackage=ALL-UNNAMED", "-XDrawDiagnostics") .outdir(classes) .files(findJavaFiles(src)) .run(Task.Expect.FAIL) .writeAll() .getOutputLines(Task.OutputKind.DIRECT); List<String> expected = Arrays.asList("- compiler.warn.module.for.option.not.found: --add-exports, undefModule", "Test.java:1:34: compiler.err.doesnt.exist: undefPackage", "1 error", "1 warning"); if (!expected.equals(log)) throw new Exception("expected output not found: " + log); }
Example #9
Source File: JavacTemplateTestBase.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
private File compile(List<File> classpaths, List<JavaFileObject> files, boolean generate) throws IOException { JavaCompiler systemJavaCompiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fm = systemJavaCompiler.getStandardFileManager(null, null, null); if (classpaths.size() > 0) fm.setLocation(StandardLocation.CLASS_PATH, classpaths); JavacTask ct = (JavacTask) systemJavaCompiler.getTask(null, fm, diags, compileOptions, null, files); if (generate) { File destDir = new File(root, Integer.toString(counter.incrementAndGet())); // @@@ Assert that this directory didn't exist, or start counter at max+1 destDir.mkdirs(); fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(destDir)); ct.generate(); return destDir; } else { ct.analyze(); return nullDir; } }
Example #10
Source File: TestClose.java From hottub with GNU General Public License v2.0 | 6 votes |
public static void add(ProcessingEnvironment env, Runnable r) { try { JavacTask task = JavacTask.instance(env); TaskListener l = ((BasicJavacTask) task).getTaskListeners().iterator().next(); // The TaskListener is an instanceof TestClose, but when using the // default class loaders. the taskListener uses a different // instance of Class<TestClose> than the anno processor. // If you try to evaluate // TestClose tc = (TestClose) (l). // you get the following somewhat confusing error: // java.lang.ClassCastException: TestClose cannot be cast to TestClose // The workaround is to access the fields of TestClose with reflection. Field f = l.getClass().getField("runnables"); @SuppressWarnings("unchecked") List<Runnable> runnables = (List<Runnable>) f.get(l); runnables.add(r); } catch (Throwable t) { t.printStackTrace(); } }
Example #11
Source File: Abort.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
public static void main(String... args) throws Exception { String SCRATCH_DIR = System.getProperty("user.dir"); JavaCompiler javacTool = ToolProvider.getSystemJavaCompiler(); java.io.File testDir = new java.io.File(SCRATCH_DIR); sourceA.dumpTo(testDir); sourceB.dumpTo(testDir); DiagnosticChecker diagChecker = new DiagnosticChecker(); JavacTask ct = (JavacTask)javacTool.getTask(null, null, diagChecker, Arrays.asList("-XDrawDiagnostics", "-cp", testDir.getAbsolutePath()), null, Arrays.asList(sourceA.asJFO(testDir))); try { ct.analyze(); } catch (Throwable ex) { //ignore abort exception thrown by javac } if (!diagChecker.errorFound) { throw new AssertionError("Missing diagnostic"); } }
Example #12
Source File: T6993305.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
void run() throws Exception { File testSrc = new File(System.getProperty("test.src")); JavacTool tool = JavacTool.create(); StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null); File f = new File(testSrc, T6993305.class.getSimpleName() + ".java"); Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjects(f); JavacTask task = tool.getTask(null, fm, null, null, null, fos); Iterable<? extends CompilationUnitTree> cus = task.parse(); TestScanner s = new TestScanner(); s.scan(cus, task); if (errors > 0) throw new Exception(errors + " errors occurred"); }
Example #13
Source File: InnerClassCannotBeVerified.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
void run() throws Exception { JavaCompiler comp = ToolProvider.getSystemJavaCompiler(); JavaSource source = new JavaSource(); JavacTask ct = (JavacTask)comp.getTask(null, null, null, null, null, Arrays.asList(source)); try { if (!ct.call()) { throw new AssertionError(errorMessage + source.getCharContent(true)); } } catch (Throwable ex) { throw new AssertionError(errorMessage + source.getCharContent(true)); } check(); }
Example #14
Source File: T6457284.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws IOException { Context context = new Context(); MyMessages.preRegister(context); JavacTool tool = JavacTool.create(); JavacTask task = tool.getTask(null, null, null, null, null, List.of(new MyFileObject()), context); task.parse(); for (Element e : task.analyze()) { if (!e.getEnclosingElement().toString().equals("compiler.misc.unnamed.package")) throw new AssertionError(e.getEnclosingElement()); System.out.println("OK: " + e.getEnclosingElement()); return; } throw new AssertionError("No top-level classes!"); }
Example #15
Source File: T6733837.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
public void exec() { JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) { public CharSequence getCharContent(boolean ignoreEncodingErrors) { return "\tclass ErroneousWithTab"; } }; StringWriter sw = new StringWriter(); PrintWriter out = new PrintWriter(sw); List<? extends JavaFileObject> files = Arrays.asList(sfo); task = tool.getTask(sw, fm, null, null, null, files); try { ((JavacTask)task).analyze(); } catch (Throwable t) { throw new Error("Compiler threw an exception"); } System.err.println(sw.toString()); if (!sw.toString().contains("/Test.java")) throw new Error("Bad source name in diagnostic"); }
Example #16
Source File: ProfileOptionTest.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
@Test void testClassesInProfiles() throws Exception { for (Profile p: Profile.values()) { for (Map.Entry<Profile, List<JavaFileObject>> e: testClasses.entrySet()) { for (JavaFileObject fo: e.getValue()) { DiagnosticCollector<JavaFileObject> dl = new DiagnosticCollector<JavaFileObject>(); List<String> opts = (p == Profile.DEFAULT) ? Collections.<String>emptyList() : Arrays.asList("-profile", p.name); JavacTask task = (JavacTask) javac.getTask(null, fm, dl, opts, null, Arrays.asList(fo)); task.analyze(); List<String> expectDiagCodes = (p.value >= e.getKey().value) ? Collections.<String>emptyList() : Arrays.asList("compiler.err.not.in.profile"); checkDiags(opts + " " + fo.getName(), dl.getDiagnostics(), expectDiagCodes); } } } }
Example #17
Source File: FrontendOnlyJavacTask.java From buck with Apache License 2.0 | 5 votes |
public FrontendOnlyJavacTask(JavacTask task) { super(task); javacTask = task; // Add the entering plugin first so that all other plugins and annotation processors will // run with the TreeBackedElements already entered addPlugin(new EnteringPlugin()); }
Example #18
Source File: GenStubs.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
public boolean run(String sourcepath, File outdir, List<String> classes) { //System.err.println("run: sourcepath:" + sourcepath + " outdir:" + outdir + " classes:" + classes); if (sourcepath == null) throw new IllegalArgumentException("sourcepath not set"); if (outdir == null) throw new IllegalArgumentException("source output dir not set"); JavacTool tool = JavacTool.create(); StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null); try { fm.setLocation(StandardLocation.SOURCE_OUTPUT, Collections.singleton(outdir)); fm.setLocation(StandardLocation.SOURCE_PATH, splitPath(sourcepath)); List<JavaFileObject> files = new ArrayList<JavaFileObject>(); for (String c: classes) { JavaFileObject fo = fm.getJavaFileForInput( StandardLocation.SOURCE_PATH, c, JavaFileObject.Kind.SOURCE); if (fo == null) error("class not found: " + c); else files.add(fo); } JavacTask t = tool.getTask(null, fm, null, null, null, files); Iterable<? extends CompilationUnitTree> trees = t.parse(); for (CompilationUnitTree tree: trees) { makeStub(fm, tree); } } catch (IOException e) { error("IO error " + e, e); } return (errors == 0); }
Example #19
Source File: TestSelfRef.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception { JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker, null, null, Arrays.asList(source)); try { ct.analyze(); } catch (Throwable ex) { throw new AssertionError("Error thron when compiling the following code:\n" + source.getCharContent(true)); } check(); }
Example #20
Source File: IntersectionTargetTypeTest.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception { JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker, null, null, Arrays.asList(source)); try { ct.analyze(); } catch (Throwable ex) { throw new AssertionError("Error thrown when compiling the following code:\n" + source.getCharContent(true)); } check(); }
Example #21
Source File: T7086601b.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception { JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker, null, null, Arrays.asList(source)); try { ct.analyze(); } catch (Throwable ex) { throw new AssertionError("Error thrown when compiling the following code:\n" + source.getCharContent(true)); } check(); }
Example #22
Source File: T7042566.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
@Override public void run() { int id = checkCount.incrementAndGet(); final JavaCompiler tool = ToolProvider.getSystemJavaCompiler(); JavaSource source = new JavaSource(id); ErrorChecker ec = new ErrorChecker(); JavacTask ct = (JavacTask)tool.getTask(null, fm.get(), ec, null, null, Arrays.asList(source)); ct.call(); check(source, ec, id); }
Example #23
Source File: StructuralMostSpecificTest.java From hottub with GNU General Public License v2.0 | 5 votes |
public void run() { JavacTask ct = (JavacTask)comp.getTask(null, fm.get(), diagChecker, Arrays.asList("-XDverboseResolution=all,-predef,-internal,-object-init"), null, Arrays.asList(source)); try { ct.analyze(); } catch (Throwable ex) { throw new AssertionError("Error thron when analyzing the following source:\n" + source.getCharContent(true)); } check(); }
Example #24
Source File: FDTest.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception { JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker, null, null, Arrays.asList(source)); try { ct.analyze(); } catch (Throwable ex) { fail("Error thrown when analyzing the following source:\n" + source.getCharContent(true)); } check(); }
Example #25
Source File: TestSelfRef.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception { JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker, null, null, Arrays.asList(source)); try { ct.analyze(); } catch (Throwable ex) { throw new AssertionError("Error thron when compiling the following code:\n" + source.getCharContent(true)); } check(); }
Example #26
Source File: ResolveHarness.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
protected void check() throws Exception { String[] options = { "-XDshouldStopPolicy=ATTR", "-XDverboseResolution=success,failure,applicable,inapplicable,deferred-inference,predef" }; AbstractProcessor[] processors = { new ResolveCandidateFinder(), null }; @SuppressWarnings("unchecked") DiagnosticListener<? super JavaFileObject>[] diagListeners = new DiagnosticListener[] { new DiagnosticHandler(false), new DiagnosticHandler(true) }; for (int i = 0 ; i < options.length ; i ++) { JavacTask ct = (JavacTask)comp.getTask(null, fm, diagListeners[i], Arrays.asList(options[i]), null, Arrays.asList(jfo)); if (processors[i] != null) { ct.setProcessors(Collections.singleton(processors[i])); } ct.analyze(); } //check diags for (Diagnostic<? extends JavaFileObject> diag : diags) { for (DiagnosticProcessor proc : diagProcessors) { if (proc.matches(diag)) { proc.process(diag); break; } } } //check all candidates have been used up for (Map.Entry<ElementKey, Candidate> entry : candidatesMap.entrySet()) { if (!seenCandidates.contains(entry.getKey())) { error("Redundant @Candidate annotation on method " + entry.getKey().elem + " sig = " + entry.getKey().elem.asType()); } } }
Example #27
Source File: EdgeCases.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
@Test public void testModuleImplicitModuleBoundaries(Path base) throws Exception { Path src = base.resolve("src"); Path src_m1 = src.resolve("m1x"); tb.writeJavaFiles(src_m1, "module m1x { exports api1; }", "package api1; public class Api1 { public void call() { } }"); Path src_m2 = src.resolve("m2x"); tb.writeJavaFiles(src_m2, "module m2x { requires m1x; exports api2; }", "package api2; public class Api2 { public static api1.Api1 get() { return null; } }"); Path src_m3 = src.resolve("m3x"); tb.writeJavaFiles(src_m3, "module m3x { requires m2x; }", "package test; public class Test { { api2.Api2.get().call(); api2.Api2.get().toString(); } }"); Path classes = base.resolve("classes"); tb.createDirectories(classes); String log = new JavacTask(tb) .options("-XDrawDiagnostics", "--module-source-path", src.toString()) .outdir(classes) .files(findJavaFiles(src)) .run(Task.Expect.FAIL) .writeAll() .getOutput(Task.OutputKind.DIRECT); if (!log.contains("Test.java:1:52: compiler.err.not.def.access.class.intf.cant.access.reason: call(), api1.Api1, api1, (compiler.misc.not.def.access.does.not.read: m3x, api1, m1x)") || !log.contains("Test.java:1:76: compiler.err.not.def.access.class.intf.cant.access: toString(), java.lang.Object")) throw new Exception("expected output not found"); }
Example #28
Source File: CompromiseSATest.java From netbeans with Apache License 2.0 | 5 votes |
private void performClassSignatureFromElementTest (final String testClassName) throws Exception { InputStream in = this.prepareData (testClassName); try { JavacTask jt = prepareJavac (); TypeElement be = ElementUtils.getTypeElementByBinaryName(jt, testClassName); assertNotNull ("Javac Error", be); String className = ClassFileUtil.encodeClassName(be); ClassFile cf = new ClassFile (in, true); String expectedName = cf.getName().getInternalName().replace('/','.'); //NOI18N assertEquals (expectedName, className); } finally { in.close (); } }
Example #29
Source File: BadLambdaExpr.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception { JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker, null, null, Arrays.asList(source)); try { ct.parse(); } catch (Throwable ex) { throw new AssertionError("Error thron when parsing the following source:\n" + source.getCharContent(true)); } check(); }
Example #30
Source File: FDTest.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception { JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker, null, null, Arrays.asList(source)); try { ct.analyze(); } catch (Throwable ex) { fail("Error thrown when analyzing the following source:\n" + source.getCharContent(true)); } check(); }