Java Code Examples for javax.tools.StandardJavaFileManager

The following are top voted examples for showing how to use javax.tools.StandardJavaFileManager. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: openjdk-jdk10   File: GetTask_FileObjectsTest.java   View source code 11 votes vote down vote up
/**
 * 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();
    try (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 2
Project: openjdk-jdk10   File: GetTask_FileObjectsTest.java   View source code 11 votes vote down vote up
/**
 * Verify null is handled correctly.
 */
@Test
public void testNull() throws Exception {
    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((JavaFileObject) null);
        try {
            DocumentationTask t = tool.getTask(null, fm, null, null, null, files);
            error("getTask succeeded, no exception thrown");
        } catch (NullPointerException e) {
            System.err.println("exception caught as expected: " + e);
        }
    }
}
 
Example 3
Project: openjdk-jdk10   File: GetTask_DocletClassTest.java   View source code 9 votes vote down vote up
/**
 * 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");
        }
    }
}
 
Example 4
Project: openjdk-jdk10   File: GetTask_FileObjectsTest.java   View source code 8 votes vote down vote up
/**
 * 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();
    try (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 5
Project: incubator-netbeans   File: MRJARCachingFileManagerTest.java   View source code 7 votes vote down vote up
public void testJavac() throws Exception {
    final JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    final StandardJavaFileManager fm = jc.getStandardFileManager(
            null,
            Locale.ENGLISH,
            Charset.forName("UTF-8"));  //NOI18N
    fm.setLocation(
            StandardLocation.CLASS_PATH,
            Collections.singleton(FileUtil.archiveOrDirForURL(mvCp.entries().get(0).getURL())));
    Iterable<JavaFileObject> res = fm.list(
            StandardLocation.CLASS_PATH,
            "", //NOI18N
            EnumSet.of(JavaFileObject.Kind.CLASS),
            true);
    assertEquals(3, StreamSupport.stream(res.spliterator(), false).count());
}
 
Example 6
Project: moduletools   File: JavacModuleParser.java   View source code 6 votes vote down vote up
public static void parse(Path moduleInfoPath, ModuleClassVisitor moduleClassVisitor) throws IOException {
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  try(StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)) {
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(moduleInfoPath);
    CompilationTask task = compiler.getTask(null, fileManager, null, null, null, compilationUnits);
    JavacTask javacTask = (JavacTask)task;
    Iterable<? extends CompilationUnitTree> units= javacTask.parse();
    CompilationUnitTree unit = units.iterator().next();

    ModuleHandler moduleHandler = new ModuleHandler(moduleClassVisitor);
    TreeVisitor<?,?> visitor = (TreeVisitor<?,?>)Proxy.newProxyInstance(TreeVisitor.class.getClassLoader(), new Class<?>[]{ TreeVisitor.class},
        (proxy, method, args) -> {
          ModuleHandler.METHOD_MAP
          .getOrDefault(method.getName(), (handler, node, v) -> { 
            throw new AssertionError("invalid node " + node.getClass());
          })
          .visit(moduleHandler, (Tree)args[0], (TreeVisitor<?,?>)proxy);
          return null;
        });

    unit.accept(visitor, null);
  }
}
 
Example 7
Project: openjdk-jdk10   File: TestDefaultMethodsSyntax.java   View source code 6 votes vote down vote up
public static void main(String... args) throws Exception {

        //create default shared JavaCompiler - reused across multiple compilations
        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
        try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {

            for (VersionKind vk : VersionKind.values()) {
                for (EnclosingKind ek : EnclosingKind.values()) {
                    for (MethodKind mk : MethodKind.values()) {
                        for (ModifierKind modk1 : ModifierKind.values()) {
                            for (ModifierKind modk2 : ModifierKind.values()) {
                                new TestDefaultMethodsSyntax(vk, ek, mk, modk1, modk2).run(comp, fm);
                            }
                        }
                    }
                }
            }
            System.out.println("Total check executed: " + checkCount);
        }
    }
 
Example 8
Project: openjdk-jdk10   File: SetLocationForModule.java   View source code 6 votes vote down vote up
@Test
public void testSystemModules(Path base) throws IOException {
    try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {
        Location locn = StandardLocation.SYSTEM_MODULES;

        Location javaCompiler = fm.getLocationForModule(locn, "java.compiler");
        // cannot easily verify default setting: could be jrt: or exploded image

        Path override1 = Files.createDirectories(base.resolve("override1"));
        fm.setLocationForModule(locn, "java.compiler", List.of(override1));
        checkEqual("override setting 1",
                fm.getLocationAsPaths(javaCompiler), override1);

        Path override2 = Files.createDirectories(base.resolve("override2"));
        fm.setLocationFromPaths(javaCompiler, List.of(override2));
        checkEqual("override setting 2",
                fm.getLocationAsPaths(javaCompiler), override2);
    }
}
 
Example 9
Project: javaide   File: JavacProcessingEnvironment.java   View source code 6 votes vote down vote up
/**
 * Returns an empty processor iterator if no processors are on the
 * relevant path, otherwise if processors are present, logs an
 * error.  Called when a service loader is unavailable for some
 * reason, either because a service loader class cannot be found
 * or because a security policy prevents class loaders from being
 * created.
 *
 * @param key The resource key to use to log an error message
 * @param e   If non-null, pass this exception to Abort
 */
