Java Code Examples for javax.tools.StandardJavaFileManager#getJavaFileObjects()

The following examples show how to use javax.tools.StandardJavaFileManager#getJavaFileObjects() . These examples are extracted from open source projects. 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: vertx-codegen   File: Compiler.java    License: Apache License 2.0 6 votes vote down vote up
public boolean compile(File... sourceFiles) throws Exception {
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  StandardJavaFileManager fm = compiler.getStandardFileManager(diagnosticListener, null, null);
  if (classOutput == null) {
    classOutput = createTempDir();
  }
  if (sourceOutput == null) {
    sourceOutput = createTempDir();
  }
  fm.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singletonList(classOutput));
  fm.setLocation(StandardLocation.SOURCE_OUTPUT, Collections.singletonList(sourceOutput));
  Iterable<? extends JavaFileObject> fileObjects = fm.getJavaFileObjects(sourceFiles);
  Writer out = new NullWriter();
  JavaCompiler.CompilationTask task = compiler.getTask(out, fm, diagnosticListener, options, null, fileObjects);
  List<Processor> processors = Collections.<Processor>singletonList(processor);
  task.setProcessors(processors);
  try {
    return task.call();
  } catch (RuntimeException e) {
    if (e.getCause() != null && e.getCause() instanceof RuntimeException) {
      throw (RuntimeException)e.getCause();
    } else {
      throw e;
    }
  }
}
 
Example 2
void run() throws Exception {
    File testSrc = new File(System.getProperty("test.src"));

    JavacTool tool = JavacTool.create();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);

    File f = new File(testSrc, T6993305.class.getSimpleName() + ".java");
    Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjects(f);
    JavacTask task = tool.getTask(null, fm, null, null, null, fos);
    Iterable<? extends CompilationUnitTree> cus = task.parse();

    TestScanner s = new TestScanner();
    s.scan(cus, task);

    if (errors > 0)
        throw new Exception(errors + " errors occurred");
}
 
Example 3
Source Project: hottub   File: T6993305.java    License: GNU General Public License v2.0 6 votes vote down vote up
void run() throws Exception {
    File testSrc = new File(System.getProperty("test.src"));

    JavacTool tool = JavacTool.create();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);

    File f = new File(testSrc, T6993305.class.getSimpleName() + ".java");
    Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjects(f);
    JavacTask task = tool.getTask(null, fm, null, null, null, fos);
    Iterable<? extends CompilationUnitTree> cus = task.parse();

    TestScanner s = new TestScanner();
    s.scan(cus, task);

    if (errors > 0)
        throw new Exception(errors + " errors occurred");
}
 
Example 4
void compileWithJSR199() throws IOException {
    String cpath = "C2.jar";
    File clientJarFile = new File(cpath);
    File sourceFileToCompile = new File("C3.java");


    javax.tools.JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    StandardJavaFileManager stdFileManager = javac.getStandardFileManager(diagnostics, null, null);

    List<File> files = new ArrayList<>();
    files.add(clientJarFile);

    stdFileManager.setLocation(StandardLocation.CLASS_PATH, files);

    Iterable<? extends JavaFileObject> sourceFiles = stdFileManager.getJavaFileObjects(sourceFileToCompile);

    if (!javac.getTask(null, stdFileManager, diagnostics, null, null, sourceFiles).call()) {
        throw new AssertionError("compilation failed");
    }
}
 
Example 5
Source Project: jpa-unit   File: TestCodeUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void compileModel(final File destinationFolder) throws IOException {

        final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

        final File[] javaFiles = destinationFolder.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(final File dir, final String name) {
                return name.endsWith(".java");
            }
        });

        final Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(javaFiles);
        compiler.getTask(null, fileManager, null, null, null, compilationUnits).call();
        fileManager.close();
    }
 
