Example usage for javax.tools DiagnosticCollector getDiagnostics

List of usage examples for javax.tools DiagnosticCollector getDiagnostics

Introduction

In this page you can find the example usage for javax.tools DiagnosticCollector getDiagnostics.

Prototype

public List<Diagnostic<? extends S>> getDiagnostics() 

Source Link

Document

Returns a list view of diagnostics collected by this object.

Usage

From source file:com.yahoo.maven.visitor.SuccessfulCompilationAsserter.java

public void assertNoCompilationErrors() throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null,
            StandardCharsets.UTF_8)) {
        List<File> javaFiles = new ArrayList<>();
        try (Stream<Path> stream = Files.walk(scratchSpace)) {
            Iterator<Path> iterator = stream.iterator();
            while (iterator.hasNext()) {
                Path path = iterator.next();
                if (Files.isRegularFile(path) && "java".equals(FilenameUtils.getExtension(path.toString()))) {
                    javaFiles.add(path.toFile());
                }/*from   w  ww . j a va  2 s  .  c  o m*/
            }
        }
        Iterable<? extends JavaFileObject> compilationUnits = fileManager
                .getJavaFileObjectsFromFiles(javaFiles);
        compiler.getTask(null, fileManager, diagnostics,
                Arrays.asList("-classpath", System.getProperty("java.class.path")), null, compilationUnits)
                .call();
    }
    int errors = 0;
    for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
        if (Diagnostic.Kind.ERROR.equals(diagnostic.getKind())) {
            System.err.println(diagnostic);
            errors++;
        }
    }
    assertEquals(0, errors);
}

From source file:com.sun.script.java.JavaCompiler.java

/**
 * compile given String source and return bytecodes as a Map.
 * //from  www  .j  a v a2  s  . com
 * @param fileName source fileName to be used for error messages etc.
 * @param source Java source as String
 * @param err error writer where diagnostic messages are written
 * @param sourcePath location of additional .java source files
 * @param classPath location of additional .class files
 * @return classBytes
 */
public Map<String, byte[]> compile(String fileName, String source, Writer err, String sourcePath,
        String classPath) {
    // to collect errors, warnings etc.
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

    // create a new memory JavaFileManager
    MemoryJavaFileManager manager = new MemoryJavaFileManager();

    // prepare the compilation unit
    List<JavaFileObject> compUnits = new ArrayList<JavaFileObject>(1);
    compUnits.add(MemoryJavaFileManager.makeStringSource(fileName, source));

    // javac options
    List<String> options = new ArrayList<String>();
    options.add("-Xlint:all");
    options.add("-g");
    options.add("-deprecation");
    if (sourcePath != null) {
        options.add("-sourcepath");
        options.add(sourcePath);
    }

    if (classPath != null) {
        options.add("-classpath");
        options.add(classPath);
    }

    // create a compilation task
    javax.tools.JavaCompiler.CompilationTask task = tool.getTask(err, manager, diagnostics, options, null,
            compUnits);

    if (task.call() == false) {
        PrintWriter perr = new PrintWriter(err);
        for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
            perr.println(diagnostic.getMessage(null));
        }
        perr.flush();
        return null;
    }

    Map<String, byte[]> classBytes = manager.getClassBytes();

    IOUtils.closeQuietly(manager);

    return classBytes;
}

From source file:iristk.flow.FlowCompiler.java

public static void compileJavaFlow(File srcFile) throws FlowCompilerException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (ToolProvider.getSystemJavaCompiler() == null) {
        throw new FlowCompilerException("Could not find Java Compiler");
    }/* www. ja v a2s  .c  om*/
    if (!srcFile.exists()) {
        throw new FlowCompilerException(srcFile.getAbsolutePath() + " does not exist");
    }
    File outputDir = new File(srcFile.getAbsolutePath().replaceFirst("([\\\\/])src[\\\\/].*", "$1") + "bin");
    if (!outputDir.exists()) {
        throw new FlowCompilerException("Directory " + outputDir.getAbsolutePath() + " does not exist");
    }
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, Locale.US,
            StandardCharsets.UTF_8);
    Iterable<? extends JavaFileObject> compilationUnits = fileManager
            .getJavaFileObjectsFromStrings(Arrays.asList(srcFile.getAbsolutePath()));
    Iterable<String> args = Arrays.asList("-d", outputDir.getAbsolutePath());
    JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, args, null,
            compilationUnits);
    boolean success = task.call();
    try {
        fileManager.close();
    } catch (IOException e) {
    }
    for (Diagnostic<? extends JavaFileObject> diag : diagnostics.getDiagnostics()) {
        if (diag.getKind() == Kind.ERROR) {
            int javaLine = (int) diag.getLineNumber();
            int flowLine = mapLine(javaLine, srcFile);
            String message = diag.getMessage(Locale.US);
            message = message.replace("line " + javaLine, "line " + flowLine);
            throw new FlowCompilerException(message, flowLine);
        }
    }
    if (!success) {
        throw new FlowCompilerException("Compilation failed for unknown reason");
    }
}

