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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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);
}
 
Example 41
Project: openjdk-jdk10   File: TestTreePath.java   Source Code and License 5 votes vote down vote up
public void run() throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (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 42
Project: openjdk-jdk10   File: TestSelfRef.java   Source Code and License 5 votes vote down vote up
void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception {
    JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker,
            null, null, Arrays.asList(source));
    try {
        ct.analyze();
    } catch (Throwable ex) {
        throw new AssertionError("Error thron when compiling the following code:\n" + source.getCharContent(true));
    }
    check();
}
 
Example 43
Project: openjdk-jdk10   File: T6458823.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new RuntimeException("can't get javax.tools.JavaCompiler!");
    }
    DiagnosticCollector<JavaFileObject> diagColl =
        new DiagnosticCollector<JavaFileObject>();
    try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {
        List<String> options = new ArrayList<String>();
        options.add("-processor");
        options.add("MyProcessor");
        options.add("-proc:only");
        List<File> files = new ArrayList<File>();
        files.add(new File(T6458823.class.getResource("TestClass.java").toURI()));
        final CompilationTask task = compiler.getTask(null, fm, diagColl,
            options, null, fm.getJavaFileObjectsFromFiles(files));
        task.call();
        int diagCount = 0;
        for (Diagnostic<? extends JavaFileObject> diag : diagColl.getDiagnostics()) {
            if (diag.getKind() != Diagnostic.Kind.WARNING) {
                throw new AssertionError("Only warnings expected");
            }
            System.out.println(diag);
            if (diag.getPosition() == Diagnostic.NOPOS) {
                throw new AssertionError("No position info in message");
            }
            if (diag.getSource() == null) {
                throw new AssertionError("No source info in message");
            }
            diagCount++;
        }
        if (diagCount != 2) {
            throw new AssertionError("unexpected number of warnings: " +
                diagCount + ", expected: 2");
        }
    }
}
 
Example 44
Project: incubator-netbeans   File: SetupHid.java   Source Code and License 5 votes vote down vote up
private static void compile(List<String> options, Iterable<File> files) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager mgr = compiler.getStandardFileManager(null, null, null);
    List<String> fullOptions = new ArrayList<String>(options);
    fullOptions.addAll(Arrays.asList("-source", "1.5", "-target", "1.5"));
    if (!compiler.getTask(null, mgr, null, fullOptions, null, mgr.getJavaFileObjectsFromFiles(files)).call()) {
        throw new IOException("compilation failed");
    }
}
 
Example 45
Project: openjdk-jdk10   File: SimpleDocTreeVisitorTest.java   Source Code and License 5 votes vote down vote up
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();
    try (StandardJavaFileManager fm = javac.getStandardFileManager(null, null, null)) {

        Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjectsFromFiles(files);

        JavacTask t = javac.getTask(null, fm, null, null, null, fos);
        DocTrees trees = DocTrees.instance(t);

        Iterable<? extends CompilationUnitTree> units = t.parse();

        Set<DocTree.Kind> found = EnumSet.noneOf(DocTree.Kind.class);
        DeclScanner ds = new DeclScanner(trees, found);
        for (CompilationUnitTree unit: units) {
            ds.scan(unit, null);
        }

        for (DocTree.Kind k: DocTree.Kind.values()) {
            if (!found.contains(k) && k != DocTree.Kind.OTHER)
                error("not found: " + k);
        }

        if (errors > 0)
            throw new Exception(errors + " errors occurred");
    }
}
 
Example 46
Project: openjdk-jdk10   File: DocCommentTreeApiTester.java   Source Code and License 5 votes vote down vote up
/**
 * Tests getting a DocCommentTree from an element, as well
 * as test if break iterator setter/getter works correctly.
 *
 * @param javaFileName a test file to be processed
 * @param expected the expected output
 * @throws java.io.IOException
 */