Example 6
void run() throws Exception {
    File testSrc = new File(System.getProperty("test.src"));

    JavacTool tool = JavacTool.create();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);

    File f = new File(testSrc, T6993305.class.getSimpleName() + ".java");
    Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjects(f);
    JavacTask task = tool.getTask(null, fm, null, null, null, fos);
    Iterable<? extends CompilationUnitTree> cus = task.parse();

    TestScanner s = new TestScanner();
    s.scan(cus, task);

    if (errors > 0)
        throw new Exception(errors + " errors occurred");
}
 
Example 7
void compileWithJSR199() throws IOException {
    String cpath = "C2.jar";
    File clientJarFile = new File(cpath);
    File sourceFileToCompile = new File("C3.java");


    javax.tools.JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    StandardJavaFileManager stdFileManager = javac.getStandardFileManager(diagnostics, null, null);

    List<File> files = new ArrayList<>();
    files.add(clientJarFile);

    stdFileManager.setLocation(StandardLocation.CLASS_PATH, files);

    Iterable<? extends JavaFileObject> sourceFiles = stdFileManager.getJavaFileObjects(sourceFileToCompile);

    if (!javac.getTask(null, stdFileManager, diagnostics, null, null, sourceFiles).call()) {
        throw new AssertionError("compilation failed");
    }
}
 
Example 8
void compileWithJSR199() throws IOException {
    String cpath = "C2.jar";
    File clientJarFile = new File(cpath);
    File sourceFileToCompile = new File("C3.java");


    javax.tools.JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    StandardJavaFileManager stdFileManager = javac.getStandardFileManager(diagnostics, null, null);

    List<File> files = new ArrayList<>();
    files.add(clientJarFile);

    stdFileManager.setLocation(StandardLocation.CLASS_PATH, files);

    Iterable<? extends JavaFileObject> sourceFiles = stdFileManager.getJavaFileObjects(sourceFileToCompile);

    if (!javac.getTask(null, stdFileManager, diagnostics, null, null, sourceFiles).call()) {
        throw new AssertionError("compilation failed");
    }
}
 
Example 9
/**
 * Verify bad file object is handled correctly.
 */
@Test
public void testBadFileObject() throws Exception {
    File testSrc = new File(System.getProperty("test.src"));
    File srcFile = new File(testSrc, "pkg/C.class");  // unacceptable file kind
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    File outDir = getOutDir();
    fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
    Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(srcFile);
    try {
        DocumentationTask t = tool.getTask(null, fm, null, null, null, files);
        error("getTask succeeded, no exception thrown");
    } catch (IllegalArgumentException e) {
        System.err.println("exception caught as expected: " + e);
    }
}
 
Example 10
/**
 * Verify that expected output files are written via the file manager,
 * for a source file read from the file system with StandardJavaFileManager.
 */
@Test
public void testStandardFileObject() throws Exception {
    File testSrc = new File(System.getProperty("test.src"));
    File srcFile = new File(testSrc, "pkg/C.java");
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    File outDir = getOutDir();
    fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
    Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(srcFile);
    DocumentationTask t = tool.getTask(null, fm, null, null, null, files);
    if (t.call()) {
        System.err.println("task succeeded");
        checkFiles(outDir, standardExpectFiles);
    } else {
        throw new Exception("task failed");
    }
}
 
Example 11
public void run() {
    File srcDir = new File(System.getProperty("test.src"));
    File thisFile = new File(srcDir, getClass().getName() + ".java");

    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = c.getStandardFileManager(null, null, null);

    List<String> opts = Arrays.asList("-proc:only", "-doe");
    Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(thisFile);
    JavacTask t = (JavacTask) c.getTask(null, fm, null, opts, null, files);
    t.setProcessors(Collections.singleton(this));
    boolean ok = t.call();
    if (!ok)
        throw new Error("compilation failed");
}
 
