Here are the examples of the java api class javax.tools.JavaFileObject taken from open source projects.
1. TestBuilderTest#testUniqueNames()
Project: FreeBuilder
File: TestBuilderTest.java
File: TestBuilderTest.java
@Test public void testUniqueNames() throws IOException { JavaFileObject source1 = new TestBuilder().build(); assertEquals("org.inferred.freebuilder.processor.util.testing.generatedcode.TestBuilderTest", getTypeNameFromSource(source1.getCharContent(false))); JavaFileObject source2 = new TestBuilder().build(); assertEquals("org.inferred.freebuilder.processor.util.testing.generatedcode.TestBuilderTest__2", getTypeNameFromSource(source2.getCharContent(false))); source1 = null; JavaFileObject source3 = new TestBuilder().build(); assertEquals("org.inferred.freebuilder.processor.util.testing.generatedcode.TestBuilderTest", getTypeNameFromSource(source3.getCharContent(false))); JavaFileObject source4 = new TestBuilder().build(); assertEquals("org.inferred.freebuilder.processor.util.testing.generatedcode.TestBuilderTest__3", getTypeNameFromSource(source4.getCharContent(false))); }
2. JavaInMemoryFileManagerTest#testIsSameFile()
Project: buck
File: JavaInMemoryFileManagerTest.java
File: JavaInMemoryFileManagerTest.java
@Test public void testIsSameFile() throws Exception { JavaFileObject fileObject1 = inMemoryFileManager.getJavaFileForOutput(locationOf("src"), "jvm.java.JavaFileParser", JavaFileObject.Kind.CLASS, null); JavaFileObject fileObject2 = inMemoryFileManager.getJavaFileForOutput(locationOf("src"), "jvm.java.JavaFileParser", JavaFileObject.Kind.CLASS, null); assertTrue(inMemoryFileManager.isSameFile(fileObject1, fileObject2)); }
3. JavaInMemoryFileManagerTest#testIsNotSameFile()
Project: buck
File: JavaInMemoryFileManagerTest.java
File: JavaInMemoryFileManagerTest.java
@Test public void testIsNotSameFile() throws Exception { JavaFileObject fileObject1 = inMemoryFileManager.getJavaFileForOutput(locationOf("src"), "jvm.java.JavaFileParser", JavaFileObject.Kind.CLASS, null); JavaFileObject fileObject2 = inMemoryFileManager.getJavaFileForOutput(locationOf("src"), "jvm.java.JavaInMemoryFileManager", JavaFileObject.Kind.CLASS, null); assertFalse(inMemoryFileManager.isSameFile(fileObject1, fileObject2)); }
4. JavaInMemoryFileManagerTest#testMultipleFilesInSamePackage()
Project: buck
File: JavaInMemoryFileManagerTest.java
File: JavaInMemoryFileManagerTest.java
@Test public void testMultipleFilesInSamePackage() throws Exception { JavaFileObject fileObject1 = inMemoryFileManager.getJavaFileForOutput(locationOf("src"), "jvm.java.JavaFileParser", JavaFileObject.Kind.CLASS, null); JavaFileObject fileObject2 = inMemoryFileManager.getJavaFileForOutput(locationOf("src"), "jvm.java.JavaInMemoryFileManager", JavaFileObject.Kind.CLASS, null); fileObject1.openOutputStream().close(); fileObject2.openOutputStream().close(); List<ZipEntry> zipEntries = outputStream.getZipEntries(); assertEquals(4, zipEntries.size()); assertEquals("jvm/", zipEntries.get(0).getName()); assertEquals("jvm/java/", zipEntries.get(1).getName()); assertEquals("jvm/java/JavaFileParser.class", zipEntries.get(2).getName()); assertEquals("jvm/java/JavaInMemoryFileManager.class", zipEntries.get(3).getName()); }
5. LibraryModuleTest#injectsOfClassMakesProvidesBindingNotAnOrphan()
Project: dagger
File: LibraryModuleTest.java
File: LibraryModuleTest.java
@Test public void injectsOfClassMakesProvidesBindingNotAnOrphan() { JavaFileObject foo = JavaFileObjects.forSourceString("Foo", "class Foo {}"); JavaFileObject module = JavaFileObjects.forSourceString("TestModule", "" + "import dagger.Module;\n" + "import dagger.Provides;\n" + "import javax.inject.Singleton;\n" + "@Module(injects = Foo.class, library = false)\n" + "class TestModule {\n" + " @Singleton @Provides Foo provideFoo() {\n" + " return new Foo() {};\n" + " }\n" + "}\n"); assertAbout(javaSources()).that(Arrays.asList(foo, module)).processedWith(daggerProcessors()).compilesWithoutError(); }
6. LibraryModuleTest#injectsOfInterfaceMakesProvidesBindingNotAnOrphan()
Project: dagger
File: LibraryModuleTest.java
File: LibraryModuleTest.java
@Test public void injectsOfInterfaceMakesProvidesBindingNotAnOrphan() { JavaFileObject foo = JavaFileObjects.forSourceString("Foo", "interface Foo {}"); JavaFileObject module = JavaFileObjects.forSourceString("TestModule", "" + "import dagger.Module;\n" + "import dagger.Provides;\n" + "import javax.inject.Singleton;\n" + "@Module(injects = Foo.class, library = false)\n" + "class TestModule {\n" + " @Singleton @Provides Foo provideFoo() {\n" + " return new Foo() {};\n" + " }\n" + "}\n"); assertAbout(javaSources()).that(Arrays.asList(foo, module)).processedWith(daggerProcessors()).compilesWithoutError(); }
7. GeneratedTypesNotReadyTest#withstandsMissingTypeReferencedInTransitiveJITDependency()
Project: dagger
File: GeneratedTypesNotReadyTest.java
File: GeneratedTypesNotReadyTest.java
@Test public void withstandsMissingTypeReferencedInTransitiveJITDependency() { JavaFileObject main = JavaFileObjects.forSourceString("Main", "" + "import javax.inject.Inject;\n" + "import myPackage.FooImpl;\n" + "class Main {\n" + " @Inject FooImpl f;\n" + "}\n"); JavaFileObject module = JavaFileObjects.forSourceString("FooModule", "" + "import dagger.Module;\n" + "import dagger.Provides;\n" + "@Module(injects = { Main.class })\n" + "class FooModule {\n" + "}\n"); assertAbout(javaSources()).that(asList(foo, module, main)).processedWith(concat(daggerProcessors(), asList(new FooImplGenerator()))).compilesWithoutError(); }
8. GeneratedTypesNotReadyTest#withstandsMissingTypeReferencedByProvidesReturnType()
Project: dagger
File: GeneratedTypesNotReadyTest.java
File: GeneratedTypesNotReadyTest.java
@Test public void withstandsMissingTypeReferencedByProvidesReturnType() { JavaFileObject main = JavaFileObjects.forSourceString("Main", "" + "import javax.inject.Inject;\n" + "class Main {\n" + " @Inject myPackage.FooImpl f;\n" + "}\n"); JavaFileObject module = JavaFileObjects.forSourceString("FooModule", "" + "import dagger.Module;\n" + "import dagger.Provides;\n" + "@Module(injects = { Main.class })\n" + "class FooModule {\n" + " @Provides myPackage.FooImpl provideFoo() {\n" + " return new myPackage.FooImpl();\n" + " }\n" + "}\n"); assertAbout(javaSources()).that(asList(foo, module, main)).processedWith(concat(daggerProcessors(), asList(new FooImplGenerator()))).compilesWithoutError(); }
9. JavaSourcesSubjectFactoryTest#failsToCompile()
Project: compile-testing
File: JavaSourcesSubjectFactoryTest.java
File: JavaSourcesSubjectFactoryTest.java
@Test public void failsToCompile() { JavaFileObject brokenFileObject = JavaFileObjects.forResource("HelloWorld-broken.java"); assertAbout(javaSource()).that(brokenFileObject).failsToCompile().withErrorContaining("not a statement").in(brokenFileObject).onLine(23).atColumn(5).and().withErrorCount(4); JavaFileObject happyFileObject = JavaFileObjects.forResource("HelloWorld.java"); assertAbout(javaSource()).that(happyFileObject).processedWith(new ErrorProcessor()).failsToCompile().withErrorContaining("expected error!").in(happyFileObject).onLine(18).atColumn(8); }
10. JavaSourcesSubjectFactoryTest#failsToCompile_throwsNotInFile()
Project: compile-testing
File: JavaSourcesSubjectFactoryTest.java
File: JavaSourcesSubjectFactoryTest.java
@Test public void failsToCompile_throwsNotInFile() { JavaFileObject fileObject = JavaFileObjects.forResource("HelloWorld.java"); JavaFileObject otherFileObject = JavaFileObjects.forResource("HelloWorld-different.java"); try { VERIFY.about(javaSource()).that(fileObject).processedWith(new ErrorProcessor()).failsToCompile().withErrorContaining("expected error!").in(otherFileObject); fail(); } catch (VerificationException expected) { assertThat(expected.getMessage()).contains(String.format("Expected an error in %s", otherFileObject.getName())); assertThat(expected.getMessage()).contains(fileObject.getName()); } }
11. PropertyAnnotationsTest#assertGeneratedMatches()
Project: auto
File: PropertyAnnotationsTest.java
File: PropertyAnnotationsTest.java
private void assertGeneratedMatches(List<String> imports, List<String> annotations, List<String> expectedAnnotations) { JavaFileObject javaFileObject = sourceCode(imports, annotations); JavaFileObject expectedOutput = expectedCode(imports, expectedAnnotations); assertAbout(javaSource()).that(javaFileObject).processedWith(new AutoValueProcessor()).compilesWithoutError().and().generatesSources(expectedOutput); }
12. BasicAnnotationProcessorTest#properlyDefersProcessing_rejectsElement()
Project: auto
File: BasicAnnotationProcessorTest.java
File: BasicAnnotationProcessorTest.java
@Test public void properlyDefersProcessing_rejectsElement() { JavaFileObject classAFileObject = JavaFileObjects.forSourceLines("test.ClassA", "package test;", "", "@" + RequiresGeneratedCode.class.getCanonicalName(), "public class ClassA {}"); JavaFileObject classBFileObject = JavaFileObjects.forSourceLines("test.ClassB", "package test;", "", "@" + GeneratesCode.class.getCanonicalName(), "public class ClassB {}"); RequiresGeneratedCodeProcessor requiresGeneratedCodeProcessor = new RequiresGeneratedCodeProcessor(); assertAbout(javaSources()).that(ImmutableList.of(classAFileObject, classBFileObject)).processedWith(requiresGeneratedCodeProcessor, new GeneratesCodeProcessor()).compilesWithoutError().and().generatesFileNamed(SOURCE_OUTPUT, "test", "GeneratedByRequiresGeneratedCodeProcessor.java"); assertThat(requiresGeneratedCodeProcessor.rejectedRounds).isEqualTo(1); }
13. BasicAnnotationProcessorTest#properlyDefersProcessing_packageElement()
Project: auto
File: BasicAnnotationProcessorTest.java
File: BasicAnnotationProcessorTest.java
@Test public void properlyDefersProcessing_packageElement() { JavaFileObject classAFileObject = JavaFileObjects.forSourceLines("test.ClassA", "package test;", "", "@" + GeneratesCode.class.getCanonicalName(), "public class ClassA {", "}"); JavaFileObject packageFileObject = JavaFileObjects.forSourceLines("test.package-info", "@" + RequiresGeneratedCode.class.getCanonicalName(), "@" + ReferencesAClass.class.getCanonicalName() + "(SomeGeneratedClass.class)", "package test;"); RequiresGeneratedCodeProcessor requiresGeneratedCodeProcessor = new RequiresGeneratedCodeProcessor(); assertAbout(javaSources()).that(ImmutableList.of(classAFileObject, packageFileObject)).processedWith(requiresGeneratedCodeProcessor, new GeneratesCodeProcessor()).compilesWithoutError().and().generatesFileNamed(SOURCE_OUTPUT, "test", "GeneratedByRequiresGeneratedCodeProcessor.java"); assertThat(requiresGeneratedCodeProcessor.rejectedRounds).isEqualTo(0); }
14. BasicAnnotationProcessorTest#properlyDefersProcessing_typeElement()
Project: auto
File: BasicAnnotationProcessorTest.java
File: BasicAnnotationProcessorTest.java
@Test public void properlyDefersProcessing_typeElement() { JavaFileObject classAFileObject = JavaFileObjects.forSourceLines("test.ClassA", "package test;", "", "@" + RequiresGeneratedCode.class.getCanonicalName(), "public class ClassA {", " SomeGeneratedClass sgc;", "}"); JavaFileObject classBFileObject = JavaFileObjects.forSourceLines("test.ClassB", "package test;", "", "@" + GeneratesCode.class.getCanonicalName(), "public class ClassB {}"); RequiresGeneratedCodeProcessor requiresGeneratedCodeProcessor = new RequiresGeneratedCodeProcessor(); assertAbout(javaSources()).that(ImmutableList.of(classAFileObject, classBFileObject)).processedWith(requiresGeneratedCodeProcessor, new GeneratesCodeProcessor()).compilesWithoutError().and().generatesFileNamed(SOURCE_OUTPUT, "test", "GeneratedByRequiresGeneratedCodeProcessor.java"); assertThat(requiresGeneratedCodeProcessor.rejectedRounds).isEqualTo(0); }
15. PropertyAnnotationsTest#assertGeneratedMatches()
Project: RetroFacebook
File: PropertyAnnotationsTest.java
File: PropertyAnnotationsTest.java
private void assertGeneratedMatches(List<String> imports, List<String> annotations, List<String> expectedAnnotations) { JavaFileObject javaFileObject = sourceCode(imports, annotations); JavaFileObject expectedOutput = expectedCode(expectedAnnotations); assert_().about(javaSource()).that(javaFileObject).processedWith(new RetroFacebookProcessor()).compilesWithoutError().and().generatesSources(expectedOutput); }
16. PropertyAnnotationsTest#assertGeneratedMatches()
Project: RetroFacebook
File: PropertyAnnotationsTest.java
File: PropertyAnnotationsTest.java
private void assertGeneratedMatches(List<String> imports, List<String> annotations, List<String> expectedAnnotations) { JavaFileObject javaFileObject = sourceCode(imports, annotations); JavaFileObject expectedOutput = expectedCode(expectedAnnotations); assert_().about(javaSource()).that(javaFileObject).processedWith(new RetroFacebookProcessor()).compilesWithoutError().and().generatesSources(expectedOutput); }
17. DetectMutableStaticFields#analyzeModule()
Project: openjdk
File: DetectMutableStaticFields.java
File: DetectMutableStaticFields.java
void analyzeModule(StandardJavaFileManager fm, String moduleName) throws IOException, ConstantPoolException, InvalidDescriptor { JavaFileManager.Location location = fm.getModuleLocation(StandardLocation.SYSTEM_MODULES, moduleName); if (location == null) throw new AssertionError("can't find module " + moduleName); 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())); } } }
18. ProfileOptionTest#testInvalidProfile_API()
Project: openjdk
File: ProfileOptionTest.java
File: ProfileOptionTest.java
// ---------- Test cases, invoked reflectively via run. ---------- @Test void testInvalidProfile_API() throws Exception { JavaFileObject fo = new StringJavaFileObject("Test.java", "class Test { }"); String badName = "foo"; List<String> opts = Arrays.asList("-profile", badName); StringWriter sw = new StringWriter(); try { JavacTask task = (JavacTask) javac.getTask(sw, fm, null, opts, null, Arrays.asList(fo)); throw new Exception("expected exception not thrown"); } catch (IllegalArgumentException e) { } }
19. T4910483#main()
Project: openjdk
File: T4910483.java
File: T4910483.java
public static void main(String... args) { JavaCompiler compiler = JavaCompiler.instance(new Context()); compiler.keepComments = true; String testSrc = System.getProperty("test.src"); JavacFileManager fm = new JavacFileManager(new Context(), false, null); JavaFileObject f = fm.getJavaFileObject(testSrc + File.separatorChar + "T4910483.java"); JCTree.JCCompilationUnit cu = compiler.parse(f); JCTree classDef = cu.getTypeDecls().head; String commentText = cu.docComments.getCommentText(classDef); // 4 '\' escapes to 2 in a string literal String expected = "Test comment abc*\\\\def"; if (!expected.equals(commentText)) { throw new AssertionError("Incorrect comment text: [" + commentText + "], expected [" + expected + "]"); } }
20. TestSearchPaths#callTask()
Project: openjdk
File: TestSearchPaths.java
File: TestSearchPaths.java
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"); }
21. SJFM_IsSameFile#test_isSameFile()
Project: openjdk
File: SJFM_IsSameFile.java
File: SJFM_IsSameFile.java
/** * Tests the isSameFile method for a specific file manager * and a series of paths. * * Note: instances of MyStandardJavaFileManager only support * encapsulating paths for files in the default file system. * * @param fm the file manager to be tested * @param paths a generator for the paths to be tested * @throws IOException */ void test_isSameFile(StandardJavaFileManager fm, Callable<List<Path>> paths) throws Exception { if (!isGetFileObjectsSupported(fm, paths.call())) return; // use distinct paths and file objects in the following two sets Iterable<? extends JavaFileObject> setA = fm.getJavaFileObjectsFromPaths(paths.call()); Iterable<? extends JavaFileObject> setB = fm.getJavaFileObjectsFromPaths(paths.call()); for (JavaFileObject a : setA) { for (JavaFileObject b : setB) { System.err.println("compare: a: " + a); System.err.println(" b: " + b); // Use the fileObject getName method to determine the expected result. // For the files being tested, getName is the absolute path. boolean expect = a.getName().equals(b.getName()); boolean actual = fm.isSameFile(a, b); if (actual != expect) { error("mismatch: actual:" + (actual ? "same" : "not same") + ", expect:" + (expect ? "same" : "not same")); } } } }
22. SJFM_AsPath#test_asPath()
Project: openjdk
File: SJFM_AsPath.java
File: SJFM_AsPath.java
/** * Tests the asPath method for a specific file manager and a series * of paths. * * Note: instances of MyStandardJavaFileManager only support * encapsulating paths for files in the default file system, * and throw UnsupportedOperationException for asPath. * * @param fm the file manager to be tested * @param paths the paths to be tested * @throws IOException */ void test_asPath(StandardJavaFileManager fm, List<Path> paths) throws IOException { if (!isGetFileObjectsSupported(fm, paths)) return; boolean expectException = (fm instanceof MyStandardJavaFileManager); Set<Path> ref = new HashSet<>(paths); for (JavaFileObject fo : fm.getJavaFileObjectsFromPaths(paths)) { try { Path path = fm.asPath(fo); if (expectException) error("expected exception not thrown: " + UnsupportedOperationException.class.getName()); boolean found = ref.remove(path); if (!found) { error("Unexpected path found: " + path + "; expected one of " + ref); } } catch (Exception e) { if (expectException && e instanceof UnsupportedOperationException) continue; error("unexpected exception thrown: " + e); } } }
23. T6852595#main()
Project: openjdk
File: T6852595.java
File: T6852595.java
public static void main(String[] args) throws IOException { JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"), Kind.SOURCE) { public CharSequence getCharContent(boolean ignoreEncodingErrors) { return "class BadName { Object o = j; }"; } }; List<? extends JavaFileObject> files = Arrays.asList(sfo); JavaCompiler tool = ToolProvider.getSystemJavaCompiler(); JavacTask ct = (JavacTask) tool.getTask(null, null, null, null, null, files); Iterable<? extends CompilationUnitTree> compUnits = ct.parse(); CompilationUnitTree cu = compUnits.iterator().next(); ClassTree cdef = (ClassTree) cu.getTypeDecls().get(0); JCVariableDecl vdef = (JCVariableDecl) cdef.getMembers().get(0); TreePath path = TreePath.getPath(cu, vdef.init); Trees.instance(ct).getScope(path); }
24. T6733837#exec()
Project: openjdk
File: T6733837.java
File: T6733837.java
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"); }
25. T6608214#main()
Project: openjdk
File: T6608214.java
File: T6608214.java
public static void main(String[] args) throws IOException { JavaFileObject sfo = new SimpleJavaFileObject(URI.create(""), Kind.SOURCE) { public CharSequence getCharContent(boolean ignoreEncodingErrors) { return "class Test<S> { <T extends S & Runnable> void test(){}}"; } }; List<? extends JavaFileObject> files = Arrays.asList(sfo); List<String> opts = Arrays.asList("-Xjcov"); JavaCompiler tool = ToolProvider.getSystemJavaCompiler(); JavacTask ct = (JavacTask) tool.getTask(null, null, null, opts, null, files); ct.analyze(); }
26. ReflectionTest#printTestSrc()
Project: openjdk
File: ReflectionTest.java
File: ReflectionTest.java
private static void printTestSrc(Iterable<? extends JavaFileObject> files) { for (JavaFileObject f : files) { System.out.println("Test file " + f.getName() + ":"); try { System.out.println("" + f.getCharContent(true)); } catch (IOException e) { throw new RuntimeException("Exception when printing test src contents for class " + f.getName(), e); } } }
27. Helper#compileCode()
Project: openjdk
File: Helper.java
File: Helper.java
// Create and compile FileObject using values for className and contents public static boolean compileCode(String className, String contents, DiagnosticCollector<JavaFileObject> diagnostics) { boolean ok = false; JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if (compiler == null) { throw new RuntimeException("can't get javax.tools.JavaCompiler!"); } JavaFileObject file = getFile(className, contents); Iterable<? extends JavaFileObject> compilationUnit = Arrays.asList(file); CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnit); ok = task.call(); return ok; }
28. Task_reuseTest#getAndRunTask()
Project: openjdk
File: Task_reuseTest.java
File: Task_reuseTest.java
private DocumentationTask getAndRunTask() throws Exception { JavaFileObject srcFile = createSimpleJavaFileObject(); DocumentationTool tool = ToolProvider.getSystemDocumentationTool(); try (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, null, null, files); if (t.call()) { System.err.println("task succeeded"); return t; } else { throw new Exception("task failed"); } } }
29. JavadocTaskImplTest#testDirectAccess2()
Project: openjdk
File: JavadocTaskImplTest.java
File: JavadocTaskImplTest.java
@Test public void testDirectAccess2() throws Exception { // error, provokes NPE JavaFileObject srcFile = null; Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile); Context c = new Context(); Messager.preRegister(c, "javadoc"); try (StandardJavaFileManager fm = new JavacFileManager(c, true, null)) { File outDir = getOutDir(); fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir)); try { DocumentationTask t = new JavadocTaskImpl(c, null, null, files); ; error("getTask succeeded, no exception thrown"); } catch (NullPointerException e) { System.err.println("exception caught as expected: " + e); } } }
30. JavadocTaskImplTest#testDirectAccess1()
Project: openjdk
File: JavadocTaskImplTest.java
File: JavadocTaskImplTest.java
@Test public void testDirectAccess1() throws Exception { JavaFileObject srcFile = createSimpleJavaFileObject(); Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile); Context c = new Context(); Messager.preRegister(c, "javadoc"); try (StandardJavaFileManager fm = new JavacFileManager(c, true, null)) { File outDir = getOutDir(); fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir)); DocumentationTask t = new JavadocTaskImpl(c, null, null, files); if (t.call()) { System.err.println("task succeeded"); } else { throw new Exception("task failed"); } } }
31. JavadocTaskImplTest#testRawCall()
Project: openjdk
File: JavadocTaskImplTest.java
File: JavadocTaskImplTest.java
@Test public void testRawCall() throws Exception { JavaFileObject srcFile = createSimpleJavaFileObject(); DocumentationTool tool = ToolProvider.getSystemDocumentationTool(); try (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); @SuppressWarnings("rawtypes") Callable t = tool.getTask(null, fm, null, null, null, files); if (t.call() == Boolean.TRUE) { System.err.println("task succeeded"); } else { throw new Exception("task failed"); } } }
32. GetTask_OptionsTest#testNull()
Project: openjdk
File: GetTask_OptionsTest.java
File: GetTask_OptionsTest.java
/** * Verify null is handled correctly. */ @Test public void testNull() throws Exception { JavaFileObject srcFile = createSimpleJavaFileObject(); DocumentationTool tool = ToolProvider.getSystemDocumentationTool(); try (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); } } }
33. GetTask_OptionsTest#testNoIndex()
Project: openjdk
File: GetTask_OptionsTest.java
File: GetTask_OptionsTest.java
/** * Verify that expected output files are written for given options. */ @Test public void testNoIndex() throws Exception { JavaFileObject srcFile = createSimpleJavaFileObject(); DocumentationTool tool = ToolProvider.getSystemDocumentationTool(); try (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); Iterable<String> options = Arrays.asList("-noindex"); DocumentationTask t = tool.getTask(null, fm, null, null, options, files); if (t.call()) { System.err.println("task succeeded"); Set<String> expectFiles = new TreeSet<String>(noIndexFiles); checkFiles(outDir, expectFiles); } else { error("task failed"); } } }
34. GetTask_FileObjectsTest#testMemoryFileObject()
Project: openjdk
File: GetTask_FileObjectsTest.java
File: GetTask_FileObjectsTest.java
/** * Verify that expected output files are written via the file manager, * for an in-memory file object. */ @Test public void testMemoryFileObject() throws Exception { JavaFileObject srcFile = createSimpleJavaFileObject(); DocumentationTool tool = ToolProvider.getSystemDocumentationTool(); try (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, null, null, files); if (t.call()) { System.err.println("task succeeded"); checkFiles(outDir, standardExpectFiles); } else { throw new Exception("task failed"); } } }
35. GetTask_FileManagerTest#testFileManager()
Project: openjdk
File: GetTask_FileManagerTest.java
File: GetTask_FileManagerTest.java
/** * Verify that an alternate file manager can be specified: * in this case, a TestFileManager. */ @Test public void testFileManager() throws Exception { JavaFileObject srcFile = createSimpleJavaFileObject(); DocumentationTool tool = ToolProvider.getSystemDocumentationTool(); StandardJavaFileManager fm = new TestFileManager(); 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, null, Arrays.asList("-verbose"), files); if (t.call()) { System.err.println("task succeeded"); checkFiles(outDir, standardExpectFiles); } else { throw new Exception("task failed"); } }
36. GetTask_DocletClassTest#testBadDoclet()
Project: openjdk
File: GetTask_DocletClassTest.java
File: GetTask_DocletClassTest.java
/** * Verify that exceptions from a doclet are thrown as expected. */ @Test public void testBadDoclet() throws Exception { JavaFileObject srcFile = createSimpleJavaFileObject(); DocumentationTool tool = ToolProvider.getSystemDocumentationTool(); try (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) { e.printStackTrace(); Throwable c = e.getCause(); if (c.getClass() == UnexpectedError.class) System.err.println("exception caught as expected: " + c); else throw e; } } }
37. GetTask_DocletClassTest#testDoclet()
Project: openjdk
File: GetTask_DocletClassTest.java
File: GetTask_DocletClassTest.java
/** * 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(); try (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"); } } }
38. JavacElements#getSourcePosition()
Project: openjdk
File: JavacElements.java
File: JavacElements.java
public JavacSourcePosition getSourcePosition(Element e, AnnotationMirror a) { Pair<JCTree, JCCompilationUnit> treeTop = getTreeAndTopLevel(e); if (treeTop == null) return null; JCTree tree = treeTop.fst; JCCompilationUnit toplevel = treeTop.snd; JavaFileObject sourcefile = toplevel.sourcefile; if (sourcefile == null) return null; JCTree annoTree = matchAnnoToTree(a, e, tree); if (annoTree == null) return null; return new JavacSourcePosition(sourcefile, annoTree.pos, toplevel.lineMap); }
39. JavaCompiler#parseFiles()
Project: openjdk
File: JavaCompiler.java
File: JavaCompiler.java
/** * Parses a list of files. */ public List<JCCompilationUnit> parseFiles(Iterable<JavaFileObject> fileObjects) { if (shouldStop(CompileState.PARSE)) return List.nil(); //parse all files ListBuffer<JCCompilationUnit> trees = new ListBuffer<>(); Set<JavaFileObject> filesSoFar = new HashSet<>(); for (JavaFileObject fileObject : fileObjects) { if (!filesSoFar.contains(fileObject)) { filesSoFar.add(fileObject); trees.append(parse(fileObject)); } } return trees.toList(); }
40. JavaCompiler#printSource()
Project: openjdk
File: JavaCompiler.java
File: JavaCompiler.java
/** Emit plain Java source for a class. * @param env The attribution environment of the outermost class * containing this class. * @param cdef The class definition to be printed. */ JavaFileObject printSource(Env<AttrContext> env, JCClassDecl cdef) throws IOException { JavaFileObject outFile = fileManager.getJavaFileForOutput(CLASS_OUTPUT, cdef.sym.flatname.toString(), JavaFileObject.Kind.SOURCE, null); if (inputFiles.contains(outFile)) { log.error(cdef.pos(), "source.cant.overwrite.input.file", outFile); return null; } else { try (BufferedWriter out = new BufferedWriter(outFile.openWriter())) { new Pretty(out, true).printUnit(env.toplevel, cdef); if (verbose) log.printVerbose("wrote.file", outFile); } return outFile; } }
41. JavaCompiler#resolveIdent()
Project: openjdk
File: JavaCompiler.java
File: JavaCompiler.java
/** Resolve an identifier. * @param msym The module in which the search should be performed * @param name The identifier to resolve */ public Symbol resolveIdent(ModuleSymbol msym, String name) { if (name.equals("")) return syms.errSymbol; JavaFileObject prev = log.useSource(null); try { JCExpression tree = null; for (String s : name.split("\\.", -1)) { if (// TODO: check for keywords !SourceVersion.isIdentifier(s)) return syms.errSymbol; tree = (tree == null) ? make.Ident(names.fromString(s)) : make.Select(tree, names.fromString(s)); } JCCompilationUnit toplevel = make.TopLevel(List.<JCTree>nil()); toplevel.modle = msym; toplevel.packge = msym.unnamedPackage; return attr.attribIdent(tree, toplevel); } finally { log.useSource(prev); } }
42. TypeEnter#finishImports()
Project: openjdk
File: TypeEnter.java
File: TypeEnter.java
void finishImports(JCCompilationUnit toplevel, Runnable resolve) { JavaFileObject prev = log.useSource(toplevel.sourcefile); try { resolve.run(); chk.checkImportsUnique(toplevel); chk.checkImportsResolvable(toplevel); chk.checkImportedPackagesObservable(toplevel); toplevel.namedImportScope.finalizeScope(); toplevel.starImportScope.finalizeScope(); } finally { log.useSource(prev); } }
43. Todo#removeByFile()
Project: openjdk
File: Todo.java
File: Todo.java
private void removeByFile(Env<AttrContext> env) { JavaFileObject file = env.toplevel.sourcefile; FileQueue fq = fileMap.get(file); if (fq == null) return; if (fq.fileContents.remove(env)) { if (fq.isEmpty()) { fileMap.remove(file); contentsByFile.remove(fq); } } }
44. Todo#addByFile()
Project: openjdk
File: Todo.java
File: Todo.java
private void addByFile(Env<AttrContext> env) { JavaFileObject file = env.toplevel.sourcefile; if (fileMap == null) fileMap = new HashMap<>(); FileQueue fq = fileMap.get(file); if (fq == null) { fq = new FileQueue(); fileMap.put(file, fq); contentsByFile.add(fq); } fq.fileContents.add(env); }
45. Attr#attribLazyConstantValue()
Project: openjdk
File: Attr.java
File: Attr.java
/** * Attribute a "lazy constant value". * @param env The env for the const value * @param variable The initializer for the const value * @param type The expected type, or null * @see VarSymbol#setLazyConstValue */ public Object attribLazyConstantValue(Env<AttrContext> env, JCVariableDecl variable, Type type) { DiagnosticPosition prevLintPos = deferredLintHandler.setPos(variable.pos()); final JavaFileObject prevSource = log.useSource(env.toplevel.sourcefile); try { Type itype = attribExpr(variable.init, env, type); if (itype.constValue() != null) { return coerce(itype, type).constValue(); } else { return null; } } finally { log.useSource(prevSource); deferredLintHandler.setPos(prevLintPos); } }
46. Attr#attribStatToTree()
Project: openjdk
File: Attr.java
File: Attr.java
public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) { breakTree = tree; JavaFileObject prev = log.useSource(env.toplevel.sourcefile); try { attribStat(stmt, env); } catch (BreakAttr b) { return b.env; } catch (AssertionError ae) { if (ae.getCause() instanceof BreakAttr) { return ((BreakAttr) (ae.getCause())).env; } else { throw ae; } } finally { breakTree = null; log.useSource(prev); } return env; }
47. Attr#attribExprToTree()
Project: openjdk
File: Attr.java
File: Attr.java
public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) { breakTree = tree; JavaFileObject prev = log.useSource(env.toplevel.sourcefile); try { attribExpr(expr, env); } catch (BreakAttr b) { return b.env; } catch (AssertionError ae) { if (ae.getCause() instanceof BreakAttr) { return ((BreakAttr) (ae.getCause())).env; } else { throw ae; } } finally { breakTree = null; log.useSource(prev); } return env; }
48. Annotate#attributeAnnotationType()
Project: openjdk
File: Annotate.java
File: Annotate.java
private void attributeAnnotationType(Env<AttrContext> env) { Assert.check(((JCClassDecl) env.tree).sym.isAnnotationType(), "Trying to annotation type complete a non-annotation type"); JavaFileObject prev = log.useSource(env.toplevel.sourcefile); try { JCClassDecl tree = (JCClassDecl) env.tree; AnnotationTypeVisitor v = new AnnotationTypeVisitor(attr, chk, syms, typeEnvs); v.scanAnnotationType(tree); tree.sym.getAnnotationTypeMetadata().setRepeatable(v.repeatable); tree.sym.getAnnotationTypeMetadata().setTarget(v.target); } finally { log.useSource(prev); } }
49. Annotate#enterTypeAnnotations()
Project: openjdk
File: Annotate.java
File: Annotate.java
/******************** * Type annotations * ********************/ /** * Attribute the list of annotations and enter them onto s. */ public void enterTypeAnnotations(List<JCAnnotation> annotations, Env<AttrContext> env, Symbol s, DiagnosticPosition deferPos, boolean isTypeParam) { Assert.checkNonNull(s, "Symbol argument to actualEnterTypeAnnotations is nul/"); JavaFileObject prev = log.useSource(env.toplevel.sourcefile); DiagnosticPosition prevLintPos = null; if (deferPos != null) { prevLintPos = deferredLintHandler.setPos(deferPos); } try { annotateNow(s, annotations, env, true, isTypeParam); } finally { if (prevLintPos != null) deferredLintHandler.setPos(prevLintPos); log.useSource(prev); } }
50. JavacTrees#asJavaFileObject()
Project: openjdk
File: JavacTrees.java
File: JavacTrees.java
static JavaFileObject asJavaFileObject(FileObject fileObject) { JavaFileObject jfo = null; if (fileObject instanceof JavaFileObject) { jfo = (JavaFileObject) fileObject; checkHtmlKind(fileObject, Kind.HTML); return jfo; } checkHtmlKind(fileObject); jfo = new HtmlFileObject(fileObject); return jfo; }
51. GenStubs#makeStub()
Project: openjdk
File: GenStubs.java
File: GenStubs.java
void makeStub(StandardJavaFileManager fm, CompilationUnitTree tree) throws IOException { CompilationUnitTree tree2 = new StubMaker().translate(tree); CompilationUnitTree tree3 = new ImportCleaner(fm).removeRedundantImports(tree2); String className = fm.inferBinaryName(StandardLocation.SOURCE_PATH, tree.getSourceFile()); JavaFileObject fo = fm.getJavaFileForOutput(StandardLocation.SOURCE_OUTPUT, className, JavaFileObject.Kind.SOURCE, null); // System.err.println("Writing " + className + " to " + fo.getName()); Writer out = fo.openWriter(); try { new Pretty(out, true).printExpr((JCTree) tree3); } finally { out.close(); } }
52. OnActivityResultModifierTest#allowedMethodModifiers()
Project: OnActivityResult
File: OnActivityResultModifierTest.java
File: OnActivityResultModifierTest.java
@Test public void allowedMethodModifiers() { //@formatter:off final JavaFileObject source = JavaFileObjects.forSourceString("test/TestActivity", Joiner.on('\n').join("package test;", "import onactivityresult.OnActivityResult;", "public class TestActivity {", "@OnActivityResult(requestCode = 3) protected void protectedResult() {}", "@OnActivityResult(requestCode = 3) protected final void protectedFinalResult() {}", "@OnActivityResult(requestCode = 3) void packageResult() {}", "@OnActivityResult(requestCode = 3) final void packageFinalResult() {}", "@OnActivityResult(requestCode = 3) public final void publicFinalResult() {}", "}")); //@formatter:on assertThatSucceeds(source); }
53. OnActivityResultModifierTest#finalClassWithAnnotatedOnActivityResultMethod()
Project: OnActivityResult
File: OnActivityResultModifierTest.java
File: OnActivityResultModifierTest.java
@Test public void finalClassWithAnnotatedOnActivityResultMethod() { //@formatter:off final JavaFileObject source = JavaFileObjects.forSourceString("test/TestActivity", Joiner.on('\n').join("package test;", "import onactivityresult.OnActivityResult;", "public final class TestActivity {", "@OnActivityResult(requestCode = 3) public final void myOnActivityResult() {}", "}")); //@formatter:on assertThatSucceeds(source); }
54. OnActivityResultModifierTest#packageClassWithAnnotatedOnActivityResultMethod()
Project: OnActivityResult
File: OnActivityResultModifierTest.java
File: OnActivityResultModifierTest.java
@Test public void packageClassWithAnnotatedOnActivityResultMethod() { //@formatter:off final JavaFileObject source = JavaFileObjects.forSourceString("test/TestActivity", Joiner.on('\n').join("package test;", "import onactivityresult.OnActivityResult;", "class TestActivity {", "@OnActivityResult(requestCode = 3) public final void myOnActivityResult() {}", "}")); //@formatter:on assertThatSucceeds(source); }
55. OnActivityResultModifierTest#protectedClassWithAnnotatedOnActivityResultMethod()
Project: OnActivityResult
File: OnActivityResultModifierTest.java
File: OnActivityResultModifierTest.java
@Test public void protectedClassWithAnnotatedOnActivityResultMethod() { //@formatter:off final JavaFileObject source = JavaFileObjects.forSourceString("test/TestActivity", Joiner.on('\n').join("package test;", "import onactivityresult.OnActivityResult;", "public class TestActivity {", "protected static class PrivateClass {", "@OnActivityResult(requestCode = 3) public final void myOnActivityResult() {}", "}", "}")); //@formatter:on assertThatSucceeds(source); }
56. OnActivityResultModifierTest#privateClassWithAnnotatedOnActivityResultMethod()
Project: OnActivityResult
File: OnActivityResultModifierTest.java
File: OnActivityResultModifierTest.java
@Test public void privateClassWithAnnotatedOnActivityResultMethod() { //@formatter:off final JavaFileObject source = JavaFileObjects.forSourceString("test/TestActivity", Joiner.on('\n').join("package test;", "import onactivityresult.OnActivityResult;", "public class TestActivity {", "private static class PrivateClass {", "@OnActivityResult(requestCode = 3) public final void myOnActivityResult() {}", "}", "}")); //@formatter:on assertAbout(javaSource()).that(source).processedWith(new OnActivityResultProcessor()).failsToCompile().withErrorContaining("@OnActivityResult classes must not be private. (test.TestActivity.PrivateClass)").in(source).onLine(4); }
57. NonAccessableTest#testPrivateModel()
Project: ngAndroid
File: NonAccessableTest.java
File: NonAccessableTest.java
@Test public void testPrivateModel() { final String content = "" + "package com.yella;\n" + "import com.ngandroid.lib.annotations.NgModel;\n" + "import com.ngandroid.lib.annotations.NgScope;\n\n" + "@NgScope \n" + "class PrivateScope {\n" + " @NgModel\n" + " protected Model model;" + "}\n" + "class Model {}"; JavaFileObject fileObject = JavaFileObjects.forSourceString("com.yella.PrivateScope", content); ASSERT.about(javaSource()).that(fileObject).processedWith(Collections.singletonList(new NgProcessor(Option.of("ng-processor/src/test/resources/emptylayout")))).failsToCompile().withErrorContaining("Unable to access field").in(fileObject).onLine(8); }
58. NonAccessableTest#testPrivateUsedMethod()
Project: ngAndroid
File: NonAccessableTest.java
File: NonAccessableTest.java
@Test public void testPrivateUsedMethod() { final String content = "" + "package com.yella;\n" + "import com.ngandroid.lib.annotations.NgModel;\n" + "import com.ngandroid.lib.annotations.NgScope;\n\n" + "@NgScope \n" + "class PrivateScope {\n" + " private void method(){\n" + " }\n" + "}"; JavaFileObject fileObject = JavaFileObjects.forSourceString("com.yella.PrivateScope", content); ASSERT.about(javaSource()).that(fileObject).processedWith(Collections.singletonList(new NgProcessor(Option.of("ng-processor/src/test/resources/test_private_method")))).failsToCompile().withErrorContaining("is not accessible").in(fileObject).onLine(7); }
59. InvalidModelTest#testStringScope()
Project: ngAndroid
File: InvalidModelTest.java
File: InvalidModelTest.java
@Test public void testStringScope() { String content = "" + "package com.x.y;" + "import com.ngandroid.lib.annotations.NgModel;\n" + "import com.ngandroid.lib.annotations.NgScope;\n\n" + "@NgScope\n" + "public final class StringScope {\n" + " @NgModel\n" + " android.view.View model;\n" + "}"; JavaFileObject file = JavaFileObjects.forSourceString("com.x.y.StringScope", content); ASSERT.about(javaSource()).that(file).processedWith(Collections.singletonList(new NgProcessor(Option.of("ng-processor/src/test/resources/emptylayout")))).failsToCompile().withErrorContaining("is missing a corresponding getter"); }
60. PresenterBinderClassTest#injectPresenterTypeBehavior_throw()
Project: Moxy
File: PresenterBinderClassTest.java
File: PresenterBinderClassTest.java
//Uncomment this when [MOXY-29] will be fixed //TODO change message text to correct // @Test public void injectPresenterTypeBehavior_throw() { JavaFileObject view = JavaFileObjects.forResource("view/InjectPresenterTypeBehaviorView.java"); getThat(Collections.singletonList(new ErrorProcessor()), JavaFileObjects.forResource("presenter/PositiveParamsViewPresenter.java"), view).failsToCompile().withErrorContaining("expected error").in(view).onLine(//tag = "", type = PresenterType.LOCAL 19).and().withErrorContaining("expected error").in(//tag="" view).onLine(//tag="" 28).and().withErrorContaining("expected error").in(view).onLine(//factory = MockPresenterFactory.class, type = PresenterType.LOCAL 22).and().withErrorContaining("expected error").in(//factory view).onLine(//factory 31).and().withErrorContaining("expected error").in(view).onLine(//presenterId = "", type = PresenterType.LOCAL 25).and().withErrorContaining("expected error").in(view).onLine(//presenterId 34).and().withErrorContaining("expected error").in(view).onLine(//tag = "", factory = MockPresenterFactory.class 37); }
61. MementoProcessor#generateMemento()
Project: memento
File: MementoProcessor.java
File: MementoProcessor.java
private void generateMemento(Set<? extends Element> elements, Element hostActivity, TypeElement activityType) throws IOException { PackageElement packageElement = processingEnv.getElementUtils().getPackageOf(hostActivity); final String simpleClassName = hostActivity.getSimpleName() + "$Memento"; final String qualifiedClassName = packageElement.getQualifiedName() + "." + simpleClassName; log("writing class " + qualifiedClassName); JavaFileObject sourceFile = processingEnv.getFiler().createSourceFile(qualifiedClassName, elements.toArray(new Element[elements.size()])); JavaWriter writer = new JavaWriter(sourceFile.openWriter()); emitClassHeader(packageElement, activityType, writer); writer.beginType(qualifiedClassName, "class", EnumSet.of(Modifier.PUBLIC, Modifier.FINAL), "Fragment", LIB_PACKAGE + ".MementoMethods"); emitFields(elements, writer); emitConstructor(simpleClassName, writer); emitReaderMethod(elements, hostActivity, writer); emitWriterMethod(elements, hostActivity, writer); writer.endType(); writer.close(); }
62. Util#toJavaFileObjects()
Project: jsweet
File: Util.java
File: Util.java
/** * Transforms a list of source files to Java file objects (used by javac). */ public static com.sun.tools.javac.util.List<JavaFileObject> toJavaFileObjects(JavaFileManager fileManager, Collection<File> sourceFiles) throws IOException { com.sun.tools.javac.util.List<JavaFileObject> fileObjects = com.sun.tools.javac.util.List.nil(); JavacFileManager javacFileManager = (JavacFileManager) fileManager; for (JavaFileObject fo : javacFileManager.getJavaFileObjectsFromFiles(sourceFiles)) { fileObjects = fileObjects.append(fo); } if (fileObjects.length() != sourceFiles.size()) { throw new IOException("invalid file list"); } return fileObjects; }
63. FileReadingTest#javaFileObjectCharacterContent()
Project: javapoet
File: FileReadingTest.java
File: FileReadingTest.java
@Test public void javaFileObjectCharacterContent() throws IOException { TypeSpec type = TypeSpec.classBuilder("Test").addJavadoc("Testing, 1, 2, 3!").addMethod(MethodSpec.methodBuilder("fooBar").build()).build(); JavaFile javaFile = JavaFile.builder("foo", type).build(); JavaFileObject javaFileObject = javaFile.toJavaFileObject(); // We can never have encoding issues (everything is in process) assertThat(javaFileObject.getCharContent(true)).isEqualTo(javaFile.toString()); assertThat(javaFileObject.getCharContent(false)).isEqualTo(javaFile.toString()); }
64. JavaFile#writeTo()
Project: javapoet
File: JavaFile.java
File: JavaFile.java
/** Writes this to {@code filer}. */ public void writeTo(Filer filer) throws IOException { String fileName = packageName.isEmpty() ? typeSpec.name : packageName + "." + typeSpec.name; List<Element> originatingElements = typeSpec.originatingElements; JavaFileObject filerSourceFile = filer.createSourceFile(fileName, originatingElements.toArray(new Element[originatingElements.size()])); try (Writer writer = filerSourceFile.openWriter()) { writeTo(writer); } catch (Exception e) { try { filerSourceFile.delete(); } catch (Exception ignored) { } throw e; } }
65. GeneratedCodeGenerator#generate()
Project: jackdaw
File: GeneratedCodeGenerator.java
File: GeneratedCodeGenerator.java
@Override public final void generate(final CodeGeneratorContext context) throws Exception { final TypeElement typeElement = context.getTypeElement(); final String packageName = context.getPackageName(); final String className = context.getClassName(getNameModifier()); final JavaFileObject file = ProcessorUtils.createSourceFile(typeElement, packageName, className); try (final Writer writer = file.openWriter(); final PrintWriter printWriter = new PrintWriter(writer)) { final TypeSpec.Builder typeSpecBuilder = generateCommon(className); generateBody(context, typeSpecBuilder); final TypeSpec typeSpec = typeSpecBuilder.build(); final JavaFile javaFile = JavaFile.builder(packageName, typeSpec).indent(SourceTextUtils.INDENT).skipJavaLangImports(true).build(); final String sourceCode = javaFile.toString(); printWriter.write(sourceCode); printWriter.flush(); } }
66. ErrorUtil#report()
Project: j2objc
File: ErrorUtil.java
File: ErrorUtil.java
@Override public void report(Diagnostic<? extends JavaFileObject> diagnostic) { JavaFileObject sourceFile = diagnostic.getSource(); String text = diagnostic.getMessage(null); String msg = diagnostic.getPosition() != Diagnostic.NOPOS ? String.format("%s:%s: %s", sourceFile.getName(), diagnostic.getLineNumber(), text) : String.format("%s: %s", sourceFile.getName(), text); switch(diagnostic.getKind()) { case ERROR: error(msg); break; case WARNING: warning(msg); break; default: Logger.getGlobal().info(msg); } }
67. Processor#generateTemplateType()
Project: immutables
File: Processor.java
File: Processor.java
private void generateTemplateType(TypeElement templateType) throws IOException, Exception { SwissArmyKnife knife = new SwissArmyKnife(processingEnv, templateType); String string = readTemplateResource(templateType, knife); Unit unit = parseUnit(string); Unit resolved = transformUnit(knife, unit); TemplateWriter writingTransformer = new TemplateWriter(knife, templateType, GeneratedTypes.getSimpleName(templateType)); CharSequence template = writingTransformer.toCharSequence(resolved); JavaFileObject templateFile = knife.environment.getFiler().createSourceFile(GeneratedTypes.getQualifiedName(knife.elements, templateType), templateType); try (Writer writer = templateFile.openWriter()) { writer.append(template); } }
68. JCodeGen#compile()
Project: h2o-3
File: JCodeGen.java
File: JCodeGen.java
public static Class compile(String class_name, String java_text) throws Exception { if (COMPILER == null) throw new UnsupportedOperationException("Unable to launch an internal instance of javac"); // Wrap input string up as a file-like java source thing JavaFileObject file = new JavaSourceFromString(class_name, java_text); // Capture all output class "files" as simple ByteArrayOutputStreams JavacFileManager jfm = new JavacFileManager(COMPILER.getStandardFileManager(null, null, null)); // Invoke javac if (!COMPILER.getTask(null, jfm, null, /*javac options*/ null, null, Arrays.asList(file)).call()) throw H2O.fail("Internal POJO compilation failed."); // Load POJO classes via a separated classloader to separate POJO namespace ClassLoader cl = new TestPojoCL(Thread.currentThread().getContextClassLoader()); for (Map.Entry<String, ByteArrayOutputStream> entry : jfm._buffers.entrySet()) { byte[] bits = entry.getValue().toByteArray(); // Call classLoader.defineClass("className",byte[]) DEFINE_CLASS_METHOD.invoke(cl, entry.getKey(), bits, 0, bits.length); } // Return the original top-level class return Class.forName(class_name, true, cl); }
69. Diagnostics#appendTo()
Project: FreeBuilder
File: Diagnostics.java
File: Diagnostics.java
/** * Appends a human-readable form of {@code diagnostic} to {@code appendable}. */ public static void appendTo(StringBuilder appendable, Diagnostic<? extends JavaFileObject> diagnostic, int indentLevel) { String indent = "\n" + Strings.repeat(" ", indentLevel); appendable.append(diagnostic.getMessage(Locale.getDefault()).replace("\n", indent)); JavaFileObject source = diagnostic.getSource(); long line = diagnostic.getLineNumber(); if (source != null && line != Diagnostic.NOPOS) { File sourceFile = new File(source.getName()); appendable.append(" (").append(sourceFile.getName()).append(":").append(line).append(")"); } }
70. Task_reuseTest#getAndRunTask()
Project: error-prone-javac
File: Task_reuseTest.java
File: Task_reuseTest.java
private DocumentationTask getAndRunTask() 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, null, null, files); if (t.call()) { System.err.println("task succeeded"); return t; } else { throw new Exception("task failed"); } }
71. JavadocTaskImplTest#testDirectAccess2()
Project: error-prone-javac
File: JavadocTaskImplTest.java
File: JavadocTaskImplTest.java
@Test public void testDirectAccess2() throws Exception { // error, provokes NPE JavaFileObject srcFile = null; Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile); Context c = new Context(); Messager.preRegister(c, "javadoc"); StandardJavaFileManager fm = new JavacFileManager(c, true, null); File outDir = getOutDir(); fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir)); try { DocumentationTask t = new JavadocTaskImpl(c, null, null, files); ; error("getTask succeeded, no exception thrown"); } catch (NullPointerException e) { System.err.println("exception caught as expected: " + e); } }
72. JavadocTaskImplTest#testDirectAccess1()
Project: error-prone-javac
File: JavadocTaskImplTest.java
File: JavadocTaskImplTest.java
@Test public void testDirectAccess1() throws Exception { JavaFileObject srcFile = createSimpleJavaFileObject(); Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile); Context c = new Context(); Messager.preRegister(c, "javadoc"); StandardJavaFileManager fm = new JavacFileManager(c, true, null); File outDir = getOutDir(); fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir)); DocumentationTask t = new JavadocTaskImpl(c, null, null, files); if (t.call()) { System.err.println("task succeeded"); } else { throw new Exception("task failed"); } }
73. JavadocTaskImplTest#testRawCall()
Project: error-prone-javac
File: JavadocTaskImplTest.java
File: JavadocTaskImplTest.java
@Test public void testRawCall() 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); @SuppressWarnings("rawtypes") Callable t = tool.getTask(null, fm, null, null, null, files); if (t.call() == Boolean.TRUE) { System.err.println("task succeeded"); } else { throw new Exception("task failed"); } }
74. GetTask_WriterTest#testWriter()
Project: error-prone-javac
File: GetTask_WriterTest.java
File: GetTask_WriterTest.java
/** * 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"); } }
75. GetTask_OptionsTest#testNull()
Project: error-prone-javac
File: GetTask_OptionsTest.java
File: GetTask_OptionsTest.java
/** * 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); } }
76. GetTask_OptionsTest#testNoIndex()
Project: error-prone-javac
File: GetTask_OptionsTest.java
File: GetTask_OptionsTest.java
/** * Verify that expected output files are written for given options. */ @Test public void testNoIndex() 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); Iterable<String> options = Arrays.asList("-noindex"); DocumentationTask t = tool.getTask(null, fm, null, null, options, files); if (t.call()) { System.err.println("task succeeded"); Set<String> expectFiles = new TreeSet<String>(standardExpectFiles); expectFiles.remove("index-all.html"); checkFiles(outDir, expectFiles); } else { error("task failed"); } }
77. GetTask_FileObjectsTest#testMemoryFileObject()
Project: error-prone-javac
File: GetTask_FileObjectsTest.java
File: GetTask_FileObjectsTest.java
/** * Verify that expected output files are written via the file manager, * for an in-memory file object. */ @Test public void testMemoryFileObject() 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, null, null, files); if (t.call()) { System.err.println("task succeeded"); checkFiles(outDir, standardExpectFiles); } else { throw new Exception("task failed"); } }
78. GetTask_FileManagerTest#testFileManager()
Project: error-prone-javac
File: GetTask_FileManagerTest.java
File: GetTask_FileManagerTest.java
/** * 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"); } }
79. GetTask_DocletClassTest#testBadDoclet()
Project: error-prone-javac
File: GetTask_DocletClassTest.java
File: GetTask_DocletClassTest.java
/** * 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; } }
80. GetTask_DocletClassTest#testDoclet()
Project: error-prone-javac
File: GetTask_DocletClassTest.java
File: GetTask_DocletClassTest.java
/** * 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"); } }
81. DetectMutableStaticFields#analyzeResource()
Project: error-prone-javac
File: DetectMutableStaticFields.java
File: DetectMutableStaticFields.java
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())); } } }
82. ProfileOptionTest#testInvalidProfile_API()
Project: error-prone-javac
File: ProfileOptionTest.java
File: ProfileOptionTest.java
// ---------- Test cases, invoked reflectively via run. ---------- @Test void testInvalidProfile_API() throws Exception { JavaFileObject fo = new StringJavaFileObject("Test.java", "class Test { }"); String badName = "foo"; List<String> opts = Arrays.asList("-profile", badName); StringWriter sw = new StringWriter(); try { JavacTask task = (JavacTask) javac.getTask(sw, fm, null, opts, null, Arrays.asList(fo)); throw new Exception("expected exception not thrown"); } catch (IllegalArgumentException e) { } }
83. T4910483#main()
Project: error-prone-javac
File: T4910483.java
File: T4910483.java
public static void main(String... args) { JavaCompiler compiler = JavaCompiler.instance(new Context()); compiler.keepComments = true; String testSrc = System.getProperty("test.src"); JavacFileManager fm = new JavacFileManager(new Context(), false, null); JavaFileObject f = fm.getFileForInput(testSrc + File.separatorChar + "T4910483.java"); JCTree.JCCompilationUnit cu = compiler.parse(f); JCTree classDef = cu.getTypeDecls().head; String commentText = cu.docComments.getCommentText(classDef); // 4 '\' escapes to 2 in a string literal String expected = "Test comment abc*\\\\def"; if (!expected.equals(commentText)) { throw new AssertionError("Incorrect comment text: [" + commentText + "], expected [" + expected + "]"); } }
84. BridgeHarness#main()
Project: error-prone-javac
File: BridgeHarness.java
File: BridgeHarness.java
public static void main(String[] args) throws Exception { //set sourcepath fm.setLocation(SOURCE_PATH, Arrays.asList(new File(System.getProperty("test.src"), "tests"))); //set output (-d) fm.setLocation(javax.tools.StandardLocation.CLASS_OUTPUT, Arrays.asList(new File(System.getProperty("user.dir")))); for (JavaFileObject jfo : fm.list(SOURCE_PATH, "", Collections.singleton(JavaFileObject.Kind.SOURCE), true)) { //for each source, compile and check against annotations new BridgeHarness(jfo).compileAndCheck(); } //if there were errors, fail if (nerrors > 0) { throw new AssertionError("Errors were found"); } }
85. LVTHarness#main()
Project: error-prone-javac
File: LVTHarness.java
File: LVTHarness.java
public static void main(String[] args) throws Exception { String testDir = System.getProperty("test.src"); fm.setLocation(SOURCE_PATH, Arrays.asList(new File(testDir, "tests"))); // Make sure classes are written to scratch dir. fm.setLocation(CLASS_OUTPUT, Arrays.asList(new File("."))); for (JavaFileObject jfo : fm.list(SOURCE_PATH, "", Collections.singleton(SOURCE), true)) { new LVTHarness(jfo).check(); } if (nerrors > 0) { throw new AssertionError("Errors were found"); } }
86. TestSearchPaths#callTask()
Project: error-prone-javac
File: TestSearchPaths.java
File: TestSearchPaths.java
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"); }
87. T6852595#main()
Project: error-prone-javac
File: T6852595.java
File: T6852595.java
public static void main(String[] args) throws IOException { JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"), Kind.SOURCE) { public CharSequence getCharContent(boolean ignoreEncodingErrors) { return "class BadName { Object o = j; }"; } }; List<? extends JavaFileObject> files = Arrays.asList(sfo); JavaCompiler tool = ToolProvider.getSystemJavaCompiler(); JavacTask ct = (JavacTask) tool.getTask(null, null, null, null, null, files); Iterable<? extends CompilationUnitTree> compUnits = ct.parse(); CompilationUnitTree cu = compUnits.iterator().next(); ClassTree cdef = (ClassTree) cu.getTypeDecls().get(0); JCVariableDecl vdef = (JCVariableDecl) cdef.getMembers().get(0); TreePath path = TreePath.getPath(cu, vdef.init); Trees.instance(ct).getScope(path); }
88. T6733837#exec()
Project: error-prone-javac
File: T6733837.java
File: T6733837.java
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"); }
89. T6608214#main()
Project: error-prone-javac
File: T6608214.java
File: T6608214.java
public static void main(String[] args) throws IOException { JavaFileObject sfo = new SimpleJavaFileObject(URI.create(""), Kind.SOURCE) { public CharSequence getCharContent(boolean ignoreEncodingErrors) { return "class Test<S> { <T extends S & Runnable> void test(){}}"; } }; List<? extends JavaFileObject> files = Arrays.asList(sfo); String bootPath = System.getProperty("sun.boot.class.path"); List<String> opts = Arrays.asList("-bootclasspath", bootPath, "-Xjcov"); JavaCompiler tool = ToolProvider.getSystemJavaCompiler(); JavacTask ct = (JavacTask) tool.getTask(null, null, null, opts, null, files); ct.analyze(); }
90. ReflectionTest#printTestSrc()
Project: error-prone-javac
File: ReflectionTest.java
File: ReflectionTest.java
private static void printTestSrc(Iterable<? extends JavaFileObject> files) { for (JavaFileObject f : files) { System.out.println("Test file " + f.getName() + ":"); try { System.out.println("" + f.getCharContent(true)); } catch (IOException e) { throw new RuntimeException("Exception when printing test src contents for class " + f.getName(), e); } } }
91. Helper#compileCode()
Project: error-prone-javac
File: Helper.java
File: Helper.java
// Create and compile FileObject using values for className and contents public static boolean compileCode(String className, String contents, DiagnosticCollector<JavaFileObject> diagnostics) { boolean ok = false; JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if (compiler == null) { throw new RuntimeException("can't get javax.tools.JavaCompiler!"); } JavaFileObject file = getFile(className, contents); Iterable<? extends JavaFileObject> compilationUnit = Arrays.asList(file); CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnit); ok = task.call(); return ok; }
92. JavacElements#getSourcePosition()
Project: error-prone-javac
File: JavacElements.java
File: JavacElements.java
public JavacSourcePosition getSourcePosition(Element e, AnnotationMirror a) { Pair<JCTree, JCCompilationUnit> treeTop = getTreeAndTopLevel(e); if (treeTop == null) return null; JCTree tree = treeTop.fst; JCCompilationUnit toplevel = treeTop.snd; JavaFileObject sourcefile = toplevel.sourcefile; if (sourcefile == null) return null; JCTree annoTree = matchAnnoToTree(a, e, tree); if (annoTree == null) return null; return new JavacSourcePosition(sourcefile, annoTree.pos, toplevel.lineMap); }
93. JavaCompiler#parseFiles()
Project: error-prone-javac
File: JavaCompiler.java
File: JavaCompiler.java
/** * Parses a list of files. */ public List<JCCompilationUnit> parseFiles(Iterable<JavaFileObject> fileObjects) { if (shouldStop(CompileState.PARSE)) return List.nil(); //parse all files ListBuffer<JCCompilationUnit> trees = new ListBuffer<>(); Set<JavaFileObject> filesSoFar = new HashSet<>(); for (JavaFileObject fileObject : fileObjects) { if (!filesSoFar.contains(fileObject)) { filesSoFar.add(fileObject); trees.append(parse(fileObject)); } } return trees.toList(); }
94. JavaCompiler#printSource()
Project: error-prone-javac
File: JavaCompiler.java
File: JavaCompiler.java
/** Emit plain Java source for a class. * @param env The attribution environment of the outermost class * containing this class. * @param cdef The class definition to be printed. */ JavaFileObject printSource(Env<AttrContext> env, JCClassDecl cdef) throws IOException { JavaFileObject outFile = fileManager.getJavaFileForOutput(CLASS_OUTPUT, cdef.sym.flatname.toString(), JavaFileObject.Kind.SOURCE, null); if (inputFiles.contains(outFile)) { log.error(cdef.pos(), "source.cant.overwrite.input.file", outFile); return null; } else { try (BufferedWriter out = new BufferedWriter(outFile.openWriter())) { new Pretty(out, true).printUnit(env.toplevel, cdef); if (verbose) log.printVerbose("wrote.file", outFile); } return outFile; } }
95. JavaCompiler#resolveIdent()
Project: error-prone-javac
File: JavaCompiler.java
File: JavaCompiler.java
/** Resolve an identifier. * @param name The identifier to resolve */ public Symbol resolveIdent(String name) { if (name.equals("")) return syms.errSymbol; JavaFileObject prev = log.useSource(null); try { JCExpression tree = null; for (String s : name.split("\\.", -1)) { if (// TODO: check for keywords !SourceVersion.isIdentifier(s)) return syms.errSymbol; tree = (tree == null) ? make.Ident(names.fromString(s)) : make.Select(tree, names.fromString(s)); } JCCompilationUnit toplevel = make.TopLevel(List.<JCTree>nil()); toplevel.packge = syms.unnamedPackage; return attr.attribIdent(tree, toplevel); } finally { log.useSource(prev); } }
96. ClassWriter#writeClass()
Project: error-prone-javac
File: ClassWriter.java
File: ClassWriter.java
/** Emit a class file for a given class. * @param c The class from which a class file is generated. */ public JavaFileObject writeClass(ClassSymbol c) throws IOException, PoolOverflow, StringOverflow { JavaFileObject outFile = fileManager.getJavaFileForOutput(CLASS_OUTPUT, c.flatname.toString(), JavaFileObject.Kind.CLASS, c.sourcefile); OutputStream out = outFile.openOutputStream(); try { writeClassFile(out, c); if (verbose) log.printVerbose("wrote.file", outFile); out.close(); out = null; } finally { if (out != null) { // if we are propagating an exception, delete the file out.close(); outFile.delete(); outFile = null; } } // may be null if write failed return outFile; }
97. Todo#removeByFile()
Project: error-prone-javac
File: Todo.java
File: Todo.java
private void removeByFile(Env<AttrContext> env) { JavaFileObject file = env.toplevel.sourcefile; FileQueue fq = fileMap.get(file); if (fq == null) return; if (fq.fileContents.remove(env)) { if (fq.isEmpty()) { fileMap.remove(file); contentsByFile.remove(fq); } } }
98. Todo#addByFile()
Project: error-prone-javac
File: Todo.java
File: Todo.java
private void addByFile(Env<AttrContext> env) { JavaFileObject file = env.toplevel.sourcefile; if (fileMap == null) fileMap = new HashMap<>(); FileQueue fq = fileMap.get(file); if (fq == null) { fq = new FileQueue(); fileMap.put(file, fq); contentsByFile.add(fq); } fq.fileContents.add(env); }
99. MethodMemberInjectorTest#testMethodInjection_shouldFail_whenInjectedMethodIsPrivate()
Project: toothpick
File: MethodMemberInjectorTest.java
File: MethodMemberInjectorTest.java
@Test public void testMethodInjection_shouldFail_whenInjectedMethodIsPrivate() { JavaFileObject source = JavaFileObjects.forSourceString("test.TestMethodInjection", // Joiner.on('\n').join(// "package test;", // "import javax.inject.Inject;", // "public class TestMethodInjection {", // " @Inject", // " private void m(Foo foo) {}", // "}", // "class Foo {}")); assert_().about(javaSource()).that(source).processedWith(memberInjectorProcessors()).failsToCompile().withErrorContaining("@Inject annotated methods must not be private : test.TestMethodInjection#m"); }
100. FieldMemberInjectorTest#testFieldInjection_shouldFail_whenFieldIsPrivate()
Project: toothpick
File: FieldMemberInjectorTest.java
File: FieldMemberInjectorTest.java
@Test public void testFieldInjection_shouldFail_whenFieldIsPrivate() { JavaFileObject source = JavaFileObjects.forSourceString("test.TestFieldInjection", // Joiner.on('\n').join(// "package test;", // "import javax.inject.Inject;", // "public class TestFieldInjection {", // " @Inject private Foo foo;", // " public TestFieldInjection() {}", // "}", // "class Foo {}")); assert_().about(javaSource()).that(source).processedWith(memberInjectorProcessors()).failsToCompile().withErrorContaining("@Inject annotated fields must be non private : test.TestFieldInjection#foo"); }