Example usage for javax.tools Diagnostic getMessage

List of usage examples for javax.tools Diagnostic getMessage

Introduction

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

Prototype

String getMessage(Locale locale);

Source Link

Document

Returns a localized message for the given locale.

Usage

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

private void showDiagnostics(DiagnosticCollector<JavaFileObject> diagnostics) {
    String message;/*from   w w w  .  j  ava2  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: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 {// ww w  .ja v  a2  s .  c  o m
        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: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 v a 2 s.  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: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 a va  2  s  .  c om
    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: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  . java  2  s.c  o 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) + "";
    }// w  w  w  . j av a  2 s  . co  m
    diagnosticBuilder.append(diagnostic.getMessage(null));
    diagnosticBuilder.append("\n");
    diagnosticBuilder.append(sourceErrorDetails);
    return diagnostic.getKind().equals(Diagnostic.Kind.ERROR);
}

From source file:org.androidtransfuse.adapter.ASTEquivalenceTest.java

@Test
public void testClassEquivalence() throws Exception {

    PackageClass testImplClassName = new PackageClass("example.test", "TestClass");
    PackageClass baseClassName = new PackageClass("example.test", "Base");
    PackageClass testClassName = new PackageClass("example.test", "Test");

    final String testImplValue = IOUtils.toString(ASTEquivalenceTest.class.getClassLoader()
            .getResourceAsStream(testImplClassName.getCanonicalName().replace(".", "/") + ".java"));
    final String baseValue = IOUtils.toString(ASTEquivalenceTest.class.getClassLoader()
            .getResourceAsStream(baseClassName.getCanonicalName().replace(".", "/") + ".java"));
    final String testValue = IOUtils.toString(ASTEquivalenceTest.class.getClassLoader()
            .getResourceAsStream(testClassName.getCanonicalName().replace(".", "/") + ".java"));

    MemoryClassLoader classLoader = new MemoryClassLoader();

    Map<PackageClass, String> targetClassMap = new HashMap<PackageClass, String>();
    targetClassMap.put(testImplClassName, testImplValue);
    targetClassMap.put(baseClassName, baseValue);
    targetClassMap.put(testClassName, testValue);

    classLoader.add(targetClassMap);/*w  w w . ja va2  s.com*/

    Class<?> testClass = Class.forName(testImplClassName.getCanonicalName(), true, classLoader);

    ASTType testClassType = classFactory.getType(testClass);

    MemoryClassLoader processorRunningClassLoader = new MemoryClassLoader();

    DiagnosticCollector<JavaFileObject> diagnosticListener = new DiagnosticCollector<JavaFileObject>();
    boolean pass = processorRunningClassLoader.add(targetClassMap, diagnosticListener,
            Collections.singletonList(new CompareProcessor(testClassType)));

    StringBuilder builder = new StringBuilder();
    for (Diagnostic<? extends JavaFileObject> diagnostic : diagnosticListener.getDiagnostics()) {
        builder.append(diagnostic.getMessage(Locale.US));
    }

    assertTrue(builder.toString(), pass);
}

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 w w. ja v  a  2s .c  om
            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);
    }
}

From source file:org.evosuite.junit.JUnitAnalyzer.java

private static List<File> compileTests(List<TestCase> tests, File dir) {

    TestSuiteWriter suite = new TestSuiteWriter();
    suite.insertAllTests(tests);//from   w  w w  .j a va 2s . c o  m

    //to get name, remove all package before last '.'
    int beginIndex = Properties.TARGET_CLASS.lastIndexOf(".") + 1;
    String name = Properties.TARGET_CLASS.substring(beginIndex);
    name += "_" + (NUM++) + "_tmp_" + Properties.JUNIT_SUFFIX; //postfix

    try {
        //now generate the JUnit test case
        List<File> generated = suite.writeTestSuite(name, dir.getAbsolutePath(), Collections.EMPTY_LIST);
        for (File file : generated) {
            if (!file.exists()) {
                logger.error("Supposed to generate " + file + " but it does not exist");
                return null;
            }
        }

        //try to compile the test cases
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null) {
            logger.error("No Java compiler is available");
            return null;
        }

        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
        Locale locale = Locale.getDefault();
        Charset charset = Charset.forName("UTF-8");
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, locale, charset);

        Iterable<? extends JavaFileObject> compilationUnits = fileManager
                .getJavaFileObjectsFromFiles(generated);

        List<String> optionList = new ArrayList<>();
        String evosuiteCP = ClassPathHandler.getInstance().getEvoSuiteClassPath();
        if (JarPathing.containsAPathingJar(evosuiteCP)) {
            evosuiteCP = JarPathing.expandPathingJars(evosuiteCP);
        }

        String targetProjectCP = ClassPathHandler.getInstance().getTargetProjectClasspath();
        if (JarPathing.containsAPathingJar(targetProjectCP)) {
            targetProjectCP = JarPathing.expandPathingJars(targetProjectCP);
        }

        String classpath = targetProjectCP + File.pathSeparator + evosuiteCP;

        optionList.addAll(Arrays.asList("-classpath", classpath));

        CompilationTask task = compiler.getTask(null, fileManager, diagnostics, optionList, null,
                compilationUnits);
        boolean compiled = task.call();
        fileManager.close();

        if (!compiled) {
            logger.error("Compilation failed on compilation units: " + compilationUnits);
            logger.error("Classpath: " + classpath);
            //TODO remove
            logger.error("evosuiteCP: " + evosuiteCP);

            for (Diagnostic<?> diagnostic : diagnostics.getDiagnostics()) {
                if (diagnostic.getMessage(null).startsWith("error while writing")) {
                    logger.error("Error is due to file permissions, ignoring...");
                    return generated;
                }
                logger.error("Diagnostic: " + diagnostic.getMessage(null) + ": " + diagnostic.getLineNumber());
            }

            StringBuffer buffer = new StringBuffer();
            for (JavaFileObject sourceFile : compilationUnits) {
                List<String> lines = FileUtils.readLines(new File(sourceFile.toUri().getPath()));

                buffer.append(compilationUnits.iterator().next().toString() + "\n");

                for (int i = 0; i < lines.size(); i++) {
                    buffer.append((i + 1) + ": " + lines.get(i) + "\n");
                }
            }
            logger.error(buffer.toString());
            return null;
        }

        return generated;

    } catch (IOException e) {
        logger.error("" + e, e);
        return null;
    }
}

From source file:org.jdto.tools.verifiercases.NestedIncorrectVerifierCase.java

@Override
public void test(List<Diagnostic<? extends JavaFileObject>> diagnostics, String stdoutS, Boolean result) {

    //in this case we should have a compilation error saying that annotation has no effect on setters.

    for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) {
        if (diagnostic.getKind() == Kind.MANDATORY_WARNING) {

            if (!StringUtils.containsIgnoreCase(diagnostic.getMessage(null), "not found on type")) {
                continue;
            } else {
                //test should succeed.
                return;
            }/*from  w w  w.ja va 2 s.  co  m*/

        }
    }

    fail("No relevant compilation warning found.");
}