Example 12
Source Project: openjdk-jdk8u   File: Test.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** Doc comment: run */
void run() throws Exception {
    File testSrc = new File(System.getProperty("test.src"));
    File thisFile = new File(testSrc, getClass().getName() + ".java");
    JavacTool javac = JavacTool.create();
    StandardJavaFileManager fm = javac.getStandardFileManager(null, null, null);
    fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File(".")));
    Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjects(thisFile);
    testAnnoProcessor(javac, fm, fos, out, EXPECT_DOC_COMMENTS);
    testTaskListener(javac, fm, fos, out, EXPECT_DOC_COMMENTS);

    if (errors > 0)
        throw new Exception(errors + " errors occurred");
}
 
Example 13
public static void main(String[] args) throws Exception {
    write(test_java, test);

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager manager =
            compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> units = manager.getJavaFileObjects(test_java);
    final StringWriter sw = new StringWriter();
    JavacTask task = (JavacTask) compiler.getTask(sw, manager, null, null,
            null, units);

    new TreeScanner<Boolean, Void>() {
        @Override
        public Boolean visitClass(ClassTree arg0, Void arg1) {
            sw.write(arg0.toString());
            return super.visitClass(arg0, arg1);
        }
    }.scan(task.parse(), null);

    System.out.println("output:");
    System.out.println(sw.toString());
    String found = sw.toString().replaceAll("\\s+", " ").trim();
    String expect = test.replaceAll("\\s+", " ").trim();
    if (!expect.equals(found)) {
        System.out.println("expect: " + expect);
        System.out.println("found:  " + found);
        throw new Exception("unexpected output");
    }
}
 
Example 14
public void run() throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager
        = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> tests
        = fileManager.getJavaFileObjects(writeTestFile());

    JavaCompiler.CompilationTask task =
        ToolProvider.getSystemJavaCompiler().getTask(
                null, null, null,
                Arrays.asList("-processor", this.getClass().getName()), null,
                tests);
    task.call();
}
 
Example 15
Source Project: TencentKona-8   File: Test.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** Doc comment: run */
void run() throws Exception {
    File testSrc = new File(System.getProperty("test.src"));
    File thisFile = new File(testSrc, getClass().getName() + ".java");
    JavacTool javac = JavacTool.create();
    StandardJavaFileManager fm = javac.getStandardFileManager(null, null, null);
    fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File(".")));
    Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjects(thisFile);
    testAnnoProcessor(javac, fm, fos, out, EXPECT_DOC_COMMENTS);
    testTaskListener(javac, fm, fos, out, EXPECT_DOC_COMMENTS);

    if (errors > 0)
        throw new Exception(errors + " errors occurred");
}
 
Example 16
public void run() throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager
        = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> tests
        = fileManager.getJavaFileObjects(writeTestFile());

    JavaCompiler.CompilationTask task =
        ToolProvider.getSystemJavaCompiler().getTask(
                null, null, null,
                Arrays.asList("-processor", this.getClass().getName()), null,
                tests);
    task.call();
}
 
Example 17
public void run() {
    File srcDir = new File(System.getProperty("test.src"));
    File thisFile = new File(srcDir, getClass().getName() + ".java");

    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = c.getStandardFileManager(null, null, null);

    List<String> opts = Arrays.asList("-proc:only", "-doe");
    Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(thisFile);
    JavacTask t = (JavacTask) c.getTask(null, fm, null, opts, null, files);
    t.setProcessors(Collections.singleton(this));
    boolean ok = t.call();
    if (!ok)
        throw new Error("compilation failed");
}
 
Example 18
Source Project: jdk8u60   File: Test.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** Doc comment: run */
void run() throws Exception {
    File testSrc = new File(System.getProperty("test.src"));
    File thisFile = new File(testSrc, getClass().getName() + ".java");
    JavacTool javac = JavacTool.create();
    StandardJavaFileManager fm = javac.getStandardFileManager(null, null, null);
    fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File(".")));
    Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjects(thisFile);
    testAnnoProcessor(javac, fm, fos, out, EXPECT_DOC_COMMENTS);
    testTaskListener(javac, fm, fos, out, EXPECT_DOC_COMMENTS);

    if (errors > 0)
        throw new Exception(errors + " errors occurred");
}
 