public void runElementAndBreakIteratorTests(String javaFileName, String expected) throws IOException {
    List<File> javaFiles = new ArrayList<>();
    javaFiles.add(new File(testSrc, javaFileName));

    List<File> dirs = new ArrayList<>();
    dirs.add(new File(testSrc));

    try (StandardJavaFileManager fm = javac.getStandardFileManager(null, null, null)) {
        fm.setLocation(javax.tools.StandardLocation.SOURCE_PATH, dirs);
        Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjectsFromFiles(javaFiles);

        final JavacTask t = javac.getTask(null, fm, null, null, null, fos);
        final DocTrees trees = DocTrees.instance(t);

        Iterable<? extends Element> elements = t.analyze();

        Element klass = elements.iterator().next();
        DocCommentTree dcTree = trees.getDocCommentTree(klass);

        List<? extends DocTree> firstSentence = dcTree.getFirstSentence();
        StringWriter sw = new StringWriter();
        DocPretty pretty = new DocPretty(sw);
        pretty.print(firstSentence);
        check("getDocCommentTree(Element)", expected, sw.toString());

        BreakIterator bi = BreakIterator.getSentenceInstance(Locale.FRENCH);
        trees.setBreakIterator(bi);
        BreakIterator nbi = trees.getBreakIterator();
        if (bi.equals(nbi)) {
            pass++;
            check("getDocCommentTree(Element) with BreakIterator", expected, sw.toString());
        } else {
            fail++;
            System.err.println("BreakIterators don't match");
        }
    }
}
 
Example 47
Project: KernelHive   File: RuntimeClassFactory.java   Source Code and License 5 votes vote down vote up
public static IPreviewProvider getPreviewProvider(File sourceFile) {
	JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
	File tmpDir = new File(System.getProperty("java.io.tmpdir"));
	try (StandardJavaFileManager fileManager = compiler
			.getStandardFileManager(null, null, null)) {
		Iterable javaFiles = fileManager.getJavaFileObjects(sourceFile);
		fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(tmpDir));
		List<String> options = Arrays.asList("-d", tmpDir.getAbsolutePath());
		compiler.getTask(null, fileManager, null, null, null, javaFiles)
				.call();
	} catch (IOException e) {
		LOGGER.log(Level.SEVERE, "Error during runtime compilation", e);
	}

	try {
		URL[] urls = new URL[]{new URL("file://" + tmpDir + "/")};
		System.out.println(urls[0].toString());
		URLClassLoader ucl = new URLClassLoader(urls);
		Class clazz = ucl.loadClass("pl.gda.pg.eti.kernelhive.gui.component.workflow.preview.PreviewProvider");
		System.out.println("Class has been successfully loaded");

		IPreviewProvider provider = (IPreviewProvider) clazz.newInstance();
		return provider;
	} catch (MalformedURLException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
		Logger.getLogger(RuntimeClassFactory.class.getName())
				.log(Level.SEVERE, "Error while creating PreviewProider", ex);
		return null;
	}
}
 
