Java Code Examples for javax.tools.JavaCompiler

The following are top voted examples for showing how to use javax.tools.JavaCompiler. 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: ReleaseOptionThroughAPI.java   Source Code and License 8 votes vote down vote up
void run() throws IOException {
    String lineSep = System.getProperty("line.separator");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
         StringWriter out = new StringWriter();
         PrintWriter outWriter = new PrintWriter(out)) {
        Iterable<? extends JavaFileObject> input =
                fm.getJavaFileObjects(System.getProperty("test.src") + "/ReleaseOption.java");
        List<String> options = Arrays.asList("--release", "7", "-XDrawDiagnostics");

        compiler.getTask(outWriter, fm, null, options, null, input).call();
        String expected =
                "ReleaseOption.java:9:49: compiler.err.doesnt.exist: java.util.stream" + lineSep +
                "1 error" + lineSep;
        if (!expected.equals(out.toString())) {
            throw new AssertionError("Unexpected output: " + out.toString());
        }
    }
}
 
Example 2
Project: monarch   File: ClassBuilder.java   Source Code and License 8 votes vote down vote up
/**
 * Compile the provided class. The className may have a package separated by /. For example:
 * my/package/myclass
 * 
 * @param className Name of the class to compile.
 * @param classCode Plain text contents of the class
 * @return The byte contents of the compiled class.
 * @throws IOException
 */
public byte[] compileClass(final String className, final String classCode) throws IOException {
  ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

  JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
  OutputStreamJavaFileManager<JavaFileManager> fileManager =
      new OutputStreamJavaFileManager<JavaFileManager>(
          javaCompiler.getStandardFileManager(null, null, null), byteArrayOutputStream);

  List<JavaFileObject> fileObjects = new ArrayList<JavaFileObject>();
  fileObjects.add(new JavaSourceFromString(className, classCode));

  List<String> options = Arrays.asList("-classpath", this.classPath);
  DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
  if (!javaCompiler.getTask(null, fileManager, diagnostics, options, null, fileObjects).call()) {
    StringBuilder errorMsg = new StringBuilder();
    for (Diagnostic d : diagnostics.getDiagnostics()) {
      String err = String.format("Compilation error: Line %d - %s%n", d.getLineNumber(),
          d.getMessage(null));
      errorMsg.append(err);
      System.err.print(err);
    }
    throw new IOException(errorMsg.toString());
  }
  return byteArrayOutputStream.toByteArray();
}
 
Example 3
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 4
Project: MaxSim   File: TestBootNativeLibraryPath.java   Source Code and License 7 votes vote down vote up
static void createTestClass() throws IOException {
    FileOutputStream fos = new FileOutputStream(TESTFILE + ".java");
    PrintStream ps = new PrintStream(fos);
    ps.println("public class " + TESTFILE + "{");
    ps.println("public static void main(String[] args) {\n");
    ps.println("System.out.println(System.getProperty(\"sun.boot.library.path\"));\n");
    ps.println("}}\n");
    ps.close();
    fos.close();

    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    String javacOpts[] = {TESTFILE + ".java"};
    if (javac.run(null, null, null,  javacOpts) != 0) {
        throw new RuntimeException("compilation of " + TESTFILE + ".java Failed");
    }
}
 
Example 5
Project: openjdk-jdk10   File: PackageInfoTest.java   Source Code and License 7 votes vote down vote up
private void compile(String option, Path destDir, Path... files)
        throws IOException
{
    System.err.println("compile...");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {
        Iterable<? extends JavaFileObject> fileObjects =
            fm.getJavaFileObjectsFromPaths(Arrays.asList(files));

        List<String> options = new ArrayList<>();
        if (option != null) {
            options.add(option);
        }
        if (destDir != null) {
            options.add("-d");
            options.add(destDir.toString());
        }
        options.add("-cp");
        options.add(System.getProperty("test.classes", "."));

        JavaCompiler.CompilationTask task =
            compiler.getTask(null, fm, null, options, null, fileObjects);
        if (!task.call())
            throw new AssertionError("compilation failed");
    }
}
 