private Iterator<Processor> handleServiceLoaderUnavailability(String key, Exception e) {
    JavaFileManager fileManager = context.get(JavaFileManager.class);

    if (fileManager instanceof JavacFileManager) {
        StandardJavaFileManager standardFileManager = (JavacFileManager) fileManager;
        Iterable<? extends File> workingPath = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
            ? standardFileManager.getLocation(ANNOTATION_PROCESSOR_PATH)
            : standardFileManager.getLocation(CLASS_PATH);

        if (needClassLoader(options.get(PROCESSOR), workingPath) )
            handleException(key, e);

    } else {
        handleException(key, e);
    }

    java.util.List<Processor> pl = Collections.emptyList();
    return pl.iterator();
}
 
Example 10
Project: openjdk-jdk10   File: ContainsTest.java   View source code 6 votes vote down vote up
void checkContains(StandardJavaFileManager fm, Location l, FileObject fo, boolean expect) throws IOException {
    boolean found = fm.contains(l, fo);
    if (found) {
        if (expect) {
            out.println("file found, as expected: " + l + " " + fo.getName());
        } else {
            error("file not found: " + l + " " + fo.getName());
        }
    } else {
        if (expect) {
            error("file found unexpectedly: " + l + " " + fo.getName());
        } else {
            out.println("file not found, as expected: " + l + " " + fo.getName());
        }
    }
}
 
Example 11
Project: openjdk-jdk10   File: T7159016.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    File src = new File("C.java");
    Writer w = new FileWriter(src);
    try {
        w.write("import static p.Generated.m;\nclass C { {m(); } }\n");
        w.flush();
    } finally {
        w.close();
    }
    JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = jc.getStandardFileManager(null, null, null)) {
        JavaCompiler.CompilationTask task = jc.getTask(null, fm, null, null, null,
                                                       fm.getJavaFileObjects(src));
        task.setProcessors(Collections.singleton(new Proc()));
        if (!task.call()) {
            throw new Error("Test failed");
        }
    }
}
 
Example 12
Project: OpenJSharp   File: JavacProcessingEnvironment.java   View source code 6 votes vote down vote up
/**
 * Returns an empty processor iterator if no processors are on the
 * relevant path, otherwise if processors are present, logs an
 * error.  Called when a service loader is unavailable for some
 * reason, either because a service loader class cannot be found
 * or because a security policy prevents class loaders from being
 * created.
 *
 * @param key The resource key to use to log an error message
 * @param e   If non-null, pass this exception to Abort
 */
