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:clear.cdb.support.test.AnnotationProcessorTestCompiler.java

/**
 * Processes the java class specified. This implementation only parses and processes the java classes and does not
 * fully compile them - i.e. it does not write class files back to the disk. Basically, {@code javac} is called with
 * {@code -proc:only}.//www.  j a v  a 2s  .co  m
 *
 * @param processor        the annotation {@link javax.annotation.processing.Processor} to use during compilation
 * @param fileManager
 * @param compilationUnits
 * @return a list of {@link Diagnostic} messages emitted during the compilation
 */
private static List<Diagnostic<? extends JavaFileObject>> compileClassInternal(Processor processor,
        StandardJavaFileManager fileManager, Iterable<? extends JavaFileObject> compilationUnits,
        String additionalOptions) throws IOException {

    DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<JavaFileObject>();

    try {
        List<String> options = new ArrayList<String>();
        options.add(COMPILER_OPTIONS);
        if (additionalOptions != null) {
            options.add(additionalOptions);
        }
        options.add("-classpath");
        options.add(System.getProperty("java.class.path"));
        JavaCompiler.CompilationTask task = COMPILER.getTask(null, fileManager, collector, options, null,
                compilationUnits);
        task.setProcessors(Arrays.asList(processor));
        task.call();

        return collector.getDiagnostics();
    } finally {
        if (fileManager != null) {
            fileManager.close();
        }
    }
}

From source file:gov.nih.nci.restgen.util.GeneratorUtil.java

public static boolean compileJavaSource(String srcFolder, String destFolder, String libFolder,
        GeneratorContext context) {/*ww w  .  j ava  2 s  .c om*/
    StandardJavaFileManager fileManager = null;
    boolean success = true;
    try {
        List<String> compilerFiles = GeneratorUtil.getFiles(srcFolder, new String[] { "java" });

        GeneratorUtil.createOutputDir(destFolder);

        List<String> options = new ArrayList<String>();
        options.add("-classpath");
        String classPathStr = GeneratorUtil.getFiles(libFolder, new String[] { "jar" }, File.pathSeparator);

        options.add(classPathStr);
        options.add("-nowarn");
        options.add("-Xlint:-unchecked");
        options.add("-d");
        options.add(destFolder);

        options.add("-s");
        options.add(srcFolder);

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
        fileManager = compiler.getStandardFileManager(diagnostics, null, null);
        Iterable<? extends JavaFileObject> compilationUnits = fileManager
                .getJavaFileObjectsFromStrings(compilerFiles);
        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null,
                compilationUnits);
        success = task.call();

        for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
            //context.getLogger().error(diagnostic.getCode());
            //context.getLogger().error(diagnostic.getKind().toString());
            //context.getLogger().error(diagnostic.getPosition() + "");
            //context.getLogger().error(diagnostic.getStartPosition() + "");
            //context.getLogger().error(diagnostic.getEndPosition() + "");
            //context.getLogger().error(diagnostic.getSource().toString());
            context.getLogger().error(diagnostic.toString());
        }
    } catch (Throwable t) {
        context.getLogger().error("Error compiling java code", t);
    } finally {
        try {
            fileManager.close();
        } catch (Throwable t) {
        }
    }
    return success;
}

From source file:hydrograph.ui.expression.editor.buttons.ValidateExpressionToolButton.java

private void showDiagnostics(DiagnosticCollector<JavaFileObject> diagnostics) {
    String message;/*  ww w.j av a  2  s.  c o  m*/
    for (Diagnostic<?> diagnostic : diagnostics.getDiagnostics()) {
        if (StringUtils.equals(diagnostic.getKind().name(), Diagnostic.Kind.ERROR.name())) {
            message = diagnostic.getMessage(null);
            new CustomMessageBox(SWT.ERROR, message, Messages.INVALID_EXPRESSION_TITLE).open();
        } else {
            new CustomMessageBox(SWT.ICON_INFORMATION, Messages.VALID_EXPRESSION_TITLE,
                    Messages.VALID_EXPRESSION_TITLE).open();
        }
        break;
    }
}

From source file:org.glowroot.common2.repo.util.Compilations.java