Example 6
Project: openjdk-jdk10   File: ModuleInfoTreeAccess.java   Source Code and License 6 votes vote down vote up
@Test
public void testTreePathForModuleDeclWithImport(Path base) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {
        Path src = base.resolve("src");
        tb.writeJavaFiles(src, "import java.lang.Deprecated; /** Test module */ @Deprecated 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 7
Project: GitHub   File: CompilerWarningIT.java   Source Code and License 6 votes vote down vote up
@Parameters(name="{0}")
public static Collection<Object[]> parameters() {
  JavaCompiler systemJavaCompiler = Compiler.systemJavaCompiler();
  JavaCompiler eclipseCompiler = Compiler.eclipseCompiler();
  return Arrays.asList(new Object[][] {
    {
      "includeAccessorsWithSystemJavaCompiler",
      systemJavaCompiler,
      config("includeDynamicAccessors", true, "includeDynamicGetters", true, "includeDynamicSetters", true, "includeDynamicBuilders", true),
      "/schema/dynamic/parentType.json",
      Matchers.empty()
    },
    {
      "includeAccessorsWithEclipseCompiler",
      eclipseCompiler,
      config("includeDynamicAccessors", true, "includeDynamicGetters", true, "includeDynamicSetters", true, "includeDynamicBuilders", true),
      "/schema/dynamic/parentType.json",
      onlyCastExceptions()
    }
  });
}
 
Example 8
Project: openjdk-jdk10   File: InterruptedExceptionTest.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 (XlintOption xlint : XlintOption.values()) {
                for (SuppressLevel suppress_decl : SuppressLevel.values()) {
                    for (SuppressLevel suppress_use : SuppressLevel.values()) {
                        for (ClassKind ck : ClassKind.values()) {
                            for (ExceptionKind ek_decl : ExceptionKind.values()) {
                                for (ExceptionKind ek_use : ExceptionKind.values()) {
                                    new InterruptedExceptionTest(xlint, suppress_decl,
                                            suppress_use, ck, ek_decl, ek_use).run(comp, fm);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
 
Example 9
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 10
Project: openjdk-jdk10   File: Basic.java   Source Code and License 6 votes vote down vote up
static void javac(Path dest, Path... sourceFiles) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fileManager =
                compiler.getStandardFileManager(null, null, null)) {

        List<File> files = Stream.of(sourceFiles)
                .map(p -> p.toFile())
                .collect(Collectors.toList());
        List<File> dests = Stream.of(dest)
                .map(p -> p.toFile())
                .collect(Collectors.toList());
        Iterable<? extends JavaFileObject> compilationUnits =
                fileManager.getJavaFileObjectsFromFiles(files);
        fileManager.setLocation(StandardLocation.CLASS_OUTPUT, dests);
        JavaCompiler.CompilationTask task =
                compiler.getTask(null, fileManager, null, null, null, compilationUnits);
        boolean passed = task.call();
        if (!passed)
            throw new RuntimeException("Error compiling " + files);
    }
}
 
Example 11
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 12
Project: openjdk-jdk10   File: BadConstantValue.java   Source Code and License 6 votes vote down vote up
private static BadClassFile loadBadClass(String className) {
    // load the class, and save the thrown BadClassFile exception
    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    JavacTaskImpl task = (JavacTaskImpl) c.getTask(null, null, null,
            Arrays.asList("-classpath", classesdir.getPath()), null, null);
    Symtab syms = Symtab.instance(task.getContext());
    task.ensureEntered();
    BadClassFile badClassFile;
    try {
        com.sun.tools.javac.main.JavaCompiler.instance(task.getContext())
                .resolveIdent(syms.unnamedModule, className).complete();
    } catch (BadClassFile e) {
        return e;
    }
    return null;
}
 
Example 13
Project: ditb   File: TestClassFinder.java   Source Code and License 6 votes vote down vote up
/**
 * Compiles the test class with bogus code into a .class file.
 * Unfortunately it's very tedious.
 * @param counter Unique test counter.
 * @param packageNameSuffix Package name suffix (e.g. ".suffix") for nesting, or "".
 * @return The resulting .class file and the location in jar it is supposed to go to.
 */
private static FileAndPath compileTestClass(long counter,
    String packageNameSuffix, String classNamePrefix) throws Exception {
  classNamePrefix = classNamePrefix + counter;
  String packageName = makePackageName(packageNameSuffix, counter);
  String javaPath = basePath + classNamePrefix + ".java";
  String classPath = basePath + classNamePrefix + ".class";
  PrintStream source = new PrintStream(javaPath);
  source.println("package " + packageName + ";");
  source.println("public class " + classNamePrefix
      + " { public static void main(String[] args) { } };");
  source.close();
  JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
  int result = jc.run(null, null, null, javaPath);
  assertEquals(0, result);
  File classFile = new File(classPath);
  assertTrue(classFile.exists());
  return new FileAndPath(packageName.replace('.', '/') + '/', classFile);
}
 
Example 14
Project: openjdk-jdk10   File: IgnoreIgnorableCharactersInInput.java   Source Code and License 6 votes vote down vote up
void run() throws Exception {
    JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
    File classesDir = new File(System.getProperty("user.dir"), "classes");
    classesDir.mkdirs();
    JavaSource[] sources = new JavaSource[]{
        new JavaSource("TestOneIgnorableChar", "AA\\u0000BB"),
        new JavaSource("TestMultipleIgnorableChar", "AA\\u0000\\u0000\\u0000BB")};
    JavacTask ct = (JavacTask)comp.getTask(null, null, null,
            Arrays.asList("-d", classesDir.getPath()),
            null, Arrays.asList(sources));
    try {
        if (!ct.call()) {
            throw new AssertionError("Error thrown when compiling test cases");
        }
    } catch (Throwable ex) {
        throw new AssertionError("Error thrown when compiling test cases");
    }
    check(classesDir,
            "TestOneIgnorableChar.class",
            "TestOneIgnorableChar$AABB.class",
            "TestMultipleIgnorableChar.class",
            "TestMultipleIgnorableChar$AABB.class");
    if (errors > 0)
        throw new AssertionError("There are some errors in the test check the error output");
}
 
Example 15
Project: mybatis-generator-plugin   File: MyBatisGeneratorTool.java   Source Code and License 6 votes vote down vote up
/**
 * 动态编译java文件
 * @param files
 */
private void compileJavaFiles(List<File> files) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    //获取java文件管理类
    StandardJavaFileManager manager = compiler.getStandardFileManager(null, null, null);
    //获取java文件对象迭代器
    Iterable<? extends JavaFileObject> it = manager.getJavaFileObjectsFromFiles(files);
    //设置编译参数
    ArrayList<String> ops = new ArrayList<>();
    ops.add("-Xlint:unchecked");
    //获取编译任务
    JavaCompiler.CompilationTask task = compiler.getTask(null, manager, null, ops, null, it);
    //执行编译任务
    task.call();
}
 
Example 16
Project: openjdk-jdk10   File: T6963934.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    File testSrc = new File(System.getProperty("test.src"));
    File thisSrc = new File(testSrc, T6963934.class.getSimpleName() + ".java");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)) {
        JavacTask task = (JavacTask) compiler.getTask(null, fileManager, null, null, null,
                fileManager.getJavaFileObjects(thisSrc));
        CompilationUnitTree tree = task.parse().iterator().next();
        int count = 0;
        for (ImportTree importTree : tree.getImports()) {
            System.out.println(importTree);
            count++;
        }
        int expected = 7;
        if (count != expected)
            throw new Exception("unexpected number of imports found: " + count + ", expected: " + expected);
    }
}
 
Example 17
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 18
Project: openjdk-jdk10   File: TestBootNativeLibraryPath.java   Source Code and License 6 votes vote down vote up
static void createTestClass() throws IOException {
    FileOutputStream fos = new FileOutputStream(TESTFILE + ".java");
    PrintStream ps = new PrintStream(fos);
    ps.println("public class " + TESTFILE + "{");
    ps.println("public static void main(String[] args) {\n");
    ps.println("System.out.println(System.getProperty(\"sun.boot.library.path\"));\n");
    ps.println("}}\n");
    ps.close();
    fos.close();

    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    String javacOpts[] = {TESTFILE + ".java"};
    if (javac.run(null, null, null,  javacOpts) != 0) {
        throw new RuntimeException("compilation of " + TESTFILE + ".java Failed");
    }
}
 
Example 19
Project: openjdk-jdk10   File: DuplicateConstantPoolEntry.java   Source Code and License 6 votes vote down vote up
void generateFilesNeeded() throws Exception {

        StringJavaFileObject[] CSource = new StringJavaFileObject[] {
            new StringJavaFileObject("C.java",
                "class C {C(String s) {}}"),
        };

        List<StringJavaFileObject> AandBSource = Arrays.asList(
                new StringJavaFileObject("A.java",
                    "class A {void test() {new B(null);new C(null);}}"),
                new StringJavaFileObject("B.java",
                    "class B {B(String s) {}}")
        );

        final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
        JavacTask compileC = (JavacTask)tool.getTask(null, null, null, null, null,
                Arrays.asList(CSource));
        if (!compileC.call()) {
            throw new AssertionError("Compilation error while compiling C.java sources");
        }
        JavacTask compileAB = (JavacTask)tool.getTask(null, null, null,
                Arrays.asList("-cp", "."), null, AandBSource);
        if (!compileAB.call()) {
            throw new AssertionError("Compilation error while compiling A and B sources");
        }
    }
 
Example 20
Project: openjdk-jdk10   File: T6557752.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    task = (JavacTask) compiler.getTask(null, null, null, null, null, List.of(new MyFileObject()));
    Iterable<? extends CompilationUnitTree> asts = task.parse();
    task.analyze();
    trees = Trees.instance(task);
    MyVisitor myVisitor = new MyVisitor();
    for (CompilationUnitTree ast : asts) {
        myVisitor.compilationUnit = ast;
        myVisitor.scan(ast, null);
    }

    if (!myVisitor.foundError) {
        throw new AssertionError("Expected error not found!");
    }
}
 
Example 21
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 22
Project: openjdk-jdk10   File: T7190862.java   Source Code and License 6 votes vote down vote up
private void run(JavaCompiler comp) {
    String code;
    for (TypeWideInstructionMap typeInstructionMap: TypeWideInstructionMap.values()) {
        if (typeInstructionMap != TypeWideInstructionMap.OBJECT) {
            code = createWideLocalSource(typeInstructionMap.type, 300);
        } else {
            code = createWideLocalSourceForObject(300);
        }
        source = new JavaSource(code);
        compile(comp);
        check(typeInstructionMap.instructions);
    }

    //an extra test for the iinc instruction
    code = createIincSource();
    source = new JavaSource(code);
    compile(comp);
    check(new String[]{"iinc_w"});
}
 
Example 23
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 24
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 25
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 26
Project: openjdk-jdk10   File: TestBootstrapMethodsCount.java   Source Code and License 6 votes vote down vote up
public void run(JavaCompiler comp) {
    JavaSource source = new JavaSource();
    JavacTaskImpl ct = (JavacTaskImpl)comp.getTask(null, null, dc,
            Arrays.asList("-g"), null, Arrays.asList(source));
    Context context = ct.getContext();
    Symtab syms = Symtab.instance(context);
    Names names = Names.instance(context);
    Types types = Types.instance(context);
    ct.addTaskListener(new Indifier(syms, names, types));
    try {
        ct.generate();
    } catch (Throwable t) {
        t.printStackTrace();
        throw new AssertionError(
                String.format("Error thrown when compiling following code\n%s",
                        source.source));
    }
    if (dc.diagFound) {
        throw new AssertionError(
                String.format("Diags found when compiling following code\n%s\n\n%s",
                        source.source, dc.printDiags()));
    }
    verifyBytecode();
}
 
Example 27
Project: openjdk-jdk10   File: Abort.java   Source Code and License 6 votes vote down vote up
public static void main(String... args) throws Exception {

        String SCRATCH_DIR = System.getProperty("user.dir");
        JavaCompiler javacTool = ToolProvider.getSystemJavaCompiler();
        java.io.File testDir = new java.io.File(SCRATCH_DIR);

        sourceA.dumpTo(testDir);
        sourceB.dumpTo(testDir);

        DiagnosticChecker diagChecker = new DiagnosticChecker();
        JavacTask ct = (JavacTask)javacTool.getTask(null, null, diagChecker,
                Arrays.asList("-XDrawDiagnostics", "-cp", testDir.getAbsolutePath()),
                null, Arrays.asList(sourceA.asJFO(testDir)));
        try {
            ct.analyze();
        } catch (Throwable ex) {
            //ignore abort exception thrown by javac
        }

        if (!diagChecker.errorFound) {
            throw new AssertionError("Missing diagnostic");
        }
    }
 
Example 28
Project: openjdk-jdk10   File: ElementStructureTest.java   Source Code and License 6 votes vote down vote up
void run(Writer output, String version) throws Exception {
    List<String> options = Arrays.asList("--release", version, "-classpath", "");
    List<ToolBox.JavaSource> files = Arrays.asList(new ToolBox.JavaSource("Test", ""));
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(null, null, null, options, null, files);

    task.analyze();

    JavaFileManager fm = task.getContext().get(JavaFileManager.class);

    for (String pack : packages(fm)) {
        PackageElement packEl = task.getElements().getPackageElement(pack);
        if (packEl == null) {
            throw new AssertionError("Cannot find package: " + pack);
        }
        new ExhaustiveElementScanner(task, output, p -> true).visit(packEl);
    }
}
 
Example 29
Project: openjdk-jdk10   File: JavacExtensionTest.java   Source Code and License 6 votes vote down vote up
static List<? extends Tree> parse(String srcfile) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> fileObjects = fileManager.getJavaFileObjects(srcfile);
    String classPath = System.getProperty("java.class.path");
    List<String> options = Arrays.asList("-classpath", classPath);
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    Context context = new Context();
    JavacTaskImpl task = (JavacTaskImpl) ((JavacTool) compiler).getTask(null, null,
            diagnostics, options, null, fileObjects, context);
    TrialParserFactory.instance(context);
    Iterable<? extends CompilationUnitTree> asts = task.parse();
    Iterator<? extends CompilationUnitTree> it = asts.iterator();
    if (it.hasNext()) {
        CompilationUnitTree cut = it.next();
        return cut.getTypeDecls();
    } else {
        throw new AssertionError("Expected compilation unit");
    }
}
 