private Iterator<Processor> handleServiceLoaderUnavailability(String key, Exception e) {
    JavaFileManager fileManager = context.get(JavaFileManager.class);

    if (fileManager instanceof JavacFileManager) {
        StandardJavaFileManager standardFileManager = (JavacFileManager) fileManager;
        Iterable<? extends File> workingPath = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
            ? standardFileManager.getLocation(ANNOTATION_PROCESSOR_PATH)
            : standardFileManager.getLocation(CLASS_PATH);

        if (needClassLoader(options.get(PROCESSOR), workingPath) )
            handleException(key, e);

    } else {
        handleException(key, e);
    }

    java.util.List<Processor> pl = Collections.emptyList();
    return pl.iterator();
}
 
Example 13
Project: OpenJSharp   File: DocFileFactory.java   View source code 6 votes vote down vote up
/**
 * Get the appropriate factory, based on the file manager given in the
 * configuration.
 */
static synchronized DocFileFactory getFactory(Configuration configuration) {
    DocFileFactory f = factories.get(configuration);
    if (f == null) {
        JavaFileManager fm = configuration.getFileManager();
        if (fm instanceof StandardJavaFileManager)
            f = new StandardDocFileFactory(configuration);
        else {
            try {
                Class<?> pathFileManagerClass =
                        Class.forName("com.sun.tools.javac.nio.PathFileManager");
                if (pathFileManagerClass.isAssignableFrom(fm.getClass()))
                    f = new PathDocFileFactory(configuration);
            } catch (Throwable t) {
                throw new IllegalStateException(t);
            }
        }
        factories.put(configuration, f);
    }
    return f;
}
 
Example 14
Project: openjdk-jdk10   File: SetLocationForModule.java   View source code 6 votes vote down vote up
@Test
public void testBasic(Path base) throws IOException {
    try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {
        Location[] locns = {
            StandardLocation.SOURCE_PATH,
            StandardLocation.CLASS_PATH,
            StandardLocation.PLATFORM_CLASS_PATH,
        };
        // set a value
        Path out = Files.createDirectories(base.resolve("out"));
        for (Location locn : locns) {
            checkException("unsupported for location",
                    IllegalArgumentException.class,
                    "location is not an output location or a module-oriented location: " + locn,
                    () -> fm.setLocationForModule(locn, "m", List.of(out)));
        }
    }
}
 
Example 15
Project: openjdk-jdk10   File: JavacProcessingEnvironment.java   View source code 6 votes vote down vote up
/**
 * Returns an empty processor iterator if no processors are on the
 * relevant path, otherwise if processors are present, logs an
 * error.  Called when a service loader is unavailable for some
 * reason, either because a service loader class cannot be found
 * or because a security policy prevents class loaders from being
 * created.
 *
 * @param key The resource key to use to log an error message
 * @param e   If non-null, pass this exception to Abort
 */
private Iterator<Processor> handleServiceLoaderUnavailability(String key, Exception e) {
    if (fileManager instanceof JavacFileManager) {
        StandardJavaFileManager standardFileManager = (JavacFileManager) fileManager;
        Iterable<? extends Path> workingPath = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
            ? standardFileManager.getLocationAsPaths(ANNOTATION_PROCESSOR_PATH)
            : standardFileManager.getLocationAsPaths(CLASS_PATH);

        if (needClassLoader(options.get(Option.PROCESSOR), workingPath) )
            handleException(key, e);

    } else {
        handleException(key, e);
    }

    java.util.List<Processor> pl = Collections.emptyList();
    return pl.iterator();
}
 
Example 16
Project: openjdk-jdk10   File: FailureAtomicity.java   View source code 6 votes vote down vote up
static void javac(Path dest, List<Path> sourceFiles) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fileManager =
                 compiler.getStandardFileManager(null, null, null)) {
        List<File> files = sourceFiles.stream()
                                      .map(p -> p.toFile())
                                      .collect(Collectors.toList());
        Iterable<? extends JavaFileObject> compilationUnits =
                fileManager.getJavaFileObjectsFromFiles(files);
        fileManager.setLocation(StandardLocation.CLASS_OUTPUT,
                                Arrays.asList(dest.toFile()));
        fileManager.setLocation(StandardLocation.CLASS_PATH,
                                Arrays.asList(TEST_CLASSES.toFile()));
        JavaCompiler.CompilationTask task = compiler
                .getTask(null, fileManager, null, null, null, compilationUnits);
        boolean passed = task.call();
        if (!passed)
            throw new RuntimeException("Error compiling " + files);
    }
}
 