Example 19
void run() throws IOException {
    File testSrc = new File(System.getProperty("test.src"));
    File testClasses = new File(System.getProperty("test.classes"));

    JavacTool tool = (JavacTool) ToolProvider.getSystemJavaCompiler();
    final ClassLoader cl = getClass().getClassLoader();
    Context c = new Context();
    StandardJavaFileManager fm = new JavacFileManager(c, true, null) {
        @Override
        protected ClassLoader getClassLoader(URL[] urls) {
            return new URLClassLoader(urls, cl) {
                @Override
                public void close() throws IOException {
                    System.err.println(getClass().getName() + " closing");
                    TestClose2.this.closedCount++;
                    TestClose2.this.closedIsLast = true;
                    super.close();
                }
            };
        }
    };

    fm.setLocation(StandardLocation.CLASS_OUTPUT,
            Collections.singleton(new File(".")));
    fm.setLocation(StandardLocation.ANNOTATION_PROCESSOR_PATH,
            Collections.singleton(testClasses));
    Iterable<? extends JavaFileObject> files =
            fm.getJavaFileObjects(new File(testSrc, TestClose2.class.getName() + ".java"));
    List<String> options = Arrays.asList(
            "--add-exports", "jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED",
            "--add-exports", "jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED",
            "--add-exports", "jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED",
            "-processor", TestClose2.class.getName());

    JavacTask task = tool.getTask(null, fm, null, options, null, files);
    task.setTaskListener(this);

    if (!task.call())
        throw new Error("compilation failed");

    if (closedCount == 0)
        throw new Error("no closing message");
    else if (closedCount > 1)
        throw new Error(closedCount + " closed messages");

    if (!closedIsLast)
        throw new Error("closing message not last");
}
 
Example 20
@Test
public void testIsomorphism() throws Exception {
    // Generate java files for interaction models
    String path = "target/temp/generated-src/testIsomorphism";

    Application.main(new String[] {
        "--namespace", "com.example",
        "--output", path,
        "--skill-name", "PetSkill",
        "--model", "en-US=models/en-US.json",
        "--model", "de-DE=models/de-DE.json"
    });

    // Compile generated code
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    File typeFile = new File(path + "/src/main/java/com/example/slots/PetType.java");
    File intentFile = new File(path + "/src/main/java/com/example/intents/PetTypeIntent.java");
    File skillFile = new File(path + "/src/main/java/com/example/PetSkill.java");
    File javaDir = new File(path + "/src/main/java");
    File resourcesDir = new File(path + "/src/main/resources");
    Iterable<? extends JavaFileObject> files = fileManager.getJavaFileObjects(typeFile, intentFile, skillFile);
    JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, null, null, files);
    assertTrue(task.call());
    fileManager.close();

    // Load the generated code
    URLClassLoader classLoader = new URLClassLoader(new URL[]{
        javaDir.toURI().toURL(),
        resourcesDir.toURI().toURL()
    });
    Class<?> clazz = classLoader.loadClass("com.example.PetSkill");
    SkillModelSupplier skillModelSupplier =  (SkillModelSupplier) clazz.newInstance();

    // Render the interaction model and ensure it equals the original interaction model
    for (Locale locale : Arrays.asList(Locale.forLanguageTag("en-US"), Locale.forLanguageTag("de-DE"))) {
        InteractionModelEnvelope expectedModel = mapper.readValue(new File("models/" + locale.toLanguageTag() + ".json"), InteractionModelEnvelope.class);
        InteractionModelEnvelope actualModel = renderer.render(skillModelSupplier.getSkillModel(), locale);
        assertEquals(
            mapper.writerWithDefaultPrettyPrinter().writeValueAsString(expectedModel),
            mapper.writerWithDefaultPrettyPrinter().writeValueAsString(actualModel));
    }
}