public static Class<?> compile(String source) throws Exception {
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();

    IsolatedClassLoader isolatedClassLoader = new IsolatedClassLoader();

    StandardJavaFileManager standardFileManager = javaCompiler.getStandardFileManager(diagnosticCollector,
            Locale.ENGLISH, UTF_8);
    standardFileManager.setLocation(StandardLocation.CLASS_PATH, getCompilationClassPath());
    JavaFileManager fileManager = new IsolatedJavaFileManager(standardFileManager, isolatedClassLoader);
    try {/*www .  j  a  va 2s . com*/
        List<JavaFileObject> compilationUnits = Lists.newArrayList();

        String className = getPublicClassName(source);
        int index = className.lastIndexOf('.');
        String simpleName;
        if (index == -1) {
            simpleName = className;
        } else {
            simpleName = className.substring(index + 1);
        }
        compilationUnits.add(new SourceJavaFileObject(simpleName, source));

        JavaCompiler.CompilationTask task = javaCompiler.getTask(null, fileManager, diagnosticCollector, null,
                null, compilationUnits);
        task.call();

        List<Diagnostic<? extends JavaFileObject>> diagnostics = diagnosticCollector.getDiagnostics();
        if (!diagnostics.isEmpty()) {
            List<String> compilationErrors = Lists.newArrayList();
            for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) {
                compilationErrors.add(checkNotNull(diagnostic.toString()));
            }
            throw new CompilationException(compilationErrors);
        }
        if (className.isEmpty()) {
            throw new CompilationException(ImmutableList.of("Class must be public"));
        }
        return isolatedClassLoader.loadClass(className);
    } finally {
        fileManager.close();
    }
}

From source file:com.jhash.oimadmin.ui.UIJavaCompile.java

public boolean compile() {
    boolean successfulCompile = false;
    DiagnosticCollector<JavaFileObject> returnedValue = Utils.compileJava(classNameText.getText(),
            sourceCode.getText(), outputDirectory);

    if (returnedValue != null) {
        StringBuilder message = new StringBuilder();
        for (Diagnostic<?> d : returnedValue.getDiagnostics()) {
            switch (d.getKind()) {
            case ERROR:
                message.append("ERROR: " + d.toString() + "\n");
            default:
                message.append(d.toString() + "\n");
            }/*from   w  w w.j a  v a  2  s . c  om*/
        }
        compileResultTextArea.setText(message.toString());
    } else {
        compileResultTextArea.setText("Compilation successful");
        successfulCompile = true;
    }
    return successfulCompile;
}

From source file:hydrograph.ui.expression.editor.evaluate.EvaluateExpression.java

boolean isValidExpression() {
    try {/*from w  ww  .  ja  v a2 s . co m*/
        DiagnosticCollector<JavaFileObject> diagnosticCollector = ValidateExpressionToolButton.compileExpresion(
                expressionEditor.getText(),
                (Map<String, Class<?>>) expressionEditor.getData(ExpressionEditorDialog.FIELD_DATA_TYPE_MAP),
                String.valueOf(expressionEditor.getData(ExpressionEditorDialog.COMPONENT_NAME_KEY)));
        if (diagnosticCollector != null && !diagnosticCollector.getDiagnostics().isEmpty()) {
            for (Diagnostic<?> diagnostic : diagnosticCollector.getDiagnostics()) {
                if (StringUtils.equals(diagnostic.getKind().name(), Diagnostic.Kind.ERROR.name())) {
                    evaluateDialog.showError(diagnostic.getMessage(Locale.ENGLISH));
                    return false;
                }
            }
        }
        return true;
    } catch (JavaModelException | MalformedURLException | IllegalAccessException
            | IllegalArgumentException exception) {
        LOGGER.error("Exception occurred while compiling expression", exception);
    } catch (InvocationTargetException exception) {
        LOGGER.warn("Exception occurred while invoking compile method for compiling expression");
        evaluateDialog.showError(exception.getCause().getMessage());
    } catch (ClassNotFoundException classNotFoundException) {
        evaluateDialog.showError("Cannot find validation jar in build path");
    }
    return false;
}

From source file:hydrograph.ui.expression.editor.buttons.ValidateExpressionToolButton.java