Example 17
Project: openjdk-jdk10   File: TestSelfRef.java   View source code 6 votes vote down vote up
public static void main(String... args) throws Exception {

        //create default shared JavaCompiler - reused across multiple compilations
        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
        try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {

            for (EnclosingKind ek : EnclosingKind.values()) {
                for (SiteKind sk : SiteKind.values()) {
                    if (sk == SiteKind.STATIC_INIT && ek == EnclosingKind.MEMBER_INNER)
                        continue;
                    for (InnerKind ik : InnerKind.values()) {
                        if (ik != InnerKind.NONE && sk == SiteKind.NONE)
                            break;
                        for (RefKind rk : RefKind.values()) {
                            new TestSelfRef(ek, sk, ik, rk).run(comp, fm);
                        }
                    }
                }
            }
            System.out.println("Total check executed: " + checkCount);
        }
    }
 
Example 18
Project: openjdk-jdk10   File: ModuleInfoTreeAccess.java   View source code 6 votes vote down vote up
@Test
public void testTreePathForModuleDecl(Path base) throws Exception {

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {
        Path src = base.resolve("src");
        tb.writeJavaFiles(src, "/** Test module */ module m1x {}");

        Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(findJavaFiles(src));
        JavacTask task = (JavacTask) compiler.getTask(null, fm, null, null, null, files);

        task.analyze();
        JavacTrees trees = JavacTrees.instance(task);
        ModuleElement mdle = (ModuleElement) task.getElements().getModuleElement("m1x");

        TreePath path = trees.getPath(mdle);
        assertNotNull("path", path);

        ModuleElement mdle1 = (ModuleElement) trees.getElement(path);
        assertNotNull("mdle1", mdle1);

        DocCommentTree docCommentTree = trees.getDocCommentTree(mdle);
        assertNotNull("docCommentTree", docCommentTree);
    }
}
 
Example 19
Project: openjdk-jdk10   File: EdgeCases.java   View source code 6 votes vote down vote up
@Test
public void testModuleSymbolOutterMostClass(Path base) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {
        Path moduleSrc = base.resolve("module-src");
        Path m1 = moduleSrc.resolve("m1x");

        tb.writeJavaFiles(m1, "module m1x { }");

        Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(findJavaFiles(moduleSrc));
        com.sun.source.util.JavacTask task =
            (com.sun.source.util.JavacTask) compiler.getTask(null, fm, null, null, null, files);

        task.analyze();

        ModuleSymbol msym = (ModuleSymbol) task.getElements().getModuleElement("m1x");

        msym.outermostClass();
    }
}
 
