javax.annotation.processing.AbstractProcessor#javax.tools.JavaFileObject源码实例Demo

下面列出了javax.annotation.processing.AbstractProcessor#javax.tools.JavaFileObject 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: netbeans   文件: Utilities.java
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;
}
 
源代码2 项目: openjdk-jdk8u   文件: ClassReader.java
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);
        }
    }
}
 
@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
    }
}
 
源代码4 项目: openjdk-8-source   文件: RootDocImpl.java
/**
 * 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;
}
 
源代码5 项目: openjdk-8-source   文件: DocTreePathScannerTest.java
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");
}
 
源代码6 项目: buck   文件: AnnotationProcessor.java
@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;
}
 
源代码7 项目: compile-testing   文件: CompilerTest.java
@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();
}
 
源代码8 项目: openjdk-8-source   文件: Log.java
/** 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);
        }
    });
}
 
源代码9 项目: buck   文件: JavaInMemoryFileObjectTest.java
@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));
}
 
源代码10 项目: jdk8u60   文件: RetentionAnnoCombo.java
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);
}
 
源代码11 项目: TencentKona-8   文件: 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");
    }
}
 
源代码12 项目: dsl-json   文件: DslValidationTest.java
@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.")
	);
}
 
源代码13 项目: TencentKona-8   文件: 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");
    }
}
 
源代码14 项目: yugong   文件: JdkCompiler.java
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);
}
 
源代码15 项目: openjdk-jdk9   文件: 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");
        }
    }
}
 
/** 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();
}
 
源代码17 项目: TencentKona-8   文件: RetentionAnnoCombo.java
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);
}
 
源代码18 项目: openjdk-jdk9   文件: TestSearchPaths.java
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);
}
 
源代码19 项目: openjdk-jdk9   文件: JavacTask.java
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;
}
 
@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);
}
 
源代码21 项目: parceler   文件: MemoryClassLoader.java
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();
}
 
源代码22 项目: openjdk-jdk9   文件: JavacFileManager.java
@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());
}
 
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);
}
 
源代码24 项目: openjdk-jdk9   文件: JavadocTool.java
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));
        }
    }
}
 
源代码25 项目: openjdk-8-source   文件: TestToString.java
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);
}
 
源代码26 项目: postman   文件: PostmanProcessorTest.java
@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");

}
 
源代码27 项目: openjdk-jdk8u   文件: SimpleDocTreeVisitorTest.java
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");
}
 
源代码28 项目: openjdk-8   文件: JavaCompiler.java
/** 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;
    }
}
 
JavacSourcePosition(JavaFileObject sourcefile,
                    int pos,
                    Position.LineMap lineMap) {
    this.sourcefile = sourcefile;
    this.pos = pos;
    this.lineMap = (pos != Position.NOPOS) ? lineMap : null;
}
 
源代码30 项目: hottub   文件: AbstractLog.java
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;
}