Example 30
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 31
Project: openjdk-jdk10   File: ModuleSourcePathTest.java   Source Code and License 6 votes vote down vote up
@Test
public void getLocation_ISA(Path base) throws Exception {
    Path src1 = base.resolve("src1");
    tb.writeJavaFiles(src1.resolve("m1x"), "module m1x { }", "package a; class A { }");
    Path src2 = base.resolve("src2");
    tb.writeJavaFiles(src2.resolve("m2x").resolve("extra"), "module m2x { }", "package b; class B { }");
    Path modules = base.resolve("modules");
    tb.createDirectories(modules);

    String FS = File.separator;
    String PS = File.pathSeparator;
    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = c.getStandardFileManager(null, null, null)) {
        fm.handleOption("--module-source-path",
                List.of(src1 + PS + src2 + FS + "*" + FS + "extra").iterator());

        try {
            Iterable<? extends Path> paths = fm.getLocationAsPaths(StandardLocation.MODULE_SOURCE_PATH);
            out.println("result: " + asList(paths));
            throw new Exception("expected IllegalStateException not thrown");
        } catch (IllegalStateException e) {
            out.println("Exception thrown, as expected: " + e);
        }

        // even if we can't do getLocation for the MODULE_SOURCE_PATH, we should be able
        // to do getLocation for the modules, which will additionally confirm the option
        // was effective as intended.
        Location locn1 = fm.getLocationForModule(StandardLocation.MODULE_SOURCE_PATH, "m1x");
        checkLocation(fm.getLocationAsPaths(locn1), List.of(src1.resolve("m1x")));
        Location locn2 = fm.getLocationForModule(StandardLocation.MODULE_SOURCE_PATH, "m2x");
        checkLocation(fm.getLocationAsPaths(locn2), List.of(src2.resolve("m2x").resolve("extra")));
    }
}
 
