javax.tools.JavaFileObject Java Examples
The following examples show how to use
javax.tools.JavaFileObject.
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 Project: netbeans Author: apache File: Utilities.java License: Apache License 2.0 | 6 votes |
public static JavacTaskImpl createJavac(JavaFileManager fm, JavaFileObject... sources) { final String version = System.getProperty("java.vm.specification.version"); //NOI18N final JavaCompiler tool = ToolProvider.getSystemJavaCompiler(); assert tool != null; Context context = new Context(); //need to preregister the Messages here, because the getTask below requires Log instance: Log.preRegister(context, DEV_NULL); JavacTaskImpl task = (JavacTaskImpl)JavacTool.create().getTask(null, fm, null, Arrays.asList("-source", version, "-target", version, "-Xjcov", "-XDshouldStopPolicy=GENERATE"), null, Arrays.asList(sources), context); NBParserFactory.preRegister(context); NBTreeMaker.preRegister(context); NBEnter.preRegister(context); return task; }
Example #2
Source Project: openjdk-jdk8u Author: AdoptOpenJDK File: ClassReader.java License: GNU General Public License v2.0 | 6 votes |
private void fillIn(PackageSymbol p, Location location, Iterable<JavaFileObject> files) { currentLoc = location; for (JavaFileObject fo : files) { switch (fo.getKind()) { case CLASS: case SOURCE: { // TODO pass binaryName to includeClassFile String binaryName = fileManager.inferBinaryName(currentLoc, fo); String simpleName = binaryName.substring(binaryName.lastIndexOf(".") + 1); if (SourceVersion.isIdentifier(simpleName) || simpleName.equals("package-info")) includeClassFile(p, fo); break; } default: extraFileActions(p, fo); } } }
Example #3
Source Project: java-n-IDE-for-Android Author: shenghuntianlang File: DiagnosticPresenter.java License: Apache License 2.0 | 6 votes |
@Override public void click(Diagnostic diagnostic) { Log.d(TAG, "click() called with: diagnostic = [" + diagnostic + "]"); mMainActivity.closeDrawer(GravityCompat.START); Object source = diagnostic.getSource(); if (source instanceof JavaFileObject && diagnostic.getKind() == Diagnostic.Kind.ERROR) { String path = ((JavaFileObject) source).getName(); int i = mPagePresenter.gotoPage(path); if (i == -1) { mPagePresenter.addPage(path, true); } EditPageContract.SourceView editor = mPagePresenter.getCurrentPage(); if (editor == null) { Log.d(TAG, "click: editor null"); return; } int startPosition = (int) diagnostic.getStartPosition(); int endPosition = (int) diagnostic.getEndPosition(); editor.highlightError(startPosition, endPosition); editor.setCursorPosition(endPosition); } else { // TODO: 19/07/2017 implement other } }
Example #4
Source Project: openjdk-8-source Author: keerath File: RootDocImpl.java License: GNU General Public License v2.0 | 6 votes |
/** * Do lazy initialization of "documentation" string. */ @Override protected String documentation() { if (documentation == null) { JavaFileObject overviewPath = getOverviewPath(); if (overviewPath == null) { // no doc file to be had documentation = ""; } else { // read from file try { documentation = readHTMLDocumentation( overviewPath.openInputStream(), overviewPath); } catch (IOException exc) { documentation = ""; env.error(null, "javadoc.File_Read_Error", overviewPath.getName()); } } } return documentation; }
Example #5
Source Project: openjdk-8-source Author: keerath File: DocTreePathScannerTest.java License: GNU General Public License v2.0 | 6 votes |
void run() throws Exception { List<File> files = new ArrayList<File>(); File testSrc = new File(System.getProperty("test.src")); for (File f: testSrc.listFiles()) { if (f.isFile() && f.getName().endsWith(".java")) files.add(f); } JavacTool javac = JavacTool.create(); StandardJavaFileManager fm = javac.getStandardFileManager(null, null, null); Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjectsFromFiles(files); JavacTask t = javac.getTask(null, fm, null, null, null, fos); DocTrees trees = DocTrees.instance(t); Iterable<? extends CompilationUnitTree> units = t.parse(); DeclScanner ds = new DeclScanner(trees); for (CompilationUnitTree unit: units) { ds.scan(unit, null); } if (errors > 0) throw new Exception(errors + " errors occurred"); }
Example #6
Source Project: buck Author: facebook File: AnnotationProcessor.java License: Apache License 2.0 | 6 votes |
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (annotations.size() == 0) return true; try { JavaFileObject sourceFile = processingEnv.getFiler().createSourceFile("com.example.gwt.shared.MyFactory"); try (PrintWriter out = new PrintWriter(sourceFile.openWriter())) { out.println("package com.example.gwt.shared;"); out.println("public class MyFactory {}"); } } catch (IOException ex) { throw new RuntimeException("Unexpected IOException caught", ex); } return false; }
Example #7
Source Project: compile-testing Author: google File: CompilerTest.java License: Apache License 2.0 | 6 votes |
@Test public void options() { NoOpProcessor processor = new NoOpProcessor(); Object[] options1 = {"-Agone=nowhere"}; JavaFileObject[] files = {HELLO_WORLD}; Compilation unused = javac() .withOptions(options1) .withOptions(ImmutableList.of("-Ab=2", "-Ac=3")) .withProcessors(processor) .compile(files); assertThat(processor.options) .containsExactly( "b", "2", "c", "3") .inOrder(); }
Example #8
Source Project: openjdk-8-source Author: keerath File: Log.java License: GNU General Public License v2.0 | 6 votes |
/** Construct a log with given I/O redirections. */ protected Log(Context context, PrintWriter errWriter, PrintWriter warnWriter, PrintWriter noticeWriter) { super(JCDiagnostic.Factory.instance(context)); context.put(logKey, this); this.errWriter = errWriter; this.warnWriter = warnWriter; this.noticeWriter = noticeWriter; @SuppressWarnings("unchecked") // FIXME DiagnosticListener<? super JavaFileObject> dl = context.get(DiagnosticListener.class); this.diagListener = dl; diagnosticHandler = new DefaultDiagnosticHandler(); messages = JavacMessages.instance(context); messages.add(Main.javacBundleName); final Options options = Options.instance(context); initOptions(options); options.addListener(new Runnable() { public void run() { initOptions(options); } }); }
Example #9
Source Project: buck Author: facebook File: JavaInMemoryFileObjectTest.java License: Apache License 2.0 | 6 votes |
@Test public void testJavaFileContent() throws Exception { String relativePath = "com/facebook/buck/java/JavaInMemoryFileObjectTest.class"; JavaInMemoryFileObject inMemoryFileObject = new JavaInMemoryFileObject( URI.create("file://tmp/" + relativePath), relativePath, JavaFileObject.Kind.CLASS); OutputStream out = inMemoryFileObject.openOutputStream(); out.write("content".getBytes()); out.close(); TestJar jar = writeToJar(inMemoryFileObject); assertEquals(7, jar.getZipEntries().size()); assertEquals(7, jar.getEntriesContent().size()); assertEquals("content", jar.getEntriesContent().get(6)); }
Example #10
Source Project: jdk8u60 Author: chenghanpeng File: RetentionAnnoCombo.java License: GNU General Public License v2.0 | 6 votes |
private boolean getCompileResult(String contents, String className, boolean shouldCompile) throws Exception{ DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); boolean ok = compileCode(className, contents, diagnostics); String expectedErrKey = "compiler.err.invalid.repeatable" + ".annotation.retention"; if (!shouldCompile && !ok) { for (Diagnostic<?> d : diagnostics.getDiagnostics()) { if (!((d.getKind() == Diagnostic.Kind.ERROR) && d.getCode().contains(expectedErrKey))) { error("FAIL: Incorrect error given, expected = " + expectedErrKey + ", Actual = " + d.getCode() + " for className = " + className, contents); } } } return (shouldCompile == ok); }
Example #11
Source Project: TencentKona-8 Author: Tencent File: GetTask_OptionsTest.java License: GNU General Public License v2.0 | 6 votes |
/** * 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"); } }
Example #12
Source Project: dsl-json Author: ngs-doo File: DslValidationTest.java License: BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void invalidJsonObjectReferences() { List<Diagnostic<? extends JavaFileObject>> diagnostics = compileTestCase(ReferenceJsonObject.class); Assert.assertEquals(3, diagnostics.size()); String error1 = diagnostics.get(0).getMessage(Locale.ENGLISH); String error2 = diagnostics.get(1).getMessage(Locale.ENGLISH); String error3 = diagnostics.get(2).getMessage(Locale.ENGLISH); Assert.assertTrue( error1.contains("'com.dslplatform.json.models.ReferenceJsonObject.ImplFailed1' is 'com.dslplatform.json.JsonObject', but it doesn't have JSON_READER field.") || error2.contains("'com.dslplatform.json.models.ReferenceJsonObject.ImplFailed1' is 'com.dslplatform.json.JsonObject', but it doesn't have JSON_READER field.") || error3.contains("'com.dslplatform.json.models.ReferenceJsonObject.ImplFailed1' is 'com.dslplatform.json.JsonObject', but it doesn't have JSON_READER field.") ); Assert.assertTrue( error1.contains("'com.dslplatform.json.models.ReferenceJsonObject.ImplFailed2' is 'com.dslplatform.json.JsonObject', but its JSON_READER field is not public and static.") || error2.contains("'com.dslplatform.json.models.ReferenceJsonObject.ImplFailed2' is 'com.dslplatform.json.JsonObject', but its JSON_READER field is not public and static.") || error3.contains("'com.dslplatform.json.models.ReferenceJsonObject.ImplFailed2' is 'com.dslplatform.json.JsonObject', but its JSON_READER field is not public and static.") ); Assert.assertTrue( error1.contains("'com.dslplatform.json.models.ReferenceJsonObject.ImplFailed3' is 'com.dslplatform.json.JsonObject', but its JSON_READER field is not of correct type.") || error2.contains("'com.dslplatform.json.models.ReferenceJsonObject.ImplFailed3' is 'com.dslplatform.json.JsonObject', but its JSON_READER field is not of correct type.") || error3.contains("'com.dslplatform.json.models.ReferenceJsonObject.ImplFailed3' is 'com.dslplatform.json.JsonObject', but its JSON_READER field is not of correct type.") ); }
Example #13
Source Project: TencentKona-8 Author: Tencent File: JavadocTaskImplTest.java License: GNU General Public License v2.0 | 6 votes |
@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"); } }
Example #14
Source Project: yugong Author: alibaba File: JdkCompiler.java License: GNU General Public License v2.0 | 6 votes |
private JavaFileManagerImpl buildFileManager(JdkCompilerClassLoader classLoader, ClassLoader loader, DiagnosticCollector<JavaFileObject> diagnostics) { StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null); if (loader instanceof URLClassLoader && (!"sun.misc.Launcher$AppClassLoader".equalsIgnoreCase(loader.getClass().getName()))) { try { URLClassLoader urlClassLoader = (URLClassLoader) loader; List<File> paths = new ArrayList<File>(); for (URL url : urlClassLoader.getURLs()) { File file = new File(url.getFile()); paths.add(file); } fileManager.setLocation(StandardLocation.CLASS_PATH, paths); } catch (Throwable e) { throw new YuGongException(e); } } return new JavaFileManagerImpl(fileManager, classLoader); }
Example #15
Source Project: openjdk-jdk9 Author: AdoptOpenJDK File: Task_reuseTest.java License: GNU General Public License v2.0 | 6 votes |
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"); } } }
Example #16
Source Project: openjdk-jdk8u-backup Author: AdoptOpenJDK File: JavacProcessingEnvironment.java License: GNU General Public License v2.0 | 6 votes |
/** Enter a set of generated class files. */ private List<ClassSymbol> enterClassFiles(Map<String, JavaFileObject> classFiles) { ClassReader reader = ClassReader.instance(context); Names names = Names.instance(context); List<ClassSymbol> list = List.nil(); for (Map.Entry<String,JavaFileObject> entry : classFiles.entrySet()) { Name name = names.fromString(entry.getKey()); JavaFileObject file = entry.getValue(); if (file.getKind() != JavaFileObject.Kind.CLASS) throw new AssertionError(file); ClassSymbol cs; if (isPkgInfo(file, JavaFileObject.Kind.CLASS)) { Name packageName = Convert.packagePart(name); PackageSymbol p = reader.enterPackage(packageName); if (p.package_info == null) p.package_info = reader.enterClass(Convert.shortName(name), p); cs = p.package_info; if (cs.classfile == null) cs.classfile = file; } else cs = reader.enterClass(name, file); list = list.prepend(cs); } return list.reverse(); }
Example #17
Source Project: TencentKona-8 Author: Tencent File: RetentionAnnoCombo.java License: GNU General Public License v2.0 | 6 votes |
private boolean getCompileResult(String contents, String className, boolean shouldCompile) throws Exception{ DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); boolean ok = compileCode(className, contents, diagnostics); String expectedErrKey = "compiler.err.invalid.repeatable" + ".annotation.retention"; if (!shouldCompile && !ok) { for (Diagnostic<?> d : diagnostics.getDiagnostics()) { if (!((d.getKind() == Diagnostic.Kind.ERROR) && d.getCode().contains(expectedErrKey))) { error("FAIL: Incorrect error given, expected = " + expectedErrKey + ", Actual = " + d.getCode() + " for className = " + className, contents); } } } return (shouldCompile == ok); }
Example #18
Source Project: openjdk-jdk9 Author: AdoptOpenJDK File: TestSearchPaths.java License: GNU General Public License v2.0 | 6 votes |
void testClassOutput() throws IOException { String test = "testClassOutput"; System.err.println("test: " + test); for (int i = 1; i <= 5; i++) { File classes = createDir(test + "/" + i + "/classes"); List<String> options; switch (i) { default: options = getOptions("-d", classes.getPath()); break; case 3: setLocation(CLASS_OUTPUT, classes); options = null; break; } List<JavaFileObject> sources = getSources("class C" + i + " { }"); callTask(options, sources); checkPath(CLASS_OUTPUT, Mode.EQUALS, classes); checkFile(CLASS_OUTPUT, "C" + i + ".class"); } tested.add(CLASS_OUTPUT); }
Example #19
Source Project: openjdk-jdk9 Author: AdoptOpenJDK File: JavacTask.java License: GNU General Public License v2.0 | 6 votes |
private Iterable<? extends JavaFileObject> joinFiles( List<String> files, List<JavaFileObject> fileObjects) { if (files == null) return fileObjects; if (internalFileManager == null) internalFileManager = compiler.getStandardFileManager(null, null, null); Iterable<? extends JavaFileObject> filesAsFileObjects = internalFileManager.getJavaFileObjectsFromStrings(files); if (fileObjects == null) return filesAsFileObjects; List<JavaFileObject> combinedList = new ArrayList<>(); for (JavaFileObject o : filesAsFileObjects) combinedList.add(o); combinedList.addAll(fileObjects); return combinedList; }
Example #20
Source Project: Eclipse-Postfix-Code-Completion Author: trylimits File: BatchFilerImpl.java License: Eclipse Public License 1.0 | 5 votes |
@Override public JavaFileObject createClassFile(CharSequence name, Element... originatingElements) throws IOException { JavaFileObject jfo = _fileManager.getJavaFileForOutput( StandardLocation.CLASS_OUTPUT, name.toString(), JavaFileObject.Kind.CLASS, null); URI uri = jfo.toUri(); if (_createdFiles.contains(uri)) { throw new FilerException("Class file already created : " + name); //$NON-NLS-1$ } _createdFiles.add(uri); return new HookedJavaFileObject(jfo, jfo.getName(), name.toString(), this); }
Example #21
Source Project: parceler Author: johncarl81 File: MemoryClassLoader.java License: Apache License 2.0 | 5 votes |
public void add(Map<String, String> map) { List<Source> list = new ArrayList<Source>(); for (Map.Entry<String, String> entry : map.entrySet()) { list.add(new Source(entry.getKey(), JavaFileObject.Kind.SOURCE, entry.getValue())); } this.compiler.getTask(null, this.manager, null, null, null, list).call(); }
Example #22
Source Project: openjdk-jdk9 Author: AdoptOpenJDK File: JavacFileManager.java License: GNU General Public License v2.0 | 5 votes |
@Override @DefinedBy(Api.COMPILER) public String inferBinaryName(Location location, JavaFileObject file) { checkNotModuleOrientedLocation(location); Objects.requireNonNull(file); // Need to match the path semantics of list(location, ...) Iterable<? extends Path> path = getLocationAsPaths(location); if (path == null) { return null; } if (file instanceof PathFileObject) { return ((PathFileObject) file).inferBinaryName(path); } else throw new IllegalArgumentException(file.getClass().getName()); }
Example #23
Source Project: openjdk-8-source Author: keerath File: StructuralMostSpecificTest.java License: GNU General Public License v2.0 | 5 votes |
public JavaSource() { super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE); source = template.replaceAll("#LR", lrk.retStr) .replaceAll("#R1", rt1.retTypeStr) .replaceAll("#R2", rt2.retTypeStr) .replaceAll("#A1", ak1.argTypeStr) .replaceAll("#A2", ak2.argTypeStr) .replaceAll("#E1", ek1.exceptionStr) .replaceAll("#E2", ek2.exceptionStr); }
Example #24
Source Project: openjdk-jdk9 Author: AdoptOpenJDK File: JavadocTool.java License: GNU General Public License v2.0 | 5 votes |
private void parse(Iterable<? extends JavaFileObject> files, ListBuffer<JCCompilationUnit> trees, boolean trace) { for (JavaFileObject fo: files) { if (uniquefiles.add(fo)) { // ignore duplicates if (trace) docenv.notice("main.Loading_source_file", fo.getName()); trees.append(parse(fo)); } } }
Example #25
Source Project: openjdk-8-source Author: keerath File: TestToString.java License: GNU General Public License v2.0 | 5 votes |
void test(String stmt) throws IOException { System.err.println("Test: " + stmt); List<String> options = Collections.<String>emptyList(); List<? extends JavaFileObject> files = Arrays.asList(new JavaSource(stmt)); JavacTask t = tool.getTask(null, fm, null, options, null, files); checkEqual(scan(t.parse()), stmt); }
Example #26
Source Project: postman Author: Workday File: PostmanProcessorTest.java License: MIT License | 5 votes |
@Test public void testMultipleErrorsAndWarnings() throws Exception { //language=JAVA final String sourceString = "package test;\n" + "import com.workday.postman.annotations.NotParceled;\n" + "import com.workday.postman.annotations.Parceled;\n" + "import com.workday.postman.annotations.PostCreateChild;\n" + "\n" + " public class TestClass {\n" + " @Parceled\n" + " final String myFinal = \"The final word.\";\n" + " @NotParceled\n" + " String myNotParceled;\n" + " @Parceled\n" + " private String myPrivate;\n" + " @Parceled\n" + " static String myStatic;\n" + " @PostCreateChild\n" + " private void onPostCreateChild(Object o) { }\n" + " }"; JavaFileObject source = JavaFileObjects.forSourceString("test.TestClass", sourceString); assertAbout(javaSource()).that(source) .processedWith(new PostmanProcessor()) .failsToCompile() .withErrorCount(3) .withErrorContaining("Cannot access final field") .and() .withErrorContaining("Cannot access private field") .and() .withErrorContaining( "Methods annotated with @PostCreateChild cannot be " + "private") .and() .withWarningCount(2) .withWarningContaining( "You marked static field myStatic as parceled") .and() .withWarningContaining("NotParceled annotations are ignored"); }
Example #27
Source Project: openjdk-jdk8u Author: AdoptOpenJDK File: SimpleDocTreeVisitorTest.java License: GNU General Public License v2.0 | 5 votes |
void run() throws Exception { List<File> files = new ArrayList<File>(); File testSrc = new File(System.getProperty("test.src")); for (File f: testSrc.listFiles()) { if (f.isFile() && f.getName().endsWith(".java")) files.add(f); } JavacTool javac = JavacTool.create(); StandardJavaFileManager fm = javac.getStandardFileManager(null, null, null); Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjectsFromFiles(files); JavacTask t = javac.getTask(null, fm, null, null, null, fos); DocTrees trees = DocTrees.instance(t); Iterable<? extends CompilationUnitTree> units = t.parse(); Set<DocTree.Kind> found = EnumSet.noneOf(DocTree.Kind.class); DeclScanner ds = new DeclScanner(trees, found); for (CompilationUnitTree unit: units) { ds.scan(unit, null); } for (DocTree.Kind k: DocTree.Kind.values()) { if (!found.contains(k) && k != DocTree.Kind.OTHER) error("not found: " + k); } if (errors > 0) throw new Exception(errors + " errors occurred"); }
Example #28
Source Project: openjdk-8 Author: bpupadhyaya File: JavaCompiler.java License: GNU General Public License v2.0 | 5 votes |
/** Try to open input stream with given name. * Report an error if this fails. * @param filename The file name of the input stream to be opened. */ public CharSequence readSource(JavaFileObject filename) { try { inputFiles.add(filename); return filename.getCharContent(false); } catch (IOException e) { log.error("error.reading.file", filename, JavacFileManager.getMessage(e)); return null; } }
Example #29
Source Project: java-n-IDE-for-Android Author: shenghuntianlang File: JavacSourcePosition.java License: Apache License 2.0 | 5 votes |
JavacSourcePosition(JavaFileObject sourcefile, int pos, Position.LineMap lineMap) { this.sourcefile = sourcefile; this.pos = pos; this.lineMap = (pos != Position.NOPOS) ? lineMap : null; }
Example #30
Source Project: hottub Author: dsrg-uoft File: AbstractLog.java License: GNU General Public License v2.0 | 5 votes |
protected DiagnosticSource getSource(JavaFileObject file) { if (file == null) return DiagnosticSource.NO_SOURCE; DiagnosticSource s = sourceMap.get(file); if (s == null) { s = new DiagnosticSource(file, this); sourceMap.put(file, s); } return s; }