Example 20
Project: dubbocloud   File: JdkCompiler.java   View source code 6 votes vote down vote up
public JdkCompiler(){
    options = new ArrayList<String>();
    options.add("-target");
    options.add("1.6");
    StandardJavaFileManager manager = compiler.getStandardFileManager(diagnosticCollector, null, null);
    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    if (loader instanceof URLClassLoader 
            && (! loader.getClass().getName().equals("sun.misc.Launcher$AppClassLoader"))) {
        try {
            URLClassLoader urlClassLoader = (URLClassLoader) loader;
            List<File> files = new ArrayList<File>();
            for (URL url : urlClassLoader.getURLs()) {
                files.add(new File(url.getFile()));
            }
            manager.setLocation(StandardLocation.CLASS_PATH, files);
        } catch (IOException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
    classLoader = AccessController.doPrivileged(new PrivilegedAction<ClassLoaderImpl>() {
        public ClassLoaderImpl run() {
            return new ClassLoaderImpl(loader);
        }
    });
    javaFileManager = new JavaFileManagerImpl(manager, classLoader);
}
 
Example 21
Project: openjdk-jdk10   File: TestDuplicateImport.java   View source code 6 votes vote down vote up
public static void main(String... args) throws Exception {

        //create default shared JavaCompiler - reused across multiple compilations
        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);

        for (ImportKind ik1 : ImportKind.values()) {
            for (ImportKind ik2 : ImportKind.values()) {
                for (QualifierKind qk1 : QualifierKind.values()) {
                    for (QualifierKind qk2 : QualifierKind.values()) {
                        for (NameKind nk1 : NameKind.values()) {
                            for (NameKind nk2 : NameKind.values()) {
                                new TestDuplicateImport(ik1, ik2, qk1, qk2, nk1, nk2).run(comp, fm);
                            }
                        }
                    }
                }
            }
        }
        System.out.println("Total check executed: " + checkCount);
    }
 
Example 22
Project: openjdk-jdk10   File: JImageGenerator.java   View source code 6 votes vote down vote up
public static boolean compile(Path source, Path destination, String... options) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager jfm = compiler.getStandardFileManager(null, null, null)) {
        List<Path> sources
                = Files.find(source, Integer.MAX_VALUE,
                (file, attrs) -> file.toString().endsWith(".java"))
                .collect(Collectors.toList());

        Files.createDirectories(destination);
        jfm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT, Collections.singleton(destination));

        List<String> opts = Arrays.asList(options);
        JavaCompiler.CompilationTask task
                = compiler.getTask(null, jfm, null, opts, null,
                jfm.getJavaFileObjectsFromPaths(sources));
        List<String> list = new ArrayList<>(opts);
        list.addAll(sources.stream()
                .map(Path::toString)
                .collect(Collectors.toList()));
        System.err.println("javac options: " + optionsPrettyPrint(list.toArray(new String[list.size()])));
        return task.call();
    }
}
 
Example 23
Project: openjdk-jdk10   File: GetTask_DocletClassTest.java   View source code 6 votes vote down vote up
/**
 * 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;
        }
    }
}
 
Example 24
Project: openjdk-jdk10   File: GetTask_FileManagerTest.java   View source code 6 votes vote down vote up
/**
 * 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");
    }
}
 
Example 25
Project: dremio-oss   File: TestClassCompilers.java   View source code 6 votes vote down vote up
@BeforeClass
public static void compileDependencyClass() throws IOException, ClassNotFoundException {
  JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
  Assume.assumeNotNull(javaCompiler);

  classes = temporaryFolder.newFolder("classes");;

  StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, Locale.ROOT, UTF_8);
  fileManager.setLocation(StandardLocation.CLASS_OUTPUT, ImmutableList.of(classes));

  SimpleJavaFileObject compilationUnit = new SimpleJavaFileObject(URI.create("FooTest.java"), Kind.SOURCE) {
    String fooTestSource = Resources.toString(Resources.getResource("com/dremio/exec/compile/FooTest.java"), UTF_8);
    @Override
    public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
      return fooTestSource;
    }
  };

  CompilationTask task = javaCompiler.getTask(null, fileManager, null, Collections.<String>emptyList(), null, ImmutableList.of(compilationUnit));
  assertTrue(task.call());
}
 
Example 26
Project: openjdk-jdk10   File: ModuleSourcePathTest.java   View source code 6 votes vote down vote up
@Test
public void setLocation(Path base) throws Exception {
    Path src = base.resolve("src");
    tb.writeJavaFiles(src.resolve("m1x"), "module m1x { }", "package a; class A { }");
    Path modules = base.resolve("modules");
    tb.createDirectories(modules);

    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = c.getStandardFileManager(null, null, null)) {
        fm.setLocationFromPaths(StandardLocation.MODULE_SOURCE_PATH, List.of(src));
        new JavacTask(tb)
                .options("-XDrawDiagnostics")
                .fileManager(fm)
                .outdir(modules)
                .files(findJavaFiles(src))
                .run()
                .writeAll();

        checkFiles(modules.resolve("m1x/module-info.class"), modules.resolve("m1x/a/A.class"));
    }
}
 
Example 27
Project: openjdk-jdk10   File: CompilerUtils.java   View source code 6 votes vote down vote up
/**
 * Compile all the java sources in {@code <source>/**} to
 * {@code <destination>/**}. The destination directory will be created if
 * it doesn't exist.
 *
 * All warnings/errors emitted by the compiler are output to System.out/err.
 *
 * @return true if the compilation is successful
 *
 * @throws IOException if there is an I/O error scanning the source tree or
 *                     creating the destination directory
 */