Example 48
Project: openjdk-jdk10   File: TestClose2.java   Source Code and License 5 votes vote down vote up
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 49
Project: otter-G   File: JdkCompileTask.java   Source Code and License 5 votes vote down vote up
public JdkCompileTask(JdkCompilerClassLoader classLoader, Iterable<String> options){
    compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new IllegalStateException("Cannot find the system Java compiler. "
                                        + "Check that your class path includes tools.jar");
    }

    this.classLoader = classLoader;
    ClassLoader loader = classLoader.getParent();
    diagnostics = new DiagnosticCollector<JavaFileObject>();
    final StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);

    if (loader instanceof URLClassLoader
        && (!loader.getClass().getName().equalsIgnoreCase("sun.misc.Launcher$AppClassLoader"))) {
        try {
            @SuppressWarnings("resource")
            URLClassLoader urlClassLoader = (URLClassLoader) loader;
            List<File> path = new ArrayList<File>();
            for (URL url : urlClassLoader.getURLs()) {
                File file = new File(url.getFile());
                path.add(file);
            }

            fileManager.setLocation(StandardLocation.CLASS_PATH, path);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    javaFileManager = new JavaFileManagerImpl(fileManager, classLoader);
    this.options = new ArrayList<String>();
    if (options != null) { // make a save copy of input options
        for (String option : options) {
            this.options.add(option);
        }
    }
}
 
Example 50
Project: openjdk-jdk10   File: ContainsTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testSimplePath(Path base) throws IOException {
    // Test that we can look up in directories in the default file system.
    Path src = base.resolve("src");
    tb.writeJavaFiles(src, "package p; class C { }");
    Path c = src.resolve("p/C.java");
    Path x = base.resolve("src2/p/C.java");
    try (StandardJavaFileManager fm = javaCompiler.getStandardFileManager(null, null, null)) {
        fm.setLocationFromPaths(StandardLocation.SOURCE_PATH, List.of(src));
        checkContains(fm, StandardLocation.SOURCE_PATH, c, true);
        checkContains(fm, StandardLocation.SOURCE_PATH, x, false);
    }
}
 
Example 51
Project: OpenJSharp   File: JavahTask.java   Source Code and License 5 votes vote down vote up
public boolean run() throws Util.Exit {

        Util util = new Util(log, diagnosticListener);

        if (noArgs || help) {
            showHelp();
            return help; // treat noArgs as an error for purposes of exit code
        }

        if (version || fullVersion) {
            showVersion(fullVersion);
            return true;
        }

        util.verbose = verbose;

        Gen g;

        if (llni)
            g = new LLNI(doubleAlign, util);
        else {
//            if (stubs)
//                throw new BadArgs("jni.no.stubs");
            g = new JNI(util);
        }

        if (ofile != null) {
            if (!(fileManager instanceof StandardJavaFileManager)) {
                diagnosticListener.report(createDiagnostic("err.cant.use.option.for.fm", "-o"));
                return false;
            }
            Iterable<? extends JavaFileObject> iter =
                    ((StandardJavaFileManager) fileManager).getJavaFileObjectsFromFiles(Collections.singleton(ofile));
            JavaFileObject fo = iter.iterator().next();
            g.setOutFile(fo);
        } else {
            if (odir != null) {
                if (!(fileManager instanceof StandardJavaFileManager)) {
                    diagnosticListener.report(createDiagnostic("err.cant.use.option.for.fm", "-d"));
                    return false;
                }

                if (!odir.exists())
                    if (!odir.mkdirs())
                        util.error("cant.create.dir", odir.toString());
                try {
                    ((StandardJavaFileManager) fileManager).setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(odir));
                } catch (IOException e) {
                    Object msg = e.getLocalizedMessage();
                    if (msg == null) {
                        msg = e;
                    }
                    diagnosticListener.report(createDiagnostic("err.ioerror", odir, msg));
                    return false;
                }
            }
            g.setFileManager(fileManager);
        }

        /*
         * Force set to false will turn off smarts about checking file
         * content before writing.
         */
        g.setForce(force);

        if (fileManager instanceof JavahFileManager)
            ((JavahFileManager) fileManager).setSymbolFileEnabled(false);

        JavaCompiler c = ToolProvider.getSystemJavaCompiler();
        List<String> opts = new ArrayList<String>();
        opts.add("-proc:only");
        opts.addAll(javac_extras);
        CompilationTask t = c.getTask(log, fileManager, diagnosticListener, opts, classes, null);
        JavahProcessor p = new JavahProcessor(g);
        t.setProcessors(Collections.singleton(p));

        boolean ok = t.call();
        if (p.exit != null)
            throw new Util.Exit(p.exit);
        return ok;
    }
 
Example 52
Project: OpenJSharp   File: JavadocTool.java   Source Code and License 5 votes vote down vote up
@Override
public StandardJavaFileManager getStandardFileManager(
        DiagnosticListener<? super JavaFileObject> diagnosticListener,
        Locale locale,
        Charset charset) {
    Context context = new Context();
    context.put(Locale.class, locale);
    if (diagnosticListener != null)
        context.put(DiagnosticListener.class, diagnosticListener);
    PrintWriter pw = (charset == null)
            ? new PrintWriter(System.err, true)
            : new PrintWriter(new OutputStreamWriter(System.err, charset), true);
    context.put(Log.outKey, pw);
    return new JavacFileManager(context, true, charset);
}
 
Example 53
Project: OpenJSharp   File: RootDocImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Return the path of the overview file and null if it does not exist.
 * @return the path of the overview file and null if it does not exist.
 */
private JavaFileObject getOverviewPath() {
    for (String[] opt : options) {
        if (opt[0].equals("-overview")) {
            if (env.fileManager instanceof StandardJavaFileManager) {
                StandardJavaFileManager fm = (StandardJavaFileManager) env.fileManager;
                return fm.getJavaFileObjects(opt[1]).iterator().next();
            }
        }
    }
    return null;
}
 
Example 54
Project: openjdk-jdk10   File: TestCircularClassfile.java   Source Code and License 5 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 count = 0;
        for (SourceKind sk1 : SourceKind.values()) {
            for (SourceKind sk2 : SourceKind.values()) {
                for (TestKind tk : TestKind.values()) {
                    for (ClientKind ck : ClientKind.values()) {
                        new TestCircularClassfile("sub_"+count++, sk1, sk2, tk, ck).check(comp, fm);
                    }
                }
            }
        }
    }
}
 