From source file:com.qwazr.compiler.JavaCompiler.java

private void compile(javax.tools.JavaCompiler compiler, Collection<File> javaFiles) throws IOException {
    final DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    final StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
    try {//from  ww w  .  j  a v a  2s. c  om
        Iterable<? extends JavaFileObject> sourceFileObjects = fileManager
                .getJavaFileObjectsFromFiles(javaFiles);
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        final List<String> options = new ArrayList<String>();
        if (classPath != null) {
            options.add("-classpath");
            options.add(classPath);
        }
        options.add("-d");
        options.add(javaClassesDirectory.getAbsolutePath());
        options.add("-sourcepath");
        options.add(javaSourceDirectory.getAbsolutePath());
        javax.tools.JavaCompiler.CompilationTask task = compiler.getTask(pw, fileManager, diagnostics, options,
                null, sourceFileObjects);
        if (!task.call()) {
            for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics())
                pw.format("Error on line %d in %s%n%s%n", diagnostic.getLineNumber(),
                        diagnostic.getSource().toUri(), diagnostic.getMessage(null));
            pw.flush();
            pw.close();
            sw.close();
            throw new IOException(sw.toString());
        }
    } finally {
        IOUtils.close(fileManager);
    }
}

From source file:org.mule.devkit.apt.AbstractAnnotationProcessorTest.java