Example 32
Project: openjdk-jdk10   File: DetectMutableStaticFields.java   Source Code and License 6 votes vote down vote up
private void run()
    throws
        IOException,
        ConstantPoolException,
        InvalidDescriptor,
        URISyntaxException {

    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null)) {
        for (String module: modules) {
            analyzeModule(fm, module);
        }
    }

    if (errors.size() > 0) {
        for (String error: errors) {
            System.err.println(error);
        }
        throw new AssertionError("There are mutable fields, "
            + "please check output");
    }
}
 
Example 33
Project: openjdk-jdk10   File: T6472751.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    JavacTask task = (JavacTask) compiler.getTask(null, null, null, null, null, List.of(new MyFileObject()));
    trees = Trees.instance(task);
    positions = trees.getSourcePositions();
    Iterable<? extends CompilationUnitTree> asts = task.parse();
    for (CompilationUnitTree ast : asts) {
        new MyVisitor().scan(ast, null);
    }
}
 
Example 34
Project: Reer   File: JavaHomeBasedJavaCompilerFactory.java   Source Code and License 5 votes vote down vote up
private JavaCompiler findCompiler() {
    File realJavaHome = currentJvmJavaHomeFactory.create();
    File javaHomeFromToolProvidersPointOfView = systemPropertiesJavaHomeFactory.create();
    if (realJavaHome.equals(javaHomeFromToolProvidersPointOfView)) {
        return systemJavaCompilerFactory.create();
    }

    return SystemProperties.getInstance().withJavaHome(realJavaHome, systemJavaCompilerFactory);
}
 