Example 55
Project: openjdk-jdk10   File: Test.java   Source Code and License 5 votes vote down vote up
void testAnnoProcessor(JavacTool javac, StandardJavaFileManager fm,
        Iterable<? extends JavaFileObject> files, PrintWriter out,
        int expectedDocComments) {
    out.println("Test annotation processor");
    JavacTask task = javac.getTask(out, fm, null, null, null, files);
    AnnoProc ap = new AnnoProc(DocTrees.instance(task));
    task.setProcessors(Arrays.asList(ap));
    task.call();
    ap.checker.checkDocComments(expectedDocComments);
}
 
Example 56
Project: jdk8u-jdk   File: FDTest.java   Source Code and License 5 votes vote down vote up
void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception {
    JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker,
            null, null, Arrays.asList(source));
    try {
        ct.analyze();
    } catch (Throwable ex) {
        fail("Error thrown when analyzing the following source:\n" + source.getCharContent(true));
    }
    check();
}
 
Example 57
Project: openjdk-jdk10   File: TestLazyImportScope.java   Source Code and License 5 votes vote down vote up
void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception {
    JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker,
            null, null, Arrays.asList(source));
    try {
        ct.analyze();
    } catch (Throwable ex) {
        throw new AssertionError("Error thrown when compiling the following code:\n" + source.getCharContent(true));
    }
    check();
}
 
Example 58
Project: openjdk-jdk10   File: Probe.java   Source Code and License 5 votes vote down vote up
public static void main(String... args) throws IOException {
    if (args.length != 1) {
        System.err.println("Not enough arguments.");
        System.err.println("Usage:");
        System.err.println("    java " + Probe.class.getName() + " <output-file>");
        return ;
    }

    File outFile = new File(args[0]);
    Charset cs = Charset.forName("UTF-8");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
    OutputStream out = new FileOutputStream(outFile);

    try {
        Iterable<JavaFileObject> bcpFiles =
                fm.list(StandardLocation.PLATFORM_CLASS_PATH, "", EnumSet.of(Kind.CLASS), true);

        for (JavaFileObject jfo : bcpFiles) {
            InputStream in = new BufferedInputStream(jfo.openInputStream());
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                StringBuilder textual = new StringBuilder();
                int read;

                while ((read = in.read()) != (-1)) {
                    baos.write(read);
                    textual.append(String.format("%02x", read));
                }

                textual.append("\n");
                out.write(textual.toString().getBytes(cs));
            } finally {
                in.close();
            }
        }
    } finally {
        out.close();
    }
}
 
Example 59
Project: openjdk-jdk10   File: SJFM_GetFileObjects.java   Source Code and License 5 votes vote down vote up
/**
 * Tests the getJavaFileObjectsFromPaths method for a specific file manager
 * and a series of paths.
 *
 * Note: instances of MyStandardJavaFileManager only support
 * encapsulating paths for files in the default file system.
 *
 * @param fm  the file manager to be tested
 * @param paths  the paths to be tested
 * @throws IOException
 */
void test_getJavaFileObjectsFromPaths(StandardJavaFileManager fm, List<Path> paths)
        throws IOException {
    boolean expectException = !isGetFileObjectsSupported(fm, paths);
    try {
        compile(fm.getJavaFileObjectsFromPaths(paths));
        if (expectException)
            error("expected exception not thrown: " + IllegalArgumentException.class.getName());
    } catch (RuntimeException e) {
        if (expectException && e instanceof IllegalArgumentException)
            return;
        error("unexpected exception thrown: " + e);
    }
}
 
Example 60
Project: openjdk-jdk10   File: JavadocTool.java   Source Code and License 5 votes vote down vote up
@Override
public StandardJavaFileManager getStandardFileManager(
        DiagnosticListener<? super JavaFileObject> diagnosticListener,
        Locale locale,
        Charset charset) {
    Context context = new Context();
    context.put(Locale.class, locale);
    if (diagnosticListener != null)
        context.put(DiagnosticListener.class, diagnosticListener);
    PrintWriter pw = (charset == null)
            ? new PrintWriter(System.err, true)
            : new PrintWriter(new OutputStreamWriter(System.err, charset), true);
    context.put(Log.errKey, pw);
    return new JavacFileManager(context, true, charset);
}