public static boolean compile(Path source, Path destination, String... options)
    throws IOException
{
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager jfm = compiler.getStandardFileManager(null, null, null);

    List<Path> sources
        = Files.find(source, Integer.MAX_VALUE,
                     (file, attrs) -> (file.toString().endsWith(".java")))
               .collect(Collectors.toList());

    Files.createDirectories(destination);
    jfm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT,
                             Arrays.asList(destination));

    List<String> opts = Arrays.asList(options);
    JavaCompiler.CompilationTask task
        = compiler.getTask(null, jfm, null, opts, null,
                           jfm.getJavaFileObjectsFromPaths(sources));

    return task.call();
}
 
Example 28
Project: openjdk-jdk10   File: CompilerUtils.java   View source code 6 votes vote down vote up
/**
 * Compile the specified module from the given module sourcepath
 *
 * All warnings/errors emitted by the compiler are output to System.out/err.
 *
 * @return true if the compilation is successful
 *
 * @throws IOException if there is an I/O error scanning the source tree or
 *                     creating the destination directory
 */
public static boolean compileModule(Path source, Path destination,
                                    String moduleName, String... options) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager jfm = compiler.getStandardFileManager(null, null, null);

    try {
        Files.createDirectories(destination);
        jfm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT,
                                 Arrays.asList(destination));
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }

    Stream<String> opts = Arrays.stream(new String[] {
        "--module-source-path", source.toString(), "-m", moduleName
    });
    List<String> javacOpts = Stream.concat(opts, Arrays.stream(options))
                                    .collect(Collectors.toList());
    JavaCompiler.CompilationTask task
        = compiler.getTask(null, jfm, null, javacOpts, null, null);
    return task.call();
}
 
Example 29
Project: openjdk-jdk10   File: TestSuperclass.java   View source code 6 votes vote down vote up
public static void main(String... args) throws Exception {
    JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {
        int errors = 0;

        for (ClassKind ck: ClassKind.values()) {
            for (GenericKind gk: GenericKind.values()) {
                for (SuperKind sk: SuperKind.values()) {
                    errors += new TestSuperclass(ck, gk, sk).run(comp, fm);
                }
            }
        }

        if (errors > 0)
            throw new Exception(errors + " errors found");
    }
}
 
Example 30
Project: openjdk-jdk10   File: TestSuperclass.java   View source code 6 votes vote down vote up
int run(JavaCompiler comp, StandardJavaFileManager fm) throws IOException {
    System.err.println("test: ck:" + ck + " gk:" + gk + " sk:" + sk);
    File testDir = new File(ck + "-" + gk + "-" + sk);
    testDir.mkdirs();
    fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(testDir));

    JavaSource js = new JavaSource();
    System.err.println(js.getCharContent(false));
    CompilationTask t = comp.getTask(null, fm, null, null, null, Arrays.asList(js));
    if (!t.call())
        throw new Error("compilation failed");

    File testClass = new File(testDir, "Test.class");
    String out = javap(testClass);

    // Extract class sig from first line of Java source
    String expect = js.source.replaceAll("(?s)^(.* Test[^{]+?) *\\{.*", "$1");

    // Extract class sig from line from javap output
    String found = out.replaceAll("(?s).*\n(.* Test[^{]+?) *\\{.*", "$1");

    checkEqual("class signature", expect, found);

    return errors;
}
 
