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 File: Task_reuseTest.java From openjdk-jdk9 with 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 #2
Source File: TestSearchPaths.java From openjdk-jdk9 with 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 #3
Source File: Utilities.java From netbeans with 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 #4
Source File: JavacTask.java From openjdk-jdk9 with 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 #5
Source File: DiagnosticPresenter.java From java-n-IDE-for-Android with 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 #6
Source File: RetentionAnnoCombo.java From TencentKona-8 with 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 #7
Source File: ClassReader.java From openjdk-jdk8u with 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 #8
Source File: RootDocImpl.java From openjdk-8-source with 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 #9
Source File: DocTreePathScannerTest.java From openjdk-8-source with 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 #10
Source File: AnnotationProcessor.java From buck with 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 #11
Source File: CompilerTest.java From compile-testing with 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 #12
Source File: Log.java From openjdk-8-source with 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 #13
Source File: JavaInMemoryFileObjectTest.java From buck with 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 #14
Source File: RetentionAnnoCombo.java From jdk8u60 with 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 #15
Source File: GetTask_OptionsTest.java From TencentKona-8 with 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 #16
Source File: DslValidationTest.java From dsl-json with 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 #17
Source File: JavadocTaskImplTest.java From TencentKona-8 with 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 #18
Source File: JavacProcessingEnvironment.java From openjdk-jdk8u-backup with 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 #19
Source File: JdkCompiler.java From yugong with 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 #20
Source File: BatchFilerImpl.java From Eclipse-Postfix-Code-Completion with 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 File: GenericOverrideTest.java From hottub with GNU General Public License v2.0 | 5 votes |
public JavaSource() { super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE); source = template.replace("#S1", sig1.paramStr). replace("#S2", sig2.paramStr). replace("#R1", rt1.retStr). replace("#R2", rt2.retStr). replace("#R3", rt3.retStr). replace("#TA1", ta1.typeargStr). replace("#TA2", ta2.typeargStr). replace("#TA3", ta3.typeargStr); }
Example #22
Source File: ClassReader.java From javaide with GNU General Public License v3.0 | 5 votes |
/** * Implement policy to choose to derive information from a source * file or a class file when both are present. May be overridden * by subclasses. */ protected JavaFileObject preferredFileObject(JavaFileObject a, JavaFileObject b) { if (preferSource) return (a.getKind() == JavaFileObject.Kind.SOURCE) ? a : b; else { long adate = a.getLastModified(); long bdate = b.getLastModified(); // 6449326: policy for bad lastModifiedTime in ClassReader //assert adate >= 0 && bdate >= 0; return (adate > bdate) ? a : b; } }
Example #23
Source File: ZipArchive.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
@Override public boolean isNameCompatible(String cn, JavaFileObject.Kind k) { cn.getClass(); // null check if (k == Kind.OTHER && getKind() != k) { return false; } return name.equals(cn + k.extension); }
Example #24
Source File: T7042566.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
public void report(Diagnostic<? extends JavaFileObject> diagnostic) { if (diagnostic.getKind() == Diagnostic.Kind.ERROR) { errDiags = errDiags .append(diagnostic.getMessage(Locale.getDefault())); errorFound = true; } }
Example #25
Source File: GenericOverrideTest.java From openjdk-8 with GNU General Public License v2.0 | 5 votes |
public JavaSource() { super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE); source = template.replace("#S1", sig1.paramStr). replace("#S2", sig2.paramStr). replace("#R1", rt1.retStr). replace("#R2", rt2.retStr). replace("#R3", rt3.retStr). replace("#TA1", ta1.typeargStr). replace("#TA2", ta2.typeargStr). replace("#TA3", ta3.typeargStr); }
Example #26
Source File: JavacFileManager.java From openjdk-jdk9 with 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 #27
Source File: StructuralMostSpecificTest.java From openjdk-8-source with 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 #28
Source File: JavadocTool.java From openjdk-jdk9 with 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 #29
Source File: BaseFileManager.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
public CharBuffer getCachedContent(JavaFileObject file) { ContentCacheEntry e = contentCache.get(file); if (e == null) return null; if (!e.isValid(file)) { contentCache.remove(file); return null; } return e.getValue(); }
Example #30
Source File: BasicSyntaxCombo.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
private void checkErrorKeys ( String className, DiagnosticCollector<JavaFileObject> diagnostics) throws Exception { String expectedErrKey = "compiler.err.illegal.start.of.type"; for (Diagnostic<?> d : diagnostics.getDiagnostics()) { if ((d.getKind() == Diagnostic.Kind.ERROR) && d.getCode().contains(expectedErrKey)) { break; // Found the expected error } else { error("Incorrect error key, expected = " + expectedErrKey + ", Actual = " + d.getCode() + " for className = " + className, srcContent); } } }