Example 35
Project: openjdk-jdk10   File: IntersectionTypeParserTest.java   Source Code and License 5 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 (CastKind ck : CastKind.values()) {
            for (TypeKind t1 : TypeKind.values()) {
                for (ArrayKind ak1 : ArrayKind.values()) {
                    Type typ1 = new Type(t1, ak1);
                    if (ck.nBounds == 1) {
                        new IntersectionTypeParserTest(ck, typ1).run(comp, fm);
                        continue;
                    }
                    for (TypeKind t2 : TypeKind.values()) {
                        for (ArrayKind ak2 : ArrayKind.values()) {
                            Type typ2 = new Type(t2, ak2);
                            if (ck.nBounds == 2) {
                                new IntersectionTypeParserTest(ck, typ1, typ2).run(comp, fm);
                                continue;
                            }
                            for (TypeKind t3 : TypeKind.values()) {
                                for (ArrayKind ak3 : ArrayKind.values()) {
                                    Type typ3 = new Type(t3, ak3);
                                    new IntersectionTypeParserTest(ck, typ1, typ2, typ3).run(comp, fm);
                                }
                            }
                        }
                    }
                }
            }
        }
        System.out.println("Total check executed: " + checkCount);
    }
}
 
Example 36
Project: openjdk-jdk10   File: Helper.java   Source Code and License 5 votes vote down vote up
public static boolean compileCode(String className, String contents,
        DiagnosticCollector<JavaFileObject> diagnostics) {
    boolean ok = false;
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new RuntimeException("can't get javax.tools.JavaCompiler!");
    }

    JavaFileObject file = getFile(className, contents);
    Iterable<? extends JavaFileObject> compilationUnit = Arrays.asList(file);

    CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnit);
    ok = task.call();
    return ok;
}
 
Example 37
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 38
Project: GitHub   File: SimpleCompiler.java   Source Code and License 5 votes vote down vote up
@Override
public JavaCompiler.CompilationTask getTask(Writer out, JavaFileManager fileManager,
        DiagnosticListener<? super JavaFileObject> diagnosticListener,
        Iterable<String> options, Iterable<String> classes,
        Iterable<? extends JavaFileObject> compilationUnits) {
    return compiler.getTask(out, fileManager, diagnosticListener, options, classes, compilationUnits);
}
 
Example 39
Project: openjdk-jdk10   File: CompleteOnClosed.java   Source Code and License 5 votes vote down vote up
public static void main(String... args) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<>();
    String source = "class Test extends CompleteOnClosedOther {" +
                    "     class Inner extends Undefined { }" +
                    "}";
    Iterable<JavaFileObject> files = Arrays.<JavaFileObject>asList(new ToolBox.JavaSource(source));
    Iterable<String> options = Arrays.asList("-processor", "CompleteOnClosed");
    CompilationTask task = compiler.getTask(null, null, collector, options, null, files);
    task.call();
    for (Diagnostic<? extends JavaFileObject> d : collector.getDiagnostics()) {
        System.out.println(d.toString());
    }
}
 
Example 40
Project: GitHub   File: Jsonschema2PojoRule.java   Source Code and License 5 votes vote down vote up
public ClassLoader compile(JavaCompiler compiler, Writer out, List<File> classpath, Map<String, Object> config) {
    if (classLoader != null) {
        throw new IllegalStateException("cannot recompile sources");
    }
    DiagnosticListener<JavaFileObject> diagnosticListener = captureDiagnostics ? new CapturingDiagnosticListener() : null;
    classLoader = CodeGenerationHelper.compile(compiler, out, getGenerateDir(), getCompileDir(), classpath, config, diagnosticListener);
    return classLoader;
}
 
Example 41
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 42
Project: openjdk-jdk10   File: NegativeCyclicDependencyTest.java   Source Code and License 5 votes vote down vote up
/**
 * Compiles sources with -XDrawDiagnostics flag and
 * returns the output of compilation.
 *
 * @param sources sources
 * @return the result of compilation
 */
private String compile(ToolBox.JavaSource...sources) {
    JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    StringWriter writer = new StringWriter();
    JavaCompiler.CompilationTask ct = jc.getTask(writer, null, null,
            Arrays.asList("-XDrawDiagnostics"),
            null, Arrays.asList(sources));
    if (ct.call()) {
        throw new RuntimeException("Expected compilation failure.");
    }
    return writer.toString().replace(ToolBox.lineSeparator, "\n");
}
 