Example 31
Project: openjdk-jdk10   File: GenericConstructorAndDiamondTest.java   View source code 6 votes vote down vote up
public static void main(String... args) throws Exception {

        //create default shared JavaCompiler - reused across multiple compilations
        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
        try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {
            for (BoundKind boundKind : BoundKind.values()) {
                for (ConstructorKind constructorKind : ConstructorKind.values()) {
                    for (TypeArgumentKind declArgKind : TypeArgumentKind.values()) {
                        for (TypeArgArity arity : TypeArgArity.values()) {
                            for (TypeArgumentKind useArgKind : TypeArgumentKind.values()) {
                                for (TypeArgumentKind diamondArgKind : TypeArgumentKind.values()) {
                                    for (ArgumentKind argKind : ArgumentKind.values()) {
                                        new GenericConstructorAndDiamondTest(boundKind, constructorKind,
                                                declArgKind, arity, useArgKind, diamondArgKind, argKind).run(comp, fm);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
 
Example 32
Project: openjdk-jdk10   File: GetTask_FileObjectsTest.java   View source code 6 votes vote down vote up
/**
 * 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();
    try (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 33
Project: openjdk-jdk10   File: GetTask_FileObjectsTest.java   View source code 6 votes vote down vote up
/**
 * Verify null is handled correctly.
 */
@Test
public void testNull() throws Exception {
    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((JavaFileObject) null);
        try {
            DocumentationTask t = tool.getTask(null, fm, null, null, null, files);
            error("getTask succeeded, no exception thrown");
        } catch (NullPointerException e) {
            System.err.println("exception caught as expected: " + e);
        }
    }
}
 
Example 34
Project: openjdk-jdk10   File: ArrayCreationTree.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    PrintWriter out = new PrintWriter(System.out, true);
    JavacTool tool = JavacTool.create();
    try (StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null)) {
        File testSrc = new File(System.getProperty("test.src"));
        Iterable<? extends JavaFileObject> f =
            fm.getJavaFileObjectsFromFiles(Arrays.asList(new File(testSrc, "ArrayCreationTree.java")));
        JavacTask task = tool.getTask(out, fm, null, null, null, f);
        Iterable<? extends CompilationUnitTree> trees = task.parse();
        out.flush();

        Scanner s = new Scanner();
        for (CompilationUnitTree t: trees)
            s.scan(t, null);
    }
}
 
Example 35
Project: openjdk-jdk10   File: BadLambdaExpr.java   View source code 6 votes vote down vote up
public static void main(String... args) throws Exception {

        //create default shared JavaCompiler - reused across multiple compilations
        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
        try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {

            for (ParameterListKind plk : ParameterListKind.values()) {
                for (ParameterKind pk : ParameterKind.values()) {
                    for (ArrowKind ak : ArrowKind.values()) {
                        for (ExprKind ek : ExprKind.values()) {
                            new BadLambdaExpr(plk, pk, ak, ek).run(comp, fm);
                        }
                    }
                }
            }
            System.out.println("Total check executed: " + checkCount);
        }
    }
 
Example 36
Project: openjdk-jdk10   File: GetTask_OptionsTest.java   View source code 6 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example 37
Project: openjdk-jdk10   File: TestGetScope.java   View source code 6 votes vote down vote up
public void run() throws IOException {
    File srcDir = new File(System.getProperty("test.src"));
    File thisFile = new File(srcDir, getClass().getName() + ".java");

    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    try (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 38
Project: openjdk-jdk10   File: GetTask_DocletClassTest.java   View source code 6 votes vote down vote up
/**
 * 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) {
            Throwable c = e.getCause();
            if (c.getClass() == UnexpectedError.class)
                System.err.println("exception caught as expected: " + c);
            else
                throw e;
        }
    }
}
 
Example 39
Project: openjdk-jdk10   File: GetTask_FileManagerTest.java   View source code 6 votes vote down vote up
/**
 * 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");
    }
}
 
Example 40
Project: Reer   File: JdkJavaCompiler.java   View source code 5 votes vote down vote up
private JavaCompiler.CompilationTask createCompileTask(JavaCompileSpec spec) {
    List<String> options = new JavaCompilerArgumentsBuilder(spec).build();
    JavaCompiler compiler = javaHomeBasedJavaCompilerFactory.create();
    CompileOptions compileOptions = spec.getCompileOptions();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, compileOptions.getEncoding() != null ? Charset.forName(compileOptions.getEncoding()) : null);
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(spec.getSource());
    return compiler.getTask(null, null, null, options, null, compilationUnits);
}