private void validation(StyledText expressionEditor) {
    try {//from   w  w  w.  ja va  2  s .  com
        DiagnosticCollector<JavaFileObject> diagnostics = compileExpresion(expressionEditor.getText(),
                (Map<String, Class<?>>) expressionEditor.getData(ExpressionEditorDialog.FIELD_DATA_TYPE_MAP),
                String.valueOf(expressionEditor.getData(ExpressionEditorDialog.COMPONENT_NAME_KEY)));
        if (diagnostics != null && !diagnostics.getDiagnostics().isEmpty())
            showDiagnostics(diagnostics);
        else {
            new CustomMessageBox(SWT.ICON_INFORMATION, Messages.VALID_EXPRESSION_TITLE,
                    Messages.VALID_EXPRESSION_TITLE).open();
        }
    } catch (JavaModelException | MalformedURLException | IllegalAccessException
            | IllegalArgumentException exception) {
        LOGGER.error("Exception occurred while compiling expression", exception);
        new CustomMessageBox(SWT.ERROR, exception.getCause().getMessage(), Messages.INVALID_EXPRESSION_TITLE)
                .open();
    } catch (InvocationTargetException exception) {
        if (exception.getCause() != null && StringUtils.isNotBlank(exception.getCause().getMessage()))
            new CustomMessageBox(SWT.ERROR, exception.getCause().getMessage(),
                    Messages.INVALID_EXPRESSION_TITLE).open();
        LOGGER.warn("Exception occurred while invoking compile method for compiling expression", exception);
    } catch (ClassNotFoundException classNotFoundException) {
        new CustomMessageBox(SWT.ERROR, "Cannot find validation jar in build path",
                Messages.INVALID_EXPRESSION_TITLE).open();
    }
}

From source file:neembuu.uploader.zip.generator.NUCompiler.java

/**
 * Compile all the given files in the given build directory.
 *
 * @param files The array of files to compiles.
 * @param buildDirectory The build directory in which put all the compiled
 * files.//from   w w w  . j a v  a 2s .c  o  m
 * @throws FileNotFoundException
 * @throws IOException
 */
private void compileFiles(File[] files, File buildDirectory) throws FileNotFoundException, IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    buildDirectory.mkdir();

    /**/
    List<String> optionList = new ArrayList<String>();
    // set compiler's classpath to be same as the runtime's
    //optionList.addAll(Arrays.asList("-classpath", "C:\\neembuuuploader\\modules\\libs\\jsoup-1.7.2.jar;C:\\neembuuuploader\\modules\\libs\\ApacheHttpComponent-4.2.5\\commons-codec-1.6.jar;C:\\neembuuuploader\\modules\\libs\\ApacheHttpComponent-4.2.5\\commons-logging-1.1.1.jar;C:\\neembuuuploader\\modules\\libs\\ApacheHttpComponent-4.2.5\\httpclient-4.2.5.jar;C:\\neembuuuploader\\modules\\libs\\ApacheHttpComponent-4.2.5\\httpclient-cache-4.2.5.jar;C:\\neembuuuploader\\modules\\libs\\ApacheHttpComponent-4.2.5\\httpcore-4.2.4.jar;C:\\neembuuuploader\\modules\\libs\\ApacheHttpComponent-4.2.5\\httpmime-4.2.5.jar;C:\\neembuuuploader\\modules\\libs\\json-java.jar;C:\\neembuuuploader\\modules\\neembuu-uploader-utils\\build\\classes;C:\\neembuuuploader\\modules\\neembuu-uploader-api\\build\\classes;C:\\neembuuuploader\\modules\\neembuu-uploader-interfaces-abstractimpl\\build\\classes;C:\\neembuuuploader\\modules\\libs\\neembuu-now-api-ui.jar;C:\\neembuuuploader\\modules\\libs\\neembuu-release1-ui-mc.jar;C:\\neembuuuploader\\modules\\neembuu-uploader-uploaders\\build\\classes;C:\\neembuuuploader\\modules\\NeembuuUploader\\build\\classes"));
    optionList.addAll(Arrays.asList("-classpath", classPath));
    optionList.addAll(Arrays.asList("-d", buildDirectory.getAbsolutePath()));

    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> compilationUnits = fileManager
            .getJavaFileObjectsFromFiles(Arrays.asList(files));

    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

    JavaCompiler.CompilationTask task = compiler.getTask(null, null, diagnostics, optionList, null,
            compilationUnits);
    boolean result = task.call();

    if (result) {
        System.out.println("Compilation was successful");
    } else {
        System.out.println("Compilation failed");

        for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
            System.out.format("Error on line %d in %s", diagnostic.getLineNumber(), diagnostic);
        }
    }
}

