javax.tools.ToolProvider Java Examples
The following examples show how to use
javax.tools.ToolProvider.
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: T6963934.java From TencentKona-8 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 #2
Source File: EagerInterfaceCompletionTest.java From TencentKona-8 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(); int n = 0; for (VersionKind versionKind : VersionKind.values()) { for (HierarchyKind hierarchyKind : HierarchyKind.values()) { for (TestKind testKind : TestKind.values()) { for (ActionKind actionKind : ActionKind.values()) { File testDir = new File(SCRATCH_DIR, "test"+n); new EagerInterfaceCompletionTest(javacTool, testDir, versionKind, hierarchyKind, testKind, actionKind).test(); n++; } } } } if (nerrors > 0) { throw new AssertionError("Some errors have been detected"); } }
Example #3
Source File: PPContextMenuManager.java From PacketProxy with Apache License 2.0 | 6 votes |
private void loadItems() throws Exception { module_list = new ArrayList<PPContextMenu>(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); JavaFileManager fm = compiler.getStandardFileManager(new DiagnosticCollector<JavaFileObject>(), null, null); Set<JavaFileObject.Kind> kind = Sets.newHashSet(JavaFileObject.Kind.CLASS); for (JavaFileObject f : fm.list(StandardLocation.CLASS_PATH, item_package, kind, false)) { Path item_file_path = Paths.get(f.getName()); Path item_file_name = item_file_path.getFileName(); String item_class_path = item_package + "." + item_file_name.toString().replaceAll("\\.class.*$", ""); @SuppressWarnings("rawtypes") Class klass = Class.forName(item_class_path); if(item_class.isAssignableFrom(klass) && !Modifier.isAbstract(klass.getModifiers())){ @SuppressWarnings("unchecked") PPContextMenu ppcm = createInstance(klass); module_list.add(ppcm); } } }
Example #4
Source File: InnerClassCannotBeVerified.java From TencentKona-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 #5
Source File: DetectMutableStaticFields.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
void analyzeResource(URI resource) throws IOException, ConstantPoolException, InvalidDescriptor { JavaCompiler tool = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null); JavaFileManager.Location location = StandardLocation.locationFor(resource.getPath()); fm.setLocation(location, com.sun.tools.javac.util.List.of( new File(resource.getPath()))); for (JavaFileObject file : fm.list(location, "", EnumSet.of(CLASS), true)) { String className = fm.inferBinaryName(location, file); int index = className.lastIndexOf('.'); String pckName = index == -1 ? "" : className.substring(0, index); if (shouldAnalyzePackage(pckName)) { analyzeClassFile(ClassFile.read(file.openInputStream())); } } }
Example #6
Source File: JGroupMain.java From dragonwell8_jdk with GNU General Public License v2.0 | 6 votes |
private String generateInitScript() throws IOException { // load script content ClassLoader loader = ToolProvider.getSystemToolClassLoader(); // JGroupInitializer.sh is in jdk/lib/tools.jar InputStream stream = loader.getResourceAsStream(INITIALIZER_NAME); if (stream == null) { throw new IOException("Cannot load " + INITIALIZER_NAME + " using system classloader"); } File script = File.createTempFile(SCRIPT_PREFIX, ".sh"); script.setExecutable(true); script.setWritable(true); script.deleteOnExit(); // copy content of initializer resource to a temp shell script file OutputStream fos = new FileOutputStream(script); int buf = 0; while ((buf = stream.read()) != -1) { fos.write(buf); } fos.close(); return script.getAbsolutePath(); }
Example #7
Source File: DynamicCompiler.java From Box with Apache License 2.0 | 6 votes |
public boolean compile() { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if (compiler == null) { LOG.error("Can not find compiler, please use JDK instead"); return false; } fileManager = new ClassFileManager(compiler.getStandardFileManager(null, null, null)); List<JavaFileObject> jFiles = new ArrayList<>(clsNodeList.size()); for (ClassNode clsNode : clsNodeList) { jFiles.add(new CharSequenceJavaFileObject(clsNode.getFullName(), clsNode.getCode().toString())); } CompilationTask compilerTask = compiler.getTask(null, fileManager, null, null, null, jFiles); return Boolean.TRUE.equals(compilerTask.call()); }
Example #8
Source File: TestBootNativeLibraryPath.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
static void createTestClass() throws IOException { FileOutputStream fos = new FileOutputStream(TESTFILE + ".java"); PrintStream ps = new PrintStream(fos); ps.println("public class " + TESTFILE + "{"); ps.println("public static void main(String[] args) {\n"); ps.println("System.out.println(System.getProperty(\"sun.boot.library.path\"));\n"); ps.println("}}\n"); ps.close(); fos.close(); JavaCompiler javac = ToolProvider.getSystemJavaCompiler(); String javacOpts[] = {TESTFILE + ".java"}; if (javac.run(null, null, null, javacOpts) != 0) { throw new RuntimeException("compilation of " + TESTFILE + ".java Failed"); } }
Example #9
Source File: T6395981.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
public static void main(String... args) { Tool compiler = ToolProvider.getSystemJavaCompiler(); Set<SourceVersion> expected = EnumSet.noneOf(SourceVersion.class); for (String arg : args) expected.add(SourceVersion.valueOf(arg)); Set<SourceVersion> found = compiler.getSourceVersions(); Set<SourceVersion> notExpected = EnumSet.copyOf(found); for (SourceVersion version : expected) { if (!found.contains(version)) throw new AssertionError("Expected source version not found: " + version); else notExpected.remove(version); } if (!notExpected.isEmpty()) throw new AssertionError("Unexpected source versions: " + notExpected); }
Example #10
Source File: JavacTemplateTestBase.java From TencentKona-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 #11
Source File: GetTask_FileObjectsTest.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
/** * Verify that expected output files are written via the file manager, * for a source file read from the file system with StandardJavaFileManager. */ @Test public void testStandardFileObject() throws Exception { File testSrc = new File(System.getProperty("test.src")); File srcFile = new File(testSrc, "pkg/C.java"); DocumentationTool tool = ToolProvider.getSystemDocumentationTool(); StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null); File outDir = getOutDir(); fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir)); Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(srcFile); DocumentationTask t = tool.getTask(null, fm, null, null, null, files); if (t.call()) { System.err.println("task succeeded"); checkFiles(outDir, standardExpectFiles); } else { throw new Exception("task failed"); } }
Example #12
Source File: BadClassfile.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
private static void test(String classname, String expected) throws Exception { File classfile = new File(System.getProperty("test.classes", "."), classname + ".class"); ClassFile cf = ClassFile.read(classfile); cf = new ClassFile(cf.magic, Target.JDK1_7.minorVersion, Target.JDK1_7.majorVersion, cf.constant_pool, cf.access_flags, cf.this_class, cf.super_class, cf.interfaces, cf.fields, cf.methods, cf.attributes); new ClassWriter().write(cf, classfile); JavaCompiler c = ToolProvider.getSystemJavaCompiler(); JavacTaskImpl task = (JavacTaskImpl) c.getTask(null, null, null, Arrays.asList("-classpath", System.getProperty("test.classes", ".")), null, null); try { Symbol clazz = com.sun.tools.javac.main.JavaCompiler.instance(task.getContext()).resolveIdent(classname); clazz.complete(); } catch (BadClassFile f) { JCDiagnostic embeddedDiag = (JCDiagnostic) f.diag.getArgs()[1]; assertEquals(expected, embeddedDiag.getCode()); assertEquals(Integer.toString(Target.JDK1_7.majorVersion), embeddedDiag.getArgs()[0]); assertEquals(Integer.toString(Target.JDK1_7.minorVersion), embeddedDiag.getArgs()[1]); } }
Example #13
Source File: GetTask_FileObjectsTest.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
/** * Verify bad file object is handled correctly. */ @Test public void testBadFileObject() throws Exception { File testSrc = new File(System.getProperty("test.src")); File srcFile = new File(testSrc, "pkg/C.class"); // unacceptable file kind DocumentationTool tool = ToolProvider.getSystemDocumentationTool(); StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null); File outDir = getOutDir(); fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir)); Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(srcFile); try { DocumentationTask t = tool.getTask(null, fm, null, null, null, files); error("getTask succeeded, no exception thrown"); } catch (IllegalArgumentException e) { System.err.println("exception caught as expected: " + e); } }
Example #14
Source File: GetTask_OptionsTest.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
/** * Verify null is handled correctly. */ @Test public void testNull() throws Exception { JavaFileObject srcFile = createSimpleJavaFileObject(); DocumentationTool tool = ToolProvider.getSystemDocumentationTool(); StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null); File outDir = getOutDir(); fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir)); Iterable<String> options = Arrays.asList((String) null); Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile); try { DocumentationTask t = tool.getTask(null, fm, null, null, options, files); error("getTask succeeded, no exception thrown"); } catch (NullPointerException e) { System.err.println("exception caught as expected: " + e); } }
Example #15
Source File: GetTask_DocletClassTest.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
/** * Verify that an alternate doclet can be specified. * * There is no standard interface or superclass for a doclet; * the only requirement is that it provides static methods that * can be invoked via reflection. So, for now, the doclet is * specified as a class. * Because we cannot create and use a unique instance of the class, * we verify that the doclet has been called by having it record * (in a static field!) the comment from the last time it was invoked, * which is randomly generated each time the test is run. */ @Test public void testDoclet() throws Exception { Random r = new Random(); int key = r.nextInt(); JavaFileObject srcFile = createSimpleJavaFileObject( "pkg/C", "package pkg; /** " + key + "*/ public class C { }"); DocumentationTool tool = ToolProvider.getSystemDocumentationTool(); StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null); File outDir = getOutDir(); fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir)); Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile); DocumentationTask t = tool.getTask(null, fm, null, TestDoclet.class, null, files); if (t.call()) { System.err.println("task succeeded"); if (TestDoclet.lastCaller.equals(String.valueOf(key))) System.err.println("found expected key: " + key); else error("Expected key not found"); checkFiles(outDir, Collections.<String>emptySet()); } else { throw new Exception("task failed"); } }
Example #16
Source File: GetTask_DocletClassTest.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
/** * Verify that exceptions from a doclet are thrown as expected. */ @Test public void testBadDoclet() throws Exception { JavaFileObject srcFile = createSimpleJavaFileObject(); DocumentationTool tool = ToolProvider.getSystemDocumentationTool(); StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null); File outDir = getOutDir(); fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir)); Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile); DocumentationTask t = tool.getTask(null, fm, null, BadDoclet.class, null, files); try { t.call(); error("call completed without exception"); } catch (RuntimeException e) { Throwable c = e.getCause(); if (c.getClass() == UnexpectedError.class) System.err.println("exception caught as expected: " + c); else throw e; } }
Example #17
Source File: GetTask_FileManagerTest.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
/** * Verify that an alternate file manager can be specified: * in this case, a PathFileManager. */ @Test public void testFileManager() throws Exception { JavaFileObject srcFile = createSimpleJavaFileObject(); DocumentationTool tool = ToolProvider.getSystemDocumentationTool(); PathFileManager fm = new JavacPathFileManager(new Context(), false, null); Path outDir = getOutDir().toPath(); fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir)); Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile); DocumentationTask t = tool.getTask(null, fm, null, null, null, files); if (t.call()) { System.err.println("task succeeded"); checkFiles(outDir, standardExpectFiles); } else { throw new Exception("task failed"); } }
Example #18
Source File: IgnoreIgnorableCharactersInInput.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
void run() throws Exception { JavaCompiler comp = ToolProvider.getSystemJavaCompiler(); File classesDir = new File(System.getProperty("user.dir"), "classes"); classesDir.mkdirs(); JavaSource[] sources = new JavaSource[]{ new JavaSource("TestOneIgnorableChar", "AA\\u0000BB"), new JavaSource("TestMultipleIgnorableChar", "AA\\u0000\\u0000\\u0000BB")}; JavacTask ct = (JavacTask)comp.getTask(null, null, null, Arrays.asList("-d", classesDir.getPath()), null, Arrays.asList(sources)); try { if (!ct.call()) { throw new AssertionError("Error thrown when compiling test cases"); } } catch (Throwable ex) { throw new AssertionError("Error thrown when compiling test cases"); } check(classesDir, "TestOneIgnorableChar.class", "TestOneIgnorableChar$AABB.class", "TestMultipleIgnorableChar.class", "TestMultipleIgnorableChar$AABB.class"); if (errors > 0) throw new AssertionError("There are some errors in the test check the error output"); }
Example #19
Source File: GetTask_WriterTest.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
/** * Verify that a writer can be provided. */ @Test public void testWriter() throws Exception { JavaFileObject srcFile = createSimpleJavaFileObject(); DocumentationTool tool = ToolProvider.getSystemDocumentationTool(); StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null); File outDir = getOutDir(); fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir)); Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); DocumentationTask t = tool.getTask(pw, fm, null, null, null, files); if (t.call()) { System.err.println("task succeeded"); checkFiles(outDir, standardExpectFiles); String out = sw.toString(); System.err.println(">>" + out + "<<"); for (String f: standardExpectFiles) { String f1 = f.replace('/', File.separatorChar); if (f1.endsWith(".html") && !out.contains(f1)) throw new Exception("expected string not found: " + f1); } } else { throw new Exception("task failed"); } }
Example #20
Source File: BadLambdaExpr.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
public static void main(String... args) throws Exception { //create default shared JavaCompiler - reused across multiple compilations JavaCompiler comp = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null); for (ParameterListKind plk : ParameterListKind.values()) { for (ParameterKind pk : ParameterKind.values()) { for (ArrowKind ak : ArrowKind.values()) { for (ExprKind ek : ExprKind.values()) { new BadLambdaExpr(plk, pk, ak, ek).run(comp, fm); } } } } System.out.println("Total check executed: " + checkCount); }
Example #21
Source File: DuplicateConstantPoolEntry.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
void generateFilesNeeded() throws Exception { StringJavaFileObject[] CSource = new StringJavaFileObject[] { new StringJavaFileObject("C.java", "class C {C(String s) {}}"), }; List<StringJavaFileObject> AandBSource = Arrays.asList( new StringJavaFileObject("A.java", "class A {void test() {new B(null);new C(null);}}"), new StringJavaFileObject("B.java", "class B {B(String s) {}}") ); final JavaCompiler tool = ToolProvider.getSystemJavaCompiler(); JavacTask compileC = (JavacTask)tool.getTask(null, null, null, null, null, Arrays.asList(CSource)); if (!compileC.call()) { throw new AssertionError("Compilation error while compiling C.java sources"); } JavacTask compileAB = (JavacTask)tool.getTask(null, null, null, Arrays.asList("-cp", "."), null, AandBSource); if (!compileAB.call()) { throw new AssertionError("Compilation error while compiling A and B sources"); } }
Example #22
Source File: TestCompileJARInClassPath.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
void compileWithJSR199() throws IOException { String cpath = "C2.jar"; File clientJarFile = new File(cpath); File sourceFileToCompile = new File("C3.java"); javax.tools.JavaCompiler javac = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>(); StandardJavaFileManager stdFileManager = javac.getStandardFileManager(diagnostics, null, null); List<File> files = new ArrayList<>(); files.add(clientJarFile); stdFileManager.setLocation(StandardLocation.CLASS_PATH, files); Iterable<? extends JavaFileObject> sourceFiles = stdFileManager.getJavaFileObjects(sourceFileToCompile); if (!javac.getTask(null, stdFileManager, diagnostics, null, null, sourceFiles).call()) { throw new AssertionError("compilation failed"); } }
Example #23
Source File: TestDefaultMethodsSyntax.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
public static void main(String... args) throws Exception { //create default shared JavaCompiler - reused across multiple compilations JavaCompiler comp = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null); for (VersionKind vk : VersionKind.values()) { for (EnclosingKind ek : EnclosingKind.values()) { for (MethodKind mk : MethodKind.values()) { for (ModifierKind modk1 : ModifierKind.values()) { for (ModifierKind modk2 : ModifierKind.values()) { new TestDefaultMethodsSyntax(vk, ek, mk, modk1, modk2).run(comp, fm); } } } } } System.out.println("Total check executed: " + checkCount); }
Example #24
Source File: T7068437.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
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()); }
Example #25
Source File: T7086601b.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
public static void main(String... args) throws Exception { //create default shared JavaCompiler - reused across multiple compilations JavaCompiler comp = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null); for (TypeKind a1 : TypeKind.values()) { for (TypeKind a2 : TypeKind.values()) { for (TypeKind a3 : TypeKind.values()) { for (MethodCallKind mck : MethodCallKind.values()) { new T7086601b(a1, a2, a3, mck).run(comp, fm); } } } } System.out.println("Total check executed: " + checkCount); }
Example #26
Source File: GenericConstructorAndDiamondTest.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
public static void main(String... args) throws Exception { //create default shared JavaCompiler - reused across multiple compilations JavaCompiler comp = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null); for (BoundKind boundKind : BoundKind.values()) { for (ConstructorKind constructorKind : ConstructorKind.values()) { for (TypeArgumentKind declArgKind : TypeArgumentKind.values()) { for (TypeArgArity arity : TypeArgArity.values()) { for (TypeArgumentKind useArgKind : TypeArgumentKind.values()) { for (TypeArgumentKind diamondArgKind : TypeArgumentKind.values()) { for (ArgumentKind argKind : ArgumentKind.values()) { new GenericConstructorAndDiamondTest(boundKind, constructorKind, declArgKind, arity, useArgKind, diamondArgKind, argKind).run(comp, fm); } } } } } } } }
Example #27
Source File: T6557752.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws IOException { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); task = (JavacTask) compiler.getTask(null, null, null, null, null, List.of(new MyFileObject())); Iterable<? extends CompilationUnitTree> asts = task.parse(); task.analyze(); trees = Trees.instance(task); MyVisitor myVisitor = new MyVisitor(); for (CompilationUnitTree ast : asts) { myVisitor.compilationUnit = ast; myVisitor.scan(ast, null); } if (!myVisitor.foundError) { throw new AssertionError("Expected error not found!"); } }
Example #28
Source File: SimpleServiceTest.java From grpc-nebula-java with Apache License 2.0 | 6 votes |
@Test public void testRpcMethodAnnotations() throws Exception { File grpcJavaFile = new File("./src/generated/main/grpc/io/grpc/testing/protobuf/SimpleServiceGrpc.java"); Assume.assumeTrue(grpcJavaFile.exists()); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); AnnotationProcessor processor = new AnnotationProcessor(); Iterable<? extends JavaFileObject> obs = fileManager.getJavaFileObjects(grpcJavaFile); CompilationTask task = compiler.getTask( null, fileManager, null, Collections.singleton("-proc:only"), Collections.singleton(SimpleServiceGrpc.class.getCanonicalName()), obs); task.setProcessors(Collections.singleton(processor)); assertTrue(task.call()); assertTrue(processor.processedClass); fileManager.close(); }
Example #29
Source File: TestMetafactoryBridges.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
public static void main(String... args) throws Exception { String SCRATCH_DIR = System.getProperty("user.dir"); //create default shared JavaCompiler - reused across multiple compilations JavaCompiler comp = ToolProvider.getSystemJavaCompiler(); int n = 0; for (SourceSet ss : SourceSet.values()) { for (List<ClassKind> sources : ss.permutations()) { for (SourcepathKind spKind : SourcepathKind.values()) { for (ClasspathKind cpKind : ClasspathKind.values()) { for (PreferPolicy pp : PreferPolicy.values()) { Set<ClassKind> deps = EnumSet.noneOf(ClassKind.class); if (cpKind.ck != null) { deps.add(cpKind.ck); } deps.addAll(sources); if (deps.size() < 3) continue; File testDir = new File(SCRATCH_DIR, "test" + n); testDir.mkdir(); try (PrintWriter debugWriter = new PrintWriter(new File(testDir, "debug.txt"))) { new TestMetafactoryBridges(testDir, sources, spKind, cpKind, pp, debugWriter).run(comp); n++; } } } } } } System.out.println("Total check executed: " + checkCount); }
Example #30
Source File: T6402077.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
public static void main(String... args) throws IOException { class MyFileObject extends SimpleJavaFileObject { MyFileObject() { super(URI.create("myfo:///Test.java"), SOURCE); } @Override public String getCharContent(boolean ignoreEncodingErrors) { // 0 1 2 // 0123456789012345678901234 return "class Test { Test() { } }"; } } JavaCompiler javac = ToolProvider.getSystemJavaCompiler(); List<JavaFileObject> compilationUnits = Collections.<JavaFileObject>singletonList(new MyFileObject()); JavacTask task = (JavacTask)javac.getTask(null, null, null, null, null, compilationUnits); Trees trees = Trees.instance(task); CompilationUnitTree toplevel = task.parse().iterator().next(); Tree tree = ((ClassTree)toplevel.getTypeDecls().get(0)).getMembers().get(0); long pos = trees.getSourcePositions().getStartPosition(toplevel, tree); if (pos != 13) throw new AssertionError(String.format("Start pos for %s is incorrect (%s)!", tree, pos)); pos = trees.getSourcePositions().getEndPosition(toplevel, tree); if (pos != 23) throw new AssertionError(String.format("End pos for %s is incorrect (%s)!", tree, pos)); }