Example usage for javax.tools Diagnostic getKind

List of usage examples for javax.tools Diagnostic getKind

Introduction

In this page you can find the example usage for javax.tools Diagnostic getKind.

Prototype

Kind getKind();

Source Link

Document

Returns the kind of this diagnostic, for example, error or warning.

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());
                }//  w ww.ja v a2 s .c  om
            }
        }
        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:hydrograph.ui.expression.editor.evaluate.EvaluateExpression.java

boolean isValidExpression() {
    try {/*from w w  w .  j av  a  2 s.  c  o  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: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   ww  w  . j  a va  2  s.c  o m*/
        }
        compileResultTextArea.setText(message.toString());
    } else {
        compileResultTextArea.setText("Compilation successful");
        successfulCompile = true;
    }
    return successfulCompile;
}

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

private void showDiagnostics(DiagnosticCollector<JavaFileObject> diagnostics) {
    String message;/* ww w.j  a v  a2  s  .com*/
    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: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");
    }//from  w w w.  j  a  va  2s . 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: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);
    }//from  w  w  w .  j  av  a2 s . co  m

    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);
        }
    }
}

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

protected boolean buildDiagnosticMessage(Diagnostic diagnostic, StringBuilder diagnosticBuilder,
        JavaFileObjectRegistry registry) {
    Object source = diagnostic.getSource();
    String sourceErrorDetails = "";
    if (source != null) {
        JavaSourceFileObject sourceFile = JavaSourceFileObject.class.cast(source);
        CharSequence sourceCode = sourceFile.getCharContent(true);
        int startPosition = Math.max((int) diagnostic.getStartPosition() - 10, 0);
        int endPosition = Math.min(sourceCode.length(), (int) diagnostic.getEndPosition() + 10);
        sourceErrorDetails = sourceCode.subSequence(startPosition, endPosition) + "";
    }/* ww w  .j  a  va2 s . c  om*/
    diagnosticBuilder.append(diagnostic.getMessage(null));
    diagnosticBuilder.append("\n");
    diagnosticBuilder.append(sourceErrorDetails);
    return diagnostic.getKind().equals(Diagnostic.Kind.ERROR);
}

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

private long getDiagnosticCountByType(DiagnosticCollector<JavaFileObject> diagnostics, Diagnostic.Kind kind) {
    long result = 0;
    for (Diagnostic<? extends JavaFileObject> e : diagnostics.getDiagnostics()) {
        if (e.getKind().equals(kind)) {
            result += 1;//from  w  w  w .j a  va2  s  .c  om
        }
    }
    return result;
}

From source file:org.apache.sysml.runtime.codegen.CodegenUtils.java

private static Class<?> compileClassJavac(String name, String src) {
    try {//from  w w  w  .  j a v a2  s  .c o  m
        //create working dir on demand
        if (_workingDir == null)
            createWorkingDir();

        //write input file (for debugging / classpath handling)
        File ftmp = new File(_workingDir + "/" + name.replace(".", "/") + ".java");
        if (!ftmp.getParentFile().exists())
            ftmp.getParentFile().mkdirs();
        LocalFileUtils.writeTextFile(ftmp, src);

        //get system java compiler
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null)
            throw new RuntimeException("Unable to obtain system java compiler.");

        //prepare file manager
        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);

        //prepare input source code
        Iterable<? extends JavaFileObject> sources = fileManager
                .getJavaFileObjectsFromFiles(Arrays.asList(ftmp));

        //prepare class path 
        URL runDir = CodegenUtils.class.getProtectionDomain().getCodeSource().getLocation();
        String classpath = System.getProperty("java.class.path") + File.pathSeparator + runDir.getPath();
        List<String> options = Arrays.asList("-classpath", classpath);

        //compile source code
        CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, sources);
        Boolean success = task.call();

        //output diagnostics and error handling
        for (Diagnostic<? extends JavaFileObject> tmp : diagnostics.getDiagnostics())
            if (tmp.getKind() == Kind.ERROR)
                System.err.println("ERROR: " + tmp.toString());
        if (success == null || !success)
            throw new RuntimeException("Failed to compile class " + name);

        //dynamically load compiled class
        URLClassLoader classLoader = null;
        try {
            classLoader = new URLClassLoader(new URL[] { new File(_workingDir).toURI().toURL(), runDir },
                    CodegenUtils.class.getClassLoader());
            return classLoader.loadClass(name);
        } finally {
            IOUtilFunctions.closeSilently(classLoader);
        }
    } catch (Exception ex) {
        LOG.error("Failed to compile class " + name + ": \n" + src);
        throw new DMLRuntimeException("Failed to compile class " + name + ".", ex);
    }
}

From source file:org.apidesign.bck2brwsr.dew.Dew.java

@Override
public void service(Request request, Response response) throws Exception {

    if (request.getMethod() == Method.POST) {
        InputStream is = request.getInputStream();
        JSONTokener tok = new JSONTokener(new InputStreamReader(is));
        JSONObject obj = new JSONObject(tok);
        String tmpHtml = obj.getString("html");
        String tmpJava = obj.getString("java");

        Compile res = Compile.create(tmpHtml, tmpJava);
        List<Diagnostic<? extends JavaFileObject>> err = res.getErrors();
        if (err.isEmpty()) {
            data = res;/*  w  ww.  j  a v  a2 s. com*/
            response.getOutputStream().write("[]".getBytes());
            response.setStatus(HttpStatus.OK_200);
        } else {

            JSONArray errors = new JSONArray();

            for (Diagnostic<? extends JavaFileObject> d : err) {
                JSONObject e = new JSONObject();
                e.put("col", d.getColumnNumber());
                e.put("line", d.getLineNumber());
                e.put("kind", d.getKind().toString());
                e.put("msg", d.getMessage(Locale.ENGLISH));
                errors.put(e);
            }

            errors.write(response.getWriter());
            response.setStatus(HttpStatus.PRECONDITION_FAILED_412);
        }

        return;
    }

    String r = request.getHttpHandlerPath();
    if (r == null || r.equals("/")) {
        r = "index.html";
    }
    if (r.equals("/result.html")) {
        response.setContentType("text/html");
        if (data != null) {
            response.getOutputBuffer().write(data.getHtml());
        }
        response.setStatus(HttpStatus.OK_200);
        return;
    }

    if (r.startsWith("/")) {
        r = r.substring(1);
    }

    if (r.endsWith(".html") || r.endsWith(".xhtml")) {
        response.setContentType("text/html");
    }
    OutputStream os = response.getOutputStream();
    try (InputStream is = Dew.class.getResourceAsStream(r)) {
        copyStream(is, os, request.getRequestURL().toString());
    } catch (IOException ex) {
        response.setDetailMessage(ex.getLocalizedMessage());
        response.setError();
        response.setStatus(404);
    }
}