From source file:de.monticore.codegen.GeneratorTest.java

/**
 * Compiles the files in the given directory, printing errors to the console
 * if any occur./*from  www.  ja v  a2s  . co m*/
 * 
 * @param sourceCodePath the source directory to be compiled
 * @return true if the compilation succeeded
 */
protected boolean compile(Path sourceCodePath) {
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    boolean compilationSuccess = false;
    Optional<CompilationTask> task = setupCompilation(sourceCodePath, diagnostics);
    if (!task.isPresent()) {
        return compilationSuccess;
    }
    compilationSuccess = task.get().call();
    if (!compilationSuccess) {
        for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
            Log.error(diagnostic.toString());
        }
    }
    return compilationSuccess;
}

From source file:gov.nih.nci.sdk.example.generator.WebServiceGenerator.java

private void compileWebServiceInterface() {
    java.util.Set<String> processedFocusDomainSet = (java.util.Set<String>) getScriptContext().getMemory()
            .get("processedFocusDomainSet");

    if (processedFocusDomainSet == null) {
        processedFocusDomainSet = new java.util.HashSet<String>();
        getScriptContext().getMemory().put("processedFocusDomainSet", processedFocusDomainSet);
    }/*  w w w. j a  va2s  . c om*/

    processedFocusDomainSet.add(getScriptContext().getFocusDomain());

    if (processedFocusDomainSet.containsAll(getScriptContext().retrieveDomainSet()) == true) { //All domains have been processed so now we can compile and generate WSDL

        StandardJavaFileManager fileManager = null;

        try {
            String jaxbPojoPath = GeneratorUtil.getJaxbPojoPath(getScriptContext());
            String servicePath = GeneratorUtil.getServicePath(getScriptContext());
            String serviceImplPath = GeneratorUtil.getServiceImplPath(getScriptContext());
            String projectRoot = getScriptContext().getProperties().getProperty("PROJECT_ROOT");

            List<String> compilerFiles = GeneratorUtil.getFiles(jaxbPojoPath, new String[] { "java" });
            compilerFiles.addAll(GeneratorUtil.getFiles(servicePath, new String[] { "java" }));
            compilerFiles.addAll(GeneratorUtil.getFiles(serviceImplPath, new String[] { "java" }));

            getScriptContext().logInfo("Compiling files: " + compilerFiles);
            // Check if output directory exist, create it
            GeneratorUtil.createOutputDir(projectRoot + File.separator + "classes");

            List<String> options = new ArrayList<String>();
            options.add("-classpath");
            String classPathStr = GeneratorUtil
                    .getFiles(new java.io.File(getScriptContext().getGeneratorBase()).getAbsolutePath()
                            + File.separator + "lib", new String[] { "jar" }, File.pathSeparator)
                    + File.pathSeparator
                    + new java.io.File(projectRoot + File.separatorChar + "classes").getAbsolutePath();

            getScriptContext().logInfo("compiler classpath is: " + classPathStr);

            options.add(classPathStr);

            options.add("-d");
            options.add(projectRoot + File.separator + "classes");

            options.add("-s");
            options.add(projectRoot + File.separator + "src/generated");

            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
            fileManager = compiler.getStandardFileManager(diagnostics, null, null);
            Iterable<? extends JavaFileObject> compilationUnits = fileManager
                    .getJavaFileObjectsFromStrings(compilerFiles);
            JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null,
                    compilationUnits);
            boolean success = task.call();

            for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
                getScriptContext().logInfo(diagnostic.getCode());
                getScriptContext().logInfo(diagnostic.getKind().toString());
                getScriptContext().logInfo(diagnostic.getPosition() + "");
                getScriptContext().logInfo(diagnostic.getStartPosition() + "");
                getScriptContext().logInfo(diagnostic.getEndPosition() + "");
                getScriptContext().logInfo(diagnostic.getSource().toString());
                getScriptContext().logInfo(diagnostic.getMessage(null));
            }
        } catch (Throwable t) {
            getScriptContext().logError(t);
        } finally {
            try {
                fileManager.close();
            } catch (Throwable t) {
            }
        }

        for (String focusDomain : getScriptContext().retrieveDomainSet()) {
            generateWebServiceArtifacts(focusDomain);
        }
    }
}