Example 43
Project: openjdk-jdk10   File: T7142086.java   Source Code and License 5 votes vote down vote up
void run(List<JavaFileObject> sources) throws Exception {
    DiagnosticChecker dc = new DiagnosticChecker();
    JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {
        JavacTask ct = (JavacTask)comp.getTask(null, fm, dc,
                null, null, sources);
        ct.analyze();
    }
}
 
Example 44
Project: incubator-netbeans   File: LayerGeneratingProcessorTest.java   Source Code and License 5 votes vote down vote up
public void testProcessingEnvironmentLeak() throws Exception { // #198604
    try {
        if (Modifier.isStatic(Class.forName("com.sun.tools.javac.code.Symtab").getField("byteType").getModifiers())) {
            System.err.println("Skipping testProcessingEnvironmentLeak due to old buggy version of javac");
            return;
        }
    } catch (Exception x) {
        System.err.println("Note: perhaps using non-javac compiler? " + x);
    }
    clearWorkDir();
    File src = new File(getWorkDir(), "src");
    AnnotationProcessorTestUtils.makeSource(src, "p.C", "@" + A.class.getCanonicalName() + " public class C {}");
    File dest = new File(getWorkDir(), "dest");
    assertTrue(dest.mkdirs());
    List<String> args = new ArrayList<String>();
    args.add("-classpath");
    args.add(dest + File.pathSeparator + System.getProperty("java.class.path"));
    args.add("-d");
    args.add(dest.getAbsolutePath());
    args.add("-sourcepath");
    args.add(src.getAbsolutePath());
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    JavaFileManager fm = compiler.getStandardFileManager(null, null, null);
    CompilationTask task = compiler.getTask(null, fm, null, args, Collections.singleton("p.C"), null);
    P p = new P();
    task.setProcessors(Collections.singleton(p));
    assertFalse(task.call());
    assertNotNull(p.env);
    Reference<?> r = new WeakReference<Object>(p.env);
    compiler = null;
    fm = null;
    task = null;
    p = null;
    assertGC("can collect ProcessingEnvironment", r);
}
 
Example 45
Project: rdf4j-schema-generator   File: AbstractSchemaSpecificTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCompilation() throws Exception {
    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    int result = compiler.run(null, null, null, output.toString());
    Assert.assertEquals("Compiling the Schema failed", 0, result);

}
 
Example 46
Project: rdf4j-schema-generator   File: SchemaGeneratorCompileTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testSchemaCompilation() throws ClassNotFoundException, MalformedURLException {
    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    int result = compiler.run(null, null, null, output.toString());
    Assert.assertEquals("Compiling the Vocab failed", 0, result);

}
 
Example 47
Project: json-log-domain   File: YamlTest.java   Source Code and License 5 votes vote down vote up
@Test
public void generateSources() throws Exception {
    Path directory = Paths.get("target/generated-sources/log/");

	JavaGenerator.generate(Paths.get("src/test/resources/yaml/agresso.yaml"), directory);
	JavaGenerator.generate(Paths.get("src/test/resources/yaml/global.yaml"), directory);
	JavaGenerator.generate(Paths.get("src/test/resources/yaml/network.yaml"), directory);
	
	// verify that the generated classes can be loaded
	for(String domain : new String[]{"agresso", "global", "network"}) {
		File network = new File(String.format("target/generated-sources/log/com/example/%s/", domain));
		File[] results = network.listFiles(new FileFilter() {
			public boolean accept(File pathname) {
				return pathname.getName().endsWith(".java");
			}
		});

		List<String> files = new ArrayList<>();
		for(File result : results) {
			files.add(result.getAbsolutePath());
		}

	    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
	    int status = compiler.run(null, null, null, files.toArray(new String[files.size()]));
	    if(status != 0) {
	    	throw new IllegalArgumentException();
	    }			
	}
}
 
Example 48
Project: openjdk-jdk10   File: T6199075.java   Source Code and License 5 votes vote down vote up
void compileAndCheck(VarargsMethod m1, VarargsMethod m2, TypeKind actual, ArgumentsArity argsArity) throws Exception {
    final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavaSource source = new JavaSource(m1, m2, actual, argsArity);
    ErrorChecker ec = new ErrorChecker();
    JavacTask ct = (JavacTask)tool.getTask(null, fm, ec,
            null, null, Arrays.asList(source));
    ct.generate();
    check(source, ec, m1, m2, actual, argsArity);
}
 
Example 49
Project: reading-and-annotate-rocketmq-3.4.6   File: DynaCode.java   Source Code and License 5 votes vote down vote up
private void compile(String[] srcFiles) throws Exception {
    String args[] = this.buildCompileJavacArgs(srcFiles);
    ByteArrayOutputStream err = new ByteArrayOutputStream();
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new NullPointerException(
            "ToolProvider.getSystemJavaCompiler() return null,please use JDK replace JRE!");
    }
    int resultCode = compiler.run(null, null, err, args);
    if (resultCode != 0) {
        throw new Exception(err.toString());
    }
}
 