/**
 * Attempts to compile the given compilation units using the Java Compiler API.
 * <p>/*w  w  w .  j av a 2 s.co m*/
 * The compilation units and all their dependencies are expected to be on the classpath.
 *
 * @param compilationUnitPaths
 *            the paths of the source files to compile, as would be expected
 *            by {@link ClassLoader#getResource(String)}
 * @return the {@link Diagnostic diagnostics} returned by the compilation,
 *         as demonstrated in the documentation for {@link JavaCompiler}
 * @see #compileTestCase(Class...)
 *
 */
protected List<Diagnostic<? extends JavaFileObject>> compileTestCase(String... compilationUnitPaths) {
    assert (compilationUnitPaths != null);

    Collection<File> compilationUnits;

    try {
        compilationUnits = findClasspathFiles(compilationUnitPaths);
    } catch (IOException exception) {
        throw new IllegalArgumentException("Unable to resolve compilation units "
                + Arrays.toString(compilationUnitPaths) + " due to: " + exception.getMessage(), exception);
    }

    DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = COMPILER.getStandardFileManager(diagnosticCollector, null, null);

    /*
     * Call the compiler with the "-proc:only" option. The "class names"
     * option (which could, in principle, be used instead of compilation
     * units for annotation processing) isn't useful in this case because
     * only annotations on the classes being compiled are accessible.
     *
     * Information about the classes being compiled (such as what they are annotated
     * with) is *not* available via the RoundEnvironment. However, if these classes
     * are annotations, they certainly need to be validated.
     */
    CompilationTask task = COMPILER.getTask(null, fileManager, diagnosticCollector, Arrays.asList("-proc:only"),
            null, fileManager.getJavaFileObjectsFromFiles(compilationUnits));
    task.setProcessors(getProcessors());
    task.call();

    try {
        fileManager.close();
    } catch (IOException exception) {
    }

    return diagnosticCollector.getDiagnostics();
}

From source file:nl.elucidator.patterns.builder.annotations.processor.AbstractAnnotationProcessorTest.java

/**
 * Attempts to compile the given compilation units using the Java Compiler API.
 * <p/>/*from  www .  j  a v a  2s.c o m*/
 * The compilation units and all their dependencies are expected to be on the classpath.
 *
 * @param compilationUnitPaths the paths of the source files to compile, as would be expected
 *                             by {@link ClassLoader#getResource(String)}
 * @return the {@link Diagnostic diagnostics} returned by the compilation,
 *         as demonstrated in the documentation for {@link JavaCompiler}
 * @see #compileTestCase(Class...)
 */
protected List<Diagnostic<? extends JavaFileObject>> compileTestCase(String... compilationUnitPaths) {
    assert (compilationUnitPaths != null);

    Collection<File> compilationUnits;

    try {
        compilationUnits = findClasspathFiles(compilationUnitPaths);
    } catch (IOException exception) {
        throw new IllegalArgumentException("Unable to resolve compilation units "
                + Arrays.toString(compilationUnitPaths) + " due to: " + exception.getMessage(), exception);
    }

    DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = COMPILER.getStandardFileManager(diagnosticCollector, null, null);

    /*
     * Call the compiler with the "-proc:only" option. The "class names"
     * option (which could, in principle, be used instead of compilation
     * units for annotation processing) isn't useful in this case because
     * only annotations on the classes being compiled are accessible.
     * 
     * Information about the classes being compiled (such as what they are annotated
     * with) is *not* available via the RoundEnvironment. However, if these classes
     * are annotations, they certainly need to be validated.
     */
    CompilationTask task = COMPILER.getTask(null, fileManager, diagnosticCollector, Arrays.asList("-proc:only"),
            null, fileManager.getJavaFileObjectsFromFiles(compilationUnits));
    task.setProcessors(getProcessors());
    task.call();

    try {
        fileManager.close();
    } catch (IOException exception) {
        //Nothing to do
    }

    return diagnosticCollector.getDiagnostics();
}

From source file:com.qrmedia.commons.test.annotation.processing.AbstractAnnotationProcessorTest.java

/**
 * Attempts to compile the given compilation units using the Java Compiler API.
 * <p>/*  w w w. j  a  v a  2  s.c  om*/
 * The compilation units and all their dependencies are expected to be on the classpath.
 * 
 * @param compilationUnitPaths
 *            the paths of the source files to compile, as would be expected
 *            by {@link ClassLoader#getResource(String)}
 * @return the {@link Diagnostic diagnostics} returned by the compilation,
 *         as demonstrated in the documentation for {@link JavaCompiler}
 * @see #compileTestCase(Class...)
 * 
 */
protected List<Diagnostic<? extends JavaFileObject>> compileTestCase(String... compilationUnitPaths) {
    assert (compilationUnitPaths != null);

    Collection<File> compilationUnits;

    try {
        compilationUnits = findClasspathFiles(compilationUnitPaths);
    } catch (IOException exception) {
        throw new IllegalArgumentException("Unable to resolve compilation units "
                + Arrays.toString(compilationUnitPaths) + " due to: " + exception.getMessage(), exception);
    }

    DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = COMPILER.getStandardFileManager(diagnosticCollector, null, null);

    /*
     * Call the compiler with the "-proc:only" option. The "class names"
     * option (which could, in principle, be used instead of compilation
     * units for annotation processing) isn't useful in this case because
     * only annotations on the classes being compiled are accessible.
     * 
     * Information about the classes being compiled (such as what they are annotated
     * with) is *not* available via the RoundEnvironment. However, if these classes
     * are annotations, they certainly need to be validated.
     */
    CompilationTask task = COMPILER.getTask(null, fileManager, diagnosticCollector, Arrays.asList("-proc:only"),
            null, fileManager.getJavaFileObjectsFromFiles(compilationUnits));
    task.setProcessors(getProcessors());
    task.call();

    try {
        fileManager.close();
    } catch (IOException exception) {
    }

    return diagnosticCollector.getDiagnostics();
}

From source file:com.tojc.ormlite.android.compiler.AbstractAnnotationProcessorTest.java

/**
 * Attempts to compile the given compilation units using the Java Compiler API.
 * <p>//  w  w w .  j ava2  s  . c o  m
 * The compilation units and all their dependencies are expected to be on the classpath.
 * @param compilationUnitPaths
 *            the paths of the source files to compile, as would be expected by
 *            {@link ClassLoader#getResource(String)}
 * @return the {@link Diagnostic diagnostics} returned by the compilation, as demonstrated in
 *         the documentation for {@link JavaCompiler}
 * @see #compileTestCase(Class...)
 */
protected List<Diagnostic<? extends JavaFileObject>> compileTestCase(String... compilationUnitPaths) {
    assert compilationUnitPaths != null;

    Collection<File> compilationUnits;

    try {
        compilationUnits = findClasspathFiles(compilationUnitPaths);
    } catch (IOException exception) {
        throw new IllegalArgumentException("Unable to resolve compilation units "
                + Arrays.toString(compilationUnitPaths) + " due to: " + exception.getMessage(), exception);
    }

    DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = COMPILER.getStandardFileManager(diagnosticCollector, null, null);

    /*
     * Call the compiler with the "-proc:only" option. The "class names" option (which could, in
     * principle, be used instead of compilation units for annotation processing) isn't useful
     * in this case because only annotations on the classes being compiled are accessible.
     * Information about the classes being compiled (such as what they are annotated with) is
     * *not* available via the RoundEnvironment. However, if these classes are annotations, they
     * certainly need to be validated.
     */
    CompilationTask task = COMPILER.getTask(null, fileManager, diagnosticCollector,
            mergeCompilerOptions(Arrays.asList("-proc:only")), null,
            fileManager.getJavaFileObjectsFromFiles(compilationUnits));
    task.setProcessors(getProcessors());
    task.call();

    try {
        fileManager.close();
    } catch (IOException exception) {
        exception.printStackTrace();
    }

    return diagnosticCollector.getDiagnostics();
}

From source file:org.bigtester.ate.model.caserunner.CaseRunnerGenerator.java

private void loadClass(String classFilePathName, String className) throws ClassNotFoundException, IOException {
    /** Compilation Requirements *********************************************************************************************/
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = getCompiler().getStandardFileManager(diagnostics, null, null);

    // This sets up the class path that the compiler will use.
    // I've added the .jar file that contains the DoStuff interface within
    // in it...//from  ww  w . j  av a  2s .  co m
    List<String> optionList = new ArrayList<String>();
    optionList.add("-classpath");
    optionList.add(getAllJarsClassPathInMavenLocalRepo());
    optionList.add("-verbose");

    File helloWorldJava = new File(classFilePathName);

    Iterable<? extends JavaFileObject> compilationUnit = fileManager
            .getJavaFileObjectsFromFiles(Arrays.asList(helloWorldJava));
    JavaCompiler.CompilationTask task = getCompiler().getTask(null, fileManager, diagnostics, optionList, null,
            compilationUnit);

    /********************************************************************************************* Compilation Requirements **/
    if (task.call()) {
        /** Load and execute *************************************************************************************************/
        // Create a new custom class loader, pointing to the directory that
        // contains the compiled
        // classes, this should point to the top of the package structure!
        //TODO the / separator needs to be revised to platform awared 
        URLClassLoader classLoader = new URLClassLoader(new URL[] {
                new File(System.getProperty("user.dir") + "/generated-code/caserunners/").toURI().toURL() },
                Thread.currentThread().getContextClassLoader());
        String addonClasspath = System.getProperty("user.dir") + "/generated-code/caserunners/";
        ClassLoaderUtil.addFileToClassPath(addonClasspath, classLoader.getParent());
        classLoader.loadClass(className);
        classLoader.close();
        /************************************************************************************************* Load and execute **/
    } else {
        for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
            System.out.format("Error on line %d in %s%n with error %s", diagnostic.getLineNumber(),
                    diagnostic.getSource(), diagnostic.getMessage(new Locale("en")));
        }
    }
}

From source file:org.abstractmeta.toolbox.compilation.compiler.impl.JavaSourceCompilerImpl.java

private String getDiagnosticString(JavaFileObjectRegistry registry,
        DiagnosticCollector<JavaFileObject> diagnostics) {
    StringBuilder diagnosticBuilder = new StringBuilder();
    for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
        buildDiagnosticMessage(diagnostic, diagnosticBuilder, registry);
    }//w  w  w  .  j av  a  2  s  .  c  o m
    return diagnosticBuilder.toString();
}