Example 50
Project: openjdk-jdk10   File: ParserTest.java   Source Code and License 5 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 (TypeQualifierArity arity : TypeQualifierArity.values()) {
                for (TypeArgumentKind tak1 : TypeArgumentKind.values()) {
                    if (arity == TypeQualifierArity.ONE) {
                        new ParserTest(arity, tak1).run(comp, fm);
                        continue;
                    }
                    for (TypeArgumentKind tak2 : TypeArgumentKind.values()) {
                        if (arity == TypeQualifierArity.TWO) {
                            new ParserTest(arity, tak1, tak2).run(comp, fm);
                            continue;
                        }
                        for (TypeArgumentKind tak3 : TypeArgumentKind.values()) {
                            if (arity == TypeQualifierArity.THREE) {
                                new ParserTest(arity, tak1, tak2, tak3).run(comp, fm);
                                continue;
                            }
                            for (TypeArgumentKind tak4 : TypeArgumentKind.values()) {
                                new ParserTest(arity, tak1, tak2, tak3, tak4).run(comp, fm);
                            }
                        }
                    }
                }
            }
        }
    }
 
Example 51
Project: openjdk-jdk10   File: AnnotationProcessing.java   Source Code and License 5 votes vote down vote up
public void createClass(CreateFileObject file, String name, String content) {
    String fileNameStub = name.replace(".", File.separator);

    try (OutputStream out = file.create().openOutputStream()) {
        Path scratch = Files.createDirectories(Paths.get(""));
        Path scratchSrc = scratch.resolve(fileNameStub + ".java").toAbsolutePath();

        Files.createDirectories(scratchSrc.getParent());

        try (Writer w = Files.newBufferedWriter(scratchSrc)) {
            w.write(content);
        }

        Path scratchClasses = scratch.resolve("classes");

        Files.createDirectories(scratchClasses);

        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
        try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {
            List<String> options = List.of("-d", scratchClasses.toString());
            Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(scratchSrc);
            CompilationTask task = comp.getTask(null, fm, null, options, null, files);

            if (!task.call()) {
                throw new AssertionError("compilation failed");
            }
        }

        Path classfile = scratchClasses.resolve(fileNameStub + ".class");

        Files.copy(classfile, out);
    } catch (IOException ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example 52
Project: openjdk-jdk10   File: JavacTask.java   Source Code and License 5 votes vote down vote up
private int runAPI(PrintWriter pw) throws IOException {
        try {
//                if (compiler == null) {
                // TODO: allow this to be set externally
//                    compiler = ToolProvider.getSystemJavaCompiler();
                compiler = JavacTool.create();
//                }

            if (fileManager == null)
                fileManager = internalFileManager = compiler.getStandardFileManager(null, null, null);
            if (outdir != null)
                setLocationFromPaths(StandardLocation.CLASS_OUTPUT, Collections.singletonList(outdir));
            if (classpath != null)
                setLocationFromPaths(StandardLocation.CLASS_PATH, classpath);
            if (sourcepath != null)
                setLocationFromPaths(StandardLocation.SOURCE_PATH, sourcepath);
            List<String> allOpts = new ArrayList<>();
            if (options != null)
                allOpts.addAll(options);

            Iterable<? extends JavaFileObject> allFiles = joinFiles(files, fileObjects);
            JavaCompiler.CompilationTask task = compiler.getTask(pw,
                    fileManager,
                    null,  // diagnostic listener; should optionally collect diags
                    allOpts,
                    classes,
                    allFiles);
            return ((JavacTaskImpl) task).doCall().exitCode;
        } finally {
            if (internalFileManager != null)
                internalFileManager.close();
        }
    }
 
Example 53
Project: QDrill   File: JDKClassCompiler.java   Source Code and License 5 votes vote down vote up
public static JDKClassCompiler newInstance(ClassLoader classLoader, boolean debug) {
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  if (compiler == null) {
    logger.warn("JDK Java compiler not available - probably you're running Drill with a JRE and not a JDK");
    return null;
  }
  return new JDKClassCompiler(compiler, classLoader, debug);
}
 
Example 54
Project: QDrill   File: JDKClassCompiler.java   Source Code and License 5 votes vote down vote up
private JDKClassCompiler(JavaCompiler compiler, ClassLoader classLoader, boolean debug) {
  super(debug);
  this.compiler = compiler;
  this.listener = new DrillDiagnosticListener();
  this.fileManager = new DrillJavaFileManager(compiler.getStandardFileManager(listener, null, Charsets.UTF_8), classLoader);
  this.compilerOptions = Lists.newArrayList(this.debug ? "-g:source,lines,vars" : "-g:none");
}
 
Example 55
Project: openjdk-jdk10   File: IntersectionTypeParserTest.java   Source Code and License 5 votes vote down vote up
void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception {
    checkCount++;
    JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker,
            null, null, Arrays.asList(source));
    ct.parse();
    if (diagChecker.errorFound) {
        throw new Error("Unexpected parser error for source:\n" +
            source.getCharContent(true));
    }
}
 
Example 56
Project: openjdk-jdk10   File: SchemaGenerator.java   Source Code and License 5 votes vote down vote up
public static boolean compile(String[] args, File episode) throws Exception {

            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
            StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
            JavacOptions options = JavacOptions.parse(compiler, fileManager, args);
            List<String> unrecognizedOptions = options.getUnrecognizedOptions();
            if (!unrecognizedOptions.isEmpty()) {
                LOGGER.log(Level.WARNING, "Unrecognized options found: {0}", unrecognizedOptions);
            }
            Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(options.getFiles());
            JavaCompiler.CompilationTask task = compiler.getTask(
                    null,
                    fileManager,
                    diagnostics,
                    options.getRecognizedOptions(),
                    options.getClassNames(),
                    compilationUnits);
            com.sun.tools.internal.jxc.ap.SchemaGenerator r = new com.sun.tools.internal.jxc.ap.SchemaGenerator();
            if (episode != null)
                r.setEpisodeFile(episode);
            task.setProcessors(Collections.singleton(r));
            boolean res = task.call();
            //Print compiler generated messages
            for( Diagnostic<? extends JavaFileObject> d : diagnostics.getDiagnostics() ) {
                 System.err.println(d.toString());
            }
            return res;
        }
 
Example 57
Project: openjdk-jdk10   File: BadClassfile.java   Source Code and License 5 votes vote down vote up
private static void test(String classname, String expected) throws Exception {
    File classfile = new File(System.getProperty("test.classes", "."), classname + ".class");
    ClassFile cf = ClassFile.read(classfile);

    cf = new ClassFile(cf.magic, Target.JDK1_7.minorVersion,
             Target.JDK1_7.majorVersion, cf.constant_pool, cf.access_flags,
            cf.this_class, cf.super_class, cf.interfaces, cf.fields,
            cf.methods, cf.attributes);

    new ClassWriter().write(cf, classfile);

    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    JavacTaskImpl task = (JavacTaskImpl) c.getTask(null, null, null, Arrays.asList("-classpath", System.getProperty("test.classes", ".")), null, null);
    Symtab syms = Symtab.instance(task.getContext());

    task.ensureEntered();

    try {
        Symbol clazz = com.sun.tools.javac.main.JavaCompiler.instance(task.getContext()).resolveIdent(syms.unnamedModule, classname);

        clazz.complete();
    } catch (BadClassFile f) {
        JCDiagnostic embeddedDiag = (JCDiagnostic) f.diag.getArgs()[1];
        assertEquals(expected, embeddedDiag.getCode());
        assertEquals(Integer.toString(Target.JDK1_7.majorVersion), embeddedDiag.getArgs()[0]);
        assertEquals(Integer.toString(Target.JDK1_7.minorVersion), embeddedDiag.getArgs()[1]);
    }
}
 
Example 58
Project: jsf-sdk   File: TemplatePrecompiler.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("serial")
private static void matchClassNames(List<String> ret, final String className)
        throws IOException {
    String packageName = className.substring(0, className.lastIndexOf('.'));
    String relativedName = className.substring(
            className.lastIndexOf('.') + 1, className.length());
    String patName = relativedName.replace("*", "(\\w+)");
    Pattern pat = Pattern.compile(patName);

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    JavaFileManager fm = compiler.getStandardFileManager(
            new DiagnosticCollector<JavaFileObject>(), null, null);
    HashSet<JavaFileObject.Kind> kind = new HashSet<JavaFileObject.Kind>() {
        {
            add(JavaFileObject.Kind.CLASS);
        }
    };

    for (JavaFileObject f : fm.list(StandardLocation.PLATFORM_CLASS_PATH, packageName, kind, false)) {
        String relatived0 = f.getName();
        String name0 = relatived0.substring(0, relatived0.length() - ".class".length());
        Matcher m = pat.matcher(name0);
        if (m.matches()) {
            String name = packageName + '.' + name0;
            if (!ret.contains(name)) {
                ret.add(name);
            }
        }
    }
}
 
Example 59
Project: guava-beta-checker   File: TestCompiler.java   Source Code and License 5 votes vote down vote up
/**
 * Compiles the given {@code sources} and returns a list of diagnostics produced by the compiler.
 */
public List<Diagnostic<? extends JavaFileObject>> compile(
    Iterable<? extends JavaFileObject> sources) {
  ScannerSupplier scannerSupplier = ScannerSupplier.fromBugCheckerClasses(checker);
  DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<>();
  JavaCompiler compiler = new BaseErrorProneJavaCompiler(scannerSupplier);
  File tmpDir = Files.createTempDir();
  CompilationTask task =
      compiler.getTask(
          new PrintWriter(System.err, true),
          null /*filemanager*/,
          collector,
          ImmutableList.of("-d", tmpDir.getAbsolutePath()),
          null /*classes*/,
          sources);
  try {
    task.call();
    return collector.getDiagnostics();
  } finally {
    File[] files = tmpDir.listFiles();
    if (files != null) {
      for (File file : files) {
        file.delete();
      }
    }
    tmpDir.delete();
  }
}
 
Example 60
Project: openjdk-jdk10   File: EagerInterfaceCompletionTest.java   Source Code and License 5 votes vote down vote up
EagerInterfaceCompletionTest(JavaCompiler javacTool, File testDir, VersionKind versionKind,
        HierarchyKind hierarchyKind, TestKind testKind, ActionKind actionKind) {
    this.javacTool = javacTool;
    this.versionKind = versionKind;
    this.hierarchyKind = hierarchyKind;
    this.testDir = testDir;
    this.testKind = testKind;
    this.actionKind = actionKind;
}